# Business Logic — JBSbatKKCourseChgeTstaDayChsht.selectKktSvKeiUw() [54 LOC]

| Field | Value |
|-------|-------|
| Fully Qualified Name | `eo.business.service.JBSbatKKCourseChgeTstaDayChsht` |
| Layer | Service (Batch Service Layer) |
| Module | `service` (Package: `eo.business.service`) |

## 1. Role

### JBSbatKKCourseChgeTstaDayChsht.selectKktSvKeiUw()

This method performs a **search operation on service contract details (サービス契約内訳)** — the line-item breakdown of a service contract within K-Opticom's customer backbone system. Given a service contract number (`svcKeiNo`) and an optional service contract detail number (`svcKeiUcwkNo`), the method queries the `KK_T_SVC_KEI_UCWK` database table to retrieve the latest record's detail number and generation registration date/time (世代登録年月日).

The business context is tied to the **daily batch processing for course changes and status day changes** — a scheduled batch job that processes customer service contract modifications. The method computes a date filter representing the **first day of the month following the batch operation date**, and uses it as part of the WHERE clause to scope the search to relevant records.

The method implements a **data-mapping pattern**: it reads a database entity, extracts two key fields, and writes them into an output interface map (`JBSbatServiceInterfaceMap`) for consumption by downstream processing or screen output. It iterates through **all matching rows** and retains the **last row's values** (a common pattern when the last record represents the most recently processed entry).

If **no records are found**, the method gracefully handles the null case by setting both output fields to empty strings — ensuring downstream consumers always receive valid, non-null values.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["selectKktSvKeiUw"])
    STEP1["Calculate next month first day
whereOpedate = getOpedateNextMonthFst"]
    STEP2["Build whereParam array
svcKeiNo, svcKeiUcwkNo, whereOpedate"]
    STEP3["Execute DB query
executeKK_T_SVC_KEI_UCWK_KK_SELECT_103
KK_T_SVC_KEI_UCWK table"]
    STEP4["Fetch first record
kktSvKeiUwMap_103 = selectNext()"]
    COND1{Is result null?
No records found?}
    BRANCH_EMPTY["Set empty strings
svcKeiUcwkNo1 = empty
geneAddDtm1 = empty"]
    BRANCH_LOOP["Read row values
svcKeiUcwkNo1 = Rtrim(SVC_KEI_UCWK_NO)
geneAddDtm1 = Rtrim(GENE_ADD_DTM)
Last iteration value wins"]
    STEP5["Fetch next row
kktSvKeiUwMap_103 = selectNext()"]
    COND2{Is next null?
Loop exit?}
    STEP6["Set output values
outmap.setString
SVC_KEI_UCWK_NO1
geneAddDtm1"]
    STEP7["Debug logging
printDebugLog"]
    END(["Return"])

    START --> STEP1 --> STEP2 --> STEP3 --> STEP4 --> COND1
    COND1 -->|Yes| BRANCH_EMPTY --> STEP6
    COND1 -->|No| BRANCH_LOOP --> STEP5 --> COND2
    COND2 -->|No| BRANCH_LOOP
    COND2 -->|Yes| STEP6
    BRANCH_EMPTY --> STEP6
    STEP6 --> STEP7 --> END
```

**Processing flow description:**

1. **Date calculation**: Computes the first day of the next month relative to the batch operation date (`opeDate`) using `getOpedateNextMonthFst()`. This produces a `yyyyMMdd` date string (e.g., `20260701`).
2. **Parameter construction**: Builds a 5-element parameter array passing `svcKeiNo` twice, `svcKeiUcwkNo` twice, and the calculated date.
3. **Database query**: Executes a SQL SELECT against `KK_T_SVC_KEI_UCWK` using the pre-defined query `KK_T_SVC_KEI_UCWK_KK_SELECT_103`.
4. **Result iteration**: Iterates through ALL returned records, overwriting local variables on each iteration — the **last row's values win**.
5. **Output mapping**: Writes the final extracted values into the output interface map keyed by `SVC_KEI_UCWK_NO1` and `GENE_ADD_DTM1`.
6. **Debug logging**: Conditionally logs the retrieved values if the debug log level is enabled.

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| 1 | `outmap` | `JBSbatServiceInterfaceMap` | Output interface map used to pass retrieved service contract detail data to downstream processing or screen output. Acts as the contract bridge between the batch service and its consumer. |
| 2 | `svcKeiNo` | `String` | Service contract number (サービス契約番号) — the unique identifier of a service contract. Passed both as a direct match and as a pattern-match parameter in the WHERE clause. |
| 3 | `svcKeiUcwkNo` | `String` | Service contract detail number (サービス契約内訳番号) — the unique identifier for a specific line-item within a service contract. Used as an exact and pattern match filter in the query. |

**Instance fields read by this method:**

| Field | Type | Business Description |
|-------|------|---------------------|
| `opeDate` | `String` | Batch operation date (yyyyMMdd format) — used as the base for computing the next month's first day date filter. |
| `logPrint` | `JBSbatLogUtil` | Logging utility instance — used for conditional debug-level log output. |
| `db_KK_T_SVC_KEI_UCWK` | `JBSbatCommonDBInterface` | Database accessor instance for the `KK_T_SVC_KEI_UCWK` table — provides the `selectNext()` method to fetch query result rows. |

## 4. CRUD Operations / Called Services

### Pre-computed evidence from code analysis graph:

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| R | `JBSbatKKCourseChgeTstaDayChsht.executeKK_T_SVC_KEI_UCWK_KK_SELECT_103` | - | `KK_T_SVC_KEI_UCWK` | Executes SQL SELECT query on service contract detail table using pre-defined query ID `KK_T_SVC_KEI_UCWK_KK_SELECT_103`. Passes 5 parameters: service contract number (×2), detail number (×2), and next-month-first-day date filter. |
| R | `JBSbatCommonDBInterface.selectNext` | - | `KK_T_SVC_KEI_UCWK` | Iteratively fetches the next row from the result set of the executed SELECT. Called once initially, then in a while-loop to traverse all matching records. Last row's values are retained. |
| R | `JBSbatCommonDBInterface.getString` | - | `KK_T_SVC_KEI_UCWK` | Extracts individual column values from the current result row — specifically `SVC_KEI_UCWK_NO` (service contract detail number) and `GENE_ADD_DTM` (generation registration date/time). |
| U | `JBSbatStringUtil.Rtrim` | JBSbatStringUtil | - | Right-trims whitespace from string values extracted from the database. Applied to both `svcKeiUcwkNo1` and `geneAddDtm1` to clean trailing spaces. |
| U | `JBSbatServiceInterfaceMap.setString` | JBSbatKKIFM151 | - | Writes the final extracted values to the output interface map under keys `SVC_KEI_UCWK_NO1` (service contract detail number 1) and `GENE_ADD_DTM1` (generation registration date/time 1). |
| R | `JBSbatKKCourseChgeTstaDayChsht.getOpedateNextMonthFst` | - | - | Computes and returns the first day of the month following the batch operation date. Produces a `yyyyMMdd` formatted string (e.g., `20260701` from `20260628`). |
| - | `JBSbatLogUtil.printDebugLog` | JBSbatLogUtil | - | Conditionally outputs debug log entries for the retrieved service contract detail number and generation registration date. Only runs when debug log level is enabled via `chkLogLevel(MODE_DEBUG)`. |

## 5. Dependency Trace

### Pre-computed evidence from code analysis graph:

No screen/batch entry points found within 8 hops. Direct callers found: 1 methods.
Terminal operations from this method: `printDebugLog` [-], `setString` [-]

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | Batch: `JBSbatKKCourseChgeTstaDayChsht.execute()` | `execute()` -> `selectKktSvKeiUw(outmap, svcKeiNo, svcKeiUcwkNo)` | `executeKK_T_SVC_KEI_UCWK_KK_SELECT_103 [R] KK_T_SVC_KEI_UCWK` |

**Call chain detail:**
- `execute()` is the primary batch entry point method of `JBSbatKKCourseChgeTstaDayChsht`. It invokes `selectKktSvKeiUw()` to retrieve service contract detail data as part of the broader batch processing workflow for course changes and status day changes.

## 6. Per-Branch Detail Blocks

**Block 1** — VARIABLE DECLARATION (L1587-1590)

Declares and initializes local variables for the extracted service contract detail number and generation registration date/time. Also declares the database interface map to hold query results.

| # | Type | Code |
|---|------|------|
| 1 | SET | `svcKeiUcwkNo1 = ""` // Service contract detail number 1 (サービス契約内訳番号：1) |
| 2 | SET | `geneAddDtm1 = ""` // Generation registration date/time 1 (世代登録年月日：1) |
| 3 | SET | `kktSvKeiUwMap_103 = null` // SQL execution result storage — service contract detail retrieval (SQL実行結果取得格納（サービス契約内訳取得）) |

**Block 2** — DATE CALCULATION (L1593-1595)

Computes the first day of the next month from the batch operation date and constructs the WHERE parameter array for the database query.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `whereOpedate = getOpedateNextMonthFst()` // Returns next month's first day in yyyyMMdd format |
| 2 | SET | `whereParam = {svcKeiNo, svcKeiUcwkNo, svcKeiNo, svcKeiUcwkNo, whereOpedate}` // 5-element WHERE clause array: service contract number (exact+pattern), detail number (exact+pattern), date filter |

**Block 3** — DATABASE QUERY EXECUTION (L1598)

Executes the SQL SELECT query against the `KK_T_SVC_KEI_UCWK` table.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `executeKK_T_SVC_KEI_UCWK_KK_SELECT_103(whereParam)` // Executes SELECT query on KK_T_SVC_KEI_UCWK table with 5 parameters |

**Block 4** — INITIAL RESULT FETCH (L1601-1602)

Fetches the first record from the query result set.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `kktSvKeiUwMap_103 = db_KK_T_SVC_KEI_UCWK.selectNext()` // Fetches the first row from the SELECT result |

**Block 5** — IF/ELSE [No records found / Has records] (L1605-1628)

Branches based on whether any records were returned from the database query.

> **Block 5** — IF `(null == kktSvKeiUwMap_103)` — No records found (L1605)
> The service contract detail search returned zero records. Both output variables are set to empty strings to ensure downstream consumers receive valid defaults.

| # | Type | Code |
|---|------|------|
| 1 | SET | `svcKeiUcwkNo1 = ""` // Service contract detail number 1 — set to empty (サービス契約内訳番号：1) |
| 2 | SET | `geneAddDtm1 = ""` // Generation registration date/time 1 — set to empty (世代登録年月日：1) |

> **Block 5.1** — ELSE — Has records (L1608)
> At least one record was returned. Iterates through ALL matching rows, extracting the detail number and date/time from each. The last iteration's values are retained (last row wins pattern).

| # | Type | Code |
|---|------|------|
| 1 | WHILE | `while (null != kktSvKeiUwMap_103)` // Iterates through all returned rows |

> **Block 5.1.1** — Inside WHILE: Extract SVC_KEI_UCWK_NO (L1612-1614)
> Reads the service contract detail number column from the current row and right-trims whitespace.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `svcKeiUcwkNo1 = JBSbatStringUtil.Rtrim(kktSvKeiUwMap_103.getString(JBSbatKK_T_SVC_KEI_UCWK.SVC_KEI_UCWK_NO))` // Service contract detail number (サービス契約内訳番号) |

> **Block 5.1.2** — Inside WHILE: Extract GENE_ADD_DTM (L1616-1618)
> Reads the generation registration date/time column from the current row and right-trims whitespace.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `geneAddDtm1 = JBSbatStringUtil.Rtrim(kktSvKeiUwMap_103.getString(JBSbatKK_T_SVC_KEI_UCWK.GENE_ADD_DTM))` // Generation registration date/time (世代登録年月日) |

> **Block 5.1.3** — Inside WHILE: Fetch next row (L1621)
> Advances to the next record. If this returns null, the loop exits and the last iteration's values are used.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `kktSvKeiUwMap_103 = db_KK_T_SVC_KEI_UCWK.selectNext()` // Fetches next row for loop continuation check |

**Block 6** — OUTPUT MAPPING (L1630-1632)

Writes the final extracted values into the output interface map. These keys correspond to the `JBSbatKKIFM151` interface format used by downstream consumers (e.g., screens or other batch stages).

| # | Type | Code |
|---|------|------|
| 1 | CALL | `outmap.setString(JBSbatKKIFM151.SVC_KEI_UCWK_NO1, svcKeiUcwkNo1)` // Sets service contract detail number 1 (サービス契約内訳番号：1) |
| 2 | CALL | `outmap.setString(JBSbatKKIFM151.GENE_ADD_DTM1, geneAddDtm1)` // Sets generation registration date/time 1 (世代登録年月日：1) |

**Block 7** — DEBUG LOGGING CONDITION (L1634-1636)

Conditionally outputs debug log entries when the debug log level is enabled. Logs the two retrieved values for troubleshooting and traceability.

| # | Type | Code |
|---|------|------|
| 1 | IF | `super.logPrint.chkLogLevel(JBSbatLogUtil.MODE_DEBUG)` // Checks if debug mode is active |
| 2 | EXEC | `super.logPrint.printDebugLog("サービス契約内訳検索（サービス契約内訳番号：1）：" + svcKeiUcwkNo1)` // Logs detail number 1 (サービス契約内訳検索（サービス契約内訳番号：1）) |
| 3 | EXEC | `super.logPrint.printDebugLog("サービス契約内訳検索（世代登録年月日：1）：" + geneAddDtm1)` // Logs date/time 1 (サービス契約内訳検索（世代登録年月日：1）) |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `svcKeiNo` | Field | Service contract number (サービス契約番号) — unique identifier for a service contract in the K-Opticom customer backbone system. |
| `svcKeiUcwkNo` | Field | Service contract detail number (サービス契約内訳番号) — unique identifier for a line-item within a service contract. Represents a specific service configuration or modification. |
| `svcKeiUcwkNo1` | Field | Service contract detail number 1 — output variable holding the retrieved detail number. The "1" suffix indicates the first/detail position in the output interface format. |
| `geneAddDtm` | Field | Generation registration date/time (世代登録年月日) — timestamp indicating when this record version was created/registered. Used for versioning and auditing service contract changes. |
| `geneAddDtm1` | Field | Generation registration date/time 1 — output variable holding the retrieved date/time value. |
| `KK_T_SVC_KEI_UCWK` | DB Table | Service contract detail table (サービス契約内訳テーブル) — stores line-item breakdowns of service contracts including detail number, registration date/time, state, pricing, and scheduling fields. |
| `KK_T_SVC_KEI_UCWK_NO` | Column | Service contract detail number column (サービス契約内訳番号) — primary identifier within the detail table. |
| `GENE_ADD_DTM` | Column | Generation registration date/time column (世代登録年月日) — timestamp for when this detail record version was created. |
| `SVC_KEI_UCWK_STAT` | Column | Service contract detail state (サービス契約内訳ステータス) — status indicator for the detail record. |
| `SVC_USE_STA_KIBO_YMD` | Column | Service usage start desired date (サービス利用開始希望年月日) — customer's requested service activation date. |
| `outmap` | Parameter | Output interface map (出力インターフェースオブジェクト) — shared data structure used to pass results between batch processing stages. Implements the service interface map pattern. |
| `JBSbatKKIFM151` | Interface | Interface format class (インターフェースフォーマット) — defines output field keys for service contract data (e.g., `SVC_KEI_UCWK_NO1`, `GENE_ADD_DTM1`). |
| `opeDate` | Field | Batch operation date (運用日) — the date the batch job is running on, used as the reference point for date calculations. |
| `getOpedateNextMonthFst` | Method | Computes the first day of the next month from the batch operation date. Used as a date filter in queries. |
| `Rtrim` | Method | Right-trims (removes trailing whitespace from) a string value. Standard data cleansing operation for database-extracted values. |
| `selectNext` | Method | Fetches the next row from a database result set. Returns `null` when no more rows are available, signaling loop termination. |
| `chkLogLevel` | Method | Checks whether a specific log level (e.g., DEBUG) is enabled for the current execution context. |
| `JBSbatLogUtil.MODE_DEBUG` | Constant | Debug log level flag — enables verbose debug logging when active. |
| `JBSbatCommonDBInterface` | Interface | Common database access interface — abstraction layer for executing SQL queries and iterating result sets. |
| `JBSbatServiceInterfaceMap` | Interface | Service interface map — data transfer object used to pass structured results between batch processing components. |
