# (DD11) Business Logic — NumericFilter.insertString() [12 LOC]

| Field | Value |
|-------|-------|
| Fully Qualified Name | `com.github.blaxk3.ui.NumericFilter` |
| Layer | Utility (Inner class in a UI component class) |
| Module | `ui` (Package: `com.github.blaxk3.ui`) |

## 1. Role

### NumericFilter.insertString()

`NumericFilter.insertString()` is a Swing `DocumentFilter` override that enforces numeric-only input into editable text fields. It intercepts every text insertion attempt (typing, paste, programmatic insert) and validates the resulting document content before allowing it to take effect. The method delegates to a private `isValid()` helper that permits digits (`0-9`) and at most one decimal point (`.`), making it suitable for currency or numeric quantity input fields. The design pattern employed is the **filter/proxy pattern**: rather than modifying incoming data, the method either approves the insertion by forwarding it to the superclass (`DocumentFilter`) or silently discards it — guaranteeing that the underlying `Document` model never contains invalid characters. Within the larger system, `NumericFilter` is a shared utility inner class (defined inside `UI.java`) that can be attached to any `JTextComponent` to provide automatic input validation without requiring per-field logic.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["insertString(fb, offset, string, attr)"])
    START --> GET_DOC["Get Document from fb"]
    GET_DOC --> INIT_SB["Initialize StringBuilder"]
    INIT_SB --> APPEND_TEXT["Append current doc text to StringBuilder"]
    APPEND_TEXT --> INSERT_STRING["Insert new string at offset"]
    INSERT_STRING --> VALID_CALL["Call isValid(sb.toString())"]
    VALID_CALL --> CHECK_EMPTY{Is text empty?}
    CHECK_EMPTY -->|true| RETURN_TRUE["Return true"]
    CHECK_EMPTY -->|false| INIT_COUNT["decimalCount = 0"]
    INIT_COUNT --> LOOP_START{"For each char in text"}
    LOOP_START -->|end| RETURN_TRUE2["Return true"]
    LOOP_START -->|continue| GET_CHAR["Get char at index i"]
    GET_CHAR --> CHECK_DOT{Is char == '.'?}
    CHECK_DOT -->|true| CHECK_DECIMAL{decimalCount != 1?}
    CHECK_DOT -->|false| CHECK_DIGIT{Is char a digit?}
    CHECK_DECIMAL -->|true| INC_DECIMAL["decimalCount++"]
    CHECK_DECIMAL -->|false| RETURN_FALSE["Return false"]
    CHECK_DIGIT -->|true| INC_I["i++"]
    CHECK_DIGIT -->|false| RETURN_FALSE
    INC_DECIMAL --> INC_I2["i++"]
    INC_I --> LOOP_START
    INC_I2 --> LOOP_START
    RETURN_TRUE --> VALID_RESULT["isValid returns true"]
    RETURN_TRUE2 --> VALID_RESULT
    RETURN_FALSE --> VALID_FALSE["isValid returns false"]
    VALID_RESULT --> DELEGATE["Call super.insertString(fb, offset, string, attr)"]
    VALID_FALSE --> END_METHOD["End - no insertion"]
    DELEGATE --> END_METHOD
```

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| 1 | `fb` | `FilterBypass` | The `FilterBypass` object passed through from the Swing `Document` pipeline; provides access to the underlying `Document` model (via `getDocument()`) and a safe channel (`super.insertString`) to commit the validated text to the UI component. |
| 2 | `offset` | `int` | The insertion position within the text document — represents the cursor caret index where the new text will be placed. |
| 3 | `string` | `String` | The text being inserted (typed characters or pasted content). It may contain digits, decimal points, or any other characters. After this method's validation, only strings matching the numeric format (digits with at most one `.`) are allowed through to the document. |
| 4 | `attr` | `AttributeSet` | The character attribute set associated with the insertion (e.g., font, color styling). Passed through to `super.insertString` to preserve formatting. Not used for validation. |

**Fields / External State Read:**

| Name | Description |
|------|-------------|
| `fb.getDocument()` | The underlying `javax.swing.text.Document` model being edited by the UI component (e.g., a `JTextField` or `JTextPane`). |

## 4. CRUD Operations / Called Services

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| CALL | `NumericFilter.isValid` | NumericFilter | - | Calls `isValid(String)` in `NumericFilter` to validate the proposed text content against numeric-only rules. |
| CALL | `DocumentFilter.insertString` (super) | DocumentFilter | - | Delegates to the superclass to actually perform the text insertion in the `Document` model, bypassing the filter loop. |

No database or service-tier CRUD operations are involved — this method operates entirely within the Swing UI presentation layer.

## 5. Dependency Trace

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | (Swing UI) | `JTextComponent.insert(String)` -> `DocumentFilter.insertString(fb, offset, string, attr)` | `super.insertString [EXEC] Document model` |

**Notes:**
- `NumericFilter.insertString` is invoked indirectly by the Swing text infrastructure whenever a user types or pastes text into a `JTextComponent` (e.g., `JTextField`, `JTextArea`) that has this `DocumentFilter` attached via `setDocument()`.
- No other Java classes in the codebase explicitly call this method; it is called purely through the Swing event dispatch pipeline.
- The only call chain originates from the Swing framework itself, not from any application-layer screen or batch.

## 6. Per-Branch Detail Blocks

**Block 1** — [BLOCK INITIALIZATION] `(lines 170-176)`

> Extract the current document state and simulate the proposed insertion by building a combined string. This is the preparation step before validation.

| # | Type | Code |
|---|------|------|
| 1 | GET | `Document doc = fb.getDocument()` | Retrieves the underlying text document model from the filter bypass. |
| 2 | SET | `StringBuilder sb = new StringBuilder()` | Initializes an empty mutable string buffer. |
| 3 | SET | `sb.append(doc.getText(0, doc.getLength()))` | Copies the entire current content of the document into the buffer. |
| 4 | EXEC | `sb.insert(offset, string)` | Simulates inserting the incoming text at the specified offset position. |

**Block 2** — [IF] `(isValid(sb.toString()))` `(line 177)`

> Validate the simulated post-insertion text. If valid, delegate to the superclass to perform the actual insertion; otherwise, do nothing (the insertion is silently rejected).

| # | Type | Code |
|---|------|------|
| 1 | CALL | `isValid(sb.toString())` | Passes the combined text to the validation helper. |
| 2 | EXEC | `super.insertString(fb, offset, string, attr)` | Commits the text to the document model, bypassing the filter. |

**Block 2.1** — [SUB-BLOCK: isValid validation logic] `(lines 194-208)`

> The `isValid` method enforces the business rule: only digits and at most one decimal point are allowed. Empty text is always valid (allows the field to be cleared).

| # | Type | Code | Business Meaning |
|---|------|------|-----------------|
| 1 | IF | `text.isEmpty()` | Empty input is always valid — allows backspace/delete to clear the field. |
| 2 | SET | `byte decimalCount = 0` | Counter tracking the number of decimal points encountered so far. |
| 3 | FOR | `for (int i = 0; i < text.length(); i++)` | Iterates over every character in the proposed text. |

**Block 2.1.1** — [IF] `(ch == '.')` `(line 201)`

> Checks if the current character is a decimal point.

| # | Type | Code | Business Meaning |
|---|------|------|-----------------|
| 1 | IF | `decimalCount != 1` | Allows the first `.` (decimalCount=0) but rejects subsequent ones (decimalCount=1). |
| 2 | SET | `decimalCount++` | Increments the decimal point counter. |

**Block 2.1.2** — [IF] `!Character.isDigit(ch)` `(line 203)`

> Rejects any character that is not a numeric digit (0-9). This blocks letters, symbols, spaces, and any non-numeric input.

| # | Type | Code | Business Meaning |
|---|------|------|-----------------|
| 1 | RETURN | `return false` | Invalid input detected — the insertion will be silently blocked by `insertString`. |

**Block 2.1.3** — [END OF VALIDATION] `(line 206)`

> If the loop completes without returning false, the text is valid.

| # | Type | Code | Business Meaning |
|---|------|------|-----------------|
| 1 | RETURN | `return true` | Text contains only digits and at most one decimal point. |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `DocumentFilter` | Java API | A Swing class that intercepts changes to `Document` content, allowing pre-validation before text is committed. |
| `FilterBypass` | Java API | A wrapper used inside `DocumentFilter` methods to access the underlying `Document` and perform super-class operations that bypass the filter itself. |
| `Document` | Java API | The model backing Swing text components (`JTextField`, `JTextArea`). Stores the actual text content being edited. |
| `AttributeSet` | Java API | A Swing interface representing text attribute metadata (font, color, etc.) associated with portions of a `Document`. |
| `Character.isDigit()` | Java API | A method that returns `true` if a character is a Unicode digit (0-9). Used to validate numeric input. |
| `super.insertString()` | Java API | Calls the parent class `DocumentFilter.insertString` to perform the actual text insertion, bypassing the filter recursion. |
| `isValid()` | Method | Private validation helper enforcing numeric-only input: digits and at most one decimal point are allowed. |
