<!--
  This file was generated by CodianoAI. It may contain occasional mistakes.
  Human review is advised for any critical information.
-->

# CardDemo Mainframe Credit Card Management – Architectural Specification

---

## 1. Introduction

**Purpose and High-Level Functionality**

CardDemo is a mainframe credit card management application designed to simulate a realistic production environment for mainframe migration and modernization exercises. The system supports account, card, transaction, customer, and user management; credit card authorization flows; reporting; and batch processing. It is engineered to run in a mainframe environment and support technology demonstrations for transaction processing, batch workflows, security, modern file/database paradigms, messaging middleware, and hybrid integration.

**Primary Goals and Intended Outcomes**

- Provide a functional demonstration environment for mainframe modernization and migration.
- Enable stakeholders to observe, measure, and validate migration techniques across transaction processing, batch, security, and data integration workloads.
- Support various data access and integration patterns used in mainframe banking applications, including hierarchical, relational, and messaging-based flows.
- Enable consistent reproduction for regression testing, automation, and modernization tool validation.
- Enable simulation of real-world credit card authorization processing, including integrations with IMS DB, DB2, and MQ, mirroring production-grade financial system requirements.

---

## 2. Functional Requirements

**Overview**

CardDemo provides both online (interactive/transactional via CICS) and batch (JCL/COBOL) functionalities, covering the life cycle of credit card operations, as well as extensible flows for authorization and fraud marking. The application includes administrative, user, and integration use cases.

### Functionalities, Inputs, Processes, Outputs, and User Interactions

#### 2.1. User Sign-on and Security

- **Input:** User enters User ID and Password on the logon screen.
- **Process:** Credential validation against a VSAM-based User Security dataset.
- **Output:** Access granted to Main Menu or Admin Menu based on user role, or an error message.

#### 2.2. Main Menu Navigation (Regular User)

- **Input:** Navigates using command keys or menu selection values.
- **Process:** Presents options for:
  - Account View/Update
  - Credit Card List/View/Update
  - Transaction List/View/Add
  - Bill Payment
  - Transaction Reports
  - Additional options if enabled (e.g., Pending Authorizations)
- **Output:** Corresponding functional screen or report.

#### 2.3. Admin Menu (Admin User)

- **Input:** Admin credentials at sign-on, navigation similar to the regular user menu.
- **Process:** Presents all user-level options plus:
  - User management: List/Add/Update/Delete user records
  - Transaction Type management: Add/Update/Delete Transaction Types (with DB2/VSAM)
- **Output:** Administrative screens leading to business transaction screens.

#### 2.4. Account Management (View/Update)

- **Input:** Account ID (key); updated account details.
- **Process:** Reads/Updates the Account VSAM file; relates Account-ID to Customer-ID via Card XREF.
- **Output:** Account details display or update status/error.

#### 2.5. Credit Card Management

- **List Cards:**  
  - **Input:** Optionally filtered by Account-ID.
  - **Process:** Browse VSAM Card Data file (with indexed and alternate index access).
  - **Output:** Paginated list of cards.
- **View Details:** Keyed by Card Number and Account-ID.
- **Update Card:** Field-level edit and update; enforces business and data validations.

#### 2.6. Transaction Management

- **List Transactions:**
  - **Input:** Optionally filtered by Transaction-ID; supports pagination.
  - **Process:** Browse VSAM Transaction data; loads 10 records per display page.
  - **Output:** List of transactions for selection.
- **View Transaction:** Selection of Transaction displays full transaction record.
- **Add Transaction:**
  - **Input:** Transaction data via screen.
  - **Process:** Field validations, creates new transaction record in VSAM file.
  - **Output:** Confirmation message with new Transaction ID, or error.

#### 2.7. Bill Payment

- **Input:** Account ID; confirmation prompt for full balance payment.
- **Process:** Fetches Account, presents current balance; on confirmation, creates a 'Bill Payment' transaction and deducts the amount from account balance; updates VSAM files.
- **Output:** Confirmation and updated account balance.

#### 2.8. User Management (Admin Only)

- List Users (Paginated list, with select/update/delete options).
- Add User: Inputs User ID, First/Last Name, Password, Role (User/Admin).
- Update User: Edits First/Last Name, Password, Role.
- Delete User.
- **Process:** CRUD operations on the user security file (VSAM Keyed dataset).

#### 2.9. Transaction Type Management (DB2-Enabled)

- **List Transaction Types:** With cursor-based navigation, DB2-backed data.
- **Add/Update/Delete Transaction Types:** Field-level validation; real-time CRUD against DB2 table(s) (CARDDEMO.TRANSACTION_TYPE and CARDDEMO.TRANSACTION_TYPE_CATEGORY).
- **Batch Import/Export:** Batch tools to sync transaction types/categories to/from DB2, with unload to VSAM/PS, supports reporting and alignment between VSAM and DB2.
- **Input:** Fields for transaction type code and description.
- **Output:** Confirmation, cursor-based screen with paging, error or status messages.

#### 2.10. Credit Card Authorization Extensions (IMS DB, DB2, MQ)

- **Real-time Authorization via MQ:**
  - **Input:** MQ message containing authorization request fields (see Data Models).
  - **Process:** Cloud/remote POS emulator sends request; MQ triggers CICS (COPAUA0C) which retrieves account and customer data, applies business rules, and sends response to reply MQ queue.
  - **Output:** MQ reply message (see Data Models); response available to POS emulator.
- **Authorization Records Storage:** All authorization details are persisted in IMS hierarchical database (root: summary, child: detail).
- **Fraud Detection & Reporting:**
  - Mark authorization as fraudulent/non-fraudulent via dedicated CICS flows.
  - Fraud records stored in DB2 (CARDDEMO.AUTHFRDS), supporting both insert and update actions.
- **Authorization Management via CICS UI:**
  - View list of pending authorizations by account with paging (COPAUS0C/CPVS).
  - Navigate to authorization detail (COPAUS1C/CPVD).
  - PF5: Mark or remove fraud flag, which updates IMS DB and DB2.
  - PF7/PF8: Scroll through authorization list and detail screens.
- **Batch Purging of Authorizations:** Periodically remove expired authorizations, adjusting credit as needed.

#### 2.11. Account Extraction Using MQ

- **Query System Date or Account Details via MQ:** Asynchronous, message-driven flows allow remote systems to request system information or account details using designated MQ queues; COACCT01 and CODATE01 programs handle these requests, reply via MQ.

#### 2.12. Reporting

- **Transaction Reports:** Batch-produced, filterable by month/year or custom; jobs submit JCL from CICS, outputs to datasets.
- **Transaction Statements:** Available in both text and HTML; batch jobs output statements to sequential datasets.
- **Custom Data Extracts:** Used for backup, archiving, data migration; batch jobs can extract both transaction and reference data (e.g., transaction type/category).

#### 2.13. Batch Processing

- **Data Initialization:** Loads base files and sample data; sequence of JCL steps/joined control cards for environment setup.
- **Daily Batch Processing:** Posts pending and daily transactions, calculates interest, updates balances, produces reports.
- **Purge and Maintenance Jobs:** 
  - Purge expired authorizations (CBPAUP0C/BMP-IMS job).
  - Backup/restore of datasets, index (AIX) creation, merge operations between daily and master datasets.

---

## 3. Non-Functional Requirements

### Performance

- Must handle typical mainframe CICS transaction rates. Paging is implemented for all record lists.
- Batch jobs must achieve acceptable throughput for data files sized to simulate realistic test environments.
- Real-time authorization MQ flows must process a high concurrency of inbound requests with sub-second average response (targeted for demonstration workloads).

### Scalability

- Supports parallel execution of CICS transactions; modular batch jobs allow for file partitioning to scale batch workloads.
- VSAM alternate indexes, DB2 secondary indexes, and IMS HIDAM structure ensure efficient access paths for key-driven and list operations.
- MQ-based interfaces support horizontal scaling across messaging clients and producers.

### Maintainability

- Source structured with standard mainframe code and copybook separation.
- All record layouts, common screen fields, validation logic, and utility subroutines are factored into reusable copybooks.
- Layered approach for UI, business logic, and data access enables independent enhancements.

### Security

- User authentication and authorization are enforced via User Security VSAM datasets.
- Functionality is gated by user/admin role distinction; administrative features require explicit role assignment.
- RACF integration is provided for enhanced dataset and transaction-level security; example JCLs included.
- Fraud detection and audit marking are governed by authorization and data protection rules as in financial systems.

### Constraints / Limitations

- Requires mainframe environment with CICS, VSAM, JCL, batch processing support.
- Optional features require DB2, IMS DB, and MQ; not all modules accessible without these subsystems.
- No web/distributed/non-mainframe user interface is provided.
- Database, batch, and MQ flows use simulation-scale data, not production-sized inputs.
- Cloud client for MQ-based authorization is not supplied, but message format is fully documented for interoperability.

---

## 4. System Architecture Overview

### System Overview

- CardDemo is a monolithic, yet modular, mainframe application orchestrating interactive CICS, batch, and messaging workflows alongside relational (DB2), hierarchical (IMS DB), and file-based (VSAM) data storage.
- The architecture enables both legacy patterns (VSAM transaction batches, CICS screens) and modern integration flows (DB2 CRUD, MQ-driven requests, hybrid IMS/DB2 commits).

### Architecture Patterns

- **Transactional Processing Pattern:** All interactive UI and business flows via CICS transactions with BMS mapsets and modularized COBOL programs.
- **Batch Processing Pattern:** All background processes initiated by JCL, executed via COBOL/assembler, and operate on VSAM/flat files.
- **Layered Architectural Pattern:** Presentation (BMS), business logic (modular programs), and data access (VSAM, DB2, IMS, MQ) are clearly separated.
- **Data Integration Pattern:** MQ-driven entry points allow asynchronous and decoupled external integration, with IMS, DB2, and VSAM as persistence targets.
- **Request/Response Messaging:** MQ-based interactions for inbound/outbound credit card authorization and account queries.
- **ETL Pattern:** Cross-database/file extracts (e.g., DB2-to-VSAM for transaction type/category), batch transformations, and periodic synchronization.

### Design Patterns

- **Command Pattern:** Each CICS transaction as a discrete command boundary.
- **Cursor-Based Paging:** Online DB2 flows (e.g., transaction type listing) use cursor-driven paging for large lists.
- **Role-Based Access Control:** Enforcement of admin/user privileges at screen and business logic layers.
- **Composite-Extension Pattern:** Modular optional flows (authorization, fraud, MQ interfaces) do not affect core if subsystem is disabled.

### Main Architectural Components and Roles

- **CICS Programs:** All interactive user functions and business logic, including card management, user management, transaction flows, and authorization management.
- **Batch COBOL Programs:** All jobs for reporting, population, extract, maintenance, and purge functions.
- **Assembler Modules:** Utility routines for date, timing, low-level systems interactions (e.g., MVSWAIT).
- **VSAM Datasets:** Store primary business data: accounts, cards, transactions, user data, cross-references.
- **DB2:** Persistent store for transaction type reference/master data, transaction categories, and fraud marking records (AUTHFRDS).
- **IMS DB:** Hierarchical database (HIDAM) for credit card authorization summaries (root) and details (child); supports reporting and real-time integration flows.
- **MQ:** Messaging middleware for asynchronous flows including authorization requests/responses, and account/date queries.
- **RACF:** System security layer, with sample integration for transaction, dataset, and user protection.

### Technology-Stack / Framework Choices

- **Languages:** COBOL (core, CICS, batch); Assembler (utilities).
- **Online Transaction Processing:** CICS (BMS maps, COBOL programs, mapsets).
- **Batch Processing:** JCL for orchestration, job procs for standardization.
- **File Storage:** VSAM (KSDS, ESDS, RRDS, AIX); sequential datasets for backups and extracts.
- **Database:** DB2 for reference/lookup/fraud data; IMS DB for hierarchical authorization summaries and detail.
- **Messaging/Integration:** MQ for input/output queues, request/response, and triggers.
- **Security:** RACF integrated (via sample JCL).
- **Screen Layouts:** BMS macros for all interactive UI.

---

## 5. Component Relationships

- All core business data, including accounts, cards, transactions, user credentials, are stored in VSAM files. CICS and batch programs use keyed and alternate index access.
- CICS front-end programs can submit batch JCL (for reports/statements) via extra-partition transient data queues.
- User authentication determines available menu and function set (user/admin).
- Transaction type and category management uses DB2 as the system of record, with extract/sync to VSAM for reporting.
- MQ interfaces enable asynchronous processing for both authorization (POS emulation) and other account/date queries, with CICS programs (e.g., COPAUA0C) acting as MQ triggers.
- IMS DB holds hierarchical authorization records; CICS/COBOL programs participate in two-phase commit with DB2 and IMS.
- The fraud marking of authorizations in DB2 is linked to actions in CICS authorization detail flows.
- Batch and real-time processing are strictly separated but communicate via shared datasets and standardized data layouts.

### Integration Patterns Used

- Copybooks enforce uniform record layouts and field mappings across all programs and access points.
- Database/file synchronization (DB2 to VSAM) for reporting and operational alignment.
- MQ-driven request/response flows for external integration, real-time authorizations.
- Cursor/array-based data access for paged list screens.
- Assembler routines called from COBOL for system utilities.
- Two-phase commit protocols used when updating both DB2 and IMS in fraud flows.

---

## 6. Data Flow

### 6.1. Data Storage and Retrieval

- **VSAM (KSDS):** All business data (accounts, cards, transactions, users, cross-references) primary storage; AIX used for alternate keys.
- **DB2:** Stores transaction type master (TR_TYPE), type category (TRC_TYPE_CATEGORY), and fraud-tracking records (AUTHFRDS).
- **IMS DB (HIDAM):** Root segment: authorization summary (PAUTSUM0). Child segment: authorization detail (PAUTDTL1). HIDAM index for efficient lookup by key.
- **MQ:** Inbound queues for authorization and data requests, outbound for replies.

### 6.2. Data Processing and Transformation

- All record layouts, including IMS segments and DB2 tables, defined as COBOL copybooks for serialization and structural parity.
- ETL batch jobs to synchronize DB2 and VSAM reference data daily or per schedule.
- Authorization processing parses inbound MQ CSV-string messages, validates fields, and applies business rules before persisting in IMS/DB2 and responding on MQ.
- Cursor-based handling for online paginated screens over DB2 tables.

### 6.3. Data Validation and Error Handling

- Online screens: Real-time field validation with context-sensitive error messages and field-level highlighting.
- All batch and integration jobs: Status/error code checking; message construction for MQ error replies or CICS TDQ logging.
- Utilities for date validation, required/numeric/alphanumeric field checking, and cross-field dependencies.

### 6.4. Data Security and Privacy

- User credentials and roles stored in VSAM User Security datasets; checked on sign-on and for all sensitive actions.
- Administrative flows protected by role gates and menu isolation.
- Optionally, RACF enforces security at the dataset and transaction level.
- No sensitive data leaves the system except via explicitly designed extract jobs.
- Fraud marking requires explicit user (typically admin) action; audit trail persisted in DB2.

### 6.5. Data Synchronization, Backup, and Archiving

- Daily extracts synchronize DB2 transaction type/category to VSAM and sequential datasets to align reporting and online screens.
- Batch jobs back up VSAM files to sequential datasets (GDG for rolling generations); purge and maintenance batch flows.
- Re-initialization scripts and jobs support repeatable environment resets for regression or demonstration.
- GDG datasets used for controlled data retention for reports, statements, and backups.

### 6.6. Data Models (Authorization Extension)

- **Authorization Request (MQ Input, CSV):**
  - AUTH-DATE, AUTH-TIME, CARD-NUM, AUTH-TYPE, CARD-EXPIRY-DATE, MESSAGE-TYPE, MESSAGE-SOURCE, PROCESSING-CODE, TRANSACTION-AMT, MERCHANT-CATAGORY-CODE, ACQR-COUNTRY-CODE, POS-ENTRY-MODE, MERCHANT-ID, MERCHANT-NAME, MERCHANT-CITY, MERCHANT-STATE, MERCHANT-ZIP, TRANSACTION-ID
- **Authorization Response (MQ Output, CSV):**
  - CARD-NUM, TRANSACTION-ID, AUTH-ID-CODE, AUTH-RESP-CODE, AUTH-RESP-REASON, APPROVED-AMT
- **IMS DB Segments:**
  - PAUTSUM0 (summary, key ACCNTID): account/summary level per customer/account
  - PAUTDTL1 (child, key PAUT9CTS): per-authorization event detail (see CIPAUDTY.cpy for field breakdown)
- **DB2 AUTHFRDS Table:** Fraud marking records including all request/response/merchant/amount fields, fraud status, report date, account and customer IDs.

---

## 7. Key Design Decisions

### Important Architectural Decisions and Rationale

- **VSAM as Core Storage:** Central for mainframe workload realism and modernization tool coverage.
- **Multi-Model Data Architecture:** Combination of VSAM, IMS DB (hierarchical), and DB2 (relational) mirrors real banking IT landscapes.
- **Role Separation and Security:** Functionality is strictly partitioned by user type and role; administrative functions segregated at both menu and data levels.
- **Paging and List Scalability:** All lists over VSAM or DB2 implement cursor-based or array-based paging.
- **Isolation of Optional Features:** DB2, IMS, and MQ modules are architected for optional deployment, with clear boundaries and no cross-impact.
- **Batch-Online Integration via TDQ:** CICS screens submit batch jobs through TDQ for seamless user-driven reporting and extract flows.
- **Copybook-Centric Design:** Ensures absolute field and structure parity across CICS, batch, IMS, and integration components.
- **Real-Time Messaging Integration (MQ):** Authorization and data requests are processed via MQ, with format and error handling designed for interoperability and demonstration.
- **Two-Phase Commit Transactions:** DB2 and IMS commits are coordinated in fraud flows to preserve transactional integrity.
- **Assembler/Utility Subroutines:** For high-precision timing or system services not exposed in standard COBOL.
- **Extensible Design for Modern Integration:** Structure supports extension with further hybrid flows or APIs as needed.

### Design Patterns Implemented

- Command, Layered, Cursor-Based Paging, CRUD, Role-Based Access, Request/Response, ETL, Table-Driven Menu, Two-Phase Commit for distributed data integrity.

### Scalability and Performance Considerations

- Indexed and alternate-indexed datasets enable efficient key/path access.
- All UI list flows are paginated to cap per-transaction data loads.
- Batch ETL, extract, and purge jobs are modular, supporting concurrency through dataset partitioning/locking.
- MQ/Messaging is used for scalable, asynchronous interfacing with external systems, controlled via process limits per transaction.

---

## 8. Deployment Architecture

### Recommended Deployment Topology

- **CICS Online Region:** Hosts all interactive COBOL programs and BMS mapsets, VSAM, and (as enabled) DB2, IMS, and MQ connectivity.
- **Batch Region:** Schedules and runs JCL-based jobs for data initialization, daily posting, reporting, backup, and batch ETL/synchronization jobs; may run in the same or distinct LPARs.
- **Datasets:**
  - VSAM clusters for all master data (accounts, cards, transactions, cross-references, user security).
  - Flat files and GDGs for batch input, output, reporting, backup, and statements.
- **Database Subsystems:**
  - **DB2:** For transaction types, categories, fraud tracking (AUTHFRDS).
  - **IMS DB:** For authorization summary/detail, HIDAM with separate data and index.
- **Messaging:** MQ managers configured for inbound (request) and outbound (reply) queues for authorization and query flows.
- **Security:** RACF profiles and permissions for datasets, programs, and transactions, able to be enabled or bypassed as test policies require.

### Infrastructure / Environment Requirements

- IBM mainframe LPAR with installed and configured CICS, VSAM, JCL, and batch management.
- VSAM and flat file storage pools for all datasets per defined naming conventions; PDS for program, job, and copybook sources.
- DB2 subsystem for reference and fraud tables, with required tablespace, indexes, and authorities.
- IMS DB subsystem for authorization, with DBD/PSB as specified.
- MQ subsystem(s) for queue/manager definition, routing, and monitored triggers for CICS program invocation.
- FTP/SFTP utilities as needed for extracts and integration, batch utility libraries.
- JCL procedures and sample jobs for all compilation, initialization, batch, and utility tasks.

### Environment Considerations

- All source components are managed in partitioned datasets with enforced naming conventions.
- CICS resource definitions for files, programs, mapsets, transactions, DB2 entry/plan, and MQ enablement installed and activated via sample JCL or CEDA commands.
- Initialization, backup, and maintenance jobs for all datasets and database tables are provided and scheduled via standard mainframe operations procedures.
- All IMS, DB2, and MQ integration points are parameterized for site portability.
- Application designed for repeatable initialization for demo, regression, and test automation.

---

This specification defines the consolidated, technology-agnostic architecture for CardDemo, integrating its advanced authorization extension, hybrid integration, and modernized core banking flows. All requirements, relationships, and decisions are directly traceable to the documented system artifacts and descriptions provided.