# KKW02501SFLogic

## Purpose

`KKW02501SFLogic` is the central business-logic class for the **E-Mail Information Update** screen in the JP Online (JP Online is a Japanese internet service provider) customer self-service web application. It handles four distinct operations on a customer's email account: **update** (change address, capacity, alias, or virus check settings), **dismantle** (cancel the email service), **reactivate** (restore a cancelled email service), and **cancel reservation** (cancel a pending service reservation). This class serves as the orchestrator that gathers input from the UI, calls backend services, maps results back to the screen, and routes the user to the appropriate next screen or error message.

## Design

This class follows the **front-controller / action-handler pattern** common to web frameworks built on top of JCC (the underlying application server framework). It extends `JCCWebBusinessLogic`, which provides base infrastructure for screen state management, service invocation, and data bean access.

Each user action on the screen maps to a public `actionXxx()` method (e.g., `actionInit()`, `actionUpdCfm()`, `actionFix()`). These methods:

1. Extract data from the screen's `X31SDataBeanAccess` (the form-backed data transfer object).
2. Prepare input parameters into a `HashMap<String, Object>` input map.
3. Call one or more backend services via the private `doService()` wrapper, which invokes the service through `invokeService()`.
4. Map the service output back into the data bean using dedicated mapper instances (e.g., `KKSV0427_KKSV0427OPDBMapper`).
5. Set the next-screen destination via the common info bean and display any confirmation or error messages.

The class also manages **state flags** that track which fields have changed (email address, alias, mailbox capacity, virus check) to determine what sub-service items to register for the operations sub-service contract system.

## Key Methods

### Screen lifecycle actions

#### `actionInit() → boolean`

The entry point when the screen first loads. It performs three major tasks:

- **Maps customer contract data** from the preceding screen's context (`setHktgiBean()`) — SYSID, service contract number, operation sub-service number, transmission division (`trans_div`), and movement reason codes.
- **Calls the initialization service** `KKSV0427 / KKSV0427OP` to fetch the current email account settings (address, alias, mailbox capacity, virus check status, subscription service details).
- **Maps the service response** into the screen data bean (`storeDataBeanInitsrv()`), sets up the mailbox capacity pull-down options, parses email addresses into account and domain parts, and initializes virus check and charge flags.

After initialization, it checks the `trans_div` (processing division) to determine which operation mode the screen is in — update, dismantle, reactivate, or cancel reservation — and validates that the current service contract state allows the requested operation. If the state is incompatible, it disables the update/restore button and displays an appropriate error message.

**Parameters:** None (uses screen state from base class).
**Returns:** `true` for normal completion.
**Side effects:** Populates the screen data bean with all current email settings, sets up pull-down lists for mailbox capacity and virus check, and configures the next-screen destination.

#### `actionUpdCfm() → boolean`

Handles the **Update Confirm** button press. This is the review step where the user sees their changes before final submission.

- Determines the operation type from `trans_div` and calls the appropriate input setup method (`setDslsrv()` for dismantle, `setChgesrv()` for update).
- For update operations, adds validation that **mailbox capacity cannot be decreased** (a business rule enforced via message `EKK0290_JW`).
- For update operations, also checks for virus check error flags and family plan restrictions.
- Calls `KKSV0429 / KKSV0429OP` for dismantle or `KKSV0428 / KKSV0428OP` for update.
- Maps results back and checks for any `RTN_MSG_ID` returned from the service. If empty, proceeds to the confirmation screen (KKW02502). If a return message ID exists, displays the corresponding error/warning message and stays on this screen.
- After a successful update, checks if the email address was changed and displays a specific message about alias cancellation if the account was in "accepted" or "under review" status.

**Parameters:** None.
**Returns:** `true` on success, `false` if validation fails (e.g., capacity decrease attempt).
**Side effects:** Invokes backend services, sets next-screen to KKW02502 (update confirmation screen).

#### `actionFix() → boolean`

Handles the **Confirm** button press on the confirmation screen. This commits the changes to the backend.

The flow mirrors `actionUpdCfm()` but with a crucial difference: it passes `FUNC_CD_1` (confirm execution) instead of `FUNC_CD_2` (confirmation display) to the input setup methods. This tells the mappers to include actual change data rather than just review data.

- For dismantle: calls `setDslsrv()`, then `KKSV0429 / KKSV0429OP`, then maps results, then calls `exeAxmRenkei()` for AxM (account management) integration.
- For update: calls `setChgesrv()`, then `KKSV0428 / KKSV0428OP`, then maps results.
- For reactivate: calls `setKaihksrv()`, then `KKSV0430 / KKSV0430OP`, then maps results, then calls `exeAxmRenkei()`.
- For cancel reservation: calls `setRsvclsrv()`, then `KKSV0431 / KKSV0431OP`, then maps results.

After the service call, sets the next screen to **KKW02503** (completion/confirmation screen) and displays a message like "E-Mail Information Updated" or "E-Mail Information Cancelled".

**Parameters:** None.
**Returns:** `true` on success.
**Side effects:** Commits changes via backend services, triggers AxM integration for dismantle/reactivate operations.

#### `actionShusei() → boolean`

Handles the **Edit** button press on the confirmation screen. Returns the user to the edit screen (KKW02501) to make further changes. A simple navigation method that sets the next screen to `SCREEN_ID_KKW02501`.

#### `actionBack() → boolean`

Returns the user to the **calling screen** by reading the previous screen ID from the common info bean.

#### `actionFin() → boolean`

Ends the session and returns to the calling screen, same behavior as `actionBack()` but semantically indicates session completion.

#### `actionClear() → boolean`

Performs a **clear/reset** of the form. Clears input fields for email address, alias, and mailbox capacity pull-downs, then re-runs the initialization service (`KKSV0427`) to repopulate the screen with current data — effectively resetting user edits to the original values.

### Backend service orchestration

#### `doService(String usecase_id, String operation_id, HashMap<String, Object> inputMap, HashMap<String, Object> resultOutputMap) → X31CMessageResult`

A private wrapper around the framework's `invokeService()` method. Takes a usecase ID and operation ID (e.g., `"KKSV0427"`, `"KKSV0428"`, `"KKSV0429"`, `"KKSV0430"`, `"KKSV0431"`) and the input/output maps, sets them into a parameter map with standard telegram info keys, and invokes the backend service. Returns an `X31CMessageResult` object if an error occurred, or `null` on success.

**Parameters:**
- `usecase_id`: The service usecase identifier (e.g., `"KKSV0427"`).
- `operation_id`: The operation identifier (e.g., `"KKSV0427OP"`).
- `inputMap`: The input parameters for the service.
- `resultOutputMap`: The output map to receive service results.

**Returns:** `X31CMessageResult` — error details if the service returned an error, `null` otherwise.

### Data preparation for services (input mapping)

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

Copies customer contract data from the preceding screen's context bean into the current screen's data bean. This includes: operation date, SYSID, service contract number, transmission division (`trans_div`), movement division, movement reason codes and memo, operation sub-service contract number, submission number, and submission detail number. Called during `actionInit()`.

#### `setInitsrv(X31SDataBeanAccess[] paramBean, HashMap<String, Object> inputMap) → void`

Prepares input data for the initialization service (`KKSV0427`). Sets the operation date, operation date-time stamp, update permission flag, and return message ID. Then calls multiple mapper methods (`setKKSV042701SC` through `setKKSV042714SC`) to populate the input map with values from the data bean for each sub-service item (email address, alias, mailbox capacity, virus check, POP ID, etc.).

#### `setChgesrv(X31SDataBeanAccess[] paramBean, HashMap<String, Object> inputMap, String func_cd) → void`

Prepares input data for the **update service** (`KKSV0428`). When `func_cd` equals `FUNC_CD_2` (confirmation display), it also calls `setAgingTgList()` to create the aging target list, `setChgFlags()` to compute change state flags, `setSbopsvckeiList()` to build the subscription service contract list, and `setVirusSvcChrgStaymd()` to calculate virus check service charge end dates. Then calls the mapper methods (`KKSV0428_KKSV0428OPDBMapper`) to populate the input map.

#### `setDslsrv(X31SDataBeanAccess[] paramBean, HashMap<String, Object> inputMap, String func_cd) → void`

Prepares input data for the **dismantle service** (`KKSV0429`). Same structure as `setChgesrv()` — calls aging target list setup, subscription service contract list setup, and virus charge date setup when in confirmation mode, then maps to input via `KKSV0429_KKSV0429OPDBMapper`.

#### `setKaihksrv(X31SDataBeanAccess[] paramBean, HashMap<String, Object> inputMap, String func_cd) → void`

Prepares input data for the **reactivation service** (`KKSV0430`). Sets the reactivation date from the operation date, creates the aging target list, clears the return message ID, sets a progress note prefix ("E-Mail Information + Reactivation"), and maps data via `KKSV0430_KKSV0430OPDBMapper` including the additional `setJKKHakkoSODCC` (SOD issuance) and `setAddSjishoCC` (instruction sheet CC) mappers.

#### `setRsvclsrv(X31SDataBeanAccess[] paramBean, HashMap<String, Object> inputMap, String func_cd) → void`

Prepares input data for the **cancel reservation service** (`KKSV0431`). Creates the aging target list, clears the return message ID, sets a progress note prefix ("E-Mail Information + Cancellation"), and maps data via `KKSV0431_KKSV0431OPDBMapper` including `setJKKHakkoSODCC` and `setUpdMkmScinsprtWkCC` mappers.

### Change state tracking

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

A critical method that computes **change state flags** for each editable field by comparing current values with the values the user has entered. Sets flags like `MLAD_CHG_FLG` (email address changed), `ALIAS_CHG_FLG` (alias changed), `CAPA_CHG_FLG` (capacity changed), and `VIRUS_CHK_CHG_FLG` (virus check changed). Each flag is set to one of:
- `CHG_TYPE_NOCHG` ("0") — no change
- `CHG_TYPE1` ("1") — new registration or has been changed
- `CHG_TYPE2` ("2") — continuation change (already exists) or no-change change

Also computes the additional capacity (above default) and populates the pull-down selection data for mailbox capacity and virus check.

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

Creates the **aging target list** — a list of items that need aging management. Sets email address, alias, POP ID, mailbox capacity, and virus check as aging targets with their respective codes (`AGING_SBT_CD_MLAD = "009"`, `AGING_SBT_CD_ALIAS = "008"`, `AGING_SBT_CD_POPID = "007"`). This list is sent to the backend services for processing.

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

Builds the **subscription service contract list** based on the change state flags computed by `setChgFlags()`. Only adds entries for items that have actually changed (alias, mailbox capacity, or virus check). Each entry includes the subscription service contract number, generation/addition date-time, subscription service code (`SBOP_SVC_CD_ALIAS = "D01"`, `SBOP_SVC_CD_MAIL_CAPA = "D02"`, `SBOP_SVC_CD_VCHK = "D03"`), and update date-time.

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

Calculates the **virus check service charge end date** when the virus check setting is being changed to "none" (`CHG_TYPE2`). If virus check is being removed and it was a paid service, determines the charge end date (either one day before the operation date, or the end of the billing period) and whether the charge flag is applied. Uses the `getHiChrgJdg()` helper which calls `JKKWebCommon.jdgHiChrg()` for the non-charge determination logic.

### Data mapping from services (output mapping)

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

The largest method in the class. Maps output from the initialization service (`KKSV0427`) back into the screen data bean. Performs:
- Mapping of all sub-service item outputs via `KKSV0427_KKSV0427OPDBMapper` getter methods.
- Calls `setSbopInf()` to determine whether to display subscription service information.
- Calculates mailbox capacity pull-down options via `calclulateMailBoxCapacities()`.
- Parses the email address into account and domain parts via `getEmailAccountStr()`.
- Sets up virus check display ("有" or "無") based on subscription service existence.
- For update mode, populates the current value display fields, sets the pull-down to the current selection, and computes the charge display flag for virus check.

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

Maps results from the update service (`KKSV0428`) using `KKSV0428_KKSV0428OPDBMapper.getOpsvckeiChgCC()`.

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

Maps results from the dismantle service (`KKSV0429`) using `KKSV0429_KKSV0429OPDBMapper.getOpsvckeiDslCC()`.

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

Maps results from the reactivation service (`KKSV0430`) using `KKSV0430_KKSV0430OPDBMapper.getOpsvckeiKaihkCC()`.

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

Maps results from the cancel reservation service (`KKSV0431`) using `KKSV0431_KKSV0431OPDBMapper.getOpsvckeiCnslCC()`.

### Helper methods

#### `getHiChrgJdg(String svcChrgStaYmd, String subOpSvcUseStaYmd, String subOpSvcUseEndYmd) → HashMap<String, Object>`

Performs a **non-charge determination** for virus check services. Constructs a target data map with the service charge start date, subscription service use start/end dates, and operation sub-type flag, then calls `JKKWebCommon.jdgHiChrg()` to determine whether the service should be free or chargeable. Returns the result including `svcChrgEndYmd` and `chrgFlg`.

#### `getMsgRep(String trandiv, String rtn_msg_id) → String[]`

Returns **message replacement strings** for error/warning messages returned from services. For example, if dismantle returns message `EKB0690_NW` (past date), it returns `["利用終了日", "過去"]` to replace placeholders in the message template.

#### `getEmailAccountStr(String srcMlad) → String`

Extracts the **account portion** (everything before `@`) from an email address string.

#### `calclulateMailBoxCapacities(X31SDataBeanAccess svcFormBean) → TreeMap<Integer, String>`

Builds the **mailbox capacity pull-down list**. Reads initial value, maximum value, and increment value from the `MLBOX_CAPA_SET_INFO` data bean, then generates a `TreeMap` mapping capacity in MB to a human-readable string (e.g., "1000MB" or "0.98GB" using binary GB conversion). Also sets the `CAPA_DEFAULT` field.

#### `fineCapa(int i) → String`

Converts a capacity value in MB to a human-readable string. Values >= 1000MB are displayed as X.X GB (using 1024-based conversion). Smaller values are displayed as XMB.

#### `setPullDownIdx(X31SDataBeanAccessArray pulldown_info, String paramString) → boolean`

Sets the **selected index** of a pull-down list to match a given code value. Iterates through the pull-down items and sets the index where the code matches. Returns `true` if a match was found, `false` if not (and the index is reset to 0).

#### `setListSelectData(X31SDataBeanAccess[] paramBean, String srcListKey, String setBeanKey, String setBeanKey2) → void`

Copies the **selected value** from a pull-down list to a target data bean field. Reads the selected index from the pull-down, gets the code and code-name at that index, and sets them into the specified bean keys. Handles special logic for virus check when a family plan is active.

#### `setSbopInf(X31SDataBeanAccess[] para) → void`

Determines whether to **display subscription service information** on the screen. For reactivation or cancel reservation modes, checks if the sub-service detail numbers match or if the service status is "cancelled" — if not, clears the alias and virus check fields on the display side.

#### `isRetSbopInfForKaihk(X31SDataBeanAccess[] para, String opMskmDtlNoKey, String sbopKey) → boolean`

Helper for reactivation mode. Compares the operation submission detail number with the sub-service detail number. Returns `true` if they match (or either is blank), meaning the subscription service info should be retained.

#### `isRetSbopInfForRsvCl(X31SDataBeanAccess[] para, String stat) → boolean`

Helper for cancel reservation mode. Checks if the service status is "cancelled" (`SVC_KEI_STAT_910` or `SVC_KEI_STAT_920`). Returns `true` if cancelled, meaning the subscription service info should be retained.

#### `exeAxmRenkei(X31SDataBeanAccess[] paramBean, HashMap inputMap) → void`

Executes the **AxM integration service** (`CKSV9001 / CKSV9001OP`). Only runs for dismantle operations on the same day as the service end date (not future-dated dismantle). Sets the SYSID as a parameter and invokes the AxM service to synchronize account management data.

## Relationships

```mermaid
flowchart TD
    A["WEBGAMEN_KKW025010PJP"] -->|calls| B["KKW02501SFLogic"]
    C["WEBGAMEN_KKW025020PJP"] -->|reads result| B
    D["WEBGAMEN_KKW025030PJP"] -->|reads result| B
    E["x31business_logic_KKW02501SF.xml"] -->|configures| B
    B -->|extends| F["JCCWebBusinessLogic"]
    B -->|uses| G["KKSV0427: Init service"]
    B -->|uses| H["KKSV0428: Update service"]
    B -->|uses| I["KKSV0429: Dismantle service"]
    B -->|uses| J["KKSV0430: Reactivation service"]
    B -->|uses| K["KKSV0431: Cancellation service"]
    B -->|uses| L["AxM integration CKSV9001"]
```

### Inbound (who depends on this class)

| Class | Relationship |
|---|---|
| `WEBGAMEN_KKW025010PJP` | Calls this class for the initial edit screen |
| `WEBGAMEN_KKW025020PJP` | Displays the update confirmation result |
| `WEBGAMEN_KKW025030PJP` | Displays the completion/confirmation result |
| `x31business_logic_KKW02501SF.xml` | Configures this class as the business logic component |

### Outbound (this class depends on)

| Class | Purpose |
|---|---|
| `JCCWebBusinessLogic` | Base class providing screen state, service invocation, and data bean access infrastructure |

## Usage Example

A typical request flow proceeds as follows:

1. **User requests** the email information update screen → `WEBGAMEN_KKW025010PJP` creates an instance of `KKW02501SFLogic` and calls `actionInit()`.
2. **`actionInit()`** retrieves customer contract data from the preceding screen, calls the init service `KKSV0427` to fetch current email settings, maps results to the data bean, and renders the edit screen.
3. **User modifies** email address, mailbox capacity, alias, or virus check settings and clicks "Update Confirm".
4. **`actionUpdCfm()`** validates the changes (e.g., no capacity decrease), calls the update service `KKSV0428`, maps results, and navigates to the confirmation screen `KKW02502`.
5. **User clicks "Confirm"** on the confirmation screen → `WEBGAMEN_KKW025020PJP` calls `actionFix()`, which commits the changes to the backend via `KKSV0428`.
6. **User is directed** to the completion screen `KKW02503` (`WEBGAMEN_KKW025030PJP`).

For **dismantle operations**, the flow is similar but invokes `KKSV0429` and triggers AxM integration via `exeAxmRenkei()`. For **reactivate operations**, it invokes `KKSV0430` and similarly triggers AxM integration.

## Notes for Developers

- **Thread safety**: The class holds no mutable instance state beyond what the framework (`JCCWebBusinessLogic`) provides. Each request creates a new instance or reuses a request-scoped instance. Do not add instance fields that store request-specific data.
- **Screen flow**: The class manages a 3-screen flow: KKW02501 (edit) → KKW02502 (confirmation) → KKW02503 (completion). Navigation between screens is controlled via the `CommonInfoCFConst.NEXT_SCREEN_ID` field in the common info bean.
- **Transmission division (`trans_div`)**: This constant field on the data bean determines the operation mode (update, dismantle, reactivate, cancel reservation) and drives all branching logic. It is set by the calling screen and must not be modified by this class.
- **Change state flags**: The `setChgFlags()` method is critical for correctness. It must be called before `setSbopsvckeiList()` to ensure the subscription service contract list is built with accurate change flags. If a field has not changed, its flag is `CHG_TYPE_NOCHG` ("0") and no subscription service entry is created.
- **Capacity decrease prevention**: A business rule prevents users from decreasing their mailbox capacity below the current value. This is enforced in `actionUpdCfm()` with a direct check and early return of `false`.
- **AxM integration**: The `exeAxmRenkei()` method is only triggered for dismantle and reactivate operations on the same day as the service end date. Future-dated dismantle operations skip this step.
- **Virus check charge logic**: When virus check is being changed from "yes" to "no" and the service is still within the chargeable billing period, the charge end date is calculated as the end of the billing month. If the operation date is before the service charge start date, the service is treated as free.
- **Data bean naming convention**: Many constants are defined in `KKW02501SFConst`. The data bean uses a consistent key naming scheme (e.g., `MLAD` for email address, `ALIAS` for alias, `CAPA` for mailbox capacity). Consult that constant class for the full field inventory.
- **Framework mapper pattern**: The class uses generated mapper classes (`KKSV0427_KKSV0427OPDBMapper`, etc.) that are instantiated per method call. These mappers handle the serialization between the data bean and the service input/output maps. They are not reusable across requests.
- **Japanese message constants**: Error and info messages use message IDs (e.g., `EKB0370__I`, `EKK0290_JW`) that are resolved by the framework's message lookup. The `getMsgRep()` method provides replacement text for messages with placeholders.
