# Eo

## Overview

The `eo` package is the **customer base system** (顧客基幹システム) for K-Opticom -- a massive Java batch processing framework used for telecommunications customer management. It is not a web-oriented or real-time system. Instead, it is a scheduled batch processing engine that runs nightly or at regular intervals: reading input files or querying databases, applying complex business rules, writing output files, and updating the database.

At its core sits the `eo.business` package, which contains the `eo.business.service` sub-package -- home to over 2,461 batch service classes spanning dozens of functional domains including billing, pricing, course changes, delivery logistics, service orders, validation, and customer account management. All services are built on the JBSbat framework, which provides a standardized three-phase lifecycle (`initial()` → `execute()` → `terminal()`).

```mermaid
flowchart TD
    A["eo
Telecom Customer Base System"] --> B["eo.business
Core Business Layer"]
    A --> C["eo.ejb.common.db
Database Entities"]
    A --> D["eo.business.util.file
File Utilities"]
    A --> E["eo.web.webview
Web Interface Layer"]
    B --> F["eo.business.service
2,461 Batch Services"]
    F --> G["KK Core Services
Course changes, contracts"]
    F --> H["KV Validation
Discount, fee, pricing checks"]
    F --> I["AC Accounting
Price calculations"]
    F --> J["CH Billing
Delinquency, payments"]
    F --> K["DK Delivery
Logistics, notices"]
    F --> L["SC Service Orders
Mobile orders, moves"]
    H --> G
    H --> I
    G --> I
    H --> J
```

The system communicates with external partners and systems through FTP file exchange, an enterprise service bus (ESB), and integrations with ClearPath (credit card authorization), Claris (financial processing), IBUKI (billing system), and CASE/SPRI (support case and partner file delivery).

## Sub-module Guide

### Business (`eo.business`)

The `eo.business` package is the core business processing layer. Its primary responsibility is orchestrating the full lifecycle of customer interactions -- from new customer sign-up through course changes, service modifications, billing, delinquency management, and eventual churn. The bulk of this logic lives in the `eo.business.service` sub-package.

**What it does:** Applies complex telecom-specific business rules to customer data. This includes price course calculations, discount eligibility verification, temporary fee management, contract change registration, and post-delinquency forwarding.

**How the domains within `eo.business.service` relate:**

The 2,461 service classes are organized into functional domains identified by two-letter prefixes. These domains are not siloed; they form an integrated workflow that follows the customer lifecycle:

| Prefix | Domain | Responsibility |
|--------|--------|----------------|
| `KK` | Core services | Course changes, service contracts, change reservations |
| `KV` | Validation | Contract change validation, discount verification, fee checks |
| `AC` | Accounting | Price calculations, accounting mappings, 050 app call validation |
| `CH` | Billing | Delinquency forwarding, payment agency data, sales authorization |
| `DK` | Delivery | Corporate delivery import, logistics file generation |
| `SC` / `SCEM` | Service Orders | Mobile order data extraction, EM move imports |
| `FU` | Frontend | E-front login block registration |
| `KU` | K-Opticom unified | Case information sharing |
| `TU` | Telephone services | NTT application results |
| `WC` | Watch control | Viewing change control |

**Customer lifecycle example:**

1. **New customer signs up** -- `KK` registers the course/service change; `KV` validates discount eligibility and temporary fees; `AC` calculates the accounting price.
2. **Customer changes course** -- `KK` processes the change; `KV` re-validates; `AC` recalculates pricing.
3. **Customer defaults** -- `CH` registers post-delinquency forwarding; `DK` may generate delivery notices.
4. **Customer moves** -- `SC`/`SCEM` imports move data; `KK` updates service contracts.

The **KV (validation) domain** is particularly cross-cutting. It implements a three-mode interface (`mastProcFlg`, `matchProcFlg`, `tranProcFlg`) and can be invoked as part of any KK course change or contract modification workflow to ensure pricing, discounts, and fees are correct before the change takes effect. This makes KV a gatekeeper that sits between data entry and data persistence across the system.

## Key Patterns and Architecture

### Service Class Lifecycle

All 2,461 service classes extend `JBSbatBusinessService` and follow a uniform three-phase lifecycle:

```mermaid
flowchart TD
    A["JBSbatBusinessService
Base class"] --> B["initial()"]
    B --> C["execute()"]
    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()"]

    subgraph Setup
        B
    end
    subgraph Processing
        C
        D
        E
        F
    end
    subgraph Cleanup
        H
    end
    B -->|calls| C
    C -->|populates| D
    D -->|uses| E
    D -->|uses| F
    E -->|writes| G
    F -->|writes| G
    G -->|calls| H
```

- **`initial(JBSbatCommonItem)`** -- Instantiates `JBSbatSQLAccess` for each table used, reads `freeItem` parameters (typically semicolon-delimited file paths and processing flags), and initializes working variables.
- **`execute()`** -- Reads input (flat files or database queries), validates records, applies business rules, updates the database, and writes output files. Returns a `JBSbatOutputItem` with results.
- **`terminal()`** -- Closes all `JBSbatSQLAccess` objects and logs summary statistics. Failure to close SQL access objects can leave database connections open, causing resource exhaustion.

### Three Common Processing Patterns

**Pattern 1: Simple File-Based Transform**

The majority of service classes follow a straightforward read-process-write pattern:

```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"]
```

Representative examples include `JBSbatACKaikPrcCalc` (accounting price calculation) and `JBSbatAC050ApKoInfInputChk` (050 app call validation).

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

Classes implementing `JBSbatMatchServiceInterface` support phased batch execution. By controlling `mastProcFlg`, `matchProcFlg`, and `tranProcFlg` via `freeItem` parameters, the same class can be run in different modes: mast (process reference/master data), match (match input against master data), or tran (process transaction data). `JBSbatKVWribVrfyChokiInfo` (discount verification) is a key example.

**Pattern 3: Complex Multi-Table Operations**

Some service classes, like `JBSBatKKCrsChgIktAdd` (course change batch registration), touch 15+ database tables and implement intricate workflows involving service contracts, price courses, address changes, delivery work, and workflow management. These can span nearly 2,000 lines and demonstrate the system's ability to orchestrate multi-step business processes atomically within a single batch run.

### Naming Convention

Class names encode both domain and operation type:

| Prefix | Domain | Example |
|--------|--------|---------|
| `AC` | Accounting | `JBSbatACKaikPrcCalc` -- accounting price calculation |
| `CH` | Billing | `JBSBatCHDslAfMvTkskInfIktAdd` -- post-delinquency forwarding |
| `KK` | Core services | `JBSBatKKCrsChgIktAdd` -- course change registration |
| `KV` | Validation | `JBSbatKVCheckKicjkn` -- contract change temporary fee check |
| `DK` | Delivery | `JBSBatDKHjHaisoInfoAdd` -- corporate delivery import |
| `SC` | Service Order | `SCUqsodDataCst` -- UQ-SOD data extraction |

Operation suffixes indicate the type of work: `Trkm` (import), `Chsht` (extract), `IktAdd` (batch registration), `Saksi` (create), `Add` (register), `Upd` (update), `Chk` (check), `Calc` (calculation).

### Cross-Cutting Validation (KV)

The KV domain operates as a cross-cutting concern. When any contract change occurs, KV validates:

- Discount eligibility (long-term use, immediate, family pack, hybrid, installment, campaign overlap, set discounts)
- Fee correctness (temporary fees, over-generation checks)
- Billing option charge periods
- Date setting validity
- Service contract start-point accuracy

This ensures business rules are enforced consistently regardless of the entry point.

### File Validation Pattern

Input file validation uses `isSingleCheckXX()` methods (e.g., `isSingleCheckCHIFM336()`, `isSingleCheckKKIFM714()`). These accept `HashMap rsMap` and `HashMap itemvalueMap` parameters and check field lengths, formats, ranges, and referential integrity. Error codes follow the pattern `<DOMAIN><FILE_CODE>` (e.g., `ACIFM075`, `CHIFM336`).

## Dependencies and Integration

### Internal Dependencies

| Import | Purpose |
|--------|---------|
| `JBSbatBusinessService` | Base class for all service classes |
| `JBSbatSQLAccess` | Database access wrapper (SQL definitions abstracted) |
| `JBSbatServiceInterfaceMap` | In-memory record map for passing data between processing steps |
| `JBSbatCommonDBInterface` | DB result iteration interface |
| `JBSbatInputFileUtil` / `JBSbatOutputFileUtil` | Flat file I/O |
| `*IFM` / `*IFE` file classes | Flat file format definitions (one per domain) |
| `JBSbatKK_T_SVC_KEI` | Table column definitions for service contracts |

### Cross-Module Integration

The `eo.business.service` 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`) for user-facing interaction

### External System Integration

Batches communicate with external systems through:

- **FTP file exchange** -- Sending and receiving files with partners
- **ESB** -- Enterprise service bus calls via `JCCBatchEsbInterface`
- **ClearPath** -- Credit card authorization via `JKKBatClarisAuthCrdt`
- **Claris** -- Financial processing
- **IBUKI** -- Billing system
- **CASE / SPRI** -- Support case and partner file delivery

### Key Database Tables

| Prefix | Domain | Examples |
|--------|--------|---------|
| `KK_T_SVC_KEI` | Service contracts | Main service contract table |
| `KK_T_SEIKY_KEI` | Billing contracts | Billing contract records |
| `KK_M_PCRS` | Price courses | Price course definitions |
| `KK_T_IDO_RSV` | Change reservations | Course change reservations |
| `KK_T_DSL_AF_TNKYS_IF` | Post-delinquency forwarding | Forwarding addresses |
| `KK_T_KICJKN` | Temporary fees | Contract temporary fees |
| `CH_T_TOKUSOKU` | Special notes | Customer remarks |
| `SC_T_MOBILE_ORDER` | Mobile orders | Service order data |
| `DK_T_HAISO` | Delivery | Delivery records |
| `ZM_M_SYS_PARAM_KNRI` | System parameters | Batch configuration |

All database access goes through `JBSbatSQLAccess`, which wraps SQL definitions (e.g., `CH_SELECT_017`, `KK_INSERT_002`) defined centrally in the framework.

## Notes for Developers

### Batch Lifecycle Requirements

Every service class must implement three methods correctly:

1. **`initial(JBSbatCommonItem)`** -- Must call `super.setCommonInfo(commonItem)` and set up all `JBSbatSQLAccess` instances.
2. **`execute(...)`** -- Must return `JBSbatOutputItem` (or `void` in some variants) with processing results.
3. **`terminal()`** -- Must call `super.terminal()` and close all `JBSbatSQLAccess` objects. Failure to close SQL access objects can leave database connections open, causing resource exhaustion.

### Monetary Calculations

Always use `BigDecimal` for monetary values, never `double`. Helper methods like `addDecimalPoint()` and `deleteDecimalPoint()` handle position-based decimal placement for fixed-format files. The constant `BIGDECIMAL_100` is commonly used for percentage-based adjustments.

### File Encoding

Historical versions had encoding issues (EUC-JP vs UTF-8). New code should be aware of the encoding expected by each file format. The version history of `JBSbatAC050ApKoInfInputChk` documents several encoding fixes.

### Thread Safety

These classes are not thread-safe. Each batch invocation creates new instances. Do not share state between concurrent executions.

### FreeItem Parameter

The `freeItem` parameter is a semicolon-delimited string. Its structure (order and meaning of elements) is domain-specific. Consult existing similar classes before defining a new format.

### Deferred Processing

Some batches support delayed processing (`CC_T_DLYD_TRN_REQ`). When a record cannot be processed immediately due to a transient error, it is queued for retry rather than failing outright. This is particularly important for payment and billing operations that depend on external system availability.

### 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 SQL definitions in the framework's SQL definition files
9. Create IFM/DEF file definition files for any flat file I/O

### Domain-Specific Conventions

- **`sysWkTime`** -- Used for current date/time comparisons; most validation batches reject future-dated records by comparing against `sysWkTime` (online date + system time).
- **`opeDate`** -- The operation date for the batch run; tracked in the base class.
- **`onlineOpeDate`** -- The online date for real-time reference; distinct from the batch operation date.
- **`tmpKaikPrcSnstWayList`** -- Cached accounting price calculation methods, used as a lookup map during transform operations.

### Common Constants and Utilities

| Source | Usage |
|--------|-------|
| `JPCBatchMessageConstant` | Batch message codes |
| `JACStrConst` | String constants |
| `JKKBatConst` / `JBSbatKKConst` | KK-domain constants |
| `JCCBatCommon` | Common batch utilities |
| `JACbatDebugLogUtil` | Debug logging |
| `JACbatParamUtil` | Business parameter access |
| `JCHStringUtil` | String manipulation utilities |
