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.
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
## Format: `[ID] [P?] [Story] Description`
-**[P]**: Can run in parallel (different files, no dependencies)
-**[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
---
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: Project initialization and basic structure
-[] T001 [P] Create directory structure for static assets in `src/main/resources/web/` (html, css, js, js/vendor)
-[] T002 [P] Download and place `lossless-json.js` (v4.3.3) in `src/main/resources/web/js/vendor/lossless-json.js`
-[] T003 [P] Create base HTML shell `src/main/resources/web/index.html` with `<script src="js/vendor/lossless-json.js"></script>` loaded before application JS
-[] T004 [P] Create base CSS stylesheet `src/main/resources/web/css/style.css`
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
-[] T005 Implement static file serving logic in `com.banking.server.HttpServerApp` (serve files from `/web/` directory)
-[] T006 Implement basic API response wrapper and error handling in `com.banking.server.RequestHandler` to ensure consistent JSON responses
-[] T007 [P] Implement `WebSession` management logic in `src/main/resources/web/js/session.js` (wrappers for `sessionStorage` to track `currentAccountId`, `pendingTransaction`, and `systemStatus`)
-[] T008 [P] Implement the `LosslessJSON` utility wrapper in `src/main/resources/web/js/utils.js` (providing `parse` and `.toString()` formatting for monetary values)
-[] T009 [P] Create shared UI components for messages and status indicators in `src/main/resources/web/js/ui.js`
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
---
## Phase 3: User Story 1 - Account Overview Dashboard (Priority: P1) 🎯 MVP
**Goal**: Display system status and a list of all bank accounts with their current balances.
**Independent Test**: Launch the web interface and verify that it fetches and displays the current list of accounts and balances from the server.
### Implementation for User Story 1
-[] T010 [P] Implement `GET /accounts` endpoint in `com.banking.server.RequestHandler` (returning `Array<{ "accountId": String, "balance": String }>` per spec)
-[] T011 [P] Implement service layer logic to retrieve all accounts from `com.banking.persistence.AccountRepository` in `com.banking.service.BankingService`
-[] T012 [US1] Create Dashboard view logic in `src/main/resources/web/js/dashboard.js` (calls `GET /accounts`, updates the account table)
-[] T013 [US1] Implement "System Online/Offline" status indicator in `src/main/resources/web/js/dashboard.js` (based on `GET /accounts` connectivity)
-[] T014 [US1] Implement "Refresh" button functionality in `src/main/resources/web/js/dashboard.js`
**Checkpoint**: User Story 1 should be fully functional and testable independently
---
## Phase 4: User Story 2 - Perform Withdrawal Operation (Priority: P1) 🎯 MVP
**Goal**: Submit a withdrawal request through a web form and provide immediate feedback on the outcome.
**Independent Test**: Fill out the withdrawal form for a valid account and verify that the success/failure message and updated balance are displayed.
-[] T021 [US2] Implement balance update in the UI after a successful withdrawal in `src/main/resources/web/js/withdraw.js`
**Checkpoint**: User Story 2 should be fully functional and testable independently
---
## Phase 5: User Story 3 - Idempotency and Retry Testing (Priority: P2)
**Goal**: Retry a transaction that had an unknown outcome to ensure no duplicate funds are withdrawn.
**Independent Test**: Arm a response-loss fault and then submit a withdrawal.
### Implementation for User Story 3
-[] T022 [P] Implement `POST /__test/faults/response-loss` endpoint in `com.banking.server.RequestHandler` (governed by `-Denv=test` and restricted to test environments)
-[] T023 [P] Implement the fault-matching logic in `com.banking.server.RequestHandler` (matching `accountId`, `amount` via `compareTo`, and `sequenceKey` using the target identity)
-[] T024 [US3] Implement "Pre-send" state persistence of `TransactionPayload` in `sessionStorage` before the network request in `src/main/resources/web/js/withdraw.js`
-[] T025 [US3] Implement the `UNKNOWN_OUTCOME` state handling in `src/main/resources/web/js/withdraw.js` (transitioning to this state on timeout/lost connection)
-[] T026 [US3] Implement "Retry" button logic in `src/main/resources/web/js/withdraw.js` (resending identical `accountId`, `amount`, `sequenceKey` with `isRetry = true`)
-[] T027 [US3] Verify that "Retry" submissions maintain absolute precision of the `amount` field in `src/main/resources/web/js/withdraw.js`
**Checkpoint**: User Story 3 should be fully functional and testable independently
---
## Phase 6: User Story 4 - Transaction History Review (Priority: P2)
**Goal**: View a comprehensive list of all processed transactions to audit banking activity.
**Independent Test**: Perform several transactions and verify they all appear in the history list with correct metadata.
### Implementation for User Story 4
-[] T028 [P] Implement `GET /transactions` endpoint in `com.banking.server.RequestHandler` (returning `Array<TransactionRecordView>` per spec)
-[] T029 [P] Implement service layer logic to retrieve transactions from `com.banking.persistence.TransactionLedgerRepository` in `com.banking.service.BankingService`
-[] T030 [US4] Create Transaction History view logic in `src/main/resources/web/js/dashboard.js` (calls `GET /transactions`, updates the history table)
-[] T031 [US4] Implement "Refresh" button functionality for history in `src/main/resources/web/js/dashboard.js`
**Checkpoint**: User Story 4 should be fully functional and testable independently
---
## Phase 7: User Story 5 - Account Creation (Priority: P3)
**Goal**: Create a new bank account to start performing transactions.
**Independent Test**: Use the "Create Account" form and then verify the new account appears on the Dashboard.
### Implementation for User Story 5
-[] T032 [P] Implement `POST /accounts` endpoint in `com.banking.server.RequestHandler` (handling 201 Created, 409 Conflict, 400 Bad Request)
-[] T033 [P] Implement account creation logic in `com.banking.persistence.AccountRepository` in `com.banking.service.BankingService`
-[] T034 [US5] Create Account Creation form HTML in `src/main/resources/web/index.html`
-[] T035 [US5] Implement Account Creation submission logic in `src/main/resources/web/js/accounts.js`
-[] T036 [US5] Implement validation of initial balance (non-negative) in `src/main/resources/web/js/accounts.js`
**Checkpoint**: User Story 5 should be fully functional and testable independently
---
## Phase N: Polish & Cross-Cutting Concerns
**Purpose**: Improvements that affect multiple user stories
-[] T037 [P] Implement precision tests for `lossless-json` in a dedicated test page `src/main/resources/web/test-precision.html` (covering `20.00`, `0.00000001`, `12345678901234567890.12345678`, `9007199254740993` and real `POST /withdraw` responses)
-[] T038 [P] Run `quickstart.md` validation and end-to-end e2e test suite
-[] T039 Code cleanup and refactoring of the shared `ui.js` and `session.js` components
-[] T040 [P] Update documentation in `specs/002-banking-web-interface/`
---
## Dependencies & Execution Order
### Phase Dependencies
-**Setup (Phase 1)**: No dependencies - can start immediately
-**Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
-**Foundational (Phase 2)**: All user stories depend on Foundational phase completion
-**User Stories (Phase 3+)**: All depend on Foundational phase completion
- User stories can then proceed in parallel (if staffed)
- Or sequentially in priority order (P1 → P2 → P3)
-**Polish (Final Phase)**: Polish depends on all desired user stories being complete
### User Story Dependencies
-**User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
-**User Story 2 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
-**User Story 3 (P2)**:Depends on User Story 2 (Withdrawal form and logic)
-**User Story 4 (P2)**: Can start after Foundational (Phase 2) - No dependencies on other stories
-**User Story 5 (P3)**: Can start after Foundational (Phase 2) - No dependencies on other stories
### Parallel Opportunities
- All Setup tasks marked [P] can run in parallel
- All Foundational tasks marked [P] can run [P] can run in parallel
- Once Foundational phase completes, all user stories can start in parallel (if team capacity and resources allow)
- All tests for a user story marked [P] can run in parallel
-[P] tasks within a story marked [P] can run in parallel
-[P] tasks within a story marked [P] can run in parallel
- Different user stories can lauch a user story in parallel
- Different user stories can be worked on in parallel by different team members
---
## Implementation Strategy
### MVP First (User Story 1 & 2)
1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational
3. Complete Phase 3: User Story 1 (Dashboard)
4. Complete Phase 4: User Story 2 (Withdrawal)
5.**STOP and VALIDATE**: Test User Story 1 and 2 independently
6. Deploy/demo if ready
### Incremental Delivery
1. Complete Setup + Foundational $\rightarrow$ Foundation ready
2. Complete User Story 1 $\rightarrow$ User Story 1 functional
3. Complete User Story 2 $\rightarrow$ Userت a user story in parallel
4. Complete User Story 3 $\rightarrow$ User Story 3 functional
5. Complete User Story 4 $\rightarrow$ User Story 4 $\rightarrow$ User Story 4 functional
6. Complete User Story 5 $\rightarrow$ User Story 5 $\rightarrow$ User Story 5 $\rightarrow$ User Story 5 functional
7. Complete each story adds value without and break previous stories
### Parallel Team Strategy
With multiple developers:
1. Complete Setup + працю own Setup + Foundational together