# KKA440SFLogic

## Purpose

`KKA440SFLogic` is the business logic controller for the **"KDDI Customer Information Reference"** API (KDDI向け契約者情報参照). It accepts customer identification parameters — such as name, phone number, application number, and date of birth — validates them against business rules, calls the underlying KKSV0637 service to retrieve the customer's subscription and contract data, and returns a structured response containing up to 100 output fields covering multiple phone lines, service states, and customer notices. This class sits at the core of the K-opticom customer inquiry system.

## Design

`KKA440SFLogic` is a **service facade / request handler** within the Futurity web application framework. It follows a classic front-controller pattern common in Japanese enterprise web applications:

- It is instantiated per request (non-singleton) and registered as a business logic (BL) bean in the application's XML configuration (`x31business_logic_KKA440SF.xml`), identified by `BL id="KKA440SF"`.
- The `init()` method serves as the single entry point, handling validation, error handling, and service invocation within one long sequential flow.
- It builds a response message composed of two parts — a "common sector" (error code, error details) and a "simple sector" (domain-specific result data) — which is set into a service form bean.

The class is part of the `eo.web.webview.KKA440SF` package within the K-opticom (K-Opticom) system, a telecommunications customer management platform for KDDI. The source file header notes the module name is "eo customer base system" (eo顧客基幹システム) and the author is 富士通 (Fujitsu).

## Key Methods

### `init() → boolean`

**Location:** lines 196–558
**Entry point** for the entire business logic. Invoked automatically by the Futurity framework when a request targets `BL id="KKA440SF"`.

The method performs the following phases in sequence:

1. **Service bean acquisition** — Retrieves the `X31SDataBeanAccess` form bean via `getServiceFormBean()` and the common info bean via `super.getCommonInfoBean()`.
2. **Business restriction check** — Calls `JKKApiCommon.checkRequestRestriction()` to verify the system is not in a restricted state (maintenance, etc.). If restricted, immediately returns error code `007001` with the message "メンテナンス中です。" (Under maintenance).
3. **Parameter retrieval and sanitization** — Extracts request parameters from `getRequestParams()`:
   - `KIYKSHA_MI` — Customer name (Kanji), max 45 chars
   - `KIYKSHA_MI_KN` — Customer name (Kana), max 120 chars
   - `DNW_BNGU` — EO phone number, max 11 chars, numeric only
   - `MUSKM_BNGU` — Application number, max 10 chars
   - `RNRKSK_BNGU` — Contact phone number, max 11 chars, numeric only
   - `SINNGP` — Date of birth (YYYYMMDD), max 8 chars, numeric only
   - `TNMT_STBSHO_JUSHO` — Place of use address, max 100 chars
   - `HUZN_KIYK_CHEK` — Corporate contract check ("0" or "1")

   Character encoding is converted via `JKKApiCommon.charConverter()` (v4.00.03 fix), and null values are converted to blank strings via `JKKApiCommon.setNulltoBlank()`.

4. **Required field validation** — Checks two groups of required fields:
   - **Customer name**: At least one of `KIYKSHA_MI` (Kanji) or `KIYKSHA_MI_KN` (Kana) must be present. Failure returns error code `009008` (missing required item) with simple sector status `1010`.
   - **Secondary identifier**: At least one of `DNW_BNGU`, `MUSKM_BNGU`, `RNRKSK_BNGU`, or `SINNGP` must be present. Failure returns error code `009008` with simple sector status `1020`.

5. **Value constraint validation** — Runs length checks via `isMaxLength()` for all seven input fields, and numeric validation via `isNumber()` for `DNW_BNGU`, `RNRKSK_BNGU`, and `SINNGP`. Each field-specific failure returns error code `009010` (exceeds max length) or `009009` (not a number), respectively.

6. **Corporate contract check** — Validates that `HUZN_KIYK_CHEK` (if present) is exactly "0" or "1". Failure returns error code `009008` with simple sector status `1030`.

7. **Service invocation** — Builds a parameter map with `TELEGRAM_INFO_USECASE_ID = "KKSV0637"`, configures input/output via `KKSV0637_KKSV0637OPDBMapper`, and calls `invokeService(paramMap, inputMap, outputMap)`. The mapper's `setKKSV063701CC()` method maps the request parameters to the service's input fields using the current operator date.

8. **Response handling** — Based on the service result code:
   - **Service exception with empty results** (`messageResult` has non-null message list but no more info): Returns success code `000000` with simple sector status `0` (no customer record found) and field count `0`.
   - **Service exception with messages**: Re-throws the exception.
   - **Success (`000000`)**: Maps output fields from the service response into the simple sector map via `mapper.getKKSV063701CC()`, applies Shift-JIS character conversion (v4.00.02 fix), and returns the full response.

9. **Fatal error handling** — Any uncaught exception triggers error code `009003` with simple sector status `9100`, and the exception message is stored in detail field `WDA_COM_DETAIL6`.

**Return value:** Always returns `true` (the method signals "handling complete," not "success"). The caller should inspect the response message set into the bean to determine the outcome.

**Side effects:**
- Sets the response message (`rsp_msg`) on the service form bean via `bean.sendMessageString()`.
- This response contains concatenated XML-like "common sector" and "simple sector" strings.

### `initSimpleSectorMap() → HashMap<String, Object>`

**Location:** lines 564–577
**Helper method** that creates an empty response map keyed by the 100 response parameter names (`KEY_RES_PARAM_NM[0]` through `KEY_RES_PARAM_NM[99]`). Each key is initialized to an empty string (`""`). This map serves as the template that gets populated with result data or partial error status codes before being serialized into the response. The method is called on every code path (success, validation errors, service errors) and its result is merged with the common sector to form the complete response.

### `isMaxLength(String value, String itemNm, int length) → boolean`

**Location:** lines 587–623
**Input validation utility.** Returns `true` if the given string's character length is within the specified limit, or `false` if it exceeds it.

- If `value.length() > length`, it constructs and sends an error response via `JKKApiCommon.getCommonSector()` using error code `009010`. The error detail includes the field name in `WDA_COM_DETAIL4` and the actual value in `WDA_COM_DETAIL6`.
- If the value is `null`, it returns `true` (the null check is handled earlier by `setNulltoBlank()` and required field checks).
- The method returns immediately after sending the error response, since `init()` propagates the `false` return value with `return true`.

**Parameter limits enforced by `init()`:**

| Field | Key | Max Length |
|---|---|---|
| Customer name (Kanji) | KIYKSHA_MI | 45 |
| Customer name (Kana) | KIYKSHA_MI_KN | 120 |
| EO phone number | DNW_BNGU | 11 |
| Application number | MUSKM_BNGU | 10 |
| Contact phone number | RNRKSK_BNGU | 11 |
| Date of birth | SINNGP | 8 |
| Place of use address | TNMT_STBSHO_JUSHO | 100 |

### `isNumber(String value, String itemNm) → boolean`

**Location:** lines 632–673
**Input validation utility.** Returns `true` if the given string consists entirely of numeric digits, or `false` if it contains non-numeric characters.

- Returns `true` early if the value is `null` (null-safe design).
- If the value contains non-numeric characters, constructs an error response with error code `009009` (numeric check error), storing the field name in `WDA_COM_DETAIL4` and the actual value in `WDA_COM_DETAIL6`.
- Validates `DNW_BNGU` (EO phone number), `RNRKSK_BNGU` (contact phone number), and `SINNGP` (date of birth).

## Relationships

```mermaid
flowchart LR
    A["WEBGAMEN_KKA440001PJP<br/>(Page Definition)"] --- B["KKA440SFLogic"]
    B --- C["x31business_logic_KKA440SF<br/>(BL Config)"]
    B -->|"extends"| D["JCCWebBusinessLogic"]
    B -->|"calls"| E["KKSV0637<br/>OPDBMapper"]
    B -->|"delegates"| F["JKKApiCommon"]
    B -->|"uses"| G["X31SDataBeanAccess<br/>(Form Bean)"]
```

### Inbound: Who depends on KKA440SFLogic

1. **WEBGAMEN_KKA440001PJP.xml** — The page definition file for the KDDI Customer Information Reference screen. It declares a `SERVICEFORM` (bean type `SF`) using `KKA440SFBean`, with the `<BL id="KKA440SF" class="eo.web.webview.KKA440SF.KKA440SFLogic">` nested inside. This defines the web entry point: a PC-page (`channel="PC"`, `lang="JPN"`) that navigates to `KKA440001PJP.html` with `pageback="Y"` (back-navigation enabled).

2. **x31business_logic_KKA440SF.xml** — The business logic configuration XML that registers `KKA440SFLogic` as the BL class for the `KKA440SF` ID. This is the framework's dependency injection point — the Futurity framework reads this XML and instantiates the logic class when a request targets that BL ID.

### Outbound: What KKA440SFLogic depends on

- **JCCWebBusinessLogic** — The parent class. Provides `getServiceFormBean()`, `getCommonInfoBean()`, `getRequestParams()`, `invokeService()`, and the `DEBUG_LOG` static logger. This is the framework's base class for all business logic handlers.
- **KKSV0637_KKSV0637OPDBMapper** — The data mapper for the underlying KKSV0637 service. Used to map request parameters to service input (`setKKSV063701CC`) and map service output to the response fields (`getKKSV063701CC`, `getKKSV063701CCResultCd`).
- **JKKApiCommon** — The shared API utility class. Used for: `checkRequestRestriction()`, `charConverter()`, `setNulltoBlank()`, `isNull()`, `getRtype()`, `getCommonSector()`, `getSimpleSector()`, `printDebugLog()`, and `isNumber()`.
- **X31SDataBeanAccess** — The service form bean used to read/write the response message.

## Usage Example

The typical invocation flow is orchestrated entirely by the Futurity framework:

```
Request arrives at KKA440001PJP.html page
  → Framework parses WEBGAMEN_KKA440001PJP.xml
  → Instantiates KKA440SFBean (service form)
  → Instantiates KKA440SFLogic (business logic)
  → Calls KKA440SFLogic.init()
    → init() retrieves request params from HTTP form
    → Validates all fields (required, length, numeric)
    → Invokes KKSV0637 service via invokeService()
    → Maps service response to simple sector fields
    → Sets response message into KKA440SFBean
  → Bean passes response back to the page
  → KKA440001PJP.html renders the customer information
```

Example request parameters a caller would send:

```
KIYKSHA_MI=田中太郎          (Customer name, Kanji)
KIYKSHA_MI_KN=たなかたろう  (Customer name, Kana)
DNW_BNGU=09012345678         (EO phone number, numeric)
MUSKM_BNGU=2023010100        (Application number)
RNRKSK_BNGU=0312345678       (Contact phone, numeric)
SINNGP=19900101              (Date of birth, YYYYMMDD)
TNMT_STBSHO_JUSHO=東京都渋谷区  (Address)
```

The response will contain up to 100 fields in the `rsp_msg` parameter, including:
- Search request number (`KNSK_UKTK_BNGU`), completion code (`KNRYO_CD`), detail code (`SHOSI_CD`)
- Contract state for up to 4 EO phone lines (`PRMT24`–`PRMT31`)
- Net Smart eligibility, contract status, and customer notices
- Disconnected EO phone status and information

## Notes for Developers

- **Always returns `true` from `init()`** — The boolean return value means "the method completed its handling," not "the operation was successful." The actual result is encoded in the response message fields (`WDA_COM_RESULT`, simple sector status codes). Do not use the return value to determine success/failure.

- **Thread safety** — The class has no instance fields that are modified during `init()` (all state is local to the method), so it is safe for concurrent use across requests. The parent class `JCCWebBusinessLogic` may have state — verify its threading model if subclassing or accessing inherited members.

- **Error code taxonomy** — The class uses these result codes:
  - `007001` — Business restriction (maintenance mode)
  - `009003` — Fatal exception (unhandled error)
  - `009008` — Missing required field or invalid parameter value
  - `009009` — Numeric check failure (phone number or date contains non-digits)
  - `009010` — Max length exceeded
  - `000000` — Success

- **Shift-JIS encoding** — The v4.00.02 fix introduced explicit `JKKApiCommon.charConverter(rspMsg.toString(), "Shift-JIS")` on successful responses. This is critical for Japanese character compatibility — omitting it may corrupt the response for Kanji-containing data.

- **100-element response arrays** — `KEY_RES_PARAM_NM` and `KEY_REQ_PARAM_NM` are large constant arrays. The response parameter array spans indices 0–103 (104 elements total). New response fields should be appended at the end (current highest index is 75 for `PRMT73`). Modifying existing indices risks breaking downstream callers.

- **Validation order matters** — The method checks required fields first, then field-specific constraints. If multiple validations fail, only the first one encountered is returned. This is a "fail-fast" design.

- **The `KKA440SFConst.RSP_MSG` constant** — The response message key is `"応答電信"` (response telegram). This is the bean property name used by `bean.sendMessageString()` and is consumed by the page definition.

- **Japanese character set** — The source file uses MS932 (Shift-JIS) encoding (confirmed in the XML config `encoding="MS932"`). Ensure any editors or tools preserve this encoding.

- **Version history** — The class has gone through several fixes:
  - v4.00.00 (2012/09/27): Initial creation
  - v4.00.01 (2013/02/16): Issue ST1-2013-0000362 — likely error handling / response structure
  - v4.00.02 (2013/02/17): Issue ST1-2013-0000355 — Shift-JIS conversion (current fix applied)
  - v4.00.03 (2013/02/22): Issue ST1-2013-0000401 — character conversion on request params
  - v39.00.00 (2018/10/26): eo Light equipment removal / service start response

- **The KKSV0637 service** — This is the actual backend service that performs the customer data lookup. The mapper (`KKSV0637_KKSV0637OPDBMapper`) translates between the web-layer parameter format and the service's data model. Changes to the service's contract require corresponding updates to both the mapper and this logic class.
