Arms a targeted response-loss simulation for a specific withdrawal request.
**Request:**
- Method: `POST`
- Body: `{ "accountId": String, "amount": String, "sequenceKey": Long }`
**Response:**
-`200 OK`: Fault armed for target transaction.
-`409 Conflict`: A response-loss fault is already armed for a different target.
**Constraint**:
- Must be registered in `HttpServer` only when the environment is explicitly set to test (e.g., via system property `-Denv=test`).
- Only a request matching the exact `accountId`, `amount`, and `sequenceKey` may consume this fault.
- Consumption must be atomic: the first matching request triggers the loss and clears the target.
- The response loss must occur strictly after the database transaction has successfully committed.
-**Arming must be atomic**: If a fault is already armed, subsequent requests to arm a new fault must return `409 Conflict` until the existing fault is consumed.
| `balanceAfter` | String (BigDecimal) | Balance of the account after the transaction. |
| `message` | String | Descriptive message of the outcome. |
| `timestamp` | String (ISO 8601) | Time the transaction was persisted. |
## 2. Validation Rules
-**Amounts**: All monetary amounts must be positive non-zero values.
-**Account IDs**: Must be non-empty strings.
-**Sequence Keys**: Must be monotonically increasing per account; provided as `Long` to prevent overflow.
-**Precision**: All monetary values are handled as **Strings** in JSON and UI state to avoid IEEE 754 floating-point precision loss.
## 3. State Transitions (Transaction Lifecycle)
1.**IDLE** $\rightarrow$ **PENDING**: User submits withdrawal form $\rightarrow$ `pendingTransaction` stored in `sessionStorage`**before** the network request is sent.
2.**PENDING** $\rightarrow$ **SUCCESS/ERROR**: Server responds with definitive outcome $\rightarrow$ `pendingTransaction` cleared from `sessionStorage`.
3.**PENDING** $\rightarrow$ **UNKNOWN_OUTCOME**: Request times out or connection drops $\rightarrow$ `pendingTransaction` remains in `sessionStorage`.
4.**UNKNOWN_OUTCOME** $\rightarrow$ **PENDING**: User clicks "Retry" $\rightarrow$ original `pendingTransaction` resent with `isRetry = true`.
**Input**: Feature specification from `/specs/002-banking-web-interface/spec.md`
## Summary
The goal is to implement a web-based user interface for the existing Fault-Tolerant Distributed Banking Transaction system. This includes a dashboard for account overview, a withdrawal form with idempotency/retry support, a transaction history log, and account creation capabilities. The frontend will be built using vanilla HTML/CSS/JS and served directly by the existing Java `HttpServer`.
**Target Platform**: Web Browser (Client), Linux/Windows (Server)
**Project Type**: web-service (Full-stack)
**Performance Goals**: Removed (No specified requirement).
**Constraints**: No external frontend frameworks; static assets served by Java server; strict separation of fault-injection endpoints (test-only). Monetary values in new UI API responses must be serialized as Strings, while `POST /withdraw` MUST maintain its existing numeric response format for backward compatibility.
**Monetary Parsing Strategy for `POST /withdraw`**:
To preserve precision while consuming the existing numeric JSON response without introducing a complex build system, the frontend will:
-**Selected Solution**: Use `lossless-json` (v4.3.3) included as a static JS file in `resources/web/js/vendor/lossless-json.js`.
-**Implementation**:
- Include `<script src="js/vendor/lossless-json.js"></script>` before the main application JS.
- Use `LosslessJSON.parse(responseText)` instead of `JSON.parse()` for the `POST /withdraw` response.
- Convert the resulting `LosslessNumber` values to display strings using `.toString()`.
-**Zero-Math Policy**: Monetary values must never be converted to JavaScript `Number` or used for calculations in the browser.
-**Verification**: Automated tests will verify that high-precision `BigDecimal` values (e.g., `12345678901234567890.12345678` and `9007199254740993`) are preserved exactly from the numeric JSON response to the UI display.
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
-[x]**Effectively-Once Execution**: The UI must preserve `accountId`, `amount`, and `sequenceKey` for retries, and the backend must use these to ensure idempotency. (Compliant)
-[x]**Atomic State Transitions**: All backend changes for new endpoints (`POST /accounts`) must be wrapped in atomic DB transactions. (Compliant)
-[x]**Deterministic Fault Tolerance**: The `POST /__test/faults/response-loss` endpoint allows deterministic testing of "Unknown Outcome" states. (Compliant)
-[x]**Monetary Precision**: All API responses and request bodies must use `BigDecimal` for monetary amounts. (Compliant)
-[x]**Specification-Driven Development**: This plan is derived directly from `spec.md`. (Compliant)
## Project Structure
### Documentation (this feature)
```text
specs/002-banking-web-interface/
├── plan.md # This file (/speckit-plan command output)
# Quickstart Validation Guide: Banking Web Interface
This guide describes the runnable scenarios used to validate that the Banking Web Interface meets the functional requirements and fault-tolerance guarantees.
## 1. Environment Setup
### Prerequisites
- Java 27 JDK installed.
- Maven installed.
- A modern web browser.
### Launching the Application
1. Run the server: `mvn exec:java -Dexec.mainClass="com.banking.server.HttpServerApp"`
2. Open the browser and navigate to: `http://localhost:8080`
---
## 2. Validation Scenarios
### Scenario 1: Basic Account Overview (FR-001)
1.**Action**: Load the dashboard.
2.**Expected Outcome**:
- "System Online" status is displayed.
- A table shows existing accounts (e.g., `ACC-1` with balance `100.00`).
- Clicking "Refresh" updates balances from the server.
**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
### Current State
-`RequestDTO` and `ResponseDTO` use `java.math.BigDecimal`.
-`RequestHandler` uses a default `ObjectMapper` instance.
- Default Jackson behavior for `BigDecimal`:
-**Deserialization**: Jackson can deserialize both JSON numbers (e.g., `100.00`) and JSON strings (e.g., `"100.00"`) into a `BigDecimal` without additional configuration.
-**Serialization**: By default, `BigDecimal` is serialized as a JSON number.
### Compatibility Strategy
To preserve backward compatibility for existing API clients while supporting the frontend's requirement for string transmission:
1.**Incoming (Request)**: No change needed. `objectMapper.readValue` handles both numeric and string inputs for `BigDecimal`.
2.**Outgoing (Response)**:
- The original `/withdraw` API currently returns numeric values.
- Using `@JsonFormat(shape = JsonFormat.Shape.STRING)` on `ResponseDTO` fields would change the output to strings, breaking numeric-expecting clients.
-**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.
## 3. Deterministic Fault Injection
The original `FaultInjector` uses global state, which is susceptible to "fault theft" by unrelated concurrent requests.
- If the reference is already occupied (not null), the server returns `409 Conflict` to prevent silent overwrites of an existing armed fault.
4.**Consumption**:
- In `RequestHandler`, the current request's identity is compared against the target using the scale-insensitive matching logic above.
- If they match, `AtomicReference.compareAndSet(targetIdentity, null)` is called.
- If `compareAndSet` returns true, the response loss is triggered.
5.**Ordering & Safety**:
- 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.
## 4. Monetary Precision in the Browser
### 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.
### The Strategy: UI-Specific Response DTOs
To preserve the existing `POST /withdraw` response contract for backward compatibility while ensuring absolute precision for 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.
## 4. Monetary Precision in the Browser
### The Precision Problem
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.
### The Strategy: Lossless JSON Parsing
To preserve the original API response contract (which returns numeric values) while preventing precision loss in the browser:
1.**Lossless Parsing**: The frontend will use the `lossless-json` (v4.3.3) library.
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.
3.**Implementation**:
- Use `LosslessJSON.parse(responseText)` to handle the `POST /withdraw` response.
- 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.
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.
@@ -116,13 +116,13 @@ A user creates a new bank account to start performing transactions.
...
@@ -116,13 +116,13 @@ A user creates a new bank account to start performing transactions.
-**FR-007**: The system MUST handle network timeouts or lost connections by transitioning the transaction state to `UNKNOWN_OUTCOME` on the client side.
-**FR-007**: The system MUST handle network timeouts or lost connections by transitioning the transaction state to `UNKNOWN_OUTCOME` on the client side.
-**FR-008**: The backend MUST expose new API endpoints to support:
-**FR-008**: The backend MUST expose new API endpoints to support:
-`GET /accounts`: Retrieve all accounts and balances.
-`GET /accounts`: Retrieve all accounts and balances.