Commit 033e09b1 authored by Shouib's avatar Shouib

docs: define banking web interface implementation tasks

parent 94631612
# API Contracts: Banking Web Interface
This document defines the HTTP interface between the Banking Web Interface (Frontend) and the Banking Server (Backend).
## General Constraints
- **Content-Type**: `application/json`
- **Monetary Values**:
- **Requests**: Must be transmitted as **JSON Strings** from the frontend to ensure precision.
- **Responses**:
- **New UI Endpoints (`GET /accounts`, `GET /transactions`)**: All monetary values MUST be transmitted as **JSON Strings**.
- **Existing Endpoints (`POST /withdraw`)**: MUST preserve existing contract (Numeric JSON for monetary values) for backward compatibility.
- **Encoding**: UTF-8
---
## 1. Account Management
### GET /accounts
Retrieve a list of all bank accounts and their current balances.
**Request:**
- Method: `GET`
- Parameters: None
**Response (200 OK):**
- Body: `Array<{ "accountId": String, "balance": String }>`
- Example: `[ { "accountId": "ACC-1", "balance": "100.00" }, { "accountId": "ACC-2", "balance": "50.00" } ]`
### POST /accounts
Create a new bank account.
**Request:**
- Method: `POST`
- Body: `{ "accountId": String, "initialBalance": String }`
**Response:**
- `201 Created`: Account created successfully.
- `400 Bad Request`: Invalid balance (e.g., negative).
- `409 Conflict`: Account ID already exists.
---
## 2. Transactions
### POST /withdraw
Submit a withdrawal request.
**Request:**
- Method: `POST`
- Body: `{ "accountId": String, "amount": String, "sequenceKey": Long, "isRetry": Boolean }`
**Response:**
- `200 OK`: Transaction processed.
- Body: `{ "status": String, "balanceAfter": String, "message": String }`
- Statuses: `SUCCESS`, `INSUFFICIENT_FUNDS`, `STALE_KEY`, `CONFLICTING_TRANSACTION`, `INVALID_ACCOUNT`.
- Example: `{ "status": "SUCCESS", "balanceAfter": "80.00", "message": "Withdrawal successful" }`
**Client-Side Error Handling:**
- `Timeout/Connection Loss`: Transition UI to `UNKNOWN_OUTCOME` and provide Retry button.
---
## 3. Transaction History
### GET /transactions
Retrieve all persisted transactions from the ledger.
**Request:**
- Method: `GET`
- Parameters: None
**Response (200 OK):**
- Body: `Array<{ "accountId": String, "sequenceKey": Long, "amount": String, "status": String, "balanceAfter": String, "message": String, "timestamp": String }>`
- Example: `[ { "accountId": "ACC-1", "sequenceKey": 101, "amount": "20.00", "status": "SUCCESS", "balanceAfter": "80.00", "message": "Withdrawal successful", "timestamp": "2026-11-03T10:00:00Z" } ]`
---
## 4. Fault Injection (Test-Only)
### POST /__test/faults/response-loss
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.
# Data Model: Banking Web Interface
This document defines the data structures used by the Banking Web Interface, both on the client-side (UI state) and the server-side (API contracts).
## 1. Entities
### WebSession (Client-Side State)
Tracks the current UI state and pending transactions to support idempotency and retries. Persisted in `sessionStorage`.
| Field | Type | Description |
| :--- | :--- | :--- |
| `currentAccountId` | String | The account ID currently selected for operations. |
| `pendingTransaction` | TransactionPayload \| null | The payload of a transaction currently in `UNKNOWN_OUTCOME` state. |
| `systemStatus` | "ONLINE" \| "OFFLINE" | The current connectivity status of the server. |
### TransactionPayload (Nested)
The specific details of a transaction used for submission and retry.
| Field | Type | Description |
| :--- | :--- | :--- |
| `accountId` | String | Target account for the operation. |
| `amount` | String (BigDecimal) | The amount to be withdrawn. |
| `sequenceKey` | Long | The idempotent sequence key generated for this transaction. |
| `isRetry` | Boolean | Flag indicating if this is a retry attempt. |
### TransactionIdentity (Backend/Matching Logic)
Used to identify a unique transaction for idempotency and fault-matching on the server.
| Field | Type | Matching Rule |
| :--- | :--- | :--- |
| `accountId` | String | Case-sensitive String equality |
| `amount` | BigDecimal | `compareTo(other) == 0` (Scale-insensitive numeric equality) |
| `sequenceKey` | Long | Numeric equality |
### AccountView (UI Representation)
A simplified view of a bank account for display on the dashboard.
| Field | Type | Description |
| :--- | :--- | :--- |
| `accountId` | String | Unique identifier of the account. |
| `balance` | String (BigDecimal) | Current available balance. |
### TransactionRecordView (UI Representation)
A representation of a persisted transaction from the ledger for the history log.
| Field | Type | Description |
| :--- | :--- | :--- |
| `accountId` | String | The account involved in the transaction. |
| `sequenceKey` | Long | The sequence key used for the transaction. |
| `amount` | String (BigDecimal) | The amount processed. |
| `status` | String | Outcome (e.g., `SUCCESS`, `INSUFFICIENT_FUNDS`). |
| `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`.
# Implementation Plan: Banking Web Interface
**Branch**: `002-banking-web-interface` | **Date**: 2026-11-03 | **Spec**: [spec.md](/mnt/c/Users/Shouib/IdeaProjects/banking-sdd/specs/002-banking-web-interface/spec.md)
**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`.
## Technical Context
**Language/Version**: Java 27 (Backend), Vanilla JS/HTML/CSS (Frontend)
**Primary Dependencies**: JDK HTTP Server API, Jackson (JSON)
**Storage**: Embedded H2 via JDBC
**Testing**: JUnit 5 (Backend), Manual/Browser testing (Frontend)
**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.
**Scale/Scope**: Single-user simulation, internal banking tool.
## Constitution Check
*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)
├── research.md # Phase 0 output (/speckit-plan command)
├── data-model.md # Phase 1 output (/speckit-plan command)
├── quickstart.md # Phase 1 output (/speckit-plan command)
├── contracts/ # Phase 1 output (/speckit-plan command)
└── tasks.md # Phase 2 output (/speckit-tasks command - NOT created by /speckit-plan)
```
### Source Code (repository root)
```text
src/
├── main/
│ ├── java/
│ │ └── com/banking/
│ │ ├── server/ # Extended HttpServerApp and RequestHandlers for static files and new APIs
│ │ ├── service/ # Business logic for account creation and ledger retrieval
│ │ └── persistence/ # Extended DB access for accounts and transactions (No duplicate repository package)
│ └── resources/
│ └── web/ # Static assets
│ ├── index.html
│ ├── css/
│ └── js/
└── test/
└── java/ # Updated tests including fault injection for UI paths and contract verification
```
**Structure Decision**: Option 1 (Single project) is used as the frontend is composed of static assets served by the Java backend.
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
No violations found.
# 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.
### Scenario 2: Successful Withdrawal (FR-002, FR-003)
1. **Action**: Enter `ACC-1`, amount `20.00`, and a valid `sequenceKey` in the withdrawal form. Submit.
2. **Expected Outcome**:
- UI displays a green success indicator.
- Message: "Withdrawal successful".
- Account balance updates to `80.00` on the dashboard.
### Scenario 3: Insufficient Funds (FR-003)
1. **Action**: Enter `ACC-1`, amount `1000.00`, and a valid `sequenceKey`. Submit.
2. **Expected Outcome**:
- UI displays an amber warning indicator.
- Message: "Insufficient funds to complete this transfer."
- Balance remains `80.00`.
### Scenario 4: Idempotency & Retry (FR-004, FR-007)
1. **Action**: Arm a targeted fault: `POST /__test/faults/response-loss` with body `{ "accountId": "ACC-1", "amount": "10.00", "sequenceKey": 102 }`.
2. **Action**: Submit a withdrawal for `ACC-1` of `10.00` with `sequenceKey: 102`.
3. **Expected Outcome (First Attempt)**:
- Connection closes without response.
- UI transitions to `UNKNOWN_OUTCOME` (Gray indicator).
- "Retry" button appears.
- **Verification**: Reload the browser tab; `pendingTransaction` must still be present in `sessionStorage` and UI must remain in `UNKNOWN_OUTCOME`.
4. **Action**: Click "Retry".
5. **Expected Outcome (Retry Attempt)**:
- UI submits the exact same payload (`ACC-1`, `10.00`, `102`) with `isRetry=true`.
- Server returns `SUCCESS` (since the first attempt committed but failed to respond).
- UI displays success and balance updates to `70.00`.
### Scenario 5: Transaction History Audit (FR-005)
1. **Action**: Navigate to the History page.
2. **Expected Outcome**:
- Table contains the history of `ACC-1` (e.g., the $20 withdrawal and the $10 retry).
- Only `SUCCESS` and `INSUFFICIENT_FUNDS` outcomes are listed.
### Scenario 6: Account Creation (FR-006)
1. **Action**: Open "Create Account" form. Enter ID `ACC-NEW` and initial balance `500.00`. Submit.
2. **Expected Outcome**:
- UI confirms "Account created successfully".
- `ACC-NEW` appears on the Dashboard with balance `500.00`.
---
## 3. Success Verification Matrix
| Req | Scenario | Expected Result | Verified |
| :--- | :--- | :--- | :--- |
| FR-001 | 1 | Dashboard loads and fetches accounts | [ ] |
| FR-002 | 2 | Withdrawal form submits successfully | [ ] |
| FR-003 | 2, 3 | Visual distinction for outcomes | [ ] |
| FR-004 | 4 | Retry reuses identical identity | [ ] |
| FR-005 | 5 | History log contains persisted records | [ ] |
| FR-006 | 6 | Account creation works and is reflected | [ ] |
| FR-007 | 4 | Unknown outcome state handled | [ ] |
# Architectural Research: Banking Web Interface
## 1. Existing Project Structure Analysis
The current implementation uses `com.banking.persistence` for data access.
- `AccountRepository.java`: Manages account state.
- `TransactionLedgerRepository.java`: Manages the transaction log.
- `DatabaseManager.java`: Manages JDBC connections.
**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.
### Refined Mechanism: Transaction-Targeted Faults
To ensure the intended transaction is the one that experiences response loss:
1. **State**: Use an `AtomicReference<TransactionIdentity>` to store the target for the armed fault.
- `TransactionIdentity` is a record containing `accountId`, `amount`, and `sequenceKey`.
2. **Identity Matching**: To remain consistent with `IdempotencyManager`, matching MUST NOT use `BigDecimal.equals()`. Instead:
- `accountId`: String equality.
- `amount`: `BigDecimal.compareTo(targetAmount) == 0`.
- `sequenceKey`: Primitive long equality.
3. **Arming (Preventing Overwrites)**:
- `POST /__test/faults/response-loss` accepts a JSON body: `{ "accountId": String, "amount": BigDecimal, "sequenceKey": Long }`.
- Arming uses `AtomicReference.compareAndSet(null, targetIdentity)`.
- 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.
- **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:
- `GET /accounts`: Retrieve all accounts and balances.
- **Response Schema**: `Array<{ "accountId": String, "balance": BigDecimal }>`
- **Example**: `[ { "accountId": "ACC-1", "balance": 100.00 }, { "accountId": "ACC-2", "balance": 50.00 } ]`
- **Response Schema**: `Array<{ "accountId": String, "balance": String (BigDecimal) }>`
- **Example**: `[ { "accountId": "ACC-1", "balance": "100.00" }, { "accountId": "ACC-2", "balance": "50.00" } ]`
- `GET /transactions`: Retrieve persisted transaction ledger records.
- **Response Schema**: `Array<{ "accountId": String, "sequenceKey": Long, "amount": BigDecimal, "status": String, "balanceAfter": BigDecimal, "message": String, "timestamp": Instant }>`
- **Example**: `[ { "accountId": "ACC-1", "sequenceKey": 101, "amount": 20.00, "status": "SUCCESS", "balanceAfter": 80.00, "message": "Withdrawal successful", "timestamp": "2026-11-03T10:00:00Z" } ]`
- **Response Schema**: `Array<{ "accountId": String, "sequenceKey": Long, "amount": String (BigDecimal), "status": String, "balanceAfter": String (BigDecimal), "message": String, "timestamp": String (Instant) }>`
- **Example**: `[ { "accountId": "ACC-1", "sequenceKey": 101, "amount": "20.00", "status": "SUCCESS", "balanceAfter": "80.00", "message": "Withdrawal successful", "timestamp": "2026-11-03T10:00:00Z" } ]`
- `POST /accounts`: Create a new account. **Contract**:
- **Request**: `{ "accountId": String, "initialBalance": BigDecimal }`
- **Request**: `{ "accountId": String, "initialBalance": String (BigDecimal) }`
- **Success**: HTTP 201 Created.
- **Duplicate ID**: HTTP 409 Conflict.
- **Invalid Balance**: HTTP 400 Bad Request.
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment