# Eo / Business / Service

## Overview

The `eo.business.service` package is the heart of the **eo customer base system** (eo顧客基幹システム), a massive Java batch processing framework used by K-Opticom for telecommunications customer management. It contains **2,461 indexed source files** across dozens of functional domains — everything from billing and pricing calculation to course changes, service orders, delivery logistics, and customer validation. Every class extends the `JBSbatBusinessService` base class, which provides a standardized batch lifecycle (`initial()` → `execute()` → `terminal()`), framework integration, and common infrastructure support.

This module does not handle real-time web requests. Instead, it is **scheduled batch processing** that runs nightly or at regular intervals, reading input files or querying databases, performing complex business rules, writing output files, and updating databases. It is a classic enterprise batch system built on the JBSbat framework.

## Architecture Overview

All service classes follow a three-phase lifecycle pattern:

```mermaid
flowchart TD
    A["JBSbatBusinessService
(Base class)"] --> B["initial()
Setup DB access,
read params, init state"]
    B --> C["execute()
Core business logic"]
    C --> D["JBSbatServiceInterfaceMap
In-memory record map"]
    D --> E["JBSbatSQLAccess
DB reads/writes"]
    D --> F["IFM/DEF file classes
Input/output file handling"]
    F --> G["JBSbatOutputItem
Batch result"]
    G --> H["terminal()
Close DB, clean up,
finalize logs"]
```

### Naming Conventions

Class names encode both the **functional domain** and the **operation type**:

| Prefix | Domain | Example |
|--------|--------|---------|
| `AC`   | Accounting, pricing, invoicing | `JBSbatACKaikPrcCalc` — accounting price calculation |
| `CH`   | Billing, charges, payments | `JBSBatCHDslAfMvTkskInfIktAdd` — post-delinquency forwarding registration |
| `KK`   | Core services (course changes, service contracts) | `JBSBatKKCrsChgIktAdd` — course change batch registration |
| `KV`   | Validation (contract异动, discounts, temporary fees) | `JBSbatKVCheckKicjkn` — contract change temporary fee verification |
| `DK`   | Delivery, logistics (配送) | `JBSBatDKHjHaisoInfoAdd` — corporate delivery import |
| `SC`   | Service Order (サービスオーダ) | `SCUqsodDataCst` — UQ-SOD data extraction |
| `SCEM` | EM (イー・モバイル) mobile | `SCEMIdoIfTmpstpTrkm` — EM move data temporary suspend import |
| `FU`   | Frontend, web operations | `FUeFrontLoginBlockFileIktAdd` — e-front login block file registration |
| `KU`   | K-Opticom unified integration | `KUAnkenInfoSend` — case info send |
| `TU`   | Telephone/number services | `TUNttShinTrkm` — NTT application result import |
| `WC`   | Watch control (視聴制御) | `WCCtrlchange` — viewing change control |

Operation type suffixes (embedded in the class name):
- `Trkm` — 取込 (import/load)
- `Chsht` — 抽出 (extract)
- `IktAdd` — 一括登録 (batch registration)
- `Saksi` — 作成 (create)
- `Add` — 登録 (register)
- `Upd` — 更新 (update)
- `Chk` — チェック (check)
- `Calc` — 計算 (calculation)

## Key Classes and Interfaces

### JBSbatBusinessService (Framework Base)

All 2,461 service classes extend this base class (imported from `eo.business.common`). It provides:

- **`initial(JBSbatCommonItem commonItem)`** — Called first. Sets up `JBSbatSQLAccess` instances for each table, reads batch parameters, initializes working state.
- **`execute(...)`** — The core business logic. Overridden in each subclass with domain-specific processing. Varies by class: some accept file maps (`JBSbatServiceInterfaceMap`), some take `JBSbatCommonDBInterface` directly.
- **`terminal()`** — Cleanup: closes `JBSbatSQLAccess` objects, writes final logs, reports results.

The base class tracks `opeDate` (operation date), `onlineOpeDate` (online date for real-time), `freeItem` (free-form parameter string), and a `logPrint` handler.

### JBSBatKKCrsChgIktAdd — Course Change Batch Registration

**Purpose:** Handles the batch registration of course changes (プラン変更/コース変更) for customers. This is one of the most complex classes in the package at nearly 2,000 lines.

**Key behavior:**

| Method | What it does |
|--------|-------------|
| `initial()` | Sets up DB access for 15+ tables including `KK_T_SVC_KEI` (service contracts), `KK_M_PCRS` (price courses), `KK_T_IDO_RSV` (change reservation), and more. Reads file definitions and parameters. |
| `execute()` | Reads input files, performs single-item validation (`isSingleCheckKKIFM714`, `isSingleCheckKKIFM715`), checks service contract validity, determines 1G-mansion targets, updates course change status in `KK_T_PRG`, and registers course change details. |
| `makeData()` | Transforms input records into output `JBSbatServiceInterfaceMap` structures. |
| `makeDataDlyd()` | Handles delayed processing records. |

This class touches a wide array of database tables — service contracts, price courses, address changes, delivery work, option services, and provision method contracts. It also integrates with the workflow management system (`CC_T_EFILE_KANRI`) and delayed transaction request tracking.

### JBSBatCHDslAfMvTkskInfIktAdd — Post-Delininquency Forwarding Registration

**Purpose:** Registers post-delinquency forwarding address information for dunning (督促) purposes. When a customer cancels and moves, this batch ensures collection notices can reach them.

**Key behavior:**

- Reads the "post-delinquency forwarding information batch registration file" (解約後転居先情報一括登録ファイル) and validates each record.
- Performs single-item validation via `isSingleCheckCHIFM336()`.
- Cross-references `KK_T_SEIKY_KEI` (billing contracts), `KK_T_SVC_KEI` (service contracts), and `KK_T_DSL_AF_TNKYS_IF` (post-delinquency forwarding info).
- Updates progress tracking (`KK_T_PRG`) and special notes (`CH_T_TOKUSOKU`).
- Extracts special remarks via `getPrgTkjk()` — for new registrations this is empty; for modifications it records before/after values.

### JBSbatACKaikPrcCalc — Accounting Price Calculation

**Purpose:** Calculates accounting-price mappings, converting service charges into accounting-recognized entries. Used to feed the accounting system.

**Key behavior:**

- Reads the accounting price calculation method table (`CH_M_KAIKPRC_SNSTWAY`) in `initial()` and caches it in `tmpKaikPrcSnstWayList`.
- The `execute()` method transforms each input record, applying the calculated accounting method codes and amounts.
- Uses `BigDecimal` for monetary calculations (not `double`) with a constant `BIGDECIMAL_100` for percentage-based adjustments.
- Returns an output map with the transformed accounting fields (`tmpKaikUcwkCd`, `tmpAmnt`).

This is a representative example of a simpler service class that does straightforward transformation work — read master data, process input records, write output.

### JBSBatCHKsDkCmpRealNkDataMake — Payment Agency Real Payment Data Creation

**Purpose:** Creates real payment data for payment service companies (決済代行会社), specifically for SMS-based instant payment services.

**Key behavior:**

- Queries `CH_T_SEIKY` (billing) and `CH_T_KSDKCP_NKIF_RCV` (payment agency receipt) via `JBSbatSQLAccess`.
- Joins billing contract info with payment receipt data.
- Outputs through `JBSbatCHIFM043` file definition.
- Uses `JCHStringUtil` for string manipulation.

### JBSbatAC050ApKoInfInputChk — 050 App Call Information Input Check

**Purpose:** Validates input files for the 050 app call information (050アプリ利用呼情報). The 050 app is a callback service provided by K-Opticom.

**Key behavior:**

- Reads header records (type `0`), data records (type `1`), and trailer records (type `8`) from flat files.
- Performs extensive single-item validation via `isSingleCheckACIFM075()`, `isSingleCheckACIFM076()`, and `isSingleCheckACIFM077()` — covering fields like billing phone number, origin number, destination number, call start/end timestamps, call duration, call cost, and service division.
- Validates future dates via `checkFutureData()`.
- Creates both valid output data and error data files via `createData()` and `createErrData()`.
- Handles decimal point placement with `addDecimalPoint()` and `deleteDecimalPoint()`.

This class is representative of input-validation-heavy batches that read flat files, validate records, and produce both clean and error output files.

### JBSBatSCEMIdoIfTmpstpTrkm — EM (i-mobile) Move Data Temporary Suspend Import

**Purpose:** Imports EM (イー・モバイル) contract move data for temporary suspension states.

**Key behavior:**

- Reads from `SC_T_EM_ODR_SRINF` (EM order send/receive info), `SC_T_MOBILE_ORDER` (mobile order), `SC_T_UQ_ODR_SRINF` (UQ order), and `SC_T_SPOT_ODR_SRINF` (SPOT order).
- Updates status information in the database after processing.
- Validates input records and generates error lists via `JBSbatSCIFE022` and `JBSbatSCIFE023` file definitions.

### JBSBatCHSalesAuthoriJssiHojin — Sales Authorization Request (Corporate)

**Purpose:** Handles sales authorization requests for corporate (法人) customers, integrating with the Claris credit card authentication system.

**Key behavior:**

- Reads system parameters from `ZM_M_SYS_PARAM_KNRI` including retry counts.
- Uses `JKKBatClarisAuthCrdt` for Claris credit card integration.
- Has retry logic controlled by `salesAuthoriRetryCount`.
- Uses `trnResultCdMap` to map transaction result codes.

### JBSbatKVWribVrfyChokiInfo — Discount Verification: Long-Term Use Discount / Immediate Discount

**Purpose:** Validates long-term use discount (通常割) and immediate discount (即割) application. Ensures discounts are only applied to eligible price plans and that conflicting discount combinations are caught.

**Key behavior:**

- Implements `JBSbatMatchServiceInterface` (a three-mode interface: mast, match, tran processing).
- Validates that long-term use discount and immediate discount are not applied to ineligible price plans.
- Catches cases where both discount types are applied simultaneously.
- Produces validation error output via `JBSbatKVIFM016`, `JBSbatKVIFM017`, `JBSbatKVIFM019` file definitions.

### JBSBatDKHjHaisoInfoAdd — Corporate Delivery Information Import

**Purpose:** Imports corporate delivery information for logistics operations, linking indoor device models, catalog master, and delivery targets.

**Key behavior:**

- Reads `ZM_M_TAKNKIKI_MODEL` (indoor device models) and `ZM_M_CD_NM_KANRI` (code name management).
- Processes `DK_M_SOKODNA` (warehouse), `DK_T_HAISO` (delivery), and `DK_T_HAISO_TG_BPIN` (delivery targets).
- Creates delivery files via `JBSbatDKIFM036`, `JBSbatDKIFM085`, `JBSbatDKIFM091` file definitions.
- Uses `JDKBatOutputFileUtil` and `JDKCommonUtil` for output processing.

## How It Works: Common Processing Flows

### Pattern 1: Simple File-Based Transform

Most batches follow this flow:

```mermaid
flowchart TD
    A["File/DB Input"] --> B["initial() setup"]
    B --> C["execute() main logic"]
    C --> D["Single item checks"]
    C --> E["Cross-field validations"]
    C --> F["DB updates via JBSbatSQLAccess"]
    C --> G["File output via IFM classes"]
    F --> H["JBSbatServiceInterfaceMap"]
    G --> H
    H --> I["JBSbatOutputItem"]
    I --> J["terminal() cleanup"]
```

1. **`initial()`** — Instantiate `JBSbatSQLAccess` for each database table. Read `freeItem` parameters (usually file paths, operation codes, or processing flags). Initialize working variables.
2. **`execute()`** — Read input files line-by-line or query databases. For each record:
   - Validate individual fields using `isSingleCheckXX()` methods
   - Apply business rules (calculation, matching, status transitions)
   - Update databases via `JBSbatSQLAccess.executeXX()` methods
   - Write output files using IFM-defined formats
3. **`terminal()`** — Close all `JBSbatSQLAccess` objects. Log summary statistics.

### Pattern 2: Match Service (Three-Mode Processing)

Classes implementing `JBSbatMatchServiceInterface` (such as `JBSbatKVWribVrfyChokiInfo`) support three processing modes:

- **`mastProcFlg`** — Process master/reference data
- **`matchProcFlg`** — Match input against master data
- **`tranProcFlg`** — Process transaction data

These are controlled via free-item parameters and used for batch jobs that may need to be run in different phases (e.g., load reference data first, then match, then process).

### Pattern 3: Contract Validation (KV Domain)

The KV (validation) batch domain is a specialized subsystem for validating contract changes before they take effect. Key validation classes:

| Class | Validates |
|-------|-----------|
| `JBSbatKVCheckKicjkn` | Temporary fees (一時金) at contract change |
| `JBSbatKVCheckKicjknSurplus` | Temporary fee over-generation checks |
| `JBSbatKVCheckSeikyOptChrgKikan` | Billing option charge period |
| `JBSbatKVDateSetChk` / `JBSbatKVDateValidation` | Date setting validation |
| `JBSbatKVWribVrfyChokiInfo` | Long-term / immediate discount eligibility |
| `JBSbatKVWribVrfyFamilyInfo` | Family Pack discount information |
| `JBSbatKVWribVrfyHybWribCheck` | Hybrid discount validation |
| `JBSbatKVWribVrfyKapWribCheck` | Installment contract discount |
| `JBSbatKVWribVrfyOverlapCheck` | Campaign overlap validation |
| `JBSbatKVWribVrfySetWribCheck` | Set discount information |
| `JBSbatKVWribVrfyServiceSide` | Service contract start-point validation |

These are called as part of the contract change workflow (e.g., `JBSBatKKCrsChgIktAdd`) to ensure discount eligibility, fee correctness, and contract integrity.

## Data Model

The service layer interacts with a rich set of database tables. Key table naming conventions:

| Table Prefix | Domain | Examples |
|-------------|--------|---------|
| `KK_T_SVC_KEI` | Service contracts | Main service contract table |
| `KK_T_SVKEI_KAISEN_UW` | Service contract detail (line breakdown) |
| `KK_T_SEIKY_KEI` | Billing contracts |
| `KK_T_SEIKY_KEI_UCWK` | Billing contract detail |
| `KK_M_PCRS` | Price courses |
| `KK_M_PPLAN` | Price plans |
| `KK_T_IDO_RSV` | Change reservations |
| `KK_T_IDO_RSN` | Change reasons |
| `KK_T_DSL_AF_TNKYS_IF` | Post-delinquency forwarding info |
| `KK_T_KICJKN` | Contract temporary fees |
| `KK_T_ICJKN_SETTE` | Temporary fee settings |
| `KK_T_KAISEN_TG_SVKEI` | Line-target service contracts |
| `KK_T_PRG` | Progress tracking |
| `CH_T_TOKUSOKU` | Special notes |
| `CH_T_PRC_TAIOKRK` | Price response records |
| `ZM_M_CD_NM_KANRI` | Code name management |
| `ZM_M_SYS_PARAM_KNRI` | System parameter management |
| `ZM_M_WORK_PARAM_KNRI` | Work parameter management |
| `ZM_T_DL_FILE_KANRI` | Download file management |
| `SC_T_EM_ODR_SRINF` | EM order send/receive info |
| `SC_T_MOBILE_ORDER` | Mobile order |
| `DK_T_HAISO` | Delivery |
| `DK_T_HAISO_TG_BPIN` | Delivery target BPIN |

Table access is always through `JBSbatSQLAccess`, which wraps SQL definitions (e.g., `CH_SELECT_017`, `KK_INSERT_002`) defined in the framework. Each class declares `D_TBL_NAME_XX` constants for table names and `XX_SELECT_NNN` / `XX_UPDATE_NNN` / `XX_INSERT_NNN` constants for SQL keys.

## Dependencies and Integration

### Internal Framework Dependencies

| Import | Purpose |
|--------|---------|
| `eo.business.common.JBSbatBusinessService` | All service classes extend this |
| `eo.framework.db.JBSbatSQLAccess` | Database access wrapper |
| `eo.framework.item.JBSbatServiceInterfaceMap` | In-memory record mapping |
| `eo.framework.item.JBSbatCommonDBInterface` | DB result iteration |
| `eo.framework.file.JBSbatInputFileUtil` / `JBSbatOutputFileUtil` | Flat file I/O |
| `eo.business.util.file.*IFM*` / `*IFE*` | File format definitions |
| `eo.business.util.table.JBSbatKK_T_SVC_KEI` | Table column definitions |

### Cross-Module Integration

The module integrates with:

- **`eo.ejb.common.db`** — Database entity layer
- **`eo.business.util.file`** — File utilities
- **`eo.business.service.stub`** — Service stubs for remote calls
- **`eo.web.webview.*`** — Various web pages (e.g., `ACW00202SF`, `CHW00801SF`, `KKW14101SF`) for user interaction

### External System Integration

Batches in this module communicate with external systems through:

- **FTP file exchange** — `JBSbatACFtpPut`, `JBSbatKKFtpPut` for sending/receiving files
- **ESB** — `JCCBatchEsbInterface` for enterprise service bus calls
- **ClearPath** — Credit card authorization integration (`JKKBatClarisAuthCrdt`)
- **Claris** — Financial processing
- **IBUKI** — Billing system
- **CASE file generation** — Support case files for customer service tracking
- **SPRI file transfer** — File delivery for external partners

## Notes for Developers

### Batch Lifecycle Requirements

Every class must implement the three methods:
- `initial(JBSbatCommonItem)` — Must call `super.setCommonInfo(commonItem)` and set up all `JBSbatSQLAccess` instances
- `execute(...)` — Must return `JBSbatOutputItem` (or `void` in some variants)
- `terminal()` — Must call `super.terminal()` and close all `JBSbatSQLAccess` objects

### File Validation Pattern

Input file validation is typically done via `isSingleCheckXX()` methods that take `HashMap rsMap` and `HashMap itemvalueMap`. These methods check field lengths, formats, ranges, and referential integrity. Error codes follow the `ACIFM075`, `CHIFM336`, `KKIFM714` naming convention.

### Multi-Mode Processing

Classes implementing `JBSbatMatchServiceInterface` need all three flags (`mastProcFlg`, `matchProcFlg`, `tranProcFlg`) with getters and setters. The `freeItem` parameter (passed through `JBSbatCommonItem`) controls which modes are active.

### Common Constants

| Source | Usage |
|--------|-------|
| `JPCBatchMessageConstant` | Batch message codes (1062 imports) |
| `JACStrConst` | String constants (684 imports) |
| `JKKBatConst` / `JBSbatKKConst` | KK-domain constants (266+ imports) |
| `JCCBatCommon` | Common batch utilities (738 imports) |
| `JKKBatCommon` / `JACBatCommon` | Domain-specific utilities |
| `JACbatDebugLogUtil` | Debug logging (690 imports) |
| `JACbatParamUtil` | Business parameter access (271 imports) |

### Extending a Service

To create a new batch service:

1. Extend `JBSbatBusinessService`
2. Define table name constants (`D_TBL_NAME_XX`)
3. Define SQL key constants (`XX_SELECT_NNN`, `XX_UPDATE_NNN`, etc.)
4. Declare `JBSbatSQLAccess` instance variables
5. Implement `initial()` to set up DB access and read parameters
6. Implement `execute()` with your business logic
7. Implement `terminal()` to clean up
8. Register the SQL definitions in the framework's SQL definition files
9. If reading/writing flat files, create IFM/DEF file definition files

### Common Gotchas

- **Decimal precision:** Always use `BigDecimal` for monetary values. Helper methods like `addDecimalPoint()` and `deleteDecimalPoint()` handle position-based decimal placement for fixed-format files.
- **Future date validation:** Most input-checking batches validate against `sysWkTime` (online date + system time) to reject future-dated records.
- **File encoding:** Early versions had encoding issues (noted in `JBSbatAC050ApKoInfInputChk` version history). New code should be aware of EUC-JP vs UTF-8 file handling.
- **Thread safety:** These classes are not thread-safe. Each batch invocation creates new instances.
- **FreeItem format:** The `freeItem` parameter is a semicolon-delimited string. The order and meaning of elements is domain-specific — consult existing similar classes before changing the format.
- **Deferred processing (ディレイド):** Some batches support delayed processing via `CC_T_DLYD_TRN_REQ`. If a batch encounters an error, the record may be queued for retry rather than failing outright.
