# KKW00191SFLogic

## Purpose

`KKW00191SFLogic` is the business-logic controller for the **Investigation Cancellation** feature (調査取消) within the K-Opticom Contract Management system. When a user initiates cancellation of a service contract investigation, this class orchestrates the entire flow: retrieving inherited screen data, determining the investigation status (OK or NG), routing to the appropriate backend service, transforming database results into display-ready form data, and updating the screen state.

## Design

This class follows the **web-screen action-handler pattern** common in the Fujitsu Futurity-based web framework. It acts as a facade that coordinates data retrieval, service invocation, data transformation, and screen state management for a single screen action (KKW00191SF). The class has no direct UI bindings — it reads and writes through `X31SDataBeanAccess` objects, which serve as a shared data layer between the view and logic tiers.

```mermaid
flowchart TD
    A["KKW00191SFLogic<br/>Cancellation Screen Logic"] --> B["JCCWebBusinessLogic<br/>Base Web Logic"]
    A --> C["KKW00191SFConst<br/>Constants"]
    A --> D["KKSV0408_KKSV0408OPDBMapper<br/>Data Mapper"]
    A --> E["JKKSvkeiUpdScreenUtil<br/>Screen Update Utility"]
    A --> F["KKSV0742 Service<br/>Investigation NG Cancellation"]
    A --> G["KKSV0408 Service<br/>Investigation Cancellation"]
    A --> H["X31SDataBeanAccess<br/>Form Bean"]
    A --> I["CommonInfoBean<br/>Shared Context"]
```

## Key Methods

### `actionInit()` → `boolean`

The primary entry point for the screen. Called when the user navigates to the Investigation Cancellation screen.

**What it does:**

1. Retrieves the shared form bean (`CommonInfoBean`) and the service form bean via `super.getCommonInfoBean()` and `super.getServiceFormBean()`.
2. Wraps the service form bean into a single-element array (`paramBean`).
3. Calls `initServiceFormBean(bean)` to populate inherited data (customer name, addresses, service code, etc.) from the screen context into the form bean.
4. Reads the investigation result code (`SHOSA_DSL_FIN_CD`) from the form bean. This code determines which path to take:
   - **CD00469_1 (Investigation OK):** Calls `invokeService(paramBean)` to perform the normal investigation cancellation service, which routes to backend use case `KKSV0408`.
   - **CD00469_2 (Investigation NG):** Calls the private `shosaNgCl(paramBean)` method, which performs the Investigation NG Cancellation via backend use case `KKSV0742`.
5. Calls `JKKSvkeiUpdScreenUtil.executeAxMRnkSjisho()` with the system ID (`sysidVal`) to perform a screen update/refresh. If this utility returns `false`, it dumps the current DataBean state to the log and returns `false` (indicating failure).
6. On success, sets a UI message `EKB4390__I` ("Service contract investigation cancellation") via `JCCWebCommon.setMessageInfo()`, logs the DataBean, and returns `true`.

**Side effects:** Populates the form bean with inherited data, invokes backend services (cancellation processing), updates screen state, and writes log entries.

**Thread safety:** The class maintains a single instance variable `sysidVal` which is set during `initServiceFormBean`. This means the class is **not thread-safe** and should not be shared across concurrent requests. The instance lifecycle is managed by the web framework (likely per-request).

### `actionComp()` → `boolean`

Handles the "Completed" button press event. This is a simple post-action navigation handler.

**What it does:**

1. Retrieves the shared `CommonInfoBean`.
2. Sets the `NEXT_SCREEN_ID` and `NEXT_SCREEN_NAME` in the common info bean to point to screen `KKW01101` (the Service Contract List Confirmation screen, サービス契約一覧照会画面).
3. Returns `true` to indicate successful processing.

**Note:** The original implementation had additional navigation logic for returning from the cancellation screen, but it was removed in commit IT2-2012-0001905 because the list screen already handles the return destination.

### `invokeService(X31SDataBeanAccess[] paramBean)` → `void`

The main service invocation method for the **Investigation Cancellation** (OK path). This is where the actual backend processing happens.

**What it does:**

1. Creates three `HashMap<String, Object>` structures: `paramMap` (user case parameters), `inputMap` (mapping input data), and `outputMap` (service results).
2. Sets the reservation application date (`RSV_APLY_YMD`) on the form bean to the current operator date via `JCCWebCommon.getOpeDate()`.
3. Configures the service parameters:
   - **Use Case ID:** `UCID_KKSV0408` (the investigation cancellation use case)
   - **Operation ID:** `OPID_KKSV0408OP`
4. Instantiates `KKSV0408_KKSV0408OPDBMapper` to handle data mapping to/from the backend service.
5. Performs **upper mapping** (form bean → input map) via the mapper:
   - `setKKSV040802SC` — Maps reservation details (function code 2)
   - `setKKSV040803SC` — Maps service contract details (function code 2)
   - `setKKSV040805SC` — Maps additional data (function code 1)
   - `setJKKSvkeiShosaClCC` — Maps investigation cancellation common conditions (function code 1). Notably, this method was updated in 2014 to also accept the operator's organization code (`orgCd`) and organization name (`orgNm`) from the common info bean, supporting a "test-all-function-user" audit trail requirement.
   - `setJKKButuryuCtrlCC` — Maps delivery control conditions
   - `setJKKHakkoSODCC` — Maps issuance SOD (Start of Day) conditions
   - `setJKKTchishoAddCC` — Maps branch addition conditions
6. Calls the inherited `invokeService(paramMap, inputMap, outputMap)` from `JCCWebBusinessLogic` to execute the actual backend service call.
7. Performs **lower mapping** (output map → form bean) via:
   - `getKKSV040803SC` — Retrieves service contract details
   - `getKKSV040804SC` — Retrieves service contract agreement details
   - `getKKSV040805SC` — Retrieves additional results
8. Calls `editServiceFormBean(paramBean[0])` to transform the raw service results into display-ready format.
9. Dumps the final DataBean state to the log.

### `editServiceFormBean(X31SDataBeanAccess svcFormBean)` → `void`

Transforms raw data from the backend service into human-readable display format. Called at the end of `invokeService`.

**What it does:**

1. **Application Details Confirmation** (`MSKM_DTL_LIST`):
   - Extracts the application date (`MSKM_YMD_02`) as a YYYYMMDD string and reformats it to `YYYY/MM/DD` display format.
   - Extracts the application document number (`MSKMSHO_NO_02`) and sets it as `MSKMSHO_NO`.

2. **Service Contract Agreement Confirmation** (`SVC_KEI_LIST`):
   - Reformats the investigation date from YYYYMMDD to `YYYY/MM/DD`.
   - Extracts the service code name and price plan code name.

3. **Service Contract Common Information List** (`SVC_KEI_COM_LIST`):
   - Extracts the mansion ID (`MANSION_ID_03`) and mansion name (`MANSION_NM_03`).

This method uses `substring` operations on date strings (positions 0-4, 4-6, 6-8) to insert `/` separators. This is a simple formatting pattern but assumes the source dates are always in the expected 8-character YYYYMMDD format.

### `initServiceFormBean(X31SDataBeanAccess svcFormBean)` → `void`

Populates the service form bean with inherited data from the screen context. Called at the start of `actionInit()`.

**What it does:**

1. Calls `JCCWebCommon.getScreenInfo(this)` to retrieve inherited screen information.
2. Reads from the inherited data array (`CUST_KEI_HKTGI_LIST`), extracting the first element as the "inherited element" (`hktgElement`).
3. Stores the system ID (`HKTGI_SYSID`) in the private field `sysidVal` (used later by `actionInit` for the screen update utility).
4. Copies over 15 inherited fields from the screen context to the form bean:
   - **System ID** (`SYSID`, `SYSID_04`)
   - **Service Code** (`SVC_KEI_NO`, `SVC_KEI_NO_04`)
   - **Place/Location fields** (state name, city name, district, town, branch code) — for the usage location (利用場所)
   - **Customer name and kana** (顧客名, カナ)
   - **Contractor address fields** (state name, city name, district, town, branch code, phone number) — for the contractor (契約者)
5. Builds two full address strings by concatenating:
   - **Usage location address** (`KAISEN_ADDR`): state + city + district + town + branch code
   - **Contractor address** (`KEISHA_ADDR`): state + city + district + town + branch code
6. Copies the investigation cancellation completion code (`SHOSA_DSL_FIN_CD_04`) to the form bean. This code is read back in `actionInit()` to determine whether to route to the OK or NG service path.

All data movement uses the `sendMessageString()` pattern with either `DATABEAN_GET_VALUE` or `DATABEAN_SET_VALUE` on `X31SDataBeanAccess` objects.

### `shosaNgCl(X31SDataBeanAccess[] paramBean)` → `void` (private)

Handles the **Investigation NG Cancellation** path when the investigation result was negative (NG). This is a fallback cancellation flow.

**What it does:**

1. Creates `paramMap`, `inputMap`, and `outputMap` HashMaps for the service call.
2. Configures the service parameters:
   - **Use Case ID:** `UCID_KKSV0742` (the investigation NG cancellation use case)
   - **Operation ID:** `OPID_KKSV0742OP`
3. Builds a target data list structure:
   - Sets `func_code` to `FUNC_CD_1` in the parent map.
   - Adds the service code (`SVC_KEI_NO`) from the form bean to a `trgtDataListElement`, then adds that element to a `trgtDataList`.
   - Wraps the list in a `trgt_data` map keyed by `"trgt_data_list"`.
4. Puts the target data into `inputMap` under the key `"KKSV074201CC"`.
5. Calls the inherited `invokeService(paramMap, inputMap, outputMap)` to execute the backend service.

This method is a simplified version of `invokeService` — it does not perform upper/lower mapping via `KKSV0408_KKSV0408OPDBMapper`. Instead, it directly constructs a flat request structure for the `KKSV0742` service.

## Relationships

```mermaid
sequenceDiagram
    participant UI as User Interface
    participant Logic as KKW00191SFLogic
    participant Bean as ServiceFormBean
    participant Mapper as DBMapper
    participant Service as Backend Service
    participant Util as ScreenUpdateUtil

    UI->>Logic: actionInit()
    Logic->>Bean: initServiceFormBean(bean)
    Logic->>Bean: get SHOSA_DSL_FIN_CD
    alt Investigation OK
        Logic->>Logic: invokeService(paramBean)
        Logic->>Mapper: setKKSV040802SC
        Logic->>Mapper: setJKKSvkeiShosaClCC
        Logic->>Mapper: setJKKButuryuCtrlCC
        Logic->>Mapper: setJKKHakkoSODCC
        Logic->>Mapper: setJKKTchishoAddCC
        Mapper->>Service: invokeService
        Service-->>Mapper: outputMap
        Mapper->>Logic: getKKSV040803SC
        Mapper->>Logic: getKKSV040804SC
        Logic->>Logic: editServiceFormBean
    else Investigation NG
        Logic->>Logic: shosaNgCl(paramBean)
        Logic->>Service: KKSV0742 cancellation
    end
    Logic->>Util: executeAxMRnkSjisho
    Logic->>UI: setMessageInfo EKB4390__I
    Logic-->>UI: return true
```

### Who uses this class

| Dependent | Description |
|-----------|-------------|
| `WEBGAMEN_KKW001910PJP.xml` | The page definition file that wires this logic class to the KKW00191SF screen. Handles request dispatching and action binding. |
| `x31business_logic_KKW00191SF.xml` | The business logic configuration file (X31 framework) that registers this class as a service-level business logic handler. |

### What this class depends on

| Dependency | Role |
|------------|------|
| `JCCWebBusinessLogic` | Base class providing `invokeService(paramMap, inputMap, outputMap)`, `getCommonInfoBean()`, `getServiceFormBean()`, and `dumpDatabean()`. |
| `KKW00191SFConst` | Constants class with keys used throughout the form bean interactions. |
| `KKSV0408_KKSV0408OPDBMapper` | Data mapper for the KKSV0408 (Investigation Cancellation) backend service. Handles upper/lower mapping between form beans and service call maps. |
| `JKKSvkeiUpdScreenUtil` | Utility for screen update/refresh operations. |
| `X31SDataBeanAccess` / `X31SDataBeanAccessArray` | Framework data bean objects used for all data passing. |
| `CommonInfoBean` (via `CommonInfoCFConst`) | Shared context bean carrying session-wide state including organization info and navigation targets. |

## Usage Example

This class is used by the web framework automatically when a user navigates to the KKW00191SF screen. The typical flow is:

1. The user requests the **Service Contract Investigation Cancellation** screen (KKW00191SF). The framework instantiates `KKW00191SFLogic` and calls `actionInit()`.
2. `actionInit()` loads inherited data (customer, service, contractor info) via `initServiceFormBean()`, then checks the investigation result code.
3. If the investigation was **OK** (CD00469_1), the framework processes the cancellation through the standard KKSV0408 service. The screen displays the updated results via `editServiceFormBean()`.
4. If the investigation was **NG** (CD00469_2), the framework processes a fallback cancellation through the KKSV0742 service via `shosaNgCl()`.
5. After processing, the framework shows an informational message ("Service contract investigation cancellation") and the user can navigate back to the Service Contract List screen (KKW01101) by pressing the completed button, which triggers `actionComp()`.

## Notes for Developers

- **Not thread-safe:** The `sysidVal` instance field is set during `initServiceFormBean()` and read during `actionInit()`. This class must have a fresh instance per request; sharing instances across requests would cause data corruption.
- **Date formatting is brittle:** `editServiceFormBean()` uses hardcoded `substring()` calls (0-4, 4-6, 6-8) to format dates. If any backend field returns a date in a different format, the output will break silently.
- **Two parallel service paths:** The class handles two different backend services (KKSV0408 for OK, KKSV0742 for NG) through the same class. `shosaNgCl()` builds its request manually rather than using the `KKSV0408_KKSV0408OPDBMapper`, meaning the two paths have different data handling patterns.
- **Logging verbosity:** The class dumps full DataBean state (`dumpDatabean()`) on both the OK and NG paths, as well as on utility failures. This is helpful for debugging but may produce large log entries — consider whether all dumps are needed in production.
- **Address string concatenation:** `initServiceFormBean()` concatenates address components without any delimiter (no spaces, commas, or newlines). The resulting `KAISEN_ADDR` and `KEISHA_ADDR` fields will be a raw concatenation of the component strings.
- **Unused code:** The `parentMap` variable in `shosaNgCl()` is created and populated with `func_code` but never passed to `invokeService()`. This appears to be a remnant from a previous iteration and may be dead code.
- **Commit history:** Key features were added over time:
  - 2011/10/27: Initial creation by 富士通
  - 2012/02/09 (v5.00.00): Investigation NG cancellation path added (IT1-2013-0000148)
  - 2014/03/27 (v8.00.00): Organization code/name audit trail support (OM-2013-0002656)
