# Eo / Business

## Overview

The `eo.business` package is the core business processing layer of the **eo customer base system** (eo顧客基幹システム), a massive Java batch processing framework used by K-Opticom for telecommunications customer management. At its heart is the `eo.business.service` sub-package, which contains over 2,400 batch service classes spanning dozens of functional domains -- billing, pricing, course changes, delivery logistics, service orders, validation, and customer account management.

This is not a web-oriented or real-time system. Instead, it is a **scheduled batch processing engine** that runs nightly or at regular intervals. Each batch reads input files or queries databases, applies complex business rules, writes output files, and updates the database. It is built on the JBSbat framework, which provides a standardized lifecycle: `initial()` (setup) → `execute()` (business logic) → `terminal()` (cleanup).

## Sub-module Guide

### Service (`eo.business.service`)

The `service` package is the largest and most important sub-module within `eo.business`. It contains the 2,461 batch service classes that perform essentially all business logic in the system. Each service class follows a uniform three-phase lifecycle and is named according to a strict convention that encodes both the functional domain and the operation type.

The service module can be understood as several **functional domains**, each prefixed by a two-letter code:

| Prefix | Domain | What it handles |
|--------|--------|-----------------|
| `AC` | Accounting, pricing | Price calculations, accounting mappings, 050 app call validation |
| `CH` | Billing, charges | Delinquency forwarding, payment agency data, sales authorization |
| `KK` | Core services | Course changes, service contracts, change reservations |
| `KV` | Validation | Contract change validation, discount verification, fee checks |
| `DK` | Delivery | Corporate delivery import, logistics file generation |
| `SC` | Service Orders | Mobile order data extraction, EM move imports |
| `SCEM` | i-mobile | EM-specific contract move data |
| `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 |

### How the domains interact

The domains do not operate in isolation. A single customer lifecycle touches multiple domains:

1. **A new customer signs up** → `KK` (course/service change registration) creates the service contract; `KV` (validation) checks discount eligibility and temporary fees.
2. **A customer changes their course** → `KK` processes the course change; `KV` re-validates discount eligibility; `AC` recalculates accounting prices.
3. **A customer defaults on payment** → `CH` registers post-delinquency forwarding info; `DK` may generate delivery notices.
4. **A customer moves (EM)** → `SC` / `SCEM` imports the move data; `KK` updates service contracts accordingly.

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.

## Key Patterns and Architecture

### Service Class Lifecycle

All 2,461 service classes extend `JBSbatBusinessService` and follow this lifecycle:

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

- **`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.

### Processing Patterns

Three common processing patterns recur across the service domain:

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

The majority of service classes follow a straightforward read-process-write pattern. Input files are validated field-by-field using `isSingleCheckXX()` methods, transformed according to business rules, and written back out as output files or stored in the database.

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

`JBSbatACKaikPrcCalc` (accounting price calculation) and `JBSbatAC050ApKoInfInputChk` (050 app call validation) are representative examples -- they read input, validate, transform, and write output with minimal state.

#### 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
- **tran** -- Process transaction data

`JBSbatKVWribVrfyChokiInfo` (discount verification) is a key example, used to validate long-term-use and immediate discount eligibility.

#### 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 classes are the most complex, sometimes spanning nearly 2,000 lines. They 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 Concerns

The KV (validation) domain operates as a cross-cutting concern across the system. When any contract change occurs (typically in the KK domain), the KV domain 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 that business rules are enforced consistently regardless of the entry point.

## Dependencies and Integration

### Internal Framework Dependencies

The service layer depends on a rich ecosystem of framework classes, all within the `eo.business` and `eo.framework` packages:

| 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

### Database Tables

The service layer interacts with a rich schema. Key table prefixes:

| 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.

### 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`).

### 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

### 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 |

### 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.
