# KKW05602SFLogic

## Purpose

`KKW05602SFLogic` is the central business logic controller for the **Toki Registration** (トウキ登録) screen in the K-Opticom Contract Management System. "Toki" (トウキ) refers to number portability activation settings — the process of registering when a customer's phone number porting, cancellation, or suspension should take effect. This class orchestrates the full lifecycle of toki registration: initial screen display, data loading from the database, update confirmation, deletion confirmation, and final fix/commit — while also handling address-change migrations and dual-port (port-in/port-out) scenarios.

## Design

`KKW05602SFLogic` follows the **page-controller / action-class pattern** typical of this codebase's web architecture. It extends `JCCWebBusinessLogic`, which provides a shared framework for accessing screen beans, invoking services, and managing transfer state. Each public `action*` method maps to a screen button press (e.g., "Update", "Delete", "Fix", "Finish"), orchestrating data retrieval, validation, business rule enforcement, and navigation to the next screen.

The class acts as a **facade over two primary service invocations** (`KKSV0170` for initial data loading and `KKSV0171` for toki registration commits), using mapper objects to set up and tear down data bean mappings. It also serves as the single point of enforcement for complex business rules around portability status, service contract states, and address-change constraints.

## Key Methods

### Lifecycle Actions

#### `actionInit() → boolean`
Entry point when the user navigates to the toki registration screen. Retrieves the next screen ID from the common form bean and delegates to `actionTokiUpdInit(1)` if the screen ID is `KKW05602`. This is the standard initialization path.

#### `actionChgTokiAdd() → boolean`
Handles the "Toki Registration Category Change" button. Delegates to `actionTokiUpdInit(2)` with mode `2`, indicating the user is changing the toki registration category rather than performing a fresh initialization.

#### `actionTokiUpdInit(int mode) → boolean`
The most important method — handles full initialization of the toki update/delete screen. Mode `1` = from initial screen, mode `2` = from category change.

Steps:
1. Retrieves the service form bean and customer contract inheritance bean.
2. Sets the operation date, SYSID, service contract number, and deviation category from the inheritance bean.
3. Invokes `KKSV0170` mapper (19 service calls including customer inquiry, service contract details, phone number reservation lists, code name lookups, deviation reservations, address change details, and work data) to load all display data.
4. Runs `initDispCheck()` to validate the service contract status — only "service in progress" (`100`) or "contract canceled" (`910`) statuses allow navigation. Additionally, pause/interruption status `210` with specific pause codes is acceptable.
5. If the deviation category is `00046` (光電話・移転トウキ設定 — optical phone/relocation toki setup), runs `initAddressChangeCheck()` which validates that the project status is complete or registered.
6. Calls `setTokiInfoFromDB()` to populate the form bean with toki data (phone number, toki type, dates, contact number).
7. Builds the reserved phone number pull-down list via `setRsvTelNoPullDownList()`.

#### `actionUpd() → boolean`
Handles the "Update Confirm" button press. Sets `UPD_CANCEL_FLG` to `UPD_CANCEL_FLG_UPD` ("1"). Validates data with `kanrenCheck1()` (checks if toki has already ended) and `kanrenCheck2()` (checks if toki is in-progress and contact phone was changed — prevents inconsistent edits after activation). Sets the `UPD_RLS_JUDGE_FL` to `UPD_FL` and branches based on deviation category: if it's address change (`00019`), calls `actionCfmIdoKbn00019()`; otherwise calls `actionCfmOtherIdoKbn()`.

#### `actionRls() → boolean`
Handles the "Delete Confirm" button press. Sets `UPD_CANCEL_FLG` to `UPD_CANCEL_FLG_CANCEL` ("2"). Similar data flow to `actionUpd()` but loads data from the database for pre-edit values and sets `UPD_RLS_JUDGE_FL` to `RLS_FL`. Delegates to `actionCfmOtherIdoKbn(bean, ..., "2", ...)` with delete flag.

#### `actionFix() → boolean`
The final commit/fix action. Invokes `KKSV0171` service with `FUNC_CODE_1` (check and register mode) via `invokeServiceKKSV0171()`. Then performs a phone number status check (`initTelnoStatCheckActionCfm`) — only runs for updates, not deletes. If the status check fails, it returns true (continues anyway — the error is noted but not blocking). Sets next screen to `KKW05606` (fix completion screen).

#### `actionBack() → boolean`
Returns to the previous screen by setting the common form bean's next screen ID to the current screen ID.

#### `actionFin() → boolean`
Handles the "Finish" button. Sets the next screen to `KKW00130` (likely a master screen). Simple termination.

#### `actionOpenKKW05607() → boolean`
Opens a popup/sub-screen (KKW05607) for contact phone number entry. Passes the `rrksTelNo` (registered contact number) to the child screen via screen info and sets up the next screen navigation.

#### `actionRetKKW05607() → boolean`
Handles return from the KKW05607 sub-screen. Reads the result flag from screen info. If the sub-screen returned true, copies the confirmed contact phone number back. Sets next screen back to `KKW05602`.

#### `actionShusei() → boolean`
Handles the "Edit" button on the confirmation screen. If coming from a delete (`RLS_FL`), re-loads the original database values for toki request, start/end dates, and contact number. Otherwise, re-reads the user's current selections. Sets the next screen back to the original `KKW05602`.

### Core Business Logic Methods

#### `setTokiInfoFromDB(X31SDataBeanAccess bean, X31SDataBeanAccess custKeiHktgiBean, X31SDataBeanAccess svcUtwkEoTelBean, int mode) → void`
The central data-population method. Reads toki information from the database beans and populates the form bean for display. It determines the toki registration condition (`TOKI_ADD_OPAF`, `TOKI_ADD_DSL`, or `TOKI_ADD_BOTH`) and selectively extracts fields depending on whether it's a "transfer destination registration" or "transfer source cancellation / pause" toki type. Sets the following on the bean:
- Target phone number (`TOKI_TG_TELNO`)
- Toki request flag (`ITNTOKI_KIBO_UM`, `TOKI_KIBO_DSP`)
- Toki type code and display text
- Toki end reservation date (split to year/month/day)
- Toki start reservation date
- Transfer source phone number (`ITENM_TELNO`)
- Contact phone number (`RRKS_TELNO`)
- Reserved phone number display
- Toki content description (`TOKI_NAIYO`)
- Hidden fields via `setTokiHdn()`

#### `setTokiHdn(X31SDataBeanAccess bean, X31SDataBeanAccess svcUtwkEoTelBean) → void`
Populates hidden form fields with toki information for both "transfer source" (MT) and "transfer destination" (SK) sides, enabling the category-change pull-down to work correctly when users switch between toki types on the same screen.

#### `setCustKeiHktgiBean(X31SDataBeanAccess bean, String tokiAddCd, String tokiSbtCd, String tokiKibo, String tokiStaRsvYmd, String tokiEndRsvYmd, String itenMotoTelNo, String rrksTelNo, String rsvTelNo) → void`
Sets the customer contract inheritance bean with the selected toki parameters for the service invocation. Includes submission type code, operation date stamp, and approval status.

#### `actionCfmOtherIdoKbn(...) → void`
Handles the confirmation flow for deviation categories other than address change (00019). Populates the confirmation data bean with:
- Toki registration code, toki type code, toki request flag
- Start/end reservation dates
- Contact phone number
- Transfer source phone number

If the update flag is "1" (update), it handles special logic: if the toki registration is "transfer destination" (`ITENSAKI_ADD_TOKI`) and the transfer source service contract hasn't started yet, it automatically sets the toki start date to today if the destination service is "active" (status `100`). For cancel/pause types, if the service is "canceled" (910) or "paused" (210), it also sets the start date to today.

#### `kanrenCheck1(String selectedTokiAddCd, X31SDataBeanAccess svcUtwkEoTelBean) → boolean`
Validation check 1: returns `false` if the selected toki has already ended (i.e., `itenTokiEndYmd` is not empty). Prevents editing of completed toki registrations.

#### `kanrenCheck2(String selectedTokiAddCd, X31SDataBeanAccess bean, X31SDataBeanAccess svcUtwkEoTelBean) → boolean`
Validation check 2: prevents changing the contact phone number after toki has started (except for "transfer destination" toki). If toki is in progress and the user has modified the contact number differently from the original, returns `false` to block the update. This was added for bug OM-2014-0002513.

#### `actionCfmIdoKbn00019() → void`
Special confirmation handler for deviation category `00019` (address change / registration). Similar to `actionCfmOtherIdoKbn` but with address-change-specific data handling.

### Utility / Helper Methods

#### `isInitDispOk(String svcKeiUcwStatus, String pauseStpCd) → Boolean`
Determines if screen navigation is allowed based on service contract status. Returns `true` for statuses `100` (service in progress) or `910` (contract canceled), or for `210` (pause/interruption) with pause codes `00` or `01`.

#### `initAddressChangeCheck(...) → boolean` / `isInitAddressChangeCheckOk(...) → Boolean`
Validates address-change-specific conditions. For address change status `001`, allows navigation only if project status is `200` (work complete) or project is registered (`120`) with management project complete (`200`). Otherwise redirects to address change registration screen.

#### `getTokiAddCondtion(X31SDataBeanAccess bean) → String`
Returns the toki registration condition: `1` (cancel/pause toki only), `2` (transfer destination toki only), or `3` (both registered).

#### `getTokiNaiyo(X31SDataBeanAccess bean, String tokiSbtCd) → String`
Returns the human-readable toki content description based on the toki type code — number change notice, pause notice, or pause + contact notice.

#### `getRRSKTelNo(X31SDataBeanAccess bean, String tokiAddCd, String tokiTensoSkTelno, String tokiTensoSkSvkuwno) → String`
Returns the contact phone number. If toki is "transfer destination registration", it looks up the phone number from the transfer destination service contract number via `findTensoSkTelno()`. Otherwise returns the direct transfer destination phone number.

#### `initTelnoStatCheckActionCfm(X31SDataBeanAccess[] paramBean) → boolean` / `isInitTelnoStatCheck(String portOutStatUm) → Boolean`
Phone number status validation added for dual-port (番ポ) support (ANK-4494-00-00). Checks whether the phone number has port-out status or data search errors, and blocks navigation if so. The newer logic (STEP2) checks `TELNO_SEARCH_ERRFLG` and `PORTOUTSTATUM_ARI` instead of the original null/empty-based approach.

#### `setRsvTelNoPullDownList(X31SDataBeanAccess[] paramBean, X31SDataBeanAccess hktgKoumokuBean, String idoDiv, KKSV0170_KKSV0170OPDBMapper mapper, String tokiTgTelno) → void`
Builds the reserved phone number pull-down list. For address change deviations, pulls numbers from inheritance info. For other deviations, uses the mapper's appropriate list method based on toki type and optionally adds the transfer destination phone number.

#### `invokeServiceKKSV0171(X31SDataBeanAccess[] paramBean, String func_cd) → void`
Invokes the `KKSV0171` service for toki registration / toki update transfer toki setup. Sets up mapping for customer inquiry, service contract, content approval, service contract info change, application detail check, progress registration, SODCC, and (NEW in STEP2) phone number status judgment and phone number update.

#### `getCodeValue(String code, X31SDataBeanAccess bean, String listId) → String` / `getValueFromCd(String targetCd, String listId, X31SDataBeanAccess bean) → String` / `getValueFromCd2(String targetCd, String listId, X31SDataBeanAccess bean) → String`
Look up human-readable display values from code name management data beans. These iterate over list entries to find a matching code and return its label.

#### `getYmdData(X31SDataBeanAccess bean, String srcYmd, String yearPos, String monPos, String dayPos) → void`
Splits an 8-digit date string (YYYYMMDD) into year, month, and day components on the bean. Initializes to empty strings if the source is null, not 8 digits, or the year value exceeds `20991231`.

#### `isKyushiRev(X31SDataBeanAccess bean) → boolean`
Checks if there is a pending pause reservation by comparing the service pause start date against the operation date.

#### `getTikanStr(X31SDataBeanAccess bean) → String`
Generates the start timing message string for toki registration completion. This method maps various combinations of deviation categories and service statuses to human-readable messages like "Number in progress", "Registration complete", "Contract cancellation", or "Pause implementation".

## Relationships

```mermaid
flowchart TD
    Client["Web Client"] --> KKW05602["KKW05602SFLogic"]

    subgraph Screens
        Screen1["KKW05602<br>Toki Update Screen"]
        Screen2["KKW05604<br>Toki Confirm Screen"]
        Screen3["KKW05606<br>Toki Fix/Complete Screen"]
        Screen4["KKW05607<br>Contact Tel Input"]
    end

    Screen1 --> KKW05602
    KKW05602 --> Screen2
    Screen2 --> Screen3
    KKW05602 --> Screen4
    Screen4 --> KKW05602

    KKW05602 --> Mapper1["KKSV0170 Mapper"]
    KKW05602 --> Mapper2["KKSV0171 Mapper"]
    KKW05602 --> Mapper3["KKSV0390 Mapper"]

    subgraph Services
        Mapper1 --> SV170["SV0170 Service<br>Customer/Contract Lookups"]
        Mapper2 --> SV171["SV0171 Service<br>Toki Registration"]
    end

    KKW05602 --> JCCWeb["JCCWebBusinessLogic"]
```

### Inbound Connections (4 classes depend on this)

| Class | Relationship |
|-------|-------------|
| `WEBGAMEN_KKW056020PJP.xml` | Primary JSP page delegate — calls `actionInit`, `actionUpd`, `actionRls`, `actionShusei`, `actionFix`, `actionBack`, `actionFin` |
| `WEBGAMEN_KKW056040PJP.xml` | Confirmation screen page — references `KKW05602SFLogic` for data display after update/delete confirmation |
| `WEBGAMEN_KKW056060PJP.xml` | Fix completion screen page — references `KKW05602SFLogic` for post-fix display |
| `x31business_logic_KKW05602SF.xml` | Business logic configuration XML — registers and configures this class |

### Outbound Dependencies

| Dependency | Type | Purpose |
|------------|------|---------|
| `JCCWebBusinessLogic` | Superclass | Provides shared framework for bean access, service invocation, and screen management |
| `KKSV0170_KKSV0170OPDBMapper` | Instance | Initial data loading (customer, contract, phone numbers, codes, address change info) |
| `KKSV0171_KKSV0171OPDBMapper` | Instance | Toki registration commit (content approval, progress registration, phone number update) |
| `KKSV0390_KKSV0390OPDBMapper` | Instance (commented) | Was used for pre-screen data acquisition |
| `KKSV0391_KKSV0171OPDBMapper` | Instance (commented) | Was used for toki registration |

## Usage Example

A typical request flow for editing a toki registration:

1. User navigates to screen `KKW05602` — the JSP delegates to `actionInit()`.
2. `actionInit()` calls `actionTokiUpdInit(1)`, which invokes the `KKSV0170` service to load all customer data, contract status, phone numbers, code lists, and address change information.
3. Business rules validate the service contract status (`isInitDispOk`) and, if applicable, the address change project status (`isInitAddressChangeCheckOk`).
4. `setTokiInfoFromDB()` populates the form with the current toki data — phone number, toki type, reservation dates, contact number.
5. The user modifies the toki type, dates, or contact number, then presses "Update Confirm."
6. `actionUpd()` validates that the toki hasn't already ended (`kanrenCheck1`), that the contact number hasn't been inconsistently modified during an active toki (`kanrenCheck2`), then delegates to `actionCfmOtherIdoKbn()` to set up the confirmation screen (`KKW05604`).
7. On the confirmation screen, the user presses "Fix" — `actionFix()` invokes `KKSV0171` to register the changes, performs phone number status validation, and navigates to the fix completion screen (`KKW05606`).

```
KKW05602 (Init) → actionTokiUpdInit() → KKSV0170 → Display Screen
    → actionUpd() → kanrenCheck1/2 → actionCfmOtherIdoKbn() → KKW05604 (Confirm)
        → actionFix() → KKSV0171 (register) → KKW05606 (Fix Complete)
        → actionShusei() → KKW05602 (Back to Edit)
    → actionRls() → similar to actionUpd but for delete
    → actionBack() → Previous Screen
    → actionFin() → KKW00130 (End)
```

## Notes for Developers

- **Thread safety**: The class has instance state (`TELNO_SEARCH_ERRFLG`) used to carry error flags across method calls within a single request. This is fine for the request-per-thread model but should not be shared across requests.

- **Screen navigation**: This class manages a multi-step workflow across screens `KKW05602` → `KKW05604` → `KKW05606`, with detours to `KKW05607` for contact phone input. Each transition sets the `NEXT_SCREEN_ID` on the common form bean.

- **Date handling**: Dates are stored as 8-digit strings (YYYYMMDD) and split into year/month/day components for individual form fields. The `getYmdData()` method rejects dates >= `20991231` and initializes to empty strings.

- **Toki registration conditions**: The three states (`1` = cancel/pause only, `2` = transfer destination only, `3` = both) determine which database fields are read and which hidden fields are populated. The `getTokiAddCondtion()` method inspects both the transfer source and transfer destination toki registration codes to determine this.

- **Port-out / dual-port support**: The `ANK-4494-00-00` changes added phone number status checking (port-out status, data search errors) that gates navigation. The STEP2 implementation (`isInitTelnoStatCheck`) uses `TELNO_SEARCH_ERRFLG` and `PORTOUTSTATUM_ARI` instead of the original null-based logic.

- **Service invocation pattern**: The class uses the `invokeService(paramMap, inputMap, outputMap)` pattern from the parent class, with `set*SC()` and `get*SC()` methods on mapper objects to map data beans to/from the service parameters. The `invokeServiceKKSV0171()` method is a specialized wrapper for the toki registration service.

- **Validation guards**: Two `kanrenCheck` methods enforce business rules that can't be expressed in the database: `kanrenCheck1` prevents editing ended toki, and `kanrenCheck2` prevents changing contact numbers after toki activation.

- **Address change special handling**: When the deviation category is `00019` (address change/registration), the class takes special paths in both initialization (`initAddressChangeCheck`) and confirmation (`actionCfmIdoKbn00019`), requiring project status to reach a completion milestone.

- **The `actionFix()` final validation**: Even after successful `KKSV0171` registration, `actionFix()` performs a phone number status check. If it fails, it returns `true` (continues to the next screen) rather than blocking — the error is merely noted for the completion screen display via `getTikanStr()`.