# KKW02519SFLogic

## Purpose

`KKW02519SFLogic` is the central business logic class for the **Telephone Option Service Contract Update** screen flow in the NTT East online business system. It orchestrates a multi-screen wizard that allows operators to modify, cancel (reschedule/dissolve), or restore an option service contract — and handles the associated validation, service invocations, and error checking for dependent bundled services (such as Sender Number Display and Anshin Fakucho services).

## Design

This class follows the **web screen logic / controller** pattern common in the JCC (Japan Credit Bureau Common?) framework. It sits in the presentation tier but performs substantial business logic: coordinating service calls, validating dependency relationships between contracted services, managing DataBean state, and controlling screen navigation. It extends `JCCWebBusinessLogic`, which provides the base infrastructure for screen-level business operations.

The class acts as a **facade** over multiple backend services (KKSV0369, KKSV0370, KKSV0371, KKSV0372, KKSV0516), mapping DataBeans to service parameters via dedicated mapper objects, then routing the results back to the caller.

## State

The class maintains a single instance field:

| Field | Type | Purpose |
|-------|------|---------|
| `tranDiv` | `String` | Operation division identifier: `"変更"` (change), `"解約"` (dissolve), or `"回復"` (restore). Determines which business path is taken. |

## Static Constants (Progress-Specific Text)

| Constant | Value | Purpose |
|----------|-------|---------|
| `PRG_TKJK_1_JYOHO` | `"情報"` | Progress-specific information label |
| `PRG_TKJK_1_CHGE` | `"変更"` | "Change" designation for progress tracking |
| `PRG_TKJK_1_DSL` | `"解約"` | "Dissolve" designation for progress tracking |
| `PRG_TKJK_1_KAIHK` | `"回復"` | "Restore" designation for progress tracking |

## Key Methods

### `actionInit()` -> `boolean`

**Entry point.** Called when the screen first loads. Returns `true` on success, `false` on abnormal termination.

1. Retrieves the common info bean and service form bean.
2. Calls `getSessionData()` to pull inherited data from the previous screen.
3. Determines the target screen ID from the common info bean (`NEXT_SCREEN_ID`):
   - `KKW02519` (screen 1 - update screen) -> calls `actionInitUpdTran()` for initial display.
   - `KKW02520` (screen 2 - update confirmation screen) -> calls `actionInitUpdTran()` for direct-navigation display.
   - `KKW02521` (screen 3 - update completion screen) -> no initial display processing needed.
4. Logs the DataBean state.

This method is the gateway for all three screens in the update flow (change, dissolve, restore).

### `actionInitUpdTran()` -> `void`

The core initialization routine for the update and update confirmation screens. Invoked by `actionInit()` for both `KKW02519` and `KKW02520` screen IDs.

**Major responsibilities:**

1. **Sets operational timestamps** — Gets the current operating date (`unyo_ymd`) and date-time stamp (`unyo_ymd_tm`) and stores them in the form bean.

2. **Invokes the KKSV0369 service** (service contract inquiry) using the `KKSV0369_KKSV0369OPDBMapper`. This single service call retrieves a comprehensive set of data:
   - Service contract agreement list
   - Option service contract agreement list
   - Sub-option service contract agreement list
   - Option service agreement list
   - Customer agreement list
   - Service contract details agreement list
   - Option service contract (telephone) agreement list
   - Business parameter management (upper/lower notification limits)
   - Billing advance list
   - Telephone option service contract list
   - Telephone secure option pack operation product CC
   - Abnormality reservation list
   - Service target machine provision service contract list

3. **Maps service output back to DataBeans** using the corresponding `getKKSV0369XXSC` / `getKKSV036917CC` mapper methods.

4. **Extracts derived values:**
   - `otoku_chk_err_flg` (discount check error flag) from the operation pack config output.
   - `pack_mirai_flg` (future pack flag) for future pack existence.
   - Seiky kei no (billing contract number) and assigns it to the form bean.
   - Sets use-end date components (year/month/day) on the telephone option service bean.
   - Extracts the service contract's last update datetime.

5. **Initializes telephone option service contract information** based on whether a sub-option contract number exists:
   - **If no sub-option number:** Copies operation code and operation name from the parent option service contract. If the operation code is `"TWRYO_STIAM"` (call fee limit notification), it adjusts the call fee amount (divides by 1000). Otherwise, it formats the service start date and, for the confirmation screen with restore/reserve-cancel divisions, formats the service end date.
   - **If sub-option number exists:** Copies from the sub-option service contract and similarly formats dates.

6. **For restore or reserve-cancel operations** (`kaihk` or `rsv_cl` divisions), calls `checkOtokuChkResult()` to perform discount check processing and sets an informational message.

### `actionUpdCfm()` -> `boolean`

**Update confirmation button handler.** Displays the update confirmation screen. Returns `true` on success, `false` on error.

The behavior branches on `tranDiv`:

- **If `tranDiv` equals `"変更"` (change):**
  1. Retrieves the phone usage fee amount from the tel op service bean, multiplies by 1000 (the screen displays in thousands of yen but the service expects raw value).
  2. Invokes `kksv0516Execute()` to call the telephone option service contract update information update service.
  3. Sets the next screen to `KKW02520` (update confirmation).
  4. Displays an informational message: "Telephone Option Service Contract Information Update."

- **If `tranDiv` equals `"解約"` (dissolve):**
  1. Constructs the `useEndYmd` from year/month/day fields.
  2. Invokes `kksv0370Execute()` to call the telephone option service contract update-dissolve service.
  3. Sets the next screen to `KKW02520`.
  4. **Checks for dependent sub-option services** that may still be active. If the parent option is being dissolved and child options are in status `100` (settlement complete), `030` (suspended/broken), or `210` (in progress), error messages are displayed for:
     - Operation code `"0160"`: "ISDN telephone / Dissolve / ISDN telephone selection"
     - Operation code `"0180"`: "Sender number display / Dissolve / Non-delivery notification delivery refusal"
  5. **Checks bundled service dependencies:**
     - For Sender Number Display (`"B025"`): verifies via `isDlsCheckHsnshNoDsp()` that no dependent Anshin Fakucho service is still active.
     - For Anshin Fakucho (`"B135"`): verifies via `isDlsCheckAnsHcs()` that the dissolution date is not before the Sender Number Display's end date.
  6. **Checks future packs** — iterates through pack composition options to see if any component has a service start/end date after the operating date, displaying the "EKBE130-KW" warning if so.
  7. **Displays discount check errors** — if `otoku_chk_err_flg` is `"1"`, determines the appropriate pack name (e.g., "eo Hikari Telephone Pack 3", "eo Hikari Telephone Pack 7", "Anshin Telephone Pack", or "Apply each product separately") and displays "EKBE131-KW".
  8. Displays an informational message: "Telephone Option Service Contract Dissolution."

### `kksv0370Execute(X31SDataBeanAccess svcFormBean, String funcCd)` -> `boolean`

Calls the **telephone option service contract update-dissolve service** (KKSV0370).

- Sets the progress-specific text field with the service name plus `"情報"` + `"解約"`.
- Invokes the KKSV0370 service using `KKSV0370_KKSV0370OPDBMapper`, mapping:
  - Option service contract dissolution CC
  - Service ODa (order/dispatch) CC
  - ODa condition list (func_cd_2)
- Checks for errors via `setErrorMessageInfo()` (for ODa condition errors).
- Reads back the return message ID; if non-empty, displays it as an error and returns `false`.

### `kksv0371Execute(X31SDataBeanAccess svcFormBean, String funcCd)` -> `boolean`

Calls the **telephone option service contract update reservation cancel service** (KKSV0371).

- Invokes the KKSV0371 service using `KKSV0371_KKSV0371OPDBMapper`, mapping:
  - Option service contract reservation cancel CC
  - Application screen input support work information update CC
  - Service ODa CC
- No output mapping — the service is called and the result is implicitly handled.

### `kksv0372Execute(X31SDataBeanAccess svcFormBean, String funcCd)` -> `boolean`

Calls the **telephone option service contract update restore service** (KKSV0372).

- Sets the progress-specific text field with the service name plus `"情報"` + `"回復"`.
- Invokes the KKSV0372 service using `KKSV0372_KKSV0372OPDBMapper`, mapping:
  - Option service contract restore CC
  - Service ODa CC
  - Machine provision service contract list (service contract number)
- Reads back the return message ID; if non-empty, displays it as an error and returns `false`.

### `kksv0516Execute(X31SDataBeanAccess svcFormBean, String funcCd)` -> `boolean`

Calls the **telephone option service contract update information update service** (KKSV0516).

- Sets the progress-specific text field with the service name plus `"情報"` + `"変更"`.
- Invokes the KKSV0516 service using `KKSV0516_KKSV0516OPDBMapper`, mapping:
  - Application content approval registration
  - Application detail inquiry / follow-up work request
  - Option service contract (telephone) information change
  - eo Hikari Telephone call over-limit notification code change
  - Progress information registration
  - Application screen input support work information update CC

### `actionBack()` -> `boolean`

**Back button handler.** Sets the next screen ID to the previous screen ID (retrieved via `JCCWebCommon.getScreenId()`). Returns `true`.

### `actionFix()` -> `boolean`

**Fix/Confirm button handler.** The most complex action method — it finalizes the update based on the operation division (`tranDiv`).

- Sets the next screen to `KKW02521` (update completion screen).
- Branches on `tranDiv`:
  - **`"変更"` (change):** Invokes `kksv0516Execute()` (func_cd_1) to apply the update. Displays informational message "Telephone Option Service Contract Information Update."
  - **`"解約"` (dissolve):** Invokes `kksv0370Execute()` (func_cd_1) to dissolve. Displays message "Telephone Option Service Contract Dissolution."
  - **`"回復"` (restore):**
    1. **Anshin Fakucho restore check** (`isKaifukuCheckAnsHcs()`): Ensures no active Sender Number Display contracts block the restore.
    2. **Multi-function Luma check:** If the field `TAKINORT_KEI_UM` is blank/null, displays an error about Multi-function Luma / HWA not being registered.
    3. Invokes `kksv0372Execute()` (func_cd_1) to restore. Displays message "Telephone Option Service Contract Restoration."
  - **`"rsv_cl"` (reserve cancel):**
    1. **Sender Number Display reservation cancel check** (`isRsvClCheckHsnshNoDsp()`): Validates that no active Anshin Fakucho service blocks the cancel.
    2. **Anshin Fakucho reservation cancel check** (`isRsvClCheckAnsHcs()`): Validates that the Sender Number Display is not in "dissolution reservation" state.
    3. Invokes `kksv0371Execute()` (func_cd_1) to cancel reservation. Displays message "Telephone Option Service Contract Reservation Cancel."

### `actionShusei()` -> `boolean`

**Correction button handler.** Returns to the update screen (`KKW02519`). Returns `true`.

### `actionFin()` -> `boolean`

**Completion button handler.** Sets the next screen ID to the previous screen (via `JCCWebCommon.getScreenId()`). Returns `true`.

### `getSessionData(X31SDataBeanAccess svcFormBean)` -> `boolean`

Retrieves inherited information from the previous screen and populates the service form bean.

- Reads screen info via `JCCWebCommon.getScreenInfo()`.
- Copies from the customer info history bean:
  - SYSID, Service contract number, Service contract details number
  - Option service contract number, Sub-option service contract number
  - Anomaly division, Operation division (`tranDiv` — critical: this field determines all subsequent behavior)
  - Application number
- Copies anomaly reason codes and memo from the previous screen's anomaly list.
- Handles telephone number ordering to set tab operation information control codes.

### `getPrgTkjkSvcNm(X31SDataBeanAccess svcFormBean)` -> `String`

Returns the service name for progress tracking. If a sub-option contract number exists, returns the sub-option service name; otherwise returns the option service name. Used by `kksv0370Execute`, `kksv0372Execute`, and `kksv0516Execute` to populate the progress-specific text field.

### `checkOtokuChnkResult(X31SDataBeanAccess[] paramBean, HashMap<String, Object> outputMap)` -> `void`

Performs discount (otoku) check error processing. Called during initialization for restore and reserve-cancel operations.

1. Calls the mapper to get the KKSV036917CC (option pack config) output.
2. Reads the `otoku_chk_err_flg` and `otoku_chk_wrib_svc_cd` from the bean.
3. If the error flag is `"1"`, determines the pack name based on service code:
   - `"W00000007"`: "eo Hikan Telephone Pack 3"
   - `"W00000008"`: "eo Hikan Telephone Pack 7"
   - `"W00000023"`: "Anshin Telephone Pack"
   - Otherwise: "Apply each product separately"
4. Displays the "EKBE131-KW" warning message with the determined pack name.

### `setErrorMessageInfo(HashMap<String, Object> outputMap)` -> `boolean`

Checks for error conditions in the service output. Returns `true` if an error exists (caller should abort).

- Checks if `chk_kbn` in the KKSV037001SC output equals `"1"` (error condition).
- If so, displays the "EKBE020-KW" warning message and returns `true`.

### Dependency Validation Methods

These five methods validate whether dependent bundled services can be safely dissolved, restored, or reserved-cancelled in concert with the primary option service.

| Method | Purpose |
|--------|---------|
| `isRsvClCheckHsnshNoDsp(X31SDataBeanAccessArray, String state)` | Checks if Sender Number Display (`"B025"`) can be reservation-cancelled. Returns `false` if there is an active Anshin Fakucho service (status not `910`/`920`) when the state is `"030"` (suspended). |
| `isRsvClCheckAnsHcs(X31SDataBeanAccessArray, String stat)` | Checks if Anshin Fakucho (`"B135"`) can be reservation-cancelled. Returns `false` if Sender Number Display has a dissolution reservation. Only applies when stat is `"100"` (settlement complete). |
| `isDlsCheckHsnshNoDsp(X31SDataBeanAccessArray, String useEndYmd)` | Checks if Sender Number Display (`"B025"`) can be dissolved. Returns `false` if there is an active Anshin Fakucho service with a dissolution reservation date on or after the given end date. |
| `isDlsCheckAnsHcs(X31SDataBeanAccessArray, String useEndYmd)` | Checks if Anshin Fakucho (`"B135"`) can be dissolved. Returns `true` immediately if the end date is on or before the current operating date. Otherwise checks for Sender Number Display dependencies with pending dissolution reservations past the end date. |
| `isKaifukuCheckAnsHcs(X31SDataBeanAccessArray)` | Checks if Anshin Fakucho can be restored. Returns `false` if there are active Sender Number Display contracts that are settled (status `"030"`) with a start reservation, or have a dissolution reservation. |

**Status code reference used across these methods:**
- `"910"`: Settlement complete (解散済み)
- `"920"`: Dissolution complete (解約済み)
- `"030"`: Suspended/Broken (停止・中断中)
- `"100"`: Settlement complete (集金済)

## Relationships

```mermaid
flowchart TD
    PJP1["WEBGAMEN_KKW025190PJP"]
    PJP2["WEBGAMEN_KKW025200PJP"]
    PJP3["WEBGAMEN_KKW025210PJP"]
    XML1["x31business_logic_KKW02519SF"]
    LOGIC["KKW02519SFLogic"]
    BASE["JCCWebBusinessLogic"]
    PJP1 --> LOGIC
    PJP2 --> LOGIC
    PJP3 --> LOGIC
    XML1 --> LOGIC
    LOGIC --> BASE
```

**Inbound (4 dependents):**

| Dependent | Type | Relationship |
|-----------|------|-------------|
| `WEBGAMEN_KKW025190PJP.xml` | JSP Page | References this class for screen 1 (update screen) |
| `WEBGAMEN_KKW025200PJP.xml` | JSP Page | References this class for screen 2 (update confirmation) |
| `WEBGAMEN_KKW025210PJP.xml` | JSP Page | References this class for screen 3 (update completion) |
| `x31business_logic_KKW02519SF.xml` | Business Logic XML | Delegates business logic to this class |

**Outbound:**

| Dependency | Relationship |
|------------|-------------|
| `JCCWebBusinessLogic` | Parent class — provides base infrastructure for DataBean access, service invocation, and screen navigation |

## Usage Example

The typical usage pattern for this class follows a multi-screen wizard flow:

1. **Operator navigates from a previous screen** (e.g., service contract detail screen) to the update screen (`KKW02519`). The previous screen places data (contract numbers, operation division) into the customer info history bean.

2. **`actionInit()`** is invoked. It calls `getSessionData()` to pull the inherited data, then calls `actionInitUpdTran()` which:
   - Invokes the KKSV0369 service to fetch all current contract data.
   - Maps the results into the form bean.
   - Initializes the telephone option service contract information based on the operation division (`tranDiv`).

3. **Operator views the update screen** (`KKW02519`) and makes changes (e.g., modifying the call fee limit, setting a dissolution date).

4. **Operator clicks "Update Confirmation" (`actionUpdCfm()`)**. Depending on `tranDiv`:
   - For **change**: Multiplies the fee by 1000 and calls `kksv0516Execute()` to validate the update.
   - For **dissolve**: Calls `kksv0370Execute()` to dissolve, then performs dependent service checks.

5. **On the confirmation screen**, the operator clicks "Fix" (`actionFix()`). This:
   - Sets the next screen to the completion screen (`KKW02521`).
   - Performs the actual service invocation based on `tranDiv` (change/dissolve/restore/reserve-cancel).
   - Before any irreversible action, runs the five dependency-check methods to ensure no bundled services are blocked.

6. **The completion screen** (`KKW02521`) displays the result. The operator clicks "Fix" or "Correction" to navigate further.

## Notes for Developers

- **`tranDiv` is the critical state variable.** This single string field determines every code path taken through the class. It is set by `getSessionData()` from the previous screen's `TRAN_DIV_02` field. Ensure the upstream screen always sets this correctly.

- **The class is not thread-safe.** It holds mutable instance state (`tranDiv`) and operates within a single HTTP request's scope, which is typical for this framework.

- **Screen IDs follow a consistent numbering scheme:**
  - `KKW02519` = Update screen
  - `KKW02520` = Update confirmation screen
  - `KKW02521` = Update completion screen

- **The fee amount transformation (`* 1000`)** is a known convention: the UI displays amounts in units of 1,000 yen (e.g., entering "10" means 10,000 yen), but the backend service expects the raw value. This is handled in `actionUpdCfm()` (for change) but not in `actionInitUpdTran()` (where the initial value is divided by 1000 for display).

- **Status codes `"910"` and `"920"`** represent "settlement complete" and "dissolution complete" respectively — both are considered "terminal" states that allow the parent operation to proceed. The code uses `||` (or) logic: `!("910".equals(...) || "920".equals(...))` means "still active if neither terminal status matches."

- **Discount check (`otoku_chk_err_flg`)** is set by the KKSV036917CC operation pack config service. If set to `"1"`, the system warns the user that they may lose a discount if they proceed. The specific pack name varies by service code (`W00000007`, `W00000008`, `W00000023`, or default).

- **The class uses `invokeService()`** inherited from `JCCWebBusinessLogic` to call backend services. This is the primary mechanism for remote service invocation, using the `paramMap`/`inputMap`/`outputMap` pattern.

- **The `checkOtokuChnkResult()`** method has a typo in its name (missing `k` in "Result"). This is a pre-existing issue in the source code.

- **Multiple mapper objects** are created per service call (`KKSV0369_...`, `KKSV0370_...`, etc.). Each mapper handles the DataBean-to-service-parameter mapping for a specific service. These mapper classes are not part of this documentation but should be consulted for the exact field mappings.

- **Error messages** are displayed via `JCCWebCommon.setMessageInfo()`. The message IDs (e.g., `EKB0370__I`, `EKB1760__I`, `EKBE130_KW`) reference a message property file that is outside this class's scope.

- **The five dependency check methods** (`isRsvClCheckHsnshNoDsp`, `isRsvClCheckAnsHcs`, `isDlsCheckHsnshNoDsp`, `isDlsCheckAnsHcs`, `isKaifukuCheckAnsHcs`) implement business rules specific to NTT East's bundled service architecture. These encode the rule that Sender Number Display (`B025`) and Anshin Fakucho (`B135`) are often bundled together, and operations on one must validate the state of the other. Changes to these methods should be carefully tested as they prevent data integrity issues.
