diff --git "a/modern_code/carddemo/service.py" "b/modern_code/carddemo/service.py" new file mode 100644--- /dev/null +++ "b/modern_code/carddemo/service.py" @@ -0,0 +1,3064 @@ +from __future__ import annotations + +import sqlite3 +import re +from contextlib import contextmanager +from datetime import datetime +from decimal import Decimal, InvalidOperation +from html import escape +from pathlib import Path +from typing import Any + +from .legacy_parser import money_to_display +from .repository import connect, row_to_dict, rows_to_dicts + + +CREDIT_TYPE_CODES = {"02", "03", "05", "06"} +INTEREST_DENOMINATOR = 120000 +POSTTRAN_REJECT_REASONS = { + 100: "INVALID CARD NUMBER FOUND", + 101: "ACCOUNT RECORD NOT FOUND", + 102: "OVERLIMIT TRANSACTION", + 103: "TRANSACTION RECEIVED AFTER ACCT EXPIRATION", +} +AUTH_DECLINE_REASONS = { + "0000": "APPROVED", + "3100": "CARD, ACCOUNT, OR CUSTOMER NOT FOUND", + "4100": "INSUFFICIENT FUNDS", + "4200": "CARD NOT ACTIVE", + "4300": "ACCOUNT CLOSED", + "5100": "CARD FRAUD", + "5200": "MERCHANT FRAUD", + "9000": "AUTHORIZATION ERROR", +} +REGULAR_MENU_OPTIONS = [ + {"option": 1, "name": "Account View", "transaction": "CAVW", "program": "COACTVWC", "user_type": "U"}, + {"option": 2, "name": "Account Update", "transaction": "CAUP", "program": "COACTUPC", "user_type": "U"}, + {"option": 3, "name": "Credit Card List", "transaction": "CCLI", "program": "COCRDLIC", "user_type": "U"}, + {"option": 4, "name": "Credit Card View", "transaction": "CCDL", "program": "COCRDSLC", "user_type": "U"}, + {"option": 5, "name": "Credit Card Update", "transaction": "CCUP", "program": "COCRDUPC", "user_type": "U"}, + {"option": 6, "name": "Transaction List", "transaction": "CT00", "program": "COTRN00C", "user_type": "U"}, + {"option": 7, "name": "Transaction View", "transaction": "CT01", "program": "COTRN01C", "user_type": "U"}, + {"option": 8, "name": "Transaction Add", "transaction": "CT02", "program": "COTRN02C", "user_type": "U"}, + {"option": 9, "name": "Transaction Reports", "transaction": "CR00", "program": "CORPT00C", "user_type": "U"}, + {"option": 10, "name": "Bill Payment", "transaction": "CB00", "program": "COBIL00C", "user_type": "U"}, + {"option": 11, "name": "Pending Authorization View", "transaction": "CPVS", "program": "COPAUS0C", "user_type": "U"}, +] +ADMIN_MENU_OPTIONS = [ + {"option": 1, "name": "User List (Security)", "transaction": "CU00", "program": "COUSR00C", "user_type": "A"}, + {"option": 2, "name": "User Add (Security)", "transaction": "CU01", "program": "COUSR01C", "user_type": "A"}, + {"option": 3, "name": "User Update (Security)", "transaction": "CU02", "program": "COUSR02C", "user_type": "A"}, + {"option": 4, "name": "User Delete (Security)", "transaction": "CU03", "program": "COUSR03C", "user_type": "A"}, + {"option": 5, "name": "Transaction Type List/Update", "transaction": "CTLI", "program": "COTRTLIC", "user_type": "A"}, + {"option": 6, "name": "Transaction Type Maintenance", "transaction": "CTTU", "program": "COTRTUPC", "user_type": "A"}, +] +US_STATE_CODES = { + "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", + "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", + "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", + "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", + "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY", + "DC", +} + + +class CardDemoService: + def __init__(self, db_path: Path): + self.db_path = Path(db_path) + + @contextmanager + def _connect(self): + conn = connect(self.db_path) + try: + yield conn + finally: + conn.close() + + def summary(self) -> dict[str, Any]: + with self._connect() as conn: + counts = {} + for table in ( + "customers", + "accounts", + "cards", + "card_xrefs", + "transactions", + "transaction_types", + "transaction_categories", + "disclosure_groups", + "transaction_category_balances", + "users", + "pending_authorization_summaries", + "pending_authorization_details", + "authorization_frauds", + ): + counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] + balances = conn.execute( + """ + SELECT + COALESCE(SUM(current_balance_cents), 0) AS current_balance_cents, + COALESCE(SUM(credit_limit_cents), 0) AS credit_limit_cents + FROM accounts + """ + ).fetchone() + return { + "counts": counts, + "portfolio": { + "current_balance": money_to_display(balances["current_balance_cents"]), + "credit_limit": money_to_display(balances["credit_limit_cents"]), + }, + "claim_limit": "capability ledger and static-oracle traces only; no all-path COBOL runtime proof yet", + } + + def list_customers(self, query: str = "", limit: int = 50) -> list[dict[str, Any]]: + like = f"%{query.strip()}%" + with self._connect() as conn: + rows = conn.execute( + """ + SELECT * FROM customers + WHERE ? = '%%' + OR CAST(customer_id AS TEXT) LIKE ? + OR first_name LIKE ? + OR last_name LIKE ? + OR zip_code LIKE ? + ORDER BY customer_id + LIMIT ? + """, + (like, like, like, like, like, int(limit)), + ).fetchall() + return rows_to_dicts(rows) + + def list_accounts(self, customer_id: int | None = None, limit: int = 50) -> list[dict[str, Any]]: + with self._connect() as conn: + if customer_id is None: + rows = conn.execute("SELECT * FROM accounts ORDER BY account_id LIMIT ?", (limit,)).fetchall() + else: + rows = conn.execute( + """ + SELECT a.* FROM accounts a + JOIN card_xrefs x ON x.account_id = a.account_id + WHERE x.customer_id = ? + GROUP BY a.account_id + ORDER BY a.account_id + LIMIT ? + """, + (customer_id, limit), + ).fetchall() + return [self._decorate_money(dict(row)) for row in rows] + + def get_account_bundle(self, account_id: int) -> dict[str, Any] | None: + with self._connect() as conn: + account = row_to_dict( + conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone() + ) + if not account: + return None + cards = rows_to_dicts( + conn.execute("SELECT * FROM cards WHERE account_id = ? ORDER BY card_number", (account_id,)).fetchall() + ) + customers = rows_to_dicts( + conn.execute( + """ + SELECT DISTINCT c.* FROM customers c + JOIN card_xrefs x ON x.customer_id = c.customer_id + WHERE x.account_id = ? + ORDER BY c.customer_id + """, + (account_id,), + ).fetchall() + ) + card_numbers = [card["card_number"] for card in cards] + transactions = self.list_transactions(account_id=account_id, limit=25) + return { + "account": self._decorate_money(account), + "customers": customers, + "cards": cards, + "transactions": transactions, + "card_numbers": card_numbers, + } + + def list_cards(self, account_id: int | None = None, customer_id: int | None = None) -> list[dict[str, Any]]: + with self._connect() as conn: + if account_id is not None: + rows = conn.execute("SELECT * FROM cards WHERE account_id = ? ORDER BY card_number", (account_id,)).fetchall() + elif customer_id is not None: + rows = conn.execute( + """ + SELECT c.* FROM cards c + JOIN card_xrefs x ON x.card_number = c.card_number + WHERE x.customer_id = ? + ORDER BY c.card_number + """, + (customer_id,), + ).fetchall() + else: + rows = conn.execute("SELECT * FROM cards ORDER BY card_number LIMIT 100").fetchall() + return rows_to_dicts(rows) + + def list_transactions( + self, + *, + account_id: int | None = None, + card_number: str | None = None, + limit: int = 100, + ) -> list[dict[str, Any]]: + with self._connect() as conn: + if account_id is not None: + rows = conn.execute( + """ + SELECT t.*, tt.description AS type_description, tc.description AS category_description + FROM transactions t + LEFT JOIN transaction_types tt ON tt.type_code = t.type_code + LEFT JOIN transaction_categories tc + ON tc.type_code = t.type_code AND tc.category_code = t.category_code + JOIN cards c ON c.card_number = t.card_number + WHERE c.account_id = ? + ORDER BY t.original_timestamp DESC, t.transaction_id DESC + LIMIT ? + """, + (account_id, limit), + ).fetchall() + elif card_number: + rows = conn.execute( + """ + SELECT t.*, tt.description AS type_description, tc.description AS category_description + FROM transactions t + LEFT JOIN transaction_types tt ON tt.type_code = t.type_code + LEFT JOIN transaction_categories tc + ON tc.type_code = t.type_code AND tc.category_code = t.category_code + WHERE t.card_number = ? + ORDER BY t.original_timestamp DESC, t.transaction_id DESC + LIMIT ? + """, + (card_number, limit), + ).fetchall() + else: + rows = conn.execute( + """ + SELECT t.*, tt.description AS type_description, tc.description AS category_description + FROM transactions t + LEFT JOIN transaction_types tt ON tt.type_code = t.type_code + LEFT JOIN transaction_categories tc + ON tc.type_code = t.type_code AND tc.category_code = t.category_code + ORDER BY t.original_timestamp DESC, t.transaction_id DESC + LIMIT ? + """, + (limit,), + ).fetchall() + return [self._decorate_money(dict(row)) for row in rows] + + def transaction_report( + self, + *, + start_date: str | None = None, + end_date: str | None = None, + account_id: int | None = None, + card_number: str | None = None, + limit: int = 1000, + ) -> dict[str, Any]: + clauses: list[str] = [] + params: list[Any] = [] + if start_date: + clauses.append("substr(t.processed_timestamp, 1, 10) >= ?") + params.append(start_date[:10]) + if end_date: + clauses.append("substr(t.processed_timestamp, 1, 10) <= ?") + params.append(end_date[:10]) + if account_id is not None: + clauses.append("c.account_id = ?") + params.append(account_id) + if card_number: + clauses.append("t.card_number = ?") + params.append(card_number) + where = f"WHERE {' AND '.join(clauses)}" if clauses else "" + params.append(int(limit)) + with self._connect() as conn: + rows = conn.execute( + f""" + SELECT t.*, c.account_id, tt.description AS type_description, tc.description AS category_description + FROM transactions t + JOIN cards c ON c.card_number = t.card_number + LEFT JOIN transaction_types tt ON tt.type_code = t.type_code + LEFT JOIN transaction_categories tc + ON tc.type_code = t.type_code AND tc.category_code = t.category_code + {where} + ORDER BY t.card_number, c.account_id, t.processed_timestamp, t.transaction_id + LIMIT ? + """, + params, + ).fetchall() + decorated = [self._decorate_money(dict(row)) for row in rows] + totals_by_account: dict[int, dict[str, Any]] = {} + totals_by_card: dict[str, dict[str, Any]] = {} + for row in decorated: + amount = int(row["amount_cents"]) + account_key = int(row["account_id"]) + card_key = str(row["card_number"]) + account_total = totals_by_account.setdefault( + account_key, {"account_id": account_key, "transaction_count": 0, "total_amount_cents": 0} + ) + card_total = totals_by_card.setdefault( + card_key, {"card_number": card_key, "account_id": account_key, "transaction_count": 0, "total_amount_cents": 0} + ) + account_total["transaction_count"] += 1 + account_total["total_amount_cents"] += amount + card_total["transaction_count"] += 1 + card_total["total_amount_cents"] += amount + for total in list(totals_by_account.values()) + list(totals_by_card.values()): + total["total_amount"] = money_to_display(total["total_amount_cents"]) + total_amount_cents = sum(int(row["amount_cents"]) for row in decorated) + return { + "report_name": "Transaction Detail Report", + "legacy_job": "TRANREPT", + "legacy_program": "CBTRN03C", + "filters": { + "start_date": start_date[:10] if start_date else None, + "end_date": end_date[:10] if end_date else None, + "account_id": account_id, + "card_number": card_number, + "limit": int(limit), + }, + "rows": decorated, + "totals": { + "transaction_count": len(decorated), + "total_amount_cents": total_amount_cents, + "total_amount": money_to_display(total_amount_cents), + "by_account": sorted(totals_by_account.values(), key=lambda item: item["account_id"]), + "by_card": sorted(totals_by_card.values(), key=lambda item: item["card_number"]), + }, + "claim_limit": "Matches legacy TRANREPT seed-data joins and date filter shape; exact printed page layout is not runtime-replayed", + } + + def account_statement(self, account_id: int) -> dict[str, Any]: + with self._connect() as conn: + account = row_to_dict(conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone()) + if not account: + raise KeyError("account not found") + xrefs = rows_to_dicts( + conn.execute( + """ + SELECT * FROM card_xrefs + WHERE account_id = ? + ORDER BY card_number, customer_id + """, + (account_id,), + ).fetchall() + ) + customers = rows_to_dicts( + conn.execute( + """ + SELECT DISTINCT c.* FROM customers c + JOIN card_xrefs x ON x.customer_id = c.customer_id + WHERE x.account_id = ? + ORDER BY c.customer_id + """, + (account_id,), + ).fetchall() + ) + statement_rows = rows_to_dicts( + conn.execute( + """ + SELECT t.*, c.account_id, tt.description AS type_description, tc.description AS category_description + FROM transactions t + JOIN cards c ON c.card_number = t.card_number + LEFT JOIN transaction_types tt ON tt.type_code = t.type_code + LEFT JOIN transaction_categories tc + ON tc.type_code = t.type_code AND tc.category_code = t.category_code + WHERE c.account_id = ? + ORDER BY t.card_number, t.transaction_id + """, + (account_id,), + ).fetchall() + ) + account = self._decorate_money(account) + statement_rows = [self._decorate_money(dict(row)) for row in statement_rows] + primary = customers[0] if customers else {} + + def fixed(value: Any, width: int) -> str: + return str(value or "").strip()[:width].ljust(width) + + def record(value: str) -> str: + return value[:80].ljust(80) + + def html_record(value: str) -> str: + return value[:100] + + def legacy_amount_z(cents: int) -> str: + amount = int(cents) + sign = "-" if amount < 0 else " " + dollars, pennies = divmod(abs(amount), 100) + return f"{dollars:>9}.{pennies:02d}{sign}"[-13:] + + def legacy_amount_9(cents: int) -> str: + amount = int(cents) + sign = "-" if amount < 0 else " " + dollars, pennies = divmod(abs(amount), 100) + return f"{dollars:09d}.{pennies:02d}{sign}"[-13:] + + customer_name = " ".join( + part for part in ( + primary.get("first_name", "").strip(), + primary.get("middle_name", "").strip(), + primary.get("last_name", "").strip(), + ) + if part + ) + city_state_zip = " ".join( + part + for part in ( + primary.get("address_line_3", "").strip(), + primary.get("state", "").strip(), + primary.get("country", "").strip(), + primary.get("zip_code", "").strip(), + ) + if part + ) + total_expense_cents = sum(int(row["amount_cents"]) for row in statement_rows) + transaction_lines = [ + record( + fixed(row["transaction_id"], 16) + + " " + + fixed(row["description"], 49) + + "$" + + legacy_amount_z(row["amount_cents"]) + ) + for row in statement_rows + ] + plain_text_lines = [ + "*" * 31 + "START OF STATEMENT" + "*" * 31, + fixed(customer_name, 75) + " " * 5, + fixed(primary.get("address_line_1", ""), 50) + " " * 30, + fixed(primary.get("address_line_2", ""), 50) + " " * 30, + fixed(city_state_zip, 80), + "-" * 80, + " " * 33 + fixed("Basic Details", 14) + " " * 33, + "-" * 80, + "Account ID :" + fixed(account["account_id"], 20) + " " * 40, + "Current Balance :" + legacy_amount_9(account["current_balance_cents"]) + " " * 47, + "FICO Score :" + fixed(primary.get("fico_score", ""), 20) + " " * 40, + "-" * 80, + " " * 30 + fixed("TRANSACTION SUMMARY", 20) + " " * 30, + "-" * 80, + fixed("Tran ID", 16) + fixed("Tran Details", 51) + " Tran Amount", + "-" * 80, + *transaction_lines, + "-" * 80, + "Total EXP:" + " " * 56 + "$" + legacy_amount_z(total_expense_cents), + "*" * 32 + "END OF STATEMENT" + "*" * 32, + ] + plain_text_lines = [record(line) for line in plain_text_lines] + card_numbers = sorted({str(xref["card_number"]) for xref in xrefs}) + html_lines = [ + "
", + f"

Account Statement {escape(str(account['account_id']))}

", + f"

{escape(customer_name)}

", + f"

Current Balance: {escape(account['current_balance'])}

", + "", + "", + *[ + "" + f"" + f"" + f"" + "" + for row in statement_rows + ], + "
Tran IDTran DetailsTran Amount
{escape(str(row['transaction_id']))}{escape(str(row['description'])[:30])}{escape(legacy_amount_z(row['amount_cents']).strip())}
", + f"

Total EXP: {escape(legacy_amount_z(total_expense_cents).strip())}

", + "
", + ] + html_lines = [html_record(line) for line in html_lines] + return { + "legacy_job": "CREASTMT", + "legacy_program": "CBSTM03A", + "legacy_programs": ["CBSTM03A", "CBSTM03B"], + "source_sort_key": "card_number,transaction_id", + "statement_lines_lrecl": 80, + "html_lines_lrecl": 100, + "account": account, + "customers": customers, + "card_numbers": card_numbers, + "statement_count": len(card_numbers), + "statement_rows": statement_rows, + "transaction_count": len(statement_rows), + "total_expense_cents": total_expense_cents, + "total_expense": money_to_display(total_expense_cents), + "plain_text_lines": plain_text_lines, + "html_lines": html_lines, + "claim_limit": "Plain statement records follow CBSTM03A fixed-width source flow and CBSTM03B keyed reads over seed records; HTML remains a bounded modern rendering, not a mainframe spool replay", + } + + def interest_projection(self, *, processing_date: str | None = None, limit: int = 1000) -> dict[str, Any]: + processing_date = (processing_date or datetime.utcnow().strftime("%Y-%m-%d"))[:10] + with self._connect() as conn: + rows = conn.execute( + """ + SELECT b.account_id, b.type_code, b.category_code, b.balance_cents, + a.group_id, c.card_number, + COALESCE(d.interest_rate_basis_points, fallback.interest_rate_basis_points, 0) + AS interest_rate_basis_points + FROM transaction_category_balances b + JOIN accounts a ON a.account_id = b.account_id + LEFT JOIN cards c ON c.account_id = b.account_id + AND c.card_number = ( + SELECT MIN(card_number) FROM cards c2 WHERE c2.account_id = b.account_id + ) + LEFT JOIN disclosure_groups d + ON d.group_id = a.group_id AND d.type_code = b.type_code AND d.category_code = b.category_code + LEFT JOIN disclosure_groups fallback + ON fallback.group_id = 'DEFAULT' AND fallback.type_code = b.type_code + AND fallback.category_code = b.category_code + ORDER BY b.account_id, b.type_code, b.category_code + LIMIT ? + """, + (int(limit),), + ).fetchall() + detail_rows: list[dict[str, Any]] = [] + account_totals: dict[int, dict[str, Any]] = {} + for raw in rows: + row = dict(raw) + balance_cents = int(row["balance_cents"]) + rate_bps = int(row["interest_rate_basis_points"]) + interest_cents = int((balance_cents * rate_bps) / INTEREST_DENOMINATOR) + detail = { + **row, + "balance": money_to_display(balance_cents), + "interest_rate_percent": f"{rate_bps // 100}.{rate_bps % 100:02d}", + "monthly_interest_cents": interest_cents, + "monthly_interest": money_to_display(interest_cents), + } + detail_rows.append(detail) + account_id = int(row["account_id"]) + total = account_totals.setdefault( + account_id, + { + "account_id": account_id, + "card_number": row.get("card_number") or "", + "category_count": 0, + "total_interest_cents": 0, + }, + ) + total["category_count"] += 1 + total["total_interest_cents"] += interest_cents + generated_transactions: list[dict[str, Any]] = [] + for account_id, total in sorted(account_totals.items()): + total["total_interest"] = money_to_display(total["total_interest_cents"]) + generated_transactions.append( + { + "transaction_id": f"INT{account_id:013d}", + "type_code": "01", + "category_code": "0005", + "source": "System", + "description": f"Int. for a/c {account_id}", + "amount_cents": total["total_interest_cents"], + "amount": total["total_interest"], + "card_number": total["card_number"], + "original_timestamp": f"{processing_date} 00:00:00.000000", + "processed_timestamp": f"{processing_date} 00:00:00.000000", + "account_id": account_id, + } + ) + total_interest_cents = sum(item["total_interest_cents"] for item in account_totals.values()) + return { + "legacy_job": "INTCALC", + "legacy_program": "CBACT04C", + "processing_date": processing_date, + "formula": "(transaction_category_balance * disclosure_interest_rate) / 1200", + "rows": detail_rows, + "account_totals": sorted(account_totals.values(), key=lambda item: item["account_id"]), + "generated_transactions": generated_transactions, + "totals": { + "account_count": len(account_totals), + "category_balance_count": len(detail_rows), + "total_interest_cents": total_interest_cents, + "total_interest": money_to_display(total_interest_cents), + }, + "claim_limit": "Uses TCATBALF and DISCGRP seed records plus CBACT04C formula; no legacy runtime trace attached", + } + + def combined_transactions(self, *, processing_date: str | None = None, limit: int = 1000) -> dict[str, Any]: + existing = self.transaction_report(limit=100000)["rows"] + interest = self.interest_projection(processing_date=processing_date)["generated_transactions"] + rows: list[dict[str, Any]] = [] + for row in existing: + rows.append({**row, "combine_source": "TRANSACT.BKUP(0)"}) + for row in interest: + rows.append({**row, "combine_source": "SYSTRAN(0)"}) + rows.sort(key=lambda row: str(row.get("transaction_id") or "")[:16]) + limited = rows[: int(limit)] + return { + "legacy_job": "COMBTRAN", + "legacy_program": "SORT", + "source_datasets": [ + "AWS.M2.CARDDEMO.TRANSACT.BKUP(0)", + "AWS.M2.CARDDEMO.SYSTRAN(0)", + ], + "sort": { + "symbol": "TRAN-ID", + "start": 1, + "length": 16, + "type": "CH", + "order": "A", + }, + "sortout_dataset": "AWS.M2.CARDDEMO.TRANSACT.COMBINED(+1)", + "repro_target": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "rows": limited, + "source_counts": { + "transaction_master": len(existing), + "interest_projection": len(interest), + "transact_bkup_current": len(existing), + "systran_current": len(interest), + "total_combined": len(rows), + "returned": len(limited), + }, + "claim_limit": "Models COMBTRAN SORTIN concatenation, TRAN-ID ascending sort, SORTOUT generation, and IDCAMS REPRO target over seed transactions and generated INTCALC previews", + } + + def transaction_master_backup(self, *, limit: int = 20) -> dict[str, Any]: + with self._connect() as conn: + rows = rows_to_dicts( + conn.execute( + """ + SELECT transaction_id, type_code, category_code, amount_cents, card_number + FROM transactions + ORDER BY transaction_id + """ + ).fetchall() + ) + limited = rows[: int(limit)] + return { + "legacy_job": "TRANBKP", + "legacy_proc": "REPROC", + "legacy_programs": ["REPROC", "IDCAMS"], + "source_dataset": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "backup_dataset": "AWS.M2.CARDDEMO.TRANSACT.BKUP(+1)", + "delete_targets": [ + "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX", + ], + "define_cluster": { + "name": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "keys": {"length": 16, "offset": 0}, + "record_size": {"min": 350, "max": 350}, + "organization": "INDEXED", + "shareoptions": "2 3", + }, + "lrecl": 350, + "record_count": len(rows), + "preview_records": [ + { + **row, + "record_length": 350, + "key": str(row["transaction_id"])[:16], + "amount": money_to_display(row["amount_cents"]), + } + for row in limited + ], + "claim_limit": "Models TRANBKP REPROC backup, IDCAMS delete tolerance, and KSDS redefine metadata over the modern transaction master; no physical VSAM cluster is created", + } + + def transaction_type_extract(self) -> dict[str, Any]: + with self._connect() as conn: + type_rows = rows_to_dicts( + conn.execute("SELECT type_code, description FROM transaction_types ORDER BY type_code").fetchall() + ) + category_rows = rows_to_dicts( + conn.execute( + """ + SELECT type_code, category_code, description + FROM transaction_categories + ORDER BY type_code, category_code + """ + ).fetchall() + ) + type_records = [ + f"{row['type_code'][:2].ljust(2)}{row['description'][:50].ljust(50)}{'0' * 8}" + for row in type_rows + ] + category_records = [ + f"{row['type_code'][:2].ljust(2)}{row['category_code'][:4].ljust(4)}{row['description'][:50].ljust(50)}{'0' * 4}" + for row in category_rows + ] + return { + "legacy_job": "TRANEXTR", + "legacy_program": "DSNTIAUL", + "legacy_plan": "DSNTIAUL", + "db2_system": "DAZ1", + "backup_datasets": { + "transaction_types": "AWS.M2.CARDDEMO.TRANTYPE.BKUP(+1)", + "transaction_categories": "AWS.M2.CARDDEMO.TRANCATG.PS.BKUP(+1)", + }, + "output_datasets": { + "transaction_types": "AWS.M2.CARDDEMO.TRANTYPE.PS", + "transaction_categories": "AWS.M2.CARDDEMO.TRANCATG.PS", + }, + "record_layouts": { + "transaction_types": "TR_TYPE || CHAR(TR_DESCRIPTION,50) || 8 zero filler bytes", + "transaction_categories": "TRC_TYPE_CODE || TRC_TYPE_CATEGORY || CHAR(TRC_CAT_DATA,50) || 4 zero filler bytes", + }, + "lrecl": 60, + "records": { + "transaction_types": type_records, + "transaction_categories": category_records, + }, + "counts": { + "transaction_types": len(type_records), + "transaction_categories": len(category_records), + }, + "claim_limit": "Models TRANEXTR DSNTIAUL fixed-width extracts and GDG backup/output datasets over SQLite transaction reference tables", + } + + def db2_reference_setup(self) -> dict[str, Any]: + with self._connect() as conn: + type_count = int(conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0]) + category_count = int(conn.execute("SELECT COUNT(*) FROM transaction_categories").fetchone()[0]) + sample_type = row_to_dict( + conn.execute("SELECT type_code, description FROM transaction_types ORDER BY type_code LIMIT 1").fetchone() + ) + sample_category = row_to_dict( + conn.execute( + """ + SELECT type_code, category_code, description + FROM transaction_categories + ORDER BY type_code, category_code + LIMIT 1 + """ + ).fetchone() + ) + return { + "legacy_job": "CREADB21", + "legacy_jcl_job": "CREADB2", + "db2_system": "DAZ1", + "database": { + "name": "CARDDEMO", + "stogroup": "AWST1STG", + "bufferpool": "BP0", + "ccsid": "EBCDIC", + }, + "steps": [ + {"step": "FREEPLN", "program": "IKJEFT01", "control": "DB2FREE", "purpose": "free existing plans/packages"}, + {"step": "CRCRDDB", "program": "IKJEFT01", "utility": "DSNTIAD", "control": "DB2CREAT", "purpose": "create database, tablespaces, tables, indexes, grants, and foreign key"}, + {"step": "RUNTEP2", "program": "IKJEFT01", "utility": "DSNTEP4", "control": "DB2LTTYP", "purpose": "load TRANSACTION_TYPE reference rows"}, + {"step": "LDTCCAT", "program": "IKJEFT01", "utility": "DSNTEP4", "control": "DB2LTCAT", "purpose": "load TRANSACTION_TYPE_CATEGORY reference rows"}, + ], + "tablespaces": [ + {"name": "CARDSPC1", "table": "CARDDEMO.TRANSACTION_TYPE"}, + {"name": "CARDSTTC", "table": "CARDDEMO.TRANSACTION_TYPE_CATEGORY"}, + ], + "tables": { + "transaction_type": { + "name": "CARDDEMO.TRANSACTION_TYPE", + "columns": {"TR_TYPE": "CHAR(2) NOT NULL", "TR_DESCRIPTION": "VARCHAR(50) NOT NULL"}, + "primary_key": ["TR_TYPE"], + "index": "CARDDEMO.XTRAN_TYPE", + "load_count": type_count, + "sample": sample_type, + }, + "transaction_type_category": { + "name": "CARDDEMO.TRANSACTION_TYPE_CATEGORY", + "columns": { + "TRC_TYPE_CODE": "CHAR(2) NOT NULL", + "TRC_TYPE_CATEGORY": "CHAR(4) NOT NULL", + "TRC_CAT_DATA": "VARCHAR(50) NOT NULL", + }, + "primary_key": ["TRC_TYPE_CODE", "TRC_TYPE_CATEGORY"], + "foreign_key": { + "columns": ["TRC_TYPE_CODE"], + "references": "CARDDEMO.TRANSACTION_TYPE(TR_TYPE)", + "on_delete": "RESTRICT", + }, + "index": "CARDDEMO.X_TRAN_TYPE_CATG", + "load_count": category_count, + "sample": sample_category, + }, + }, + "grants": [ + "DBADM ON DATABASE CARDDEMO TO PUBLIC", + "USE OF TABLESPACE CARDDEMO.CARDSPC1 TO PUBLIC", + "USE OF TABLESPACE CARDDEMO.CARDSTTC TO PUBLIC", + "DELETE, INSERT, SELECT, UPDATE ON CARDDEMO.TRANSACTION_TYPE TO PUBLIC", + "DELETE, INSERT, SELECT, UPDATE ON CARDDEMO.TRANSACTION_TYPE_CATEGORY TO PUBLIC", + ], + "claim_limit": "Models CREADB21 Db2 DDL/load control flow and verifies loaded reference row counts in SQLite; no Db2 subsystem is provisioned", + } + + def mq_system_date(self, payload: dict[str, Any] | None = None, *, now: Any = None) -> dict[str, Any]: + payload = dict(payload or {}) + timestamp = self._coerce_mq_datetime(now if now is not None else payload.get("now")) + system_date = timestamp.strftime("%m-%d-%Y") + system_time = timestamp.strftime("%H:%M:%S") + request_message = str(payload.get("request_message") or "DATE").ljust(1000)[:1000] + reply_message = f"SYSTEM DATE : {system_date}SYSTEM TIME : {system_time}" + return { + "legacy_transaction": "CDRD", + "legacy_program": "CODATE01", + "legacy_pattern": "MQ request/reply", + "input_queue": payload.get("input_queue") or "CARD.DEMO.REQUEST.DATE", + "reply_queue": "CARD.DEMO.REPLY.DATE", + "error_queue": "CARD.DEMO.ERROR.QUEUE", + "request_message": request_message, + "reply_message": reply_message, + "system_date": system_date, + "system_time": system_time, + "message_format": { + "request_copy": "REQUEST-MSG-COPY", + "reply_length": 1000, + "mq_format": "MQFMT_STRING", + "correlation": "reply reuses MQMD message id and correl id", + }, + "source_oracle": "CODATE01 4000-PROCESS-REQUEST-REPLY uses CICS ASKTIME/FORMATTIME MMDDYYYY DATESEP('-') TIMESEP and does not validate WS-FUNC", + } + + def mq_account_inquiry(self, payload: dict[str, Any] | None = None) -> dict[str, Any]: + payload = dict(payload or {}) + request = self._mq_request_from_payload(payload, default_function="INQA") + valid_request = request["function"] == "INQA" and request["account_id"] > 0 + with self._connect() as conn: + account = None + if valid_request: + account = row_to_dict( + conn.execute( + "SELECT * FROM accounts WHERE account_id = ?", + (request["account_id"],), + ).fetchone() + ) + if account: + reply_message = self._format_account_mq_reply(account) + return { + "legacy_transaction": "CDRA", + "legacy_program": "COACCT01", + "legacy_pattern": "MQ request/reply plus ACCTDAT VSAM READ", + "input_queue": payload.get("input_queue") or "CARD.DEMO.REQUEST.ACCT", + "reply_queue": "CARD.DEMO.REPLY.ACCT", + "error_queue": "CARD.DEMO.ERROR.QUEUE", + "request": request, + "request_message": request["request_message"], + "reply_message": reply_message, + "valid_request": True, + "account": self._decorate_money(dict(account)), + "account_data": self._account_mq_data(account), + "message_format": { + "function": {"offset": 0, "length": 4, "expected": "INQA"}, + "account_id": {"offset": 4, "length": 11, "type": "PIC 9(11)"}, + "reply_length": 1000, + "mq_format": "MQFMT_STRING", + "correlation": "reply reuses MQMD message id and correl id", + }, + "source_oracle": "COACCT01 validates WS-FUNC='INQA' and WS-KEY > ZEROES, reads ACCTDAT by 11-byte account id, then moves CVACT01Y fields into WS-ACCT-RESPONSE", + } + reply_message = self._invalid_account_mq_reply( + request["account_id"], + request["function"], + include_function=not valid_request, + ) + return { + "legacy_transaction": "CDRA", + "legacy_program": "COACCT01", + "legacy_pattern": "MQ request/reply plus ACCTDAT VSAM READ", + "input_queue": payload.get("input_queue") or "CARD.DEMO.REQUEST.ACCT", + "reply_queue": "CARD.DEMO.REPLY.ACCT", + "error_queue": "CARD.DEMO.ERROR.QUEUE", + "request": request, + "request_message": request["request_message"], + "reply_message": reply_message, + "valid_request": False, + "account": None, + "account_data": None, + "error": "INVALID REQUEST PARAMETERS", + "source_oracle": "COACCT01 emits INVALID REQUEST PARAMETERS for non-INQA/zero keys and for ACCTDAT NOTFND responses", + } + + def batch_resource_setup(self, job: str | None = None) -> dict[str, Any]: + with self._connect() as conn: + counts = { + "transaction_types": int(conn.execute("SELECT COUNT(*) FROM transaction_types").fetchone()[0]), + "transaction_categories": int(conn.execute("SELECT COUNT(*) FROM transaction_categories").fetchone()[0]), + "disclosure_groups": int(conn.execute("SELECT COUNT(*) FROM disclosure_groups").fetchone()[0]), + "users": int(conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]), + "transactions": int(conn.execute("SELECT COUNT(*) FROM transactions").fetchone()[0]), + } + cics_files = ["TRANSACT", "CCXREF", "ACCTDAT", "CXACAIX", "USRSEC"] + jobs: dict[str, dict[str, Any]] = { + "DEFGDGB": { + "legacy_job": "DEFGDGB", + "legacy_program": "IDCAMS", + "function": "Setup GDG Bases", + "steps": [{"step": "STEP05", "program": "IDCAMS", "control": "DEFINE GENERATIONDATAGROUP"}], + "gdg_bases": [ + {"name": "AWS.M2.CARDDEMO.TRANSACT.BKUP", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.TRANSACT.DALY", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.TRANREPT", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.TCATBALF.BKUP", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.SYSTRAN", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.TRANSACT.COMBINED", "limit": 5, "scratch": True}, + ], + "existing_definition_policy": "IF LASTCC=12 THEN SET MAXCC=0 after each DEFINE", + "source_oracle": "DEFGDGB.jcl STEP05 IDCAMS DEFINE GENERATIONDATAGROUP statements", + }, + "DEFGDGD": { + "legacy_job": "DEFGDGD", + "legacy_programs": ["IDCAMS", "IEBGENER"], + "function": "Setup more GDG Bases for Db2", + "steps": [ + {"step": "STEP10", "program": "IDCAMS", "defines": "AWS.M2.CARDDEMO.TRANTYPE.BKUP"}, + {"step": "STEP20", "program": "IEBGENER", "source": "AWS.M2.CARDDEMO.TRANTYPE.PS", "target": "AWS.M2.CARDDEMO.TRANTYPE.BKUP(+1)", "lrecl": 60, "record_count": counts["transaction_types"]}, + {"step": "STEP30", "program": "IDCAMS", "defines": "AWS.M2.CARDDEMO.TRANCATG.PS.BKUP"}, + {"step": "STEP40", "program": "IEBGENER", "source": "AWS.M2.CARDDEMO.TRANCATG.PS", "target": "AWS.M2.CARDDEMO.TRANCATG.PS.BKUP(+1)", "lrecl": 60, "record_count": counts["transaction_categories"]}, + {"step": "STEP50", "program": "IDCAMS", "defines": "AWS.M2.CARDDEMO.DISCGRP.BKUP"}, + {"step": "STEP60", "program": "IEBGENER", "source": "AWS.M2.CARDDEMO.DISCGRP.PS", "target": "AWS.M2.CARDDEMO.DISCGRP.BKUP(+1)", "lrecl": 50, "record_count": counts["disclosure_groups"]}, + ], + "gdg_bases": [ + {"name": "AWS.M2.CARDDEMO.TRANTYPE.BKUP", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.TRANCATG.PS.BKUP", "limit": 5, "scratch": True}, + {"name": "AWS.M2.CARDDEMO.DISCGRP.BKUP", "limit": 5, "scratch": True}, + ], + "source_oracle": "DEFGDGD.jcl IDCAMS DEFINE steps and IEBGENER first-generation loads", + }, + "ESDSRRDS": { + "legacy_job": "ESDSRRDS", + "legacy_programs": ["IEFBR14", "IEBGENER", "IDCAMS"], + "function": "Create ESDS and RRDS VSAM files", + "predelete_dataset": "AWS.M2.CARDDEMO.ESDSRRDS.PS", + "instream_user_records": counts["users"], + "ps_dataset": {"name": "AWS.M2.CARDDEMO.ESDSRRDS.PS", "lrecl": 80, "recfm": "FB", "dsorg": "PS"}, + "clusters": [ + { + "name": "AWS.M2.CARDDEMO.USRSEC.VSAM.ESDS", + "organization": "NONINDEXED", + "record_size": [80, 80], + "reuse": True, + "tracks": [45, 15], + "freespace": [10, 15], + "cisz": 8192, + "data": "AWS.M2.CARDDEMO.USRSEC.VSAM.ESDS.DAT", + }, + { + "name": "AWS.M2.CARDDEMO.USRSEC.VSAM.RRDS", + "organization": "NUMBERED", + "record_size": [80, 80], + "reuse": True, + "tracks": [45, 15], + "freespace": [10, 15], + "cisz": 8192, + "data": "AWS.M2.CARDDEMO.USRSEC.VSAM.RRDS.DAT", + }, + ], + "repro_steps": [ + {"step": "STEP03", "in": "AWS.M2.CARDDEMO.ESDSRRDS.PS", "out": "AWS.M2.CARDDEMO.USRSEC.VSAM.ESDS"}, + {"step": "STEP05", "in": "AWS.M2.CARDDEMO.ESDSRRDS.PS", "out": "AWS.M2.CARDDEMO.USRSEC.VSAM.RRDS"}, + ], + "source_oracle": "ESDSRRDS.jcl instream USRSEC records, DEFINE CLUSTER ESDS/RRDS, and REPRO copy steps", + }, + "TRANIDX": { + "legacy_job": "TRANIDX", + "legacy_program": "IDCAMS", + "function": "Define AIX for transaction file", + "steps": [ + {"step": "STEP20", "program": "IDCAMS", "control": "DEFINE ALTERNATEINDEX"}, + {"step": "STEP25", "program": "IDCAMS", "control": "DEFINE PATH"}, + {"step": "STEP30", "program": "IDCAMS", "control": "BLDINDEX"}, + ], + "alternate_index": { + "name": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX", + "relate": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "keys": {"length": 26, "offset": 304}, + "nonunique": True, + "upgrade": True, + "record_size": [350, 350], + "volume": "AWSHJ1", + "cylinders": [5, 1], + "data": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX.DATA", + "index": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX.INDEX", + }, + "path": { + "name": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX.PATH", + "pathentry": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX", + }, + "bldindex": { + "indataset": "AWS.M2.CARDDEMO.TRANSACT.VSAM.KSDS", + "outdataset": "AWS.M2.CARDDEMO.TRANSACT.VSAM.AIX", + "source_record_count": counts["transactions"], + }, + "source_oracle": "TRANIDX.jcl DEFINE ALTERNATEINDEX, DEFINE PATH, and BLDINDEX statements", + }, + "CLOSEFIL": { + "legacy_job": "CLOSEFIL", + "legacy_program": "SDSF", + "function": "Close VSAM files in CICS", + "region": "CICSAWSA", + "action": "close", + "cemt_code": "CLO", + "files": cics_files, + "commands": [f"/F CICSAWSA,'CEMT SET FIL({file:<8}) CLO'" for file in cics_files], + "source_oracle": "CLOSEFIL.jcl SDSF ISFIN CEMT SET FIL commands", + }, + "OPENFIL": { + "legacy_job": "OPENFIL", + "legacy_program": "SDSF", + "function": "Open files in CICS", + "region": "CICSAWSA", + "action": "open", + "cemt_code": "OPE", + "files": cics_files, + "commands": [f"/F CICSAWSA,'CEMT SET FIL({file:<8}) OPE'" for file in cics_files], + "source_oracle": "OPENFIL.jcl SDSF ISFIN CEMT SET FIL commands", + }, + } + if job: + key = str(job).strip().upper() + if key not in jobs: + raise KeyError(f"Unknown batch resource setup job: {job}") + return jobs[key] + ordered_jobs = ["DEFGDGB", "DEFGDGD", "ESDSRRDS", "TRANIDX", "CLOSEFIL", "OPENFIL"] + return { + "legacy_jobs": ordered_jobs, + "resource_count": len(ordered_jobs), + "jobs": [jobs[name] for name in ordered_jobs], + "source_oracle": "CardDemo setup/control JCL resource definitions projected into explicit modern metadata; no datasets or CICS regions are mutated", + } + + def pending_authorization_summary( + self, + account_id: int, + *, + start_key: str | None = None, + page_size: int = 5, + ) -> dict[str, Any]: + page_size = max(1, min(int(page_size), 25)) + with self._connect() as conn: + summary = row_to_dict( + conn.execute( + "SELECT * FROM pending_authorization_summaries WHERE account_id = ?", + (account_id,), + ).fetchone() + ) + if not summary: + raise KeyError("Pending Authorization Summary NOT found...") + context = self._pending_authorization_context(conn, account_id) + start_sequence = 0 + if start_key: + row = conn.execute( + """ + SELECT sequence_no FROM pending_authorization_details + WHERE account_id = ? AND authorization_key = ? + """, + (account_id, start_key.lower()), + ).fetchone() + start_sequence = int(row["sequence_no"]) if row else 0 + rows = rows_to_dicts( + conn.execute( + """ + SELECT * FROM pending_authorization_details + WHERE account_id = ? AND sequence_no > ? + ORDER BY sequence_no + LIMIT ? + """, + (account_id, start_sequence, page_size + 1), + ).fetchall() + ) + page = rows[:page_size] + return { + "legacy_transaction": "CPVS", + "legacy_program": "COPAUS0C", + "legacy_map": "COPAU00", + "account_id": account_id, + "context": context, + "summary": self._decorate_pending_authorization_summary(summary), + "authorizations": [self._decorate_pending_authorization_detail(row) for row in page], + "page_size": page_size, + "next_page": len(rows) > page_size, + "last_key": page[-1]["authorization_key"] if page else None, + "source_oracle": "DBPAUTP0 PAUTSUM0/PAUTDTL1 IMS unload decoded with CIPAUSMY/CIPAUDTY copybook offsets", + } + + def pending_authorization_detail( + self, + account_id: int, + *, + authorization_key: str | None = None, + transaction_id: str | None = None, + ) -> dict[str, Any]: + with self._connect() as conn: + params: tuple[Any, ...] + if authorization_key: + predicate = "account_id = ? AND authorization_key = ?" + params = (account_id, authorization_key.lower()) + elif transaction_id: + predicate = "account_id = ? AND transaction_id = ?" + params = (account_id, transaction_id) + else: + predicate = "account_id = ?" + params = (account_id,) + detail = row_to_dict( + conn.execute( + f""" + SELECT * FROM pending_authorization_details + WHERE {predicate} + ORDER BY sequence_no + LIMIT 1 + """, + params, + ).fetchone() + ) + if not detail: + raise KeyError("Pending Authorization Detail NOT found...") + summary = row_to_dict( + conn.execute( + "SELECT * FROM pending_authorization_summaries WHERE account_id = ?", + (account_id,), + ).fetchone() + ) + return { + "legacy_transaction": "CPVD", + "legacy_program": "COPAUS1C", + "legacy_map": "COPAU01", + "account_id": account_id, + "summary": self._decorate_pending_authorization_summary(summary) if summary else None, + "authorization": self._decorate_pending_authorization_detail(detail), + "decline_reason_table": AUTH_DECLINE_REASONS, + "source_oracle": "COPAUS1C GU/GNP by ACCNTID and PAUT9CTS over PAUTSUM0/PAUTDTL1", + } + + def process_authorization_request(self, payload: dict[str, Any]) -> dict[str, Any]: + request = self._normalize_authorization_request(payload) + amount_cents = self._auth_request_amount_cents(request) + card_number = request["card_number"] + with self._connect() as conn: + xref = row_to_dict(conn.execute("SELECT * FROM card_xrefs WHERE card_number = ?", (card_number,)).fetchone()) + account = None + customer = None + pending_summary = None + decline_reason = "0000" + approved = True + available_cents = 0 + if not xref: + approved = False + decline_reason = "3100" + else: + account = row_to_dict( + conn.execute("SELECT * FROM accounts WHERE account_id = ?", (xref["account_id"],)).fetchone() + ) + customer = row_to_dict( + conn.execute("SELECT * FROM customers WHERE customer_id = ?", (xref["customer_id"],)).fetchone() + ) + pending_summary = row_to_dict( + conn.execute( + "SELECT * FROM pending_authorization_summaries WHERE account_id = ?", + (xref["account_id"],), + ).fetchone() + ) + if not account or not customer: + approved = False + decline_reason = "3100" + elif pending_summary: + available_cents = int(pending_summary["credit_limit_cents"]) - int( + pending_summary["credit_balance_cents"] + ) + if amount_cents > available_cents: + approved = False + decline_reason = "4100" + else: + available_cents = int(account["credit_limit_cents"]) - int(account["current_balance_cents"]) + if amount_cents > available_cents: + approved = False + decline_reason = "4100" + + response = { + "card_number": card_number, + "transaction_id": request["transaction_id"], + "auth_id_code": request["auth_time"], + "auth_resp_code": "00" if approved else "05", + "auth_resp_reason": decline_reason, + "approved_amount_cents": amount_cents if approved else 0, + } + response["approved_amount"] = money_to_display(response["approved_amount_cents"]) + response["response_csv"] = ",".join( + [ + response["card_number"], + response["transaction_id"], + response["auth_id_code"], + response["auth_resp_code"], + response["auth_resp_reason"], + self._auth_amount_display(response["approved_amount_cents"]), + "", + ] + ) + + written = False + detail: dict[str, Any] | None = None + if xref and account and customer: + summary = pending_summary or self._new_pending_summary(conn, account, xref) + self._apply_authorization_to_summary(conn, summary, amount_cents, approved, account) + detail = self._insert_pending_authorization_detail( + conn, + account_id=int(xref["account_id"]), + request=request, + response=response, + amount_cents=amount_cents, + approved=approved, + processing_datetime=payload.get("processing_datetime"), + ) + written = True + conn.commit() + return { + "legacy_transaction": "CP00", + "legacy_program": "COPAUA0C", + "request": request, + "response": response, + "approved": approved, + "available_cents": available_cents, + "decline_reason_description": AUTH_DECLINE_REASONS.get(decline_reason, "UNKNOWN"), + "written_to_pending_authorizations": written, + "source_oracle": "COPAUA0C comma-delimited MQ request parsing, available-credit decision, response CSV, summary REPL/ISRT, and detail ISRT", + "authorization": self._decorate_pending_authorization_detail(detail) if detail else None, + } + + def mark_authorization_fraud( + self, + account_id: int, + authorization_key: str, + *, + action: str = "toggle", + report_date: str | None = None, + ) -> dict[str, Any]: + report_date = report_date or datetime.now().strftime("%Y%m%d") + with self._connect() as conn: + detail = row_to_dict( + conn.execute( + """ + SELECT d.*, s.customer_id + FROM pending_authorization_details d + JOIN pending_authorization_summaries s ON s.account_id = d.account_id + WHERE d.account_id = ? AND d.authorization_key = ? + """, + (account_id, authorization_key.lower()), + ).fetchone() + ) + if not detail: + raise KeyError("Pending Authorization Detail NOT found...") + if action == "report": + fraud_status = "F" + elif action == "remove": + fraud_status = "R" + else: + fraud_status = "R" if detail["auth_fraud"] == "F" else "F" + conn.execute( + """ + UPDATE pending_authorization_details + SET auth_fraud = ?, fraud_rpt_date = ? + WHERE account_id = ? AND authorization_key = ? + """, + (fraud_status, report_date, account_id, authorization_key.lower()), + ) + detail["auth_fraud"] = fraud_status + detail["fraud_rpt_date"] = report_date + conn.execute( + """ + INSERT OR REPLACE INTO authorization_frauds ( + card_number, auth_timestamp, account_id, customer_id, authorization_key, + auth_type, card_expiry_date, message_type, message_source, auth_id_code, + auth_resp_code, auth_resp_reason, processing_code, transaction_amount_cents, + approved_amount_cents, merchant_category_code, acqr_country_code, pos_entry_mode, + merchant_id, merchant_name, merchant_city, merchant_state, merchant_zip, + transaction_id, match_status, auth_fraud, fraud_rpt_date + ) VALUES ( + :card_number, :auth_timestamp, :account_id, :customer_id, :authorization_key, + :auth_type, :card_expiry_date, :message_type, :message_source, :auth_id_code, + :auth_resp_code, :auth_resp_reason, :processing_code, :transaction_amount_cents, + :approved_amount_cents, :merchant_category_code, :acqr_country_code, :pos_entry_mode, + :merchant_id, :merchant_name, :merchant_city, :merchant_state, :merchant_zip, + :transaction_id, :match_status, :auth_fraud, :fraud_rpt_date + ) + """, + {**detail, "auth_timestamp": self._auth_timestamp(detail)}, + ) + conn.commit() + return { + "legacy_transaction": "CPVD", + "legacy_program": "COPAUS1C/COPAUS2C", + "account_id": account_id, + "authorization": self._decorate_pending_authorization_detail(detail), + "fraud_status": fraud_status, + "db2_table": "CARDDEMO.AUTHFRDS", + "source_oracle": "COPAUS1C PF5 toggles PA-AUTH-FRAUD, then COPAUS2C inserts/updates AUTHFRDS", + } + + def purge_expired_authorizations( + self, + *, + current_yyddd: int | None = None, + expiry_days: int = 5, + dry_run: bool = False, + ) -> dict[str, Any]: + current_yyddd = int(current_yyddd or datetime.now().strftime("%y%j")) + expiry_days = int(expiry_days) + with self._connect() as conn: + details = rows_to_dicts( + conn.execute("SELECT * FROM pending_authorization_details ORDER BY sequence_no").fetchall() + ) + purged: list[dict[str, Any]] = [] + touched_accounts: set[int] = set() + for detail in details: + day_diff = current_yyddd - int(detail["auth_yyddd"]) + if day_diff < expiry_days: + continue + purged.append( + { + "account_id": detail["account_id"], + "authorization_key": detail["authorization_key"], + "transaction_id": detail["transaction_id"], + "auth_yyddd": detail["auth_yyddd"], + "day_diff": day_diff, + } + ) + if dry_run: + continue + summary = row_to_dict( + conn.execute( + "SELECT * FROM pending_authorization_summaries WHERE account_id = ?", + (detail["account_id"],), + ).fetchone() + ) + if not summary: + continue + if detail["auth_resp_code"] == "00": + summary["approved_auth_count"] = int(summary["approved_auth_count"]) - 1 + summary["approved_auth_amount_cents"] = int(summary["approved_auth_amount_cents"]) - int( + detail["approved_amount_cents"] + ) + else: + summary["declined_auth_count"] = int(summary["declined_auth_count"]) - 1 + summary["declined_auth_amount_cents"] = int(summary["declined_auth_amount_cents"]) - int( + detail["transaction_amount_cents"] + ) + conn.execute( + """ + DELETE FROM pending_authorization_details + WHERE account_id = ? AND authorization_key = ? + """, + (detail["account_id"], detail["authorization_key"]), + ) + # CBPAUP0C repeats PA-APPROVED-AUTH-CNT in the summary delete predicate. + if int(summary["approved_auth_count"]) <= 0 and int(summary["approved_auth_count"]) <= 0: + conn.execute( + "DELETE FROM pending_authorization_summaries WHERE account_id = ?", + (detail["account_id"],), + ) + else: + conn.execute( + """ + UPDATE pending_authorization_summaries + SET approved_auth_count = ?, + declined_auth_count = ?, + approved_auth_amount_cents = ?, + declined_auth_amount_cents = ? + WHERE account_id = ? + """, + ( + summary["approved_auth_count"], + summary["declined_auth_count"], + summary["approved_auth_amount_cents"], + summary["declined_auth_amount_cents"], + detail["account_id"], + ), + ) + touched_accounts.add(int(detail["account_id"])) + if not dry_run: + conn.commit() + return { + "legacy_job": "CBPAUP0J", + "legacy_program": "CBPAUP0C", + "current_yyddd": current_yyddd, + "expiry_days": expiry_days, + "dry_run": dry_run, + "purged_count": len(purged), + "purged": purged[:50], + "touched_account_count": len(touched_accounts), + "source_oracle": "CBPAUP0C scans PAUTSUM0/PAUTDTL1, computes CURRENT-YYDDD - (99999 - PA-AUTH-DATE-9C), deletes expired details, and adjusts summary counters", + } + + def update_account(self, account_id: int, payload: dict[str, Any]) -> dict[str, Any]: + with self._connect() as conn: + account = row_to_dict( + conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone() + ) + if not account: + raise KeyError("Account ID NOT found...") + xref = row_to_dict( + conn.execute( + """ + SELECT * FROM card_xrefs + WHERE account_id = ? + ORDER BY card_number + LIMIT 1 + """, + (account_id,), + ).fetchone() + ) + if not xref: + raise KeyError("Account ID NOT found...") + customer = row_to_dict( + conn.execute("SELECT * FROM customers WHERE customer_id = ?", (xref["customer_id"],)).fetchone() + ) + if not customer: + raise KeyError("Customer ID NOT found...") + + account_changes, customer_changes = self._normalize_account_update_payload(account, customer, payload) + if not account_changes and not customer_changes: + raise ValueError("no supported account fields supplied") + account_delta = {key: value for key, value in account_changes.items() if account.get(key) != value} + customer_delta = {key: value for key, value in customer_changes.items() if customer.get(key) != value} + if not account_delta and not customer_delta: + raise ValueError("No changes were found.") + if account_delta: + assignments = ", ".join(f"{key} = ?" for key in account_delta) + values = list(account_delta.values()) + [account_id] + conn.execute(f"UPDATE accounts SET {assignments} WHERE account_id = ?", values) + if customer_delta: + assignments = ", ".join(f"{key} = ?" for key in customer_delta) + values = list(customer_delta.values()) + [customer["customer_id"]] + conn.execute(f"UPDATE customers SET {assignments} WHERE customer_id = ?", values) + conn.commit() + bundle = self.get_account_bundle(account_id) + if not bundle: + raise KeyError("account not found after update") + return { + **bundle["account"], + "legacy_transaction": "CAUP", + "legacy_program": "COACTUPC", + "message": "Account update successful.", + "updated_account_fields": sorted(account_delta), + "updated_customer_fields": sorted(customer_delta), + "customer": bundle["customers"][0] if bundle["customers"] else None, + "claim_limit": "Implements COACTUPC account/customer validation and SQLite rewrites over decoded seed records; CICS locking is modeled by a single local transaction", + } + + def get_card_detail(self, card_number: str, account_id: int | str | None = None) -> dict[str, Any]: + normalized_card = self._normalize_card_number(card_number) + normalized_account = ( + self._normalize_card_account_id(account_id) + if account_id is not None and str(account_id).strip() != "" + else None + ) + with self._connect() as conn: + card = row_to_dict(conn.execute("SELECT * FROM cards WHERE card_number = ?", (normalized_card,)).fetchone()) + if not card or (normalized_account is not None and int(card["account_id"]) != normalized_account): + raise KeyError("Did not find cards for this search condition") + xrefs = rows_to_dicts( + conn.execute( + """ + SELECT * FROM card_xrefs + WHERE card_number = ? + ORDER BY customer_id + """, + (normalized_card,), + ).fetchall() + ) + return { + "legacy_transaction": "CCDL", + "legacy_program": "COCRDSLC", + "message": "Displaying requested details", + "search": {"account_id": normalized_account, "card_number": normalized_card}, + "card": card, + "xrefs": xrefs, + "editable_fields": ["embossed_name", "active_status", "expiration_month", "expiration_year"], + "claim_limit": "Implements COCRDSLC account/card search-key validation and CARDDAT file lookup over decoded seed records; CICS map attributes are not runtime-replayed", + } + + def update_card(self, card_number: str, payload: dict[str, Any]) -> dict[str, Any]: + normalized_card = self._normalize_card_number(card_number) + with self._connect() as conn: + current = row_to_dict(conn.execute("SELECT * FROM cards WHERE card_number = ?", (normalized_card,)).fetchone()) + if not current: + raise KeyError("Did not find cards for this search condition") + if "account_id" in payload and str(payload.get("account_id") or "").strip(): + requested_account = self._normalize_card_account_id(payload["account_id"]) + if requested_account != int(current["account_id"]): + raise KeyError("Did not find cards for this search condition") + new_name = ( + self._normalize_card_embossed_name(payload["embossed_name"]) + if "embossed_name" in payload + else str(current["embossed_name"]) + ) + new_status = ( + self._normalize_card_status(payload["active_status"]) + if "active_status" in payload + else str(current["active_status"]) + ) + new_month, new_year = self._normalize_card_expiry_parts(current, payload) + old_year, old_month, old_day = str(current["expiration_date"]).split("-") + new_expiration_date = f"{new_year}-{new_month}-{old_day}" + old_signature = ( + str(current["embossed_name"]).strip().upper(), + str(current["active_status"]).strip().upper(), + old_month, + old_year, + ) + new_signature = (new_name.upper(), new_status, new_month, new_year) + if old_signature == new_signature: + raise ValueError("No change detected with respect to values fetched.") + conn.execute( + """ + UPDATE cards + SET embossed_name = ?, active_status = ?, expiration_date = ? + WHERE card_number = ? + """, + (new_name, new_status, new_expiration_date, normalized_card), + ) + conn.commit() + updated = dict(conn.execute("SELECT * FROM cards WHERE card_number = ?", (normalized_card,)).fetchone()) + changed_fields = [ + field + for field, old_value, new_value in ( + ("embossed_name", current["embossed_name"], updated["embossed_name"]), + ("active_status", current["active_status"], updated["active_status"]), + ("expiration_date", current["expiration_date"], updated["expiration_date"]), + ) + if old_value != new_value + ] + return { + "legacy_transaction": "CCUP", + "legacy_program": "COCRDUPC", + "message": "Changes committed to database", + "card": updated, + "changed_fields": changed_fields, + "preserved_fields": ["card_number", "account_id", "cvv", "expiration_day"], + "claim_limit": "Implements COCRDUPC name/status/month/year validation, no-change detection, hidden-field preservation, and CARDDAT rewrite over decoded seed records; CICS record locking is modeled by one local transaction", + } + + def validate_post_transaction(self, payload: dict[str, Any]) -> dict[str, Any]: + with self._connect() as conn: + return self._validate_post_transaction(conn, payload) + + def post_transaction(self, payload: dict[str, Any], *, reject_on_failure: bool = True) -> dict[str, Any]: + card_number = str(payload.get("card_number") or "").strip() + amount_cents = int(payload.get("amount_cents") or 0) + type_code = str(payload.get("type_code") or "01").zfill(2) + category_code = str(payload.get("category_code") or "0001").zfill(4) + now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.000000") + original_timestamp = str(payload.get("original_timestamp") or now)[:26] + processed_timestamp = str(payload.get("processed_timestamp") or now)[:26] + with self._connect() as conn: + validation = self._validate_post_transaction( + conn, + { + **payload, + "card_number": card_number, + "amount_cents": amount_cents, + "original_timestamp": original_timestamp, + }, + ) + transaction_id = str(payload.get("transaction_id") or self._next_transaction_id(conn)).zfill(16)[-16:] + transaction = { + "transaction_id": transaction_id, + "type_code": type_code, + "category_code": category_code, + "source": str(payload.get("source") or "POSTTRAN")[:10], + "description": str(payload.get("description") or "POSTED TRANSACTION")[:100], + "amount_cents": amount_cents, + "merchant_id": str(payload.get("merchant_id") or "000000000")[:9], + "merchant_name": str(payload.get("merchant_name") or "POSTTRAN")[:50], + "merchant_city": str(payload.get("merchant_city") or "BATCH")[:50], + "merchant_zip": str(payload.get("merchant_zip") or "N/A")[:10], + "card_number": card_number, + "original_timestamp": original_timestamp, + "processed_timestamp": processed_timestamp, + } + if not validation["accepted"]: + result = { + "legacy_job": "POSTTRAN", + "legacy_program": "CBTRN02C", + "accepted": False, + "validation": validation, + "transaction": self._decorate_money(transaction), + } + if reject_on_failure: + raise ValueError( + f"POSTTRAN reject {validation['reason_code']}: {validation['reason_description']}" + ) + return result + + account_id = int(validation["account_id"]) + conn.execute( + """ + INSERT INTO transactions ( + transaction_id, type_code, category_code, source, description, amount_cents, + merchant_id, merchant_name, merchant_city, merchant_zip, card_number, + original_timestamp, processed_timestamp + ) VALUES ( + :transaction_id, :type_code, :category_code, :source, :description, :amount_cents, + :merchant_id, :merchant_name, :merchant_city, :merchant_zip, :card_number, + :original_timestamp, :processed_timestamp + ) + """, + transaction, + ) + conn.execute( + """ + INSERT INTO transaction_category_balances(account_id, type_code, category_code, balance_cents) + VALUES (?, ?, ?, ?) + ON CONFLICT(account_id, type_code, category_code) + DO UPDATE SET balance_cents = balance_cents + excluded.balance_cents + """, + (account_id, type_code, category_code, amount_cents), + ) + credit_delta = amount_cents if amount_cents >= 0 else 0 + debit_delta = amount_cents if amount_cents < 0 else 0 + conn.execute( + """ + UPDATE accounts + SET current_balance_cents = current_balance_cents + ?, + current_cycle_credit_cents = current_cycle_credit_cents + ?, + current_cycle_debit_cents = current_cycle_debit_cents + ? + WHERE account_id = ? + """, + (amount_cents, credit_delta, debit_delta, account_id), + ) + conn.commit() + after_account = row_to_dict( + conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone() + ) + return { + "legacy_job": "POSTTRAN", + "legacy_program": "CBTRN02C", + "accepted": True, + "validation": validation, + "transaction": self._decorate_money(transaction), + "account": self._decorate_money(after_account or {}), + "claim_limit": "Implements CBTRN02C card/account/overlimit/expiration validation and account/category-balance updates from static source", + } + + def add_transaction(self, payload: dict[str, Any]) -> dict[str, Any]: + with self._connect() as conn: + validated = self._validate_transaction_add(conn, payload) + transaction = { + "transaction_id": self._next_transaction_id(conn), + "type_code": validated["type_code"], + "category_code": validated["category_code"], + "source": validated["source"], + "description": validated["description"], + "amount_cents": validated["amount_cents"], + "merchant_id": validated["merchant_id"], + "merchant_name": validated["merchant_name"], + "merchant_city": validated["merchant_city"], + "merchant_zip": validated["merchant_zip"], + "card_number": validated["card_number"], + "original_timestamp": validated["original_date"], + "processed_timestamp": validated["processed_date"], + } + conn.execute( + """ + INSERT INTO transactions ( + transaction_id, type_code, category_code, source, description, amount_cents, + merchant_id, merchant_name, merchant_city, merchant_zip, card_number, + original_timestamp, processed_timestamp + ) VALUES ( + :transaction_id, :type_code, :category_code, :source, :description, :amount_cents, + :merchant_id, :merchant_name, :merchant_city, :merchant_zip, :card_number, + :original_timestamp, :processed_timestamp + ) + """, + transaction, + ) + conn.commit() + return self._decorate_money( + { + **transaction, + "legacy_transaction": "CT02", + "legacy_program": "COTRN02C", + "account_id": validated["account_id"], + "legacy_amount": validated["legacy_amount"], + "message": f"Transaction added successfully. Your Tran ID is {transaction['transaction_id']}.", + "claim_limit": "Implements COTRN02C key resolution, confirmation, field validation, transaction-id increment, and TRANSACT write over modern SQLite", + } + ) + + def bill_payment(self, account_id: int, amount_cents: int | None = None) -> dict[str, Any]: + with self._connect() as conn: + account = conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone() + if not account: + raise KeyError("account not found") + payment_cents = int(account["current_balance_cents"]) + if payment_cents <= 0: + raise ValueError("You have nothing to pay") + if amount_cents is not None and int(amount_cents) != payment_cents: + raise ValueError("bill payment amount must equal current balance") + xref = conn.execute( + """ + SELECT * FROM card_xrefs + WHERE account_id = ? + ORDER BY card_number + LIMIT 1 + """, + (account_id,), + ).fetchone() + if not xref: + raise KeyError("account xref not found") + now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.000000") + transaction = { + "transaction_id": self._next_transaction_id(conn), + "type_code": "02", + "category_code": "0002", + "source": "POS TERM", + "description": "BILL PAYMENT - ONLINE", + "amount_cents": payment_cents, + "merchant_id": "999999999", + "merchant_name": "BILL PAYMENT", + "merchant_city": "N/A", + "merchant_zip": "N/A", + "card_number": xref["card_number"], + "original_timestamp": now, + "processed_timestamp": now, + } + conn.execute( + """ + INSERT INTO transactions ( + transaction_id, type_code, category_code, source, description, amount_cents, + merchant_id, merchant_name, merchant_city, merchant_zip, card_number, + original_timestamp, processed_timestamp + ) VALUES ( + :transaction_id, :type_code, :category_code, :source, :description, :amount_cents, + :merchant_id, :merchant_name, :merchant_city, :merchant_zip, :card_number, + :original_timestamp, :processed_timestamp + ) + """, + transaction, + ) + conn.execute( + """ + UPDATE accounts + SET current_balance_cents = current_balance_cents - ? + WHERE account_id = ? + """, + (payment_cents, account_id), + ) + conn.commit() + return self._decorate_money( + { + **transaction, + "legacy_transaction": "CB00", + "legacy_program": "COBIL00C", + "account_id": account_id, + } + ) + + def list_users(self) -> list[dict[str, Any]]: + with self._connect() as conn: + return rows_to_dicts(conn.execute("SELECT * FROM users ORDER BY user_id").fetchall()) + + def signon(self, user_id: str, password: str) -> dict[str, Any]: + normalized_user_id = self._legacy_upper(user_id, 8) + normalized_password = self._legacy_upper(password, 8) + if not normalized_user_id: + return self._signon_failure("Please enter User ID ...", "missing_user_id") + if not normalized_password: + return self._signon_failure("Please enter Password ...", "missing_password") + + with self._connect() as conn: + user = row_to_dict( + conn.execute("SELECT * FROM users WHERE user_id = ?", (normalized_user_id,)).fetchone() + ) + if not user: + return self._signon_failure("User not found. Try again ...", "user_not_found") + if str(user["password"]).strip().upper() != normalized_password: + return self._signon_failure("Wrong Password. Try again ...", "wrong_password", user_id=normalized_user_id) + + user_type = str(user["user_type"]).strip().upper()[:1] or "U" + route_transaction = "CA00" if user_type == "A" else "CM00" + route_program = "COADM01C" if user_type == "A" else "COMEN01C" + menu = self.admin_menu() if user_type == "A" else self.main_menu(user_type=user_type) + return { + "legacy_transaction": "CC00", + "legacy_program": "COSGN00C", + "authenticated": True, + "message": "Signon successful", + "user": user, + "route_transaction": route_transaction, + "route_program": route_program, + "menu": menu, + "claim_limit": "Implements COSGN00C uppercase credential lookup and admin/user routing over decoded USRSEC seed records", + } + + def main_menu(self, *, user_type: str = "U") -> dict[str, Any]: + normalized_type = self._legacy_upper(user_type, 1) or "U" + return { + "legacy_transaction": "CM00", + "legacy_program": "COMEN01C", + "map": "COMEN02Y", + "user_type": normalized_type, + "option_count": len(REGULAR_MENU_OPTIONS), + "options": [dict(row) for row in REGULAR_MENU_OPTIONS], + "invalid_option_message": "Please enter a valid option number...", + "claim_limit": "Menu options are transcribed from COMEN02Y/COMEN01C source; CICS screen state is not replayed", + } + + def admin_menu(self) -> dict[str, Any]: + return { + "legacy_transaction": "CA00", + "legacy_program": "COADM01C", + "map": "COADM02Y", + "user_type": "A", + "option_count": len(ADMIN_MENU_OPTIONS), + "options": [dict(row) for row in ADMIN_MENU_OPTIONS], + "invalid_option_message": "Please enter a valid option number...", + "claim_limit": "Admin options are transcribed from COADM02Y/COADM01C source; Db2 transaction-type maintenance remains separately graded", + } + + def select_menu_option(self, menu_transaction: str, option: int, *, user_type: str = "U") -> dict[str, Any]: + menu_transaction = self._legacy_upper(menu_transaction, 4) + normalized_type = self._legacy_upper(user_type, 1) or "U" + options = ADMIN_MENU_OPTIONS if menu_transaction == "CA00" else REGULAR_MENU_OPTIONS + selected = next((row for row in options if row["option"] == int(option)), None) + if selected is None: + raise ValueError("Please enter a valid option number...") + if selected["user_type"] == "A" and normalized_type != "A": + raise PermissionError("No access - Admin Only option...") + return { + "legacy_transaction": menu_transaction, + "selected": dict(selected), + "route_transaction": selected["transaction"], + "route_program": selected["program"], + } + + def get_user(self, user_id: str) -> dict[str, Any] | None: + normalized_user_id = self._legacy_upper(user_id, 8) + with self._connect() as conn: + return row_to_dict(conn.execute("SELECT * FROM users WHERE user_id = ?", (normalized_user_id,)).fetchone()) + + def add_user(self, payload: dict[str, Any]) -> dict[str, Any]: + user = self._normalize_user_payload(payload) + self._require_user_fields(user) + with self._connect() as conn: + try: + conn.execute( + """ + INSERT INTO users(user_id, first_name, last_name, password, user_type) + VALUES(:user_id, :first_name, :last_name, :password, :user_type) + """, + user, + ) + except sqlite3.IntegrityError as exc: + raise ValueError("User ID already exist...") from exc + conn.commit() + return { + "legacy_transaction": "CU01", + "legacy_program": "COUSR01C", + "message": f"User {user['user_id']} has been added ...", + "user": user, + } + + def update_user(self, user_id: str, payload: dict[str, Any]) -> dict[str, Any]: + normalized_user_id = self._legacy_upper(user_id, 8) + payload = {**payload, "user_id": normalized_user_id} + user = self._normalize_user_payload(payload) + self._require_user_fields(user) + with self._connect() as conn: + existing = row_to_dict( + conn.execute("SELECT * FROM users WHERE user_id = ?", (normalized_user_id,)).fetchone() + ) + if not existing: + raise KeyError("User ID NOT found...") + fields = ("first_name", "last_name", "password", "user_type") + if all(str(existing[field]) == str(user[field]) for field in fields): + raise ValueError("Please modify to update ...") + conn.execute( + """ + UPDATE users + SET first_name = :first_name, + last_name = :last_name, + password = :password, + user_type = :user_type + WHERE user_id = :user_id + """, + user, + ) + conn.commit() + return { + "legacy_transaction": "CU02", + "legacy_program": "COUSR02C", + "message": f"User {user['user_id']} has been updated ...", + "before": existing, + "user": user, + } + + def delete_user(self, user_id: str) -> dict[str, Any]: + normalized_user_id = self._legacy_upper(user_id, 8) + with self._connect() as conn: + existing = row_to_dict( + conn.execute("SELECT * FROM users WHERE user_id = ?", (normalized_user_id,)).fetchone() + ) + if not existing: + raise KeyError("User ID NOT found...") + conn.execute("DELETE FROM users WHERE user_id = ?", (normalized_user_id,)) + conn.commit() + return { + "legacy_transaction": "CU03", + "legacy_program": "COUSR03C", + "message": f"User {normalized_user_id} has been deleted ...", + "user": existing, + } + + def maintain_transaction_types(self, records: list[str] | str, *, dry_run: bool = False) -> dict[str, Any]: + input_records = records.splitlines() if isinstance(records, str) else [str(record) for record in records] + actions: list[dict[str, Any]] = [] + counts = { + "input_record_count": len(input_records), + "comment_count": 0, + "applied_count": 0, + "error_count": 0, + } + return_code = 0 + + def record_error(entry: dict[str, Any], message: str) -> None: + nonlocal return_code + entry["status"] = "error" + entry["message"] = message + counts["error_count"] += 1 + return_code = 4 + actions.append(entry) + + with self._connect() as conn: + for line_number, record in enumerate(input_records, start=1): + raw_record = record.rstrip("\r\n") + fixed_record = raw_record.ljust(53) + action_code = fixed_record[0:1] + raw_type_code = fixed_record[1:3] + raw_description = fixed_record[3:53] + entry: dict[str, Any] = { + "line_number": line_number, + "action_code": action_code, + "raw_record": raw_record[:53], + "type_code_raw": raw_type_code, + } + if action_code == "*": + entry["status"] = "comment_ignored" + entry["message"] = "IGNORING COMMENTED LINE" + counts["comment_count"] += 1 + actions.append(entry) + continue + if action_code not in {"A", "U", "D"}: + record_error(entry, "ERROR: TYPE NOT VALID") + continue + + try: + type_code = self._normalize_transaction_type_code(raw_type_code) + entry["type_code"] = type_code + description = "" + if action_code in {"A", "U"}: + description = self._normalize_transaction_type_description(raw_description.rstrip()) + entry["description"] = description + except ValueError as exc: + record_error(entry, str(exc)) + continue + + if dry_run: + entry["status"] = {"A": "would_insert", "U": "would_update", "D": "would_delete"}[action_code] + entry["message"] = "Dry run only; database unchanged" + actions.append(entry) + continue + + if action_code == "A": + existing = row_to_dict( + conn.execute( + "SELECT type_code, description FROM transaction_types WHERE type_code = ?", + (type_code,), + ).fetchone() + ) + if existing: + record_error(entry, "Error accessing: TRANSACTION_TYPE table. SQLCODE:-803") + continue + conn.execute( + "INSERT INTO transaction_types(type_code, description) VALUES(?, ?)", + (type_code, description), + ) + conn.commit() + entry["status"] = "inserted" + entry["message"] = "RECORD INSERTED SUCCESSFULLY" + elif action_code == "U": + cursor = conn.execute( + "UPDATE transaction_types SET description = ? WHERE type_code = ?", + (description, type_code), + ) + if cursor.rowcount == 0: + record_error(entry, "No records found.") + continue + conn.commit() + entry["status"] = "updated" + entry["message"] = "RECORD UPDATED SUCCESSFULLY" + else: + existing = row_to_dict( + conn.execute( + "SELECT type_code, description FROM transaction_types WHERE type_code = ?", + (type_code,), + ).fetchone() + ) + if not existing: + record_error(entry, "No records found.") + continue + dependencies = self._transaction_type_dependency_counts(conn, type_code) + entry["dependency_counts"] = dependencies + if any(dependencies.values()): + record_error(entry, "Error accessing: TRANSACTION_TYPE table. SQLCODE:-532") + continue + conn.execute("DELETE FROM transaction_types WHERE type_code = ?", (type_code,)) + conn.commit() + entry["status"] = "deleted" + entry["message"] = "RECORD DELETED SUCCESSFULLY" + counts["applied_count"] += 1 + actions.append(entry) + + return { + "legacy_job": "MNTTRDB2", + "legacy_program": "COBTUPDT", + "legacy_driver": "IKJEFT01", + "legacy_plan": "CARDDEMO", + "input_dd": "INPFILE", + "record_layout": { + "action": "column 1", + "type_code": "columns 2-3", + "description": "columns 4-53", + }, + "dry_run": dry_run, + "return_code": return_code, + "counts": counts, + "actions": actions, + "claim_limit": "Models MNTTRDB2/COBTUPDT fixed-record action routing and Db2 transaction type SQL outcomes over SQLite; exact TSO/Db2 runtime is not replayed", + } + + def transaction_types( + self, + *, + start_key: str = "", + direction: str = "forward", + type_filter: str | None = None, + description_filter: str | None = None, + page_size: int = 7, + ) -> dict[str, Any]: + page_size = max(1, int(page_size)) + normalized_direction = "backward" if str(direction).strip().lower().startswith("back") else "forward" + normalized_start = self._normalize_transaction_type_code(start_key) if str(start_key or "").strip() else "" + normalized_type_filter = ( + self._normalize_transaction_type_code(type_filter) if str(type_filter or "").strip() else "" + ) + normalized_description_filter = self._legacy_text(description_filter, 50).strip() + if normalized_direction == "forward": + start_value = normalized_start or "00" + comparator = ">=" + order = "ASC" + else: + start_value = normalized_start or "99" + comparator = "<" + order = "DESC" + clauses = [f"type_code {comparator} ?"] + params: list[Any] = [start_value] + if normalized_type_filter: + clauses.append("type_code = ?") + params.append(normalized_type_filter) + if normalized_description_filter: + clauses.append("description LIKE ?") + params.append(normalized_description_filter) + params.append(page_size + 1) + with self._connect() as conn: + fetched = rows_to_dicts( + conn.execute( + f""" + SELECT type_code, description FROM transaction_types + WHERE {" AND ".join(clauses)} + ORDER BY type_code {order} + LIMIT ? + """, + params, + ).fetchall() + ) + has_more = len(fetched) > page_size + page_rows = fetched[:page_size] + if normalized_direction == "backward": + page_rows = list(reversed(page_rows)) + return { + "legacy_transaction": "CTLI", + "legacy_program": "COTRTLIC", + "types": page_rows, + "categories": rows_to_dicts( + conn.execute( + "SELECT * FROM transaction_categories ORDER BY type_code, category_code" + ).fetchall() + ), + "page": { + "page_size": page_size, + "direction": normalized_direction, + "start_key": start_value, + "type_filter": normalized_type_filter or None, + "description_filter": normalized_description_filter or None, + "row_count": len(page_rows), + "next_page_exists": has_more if normalized_direction == "forward" else bool(page_rows), + "previous_page_exists": has_more if normalized_direction == "backward" else bool(normalized_start), + "next_start_key": fetched[page_size]["type_code"] + if has_more and normalized_direction == "forward" + else None, + "previous_start_key": page_rows[0]["type_code"] + if page_rows and normalized_direction == "backward" + else None, + "message": "No records found for this search condition." if not page_rows else None, + }, + "claim_limit": "Models COTRTLIC forward/backward DB2 cursor filters over SQLite transaction_types; update/delete actions share the COTRTUPC mutation guards", + } + + def upsert_transaction_type(self, payload: dict[str, Any]) -> dict[str, Any]: + type_code = self._normalize_transaction_type_code(payload.get("type_code")) + description = self._normalize_transaction_type_description(payload.get("description")) + with self._connect() as conn: + existing = row_to_dict( + conn.execute( + "SELECT type_code, description FROM transaction_types WHERE type_code = ?", + (type_code,), + ).fetchone() + ) + if existing and existing["description"].strip().upper() == description.strip().upper(): + raise ValueError("No change detected with respect to values fetched.") + action = "updated" if existing else "inserted" + conn.execute( + """ + INSERT INTO transaction_types(type_code, description) + VALUES(?, ?) + ON CONFLICT(type_code) DO UPDATE SET description = excluded.description + """, + (type_code, description), + ) + conn.commit() + return { + "type_code": type_code, + "description": description, + "action": action, + "legacy_transaction": "CTTU", + "legacy_program": "COTRTUPC", + "message": "Changes committed to database", + "claim_limit": "Implements COTRTUPC type-code/description validation and update-or-insert SQL flow over SQLite transaction_types; CICS confirmation is modeled by the API call boundary", + } + + def delete_transaction_type(self, type_code: str) -> dict[str, Any]: + normalized = self._normalize_transaction_type_code(type_code) + with self._connect() as conn: + existing = row_to_dict( + conn.execute( + "SELECT type_code, description FROM transaction_types WHERE type_code = ?", + (normalized,), + ).fetchone() + ) + if not existing: + raise KeyError("No record found for this key in database") + dependencies = self._transaction_type_dependency_counts(conn, normalized) + if any(dependencies.values()): + raise ValueError("Please delete associated child records first") + conn.execute("DELETE FROM transaction_types WHERE type_code = ?", (normalized,)) + conn.commit() + return { + "type_code": normalized, + "deleted": True, + "legacy_transaction": "CTTU", + "legacy_program": "COTRTUPC", + "message": "Delete committed to database", + "dependency_counts": dependencies, + } + + def _pending_authorization_context(self, conn: sqlite3.Connection, account_id: int) -> dict[str, Any]: + account = row_to_dict(conn.execute("SELECT * FROM accounts WHERE account_id = ?", (account_id,)).fetchone()) + xref = row_to_dict( + conn.execute( + "SELECT * FROM card_xrefs WHERE account_id = ? ORDER BY card_number LIMIT 1", + (account_id,), + ).fetchone() + ) + customer = ( + row_to_dict(conn.execute("SELECT * FROM customers WHERE customer_id = ?", (xref["customer_id"],)).fetchone()) + if xref + else {} + ) + card = ( + row_to_dict(conn.execute("SELECT * FROM cards WHERE card_number = ?", (xref["card_number"],)).fetchone()) + if xref + else {} + ) + return {"account": account, "customer": customer, "card": card, "xref": xref} + + def _decorate_pending_authorization_summary(self, row: dict[str, Any]) -> dict[str, Any]: + out = dict(row) + for key in ( + "credit_limit_cents", + "cash_limit_cents", + "credit_balance_cents", + "cash_balance_cents", + "approved_auth_amount_cents", + "declined_auth_amount_cents", + ): + out[key.removesuffix("_cents")] = money_to_display(out[key]) + out["account_statuses"] = [ + out.pop("account_status_1"), + out.pop("account_status_2"), + out.pop("account_status_3"), + out.pop("account_status_4"), + out.pop("account_status_5"), + ] + return out + + def _decorate_pending_authorization_detail(self, row: dict[str, Any] | None) -> dict[str, Any] | None: + if row is None: + return None + out = dict(row) + out["authorization_date"] = self._auth_date_display(out["auth_orig_date"]) + out["authorization_time"] = self._auth_time_display(out["auth_orig_time"]) + out["transaction_amount"] = money_to_display(out["transaction_amount_cents"]) + out["approved_amount"] = money_to_display(out["approved_amount_cents"]) + out["authorization_response"] = "A" if out["auth_resp_code"] == "00" else "D" + out["auth_resp_reason_description"] = AUTH_DECLINE_REASONS.get(out["auth_resp_reason"], "UNKNOWN") + return out + + def _normalize_authorization_request(self, payload: dict[str, Any]) -> dict[str, Any]: + if payload.get("request_csv"): + fields = [field.strip() for field in str(payload["request_csv"]).split(",")] + if len(fields) < 18: + raise ValueError("authorization request CSV must contain 18 comma-delimited fields") + names = [ + "auth_date", + "auth_time", + "card_number", + "auth_type", + "card_expiry_date", + "message_type", + "message_source", + "processing_code", + "transaction_amount", + "merchant_category_code", + "acqr_country_code", + "pos_entry_mode", + "merchant_id", + "merchant_name", + "merchant_city", + "merchant_state", + "merchant_zip", + "transaction_id", + ] + request = dict(zip(names, fields[:18], strict=True)) + else: + now = datetime.now() + request = { + "auth_date": str(payload.get("auth_date") or now.strftime("%y%m%d")), + "auth_time": str(payload.get("auth_time") or now.strftime("%H%M%S")), + "card_number": str(payload.get("card_number") or ""), + "auth_type": str(payload.get("auth_type") or "0100"), + "card_expiry_date": str(payload.get("card_expiry_date") or "0000"), + "message_type": str(payload.get("message_type") or "1234"), + "message_source": str(payload.get("message_source") or "102030"), + "processing_code": str(payload.get("processing_code") or "000000"), + "transaction_amount": str(payload.get("transaction_amount") or payload.get("amount") or "0.00"), + "merchant_category_code": str(payload.get("merchant_category_code") or "0000"), + "acqr_country_code": str(payload.get("acqr_country_code") or "USA"), + "pos_entry_mode": str(payload.get("pos_entry_mode") or "00"), + "merchant_id": str(payload.get("merchant_id") or "").ljust(15)[:15].rstrip(), + "merchant_name": str(payload.get("merchant_name") or "").ljust(22)[:22].rstrip(), + "merchant_city": str(payload.get("merchant_city") or "").ljust(13)[:13].rstrip(), + "merchant_state": str(payload.get("merchant_state") or "").ljust(2)[:2].rstrip(), + "merchant_zip": str(payload.get("merchant_zip") or "").ljust(9)[:9].rstrip(), + "transaction_id": str(payload.get("transaction_id") or now.strftime("%H%M%S%f")[:15]), + } + if "transaction_amount_cents" in payload: + request["transaction_amount_cents"] = int(payload["transaction_amount_cents"]) + if not request["card_number"]: + raise ValueError("card_number is required") + if not request["transaction_id"]: + raise ValueError("transaction_id is required") + request["card_number"] = request["card_number"].strip() + request["processing_code"] = request["processing_code"].strip().zfill(6)[-6:] + request["pos_entry_mode"] = request["pos_entry_mode"].strip().zfill(2)[-2:] + return request + + def _auth_request_amount_cents(self, request: dict[str, Any]) -> int: + if "transaction_amount_cents" in request: + return int(request["transaction_amount_cents"]) + text = str(request["transaction_amount"]).strip().replace("+", "") + try: + return int((Decimal(text) * 100).to_integral_value()) + except (InvalidOperation, ValueError) as exc: + raise ValueError("authorization transaction amount must be numeric") from exc + + def _auth_amount_display(self, amount_cents: int) -> str: + sign = "-" if amount_cents < 0 else "+" + value = abs(int(amount_cents)) + return f"{sign}{value // 100:010d}.{value % 100:02d}" + + def _new_pending_summary( + self, + conn: sqlite3.Connection, + account: dict[str, Any], + xref: dict[str, Any], + ) -> dict[str, Any]: + sequence_no = int( + conn.execute("SELECT COALESCE(MAX(sequence_no), 0) + 1 FROM pending_authorization_summaries").fetchone()[0] + ) + summary = { + "account_id": int(account["account_id"]), + "customer_id": int(xref["customer_id"]), + "sequence_no": sequence_no, + "auth_status": "", + "account_status_1": "", + "account_status_2": "", + "account_status_3": "", + "account_status_4": "", + "account_status_5": "00", + "credit_limit_cents": int(account["credit_limit_cents"]), + "cash_limit_cents": int(account["cash_credit_limit_cents"]), + "credit_balance_cents": 0, + "cash_balance_cents": 0, + "approved_auth_count": 0, + "declined_auth_count": 0, + "approved_auth_amount_cents": 0, + "declined_auth_amount_cents": 0, + } + columns = ", ".join(summary) + placeholders = ", ".join(f":{key}" for key in summary) + conn.execute(f"INSERT INTO pending_authorization_summaries ({columns}) VALUES ({placeholders})", summary) + return summary + + def _apply_authorization_to_summary( + self, + conn: sqlite3.Connection, + summary: dict[str, Any], + amount_cents: int, + approved: bool, + account: dict[str, Any], + ) -> None: + summary["credit_limit_cents"] = int(account["credit_limit_cents"]) + summary["cash_limit_cents"] = int(account["cash_credit_limit_cents"]) + if approved: + summary["approved_auth_count"] = int(summary["approved_auth_count"]) + 1 + summary["approved_auth_amount_cents"] = int(summary["approved_auth_amount_cents"]) + amount_cents + summary["credit_balance_cents"] = int(summary["credit_balance_cents"]) + amount_cents + summary["cash_balance_cents"] = 0 + else: + summary["declined_auth_count"] = int(summary["declined_auth_count"]) + 1 + summary["declined_auth_amount_cents"] = int(summary["declined_auth_amount_cents"]) + amount_cents + conn.execute( + """ + UPDATE pending_authorization_summaries + SET credit_limit_cents = ?, + cash_limit_cents = ?, + credit_balance_cents = ?, + cash_balance_cents = ?, + approved_auth_count = ?, + declined_auth_count = ?, + approved_auth_amount_cents = ?, + declined_auth_amount_cents = ? + WHERE account_id = ? + """, + ( + summary["credit_limit_cents"], + summary["cash_limit_cents"], + summary["credit_balance_cents"], + summary["cash_balance_cents"], + summary["approved_auth_count"], + summary["declined_auth_count"], + summary["approved_auth_amount_cents"], + summary["declined_auth_amount_cents"], + summary["account_id"], + ), + ) + + def _insert_pending_authorization_detail( + self, + conn: sqlite3.Connection, + *, + account_id: int, + request: dict[str, Any], + response: dict[str, Any], + amount_cents: int, + approved: bool, + processing_datetime: Any = None, + ) -> dict[str, Any]: + processed_at = self._coerce_auth_datetime(processing_datetime) + auth_date_key, auth_time_key, auth_yyddd, authorization_key = self._authorization_key(processed_at) + while conn.execute( + """ + SELECT 1 FROM pending_authorization_details + WHERE account_id = ? AND authorization_key = ? + """, + (account_id, authorization_key), + ).fetchone(): + auth_time_key -= 1 + authorization_key = self._pack_packed_decimal(auth_date_key, 5).hex() + self._pack_packed_decimal( + auth_time_key, 9 + ).hex() + sequence_no = int( + conn.execute("SELECT COALESCE(MAX(sequence_no), 0) + 1 FROM pending_authorization_details").fetchone()[0] + ) + detail = { + "account_id": account_id, + "sequence_no": sequence_no, + "authorization_key": authorization_key, + "auth_date_key": auth_date_key, + "auth_time_key": auth_time_key, + "auth_yyddd": auth_yyddd, + "auth_orig_date": request["auth_date"], + "auth_orig_time": request["auth_time"], + "card_number": request["card_number"], + "auth_type": request["auth_type"], + "card_expiry_date": request["card_expiry_date"], + "message_type": request["message_type"], + "message_source": request["message_source"], + "auth_id_code": response["auth_id_code"], + "auth_resp_code": response["auth_resp_code"], + "auth_resp_reason": response["auth_resp_reason"], + "processing_code": request["processing_code"], + "transaction_amount_cents": amount_cents, + "approved_amount_cents": amount_cents if approved else 0, + "merchant_category_code": request["merchant_category_code"], + "acqr_country_code": request["acqr_country_code"], + "pos_entry_mode": request["pos_entry_mode"], + "merchant_id": request["merchant_id"], + "merchant_name": request["merchant_name"], + "merchant_city": request["merchant_city"], + "merchant_state": request["merchant_state"], + "merchant_zip": request["merchant_zip"], + "transaction_id": request["transaction_id"], + "match_status": "P" if approved else "D", + "auth_fraud": "", + "fraud_rpt_date": "", + } + columns = ", ".join(detail) + placeholders = ", ".join(f":{key}" for key in detail) + conn.execute(f"INSERT INTO pending_authorization_details ({columns}) VALUES ({placeholders})", detail) + return detail + + def _coerce_auth_datetime(self, value: Any) -> datetime: + if isinstance(value, datetime): + return value + if value: + return datetime.fromisoformat(str(value).replace("Z", "+00:00")) + return datetime.now() + + def _authorization_key(self, value: datetime) -> tuple[int, int, int, str]: + auth_yyddd = int(value.strftime("%y%j")) + time_with_ms = int(value.strftime("%H%M%S")) * 1000 + (value.microsecond // 1000) + auth_date_key = 99999 - auth_yyddd + auth_time_key = 999999999 - time_with_ms + authorization_key = self._pack_packed_decimal(auth_date_key, 5).hex() + self._pack_packed_decimal( + auth_time_key, 9 + ).hex() + return auth_date_key, auth_time_key, auth_yyddd, authorization_key + + def _pack_packed_decimal(self, value: int, digits: int) -> bytes: + nibbles = f"{abs(int(value)):0{digits}d}" + ("D" if int(value) < 0 else "C") + return bytes(int(nibbles[index : index + 2], 16) for index in range(0, len(nibbles), 2)) + + def _auth_timestamp(self, row: dict[str, Any]) -> str: + raw_date = str(row["auth_orig_date"]).zfill(6) + raw_time = str(row["auth_orig_time"]).zfill(6) + year = int(raw_date[:2]) + century = 1900 if year >= 70 else 2000 + return ( + f"{century + year:04d}-{raw_date[2:4]}-{raw_date[4:6]} " + f"{raw_time[:2]}:{raw_time[2:4]}:{raw_time[4:6]}" + ) + + def _auth_date_display(self, raw_date: str) -> str: + raw_date = str(raw_date).zfill(6) + return f"{raw_date[2:4]}/{raw_date[4:6]}/{raw_date[:2]}" + + def _auth_time_display(self, raw_time: str) -> str: + raw_time = str(raw_time).zfill(6) + return f"{raw_time[:2]}:{raw_time[2:4]}:{raw_time[4:6]}" + + def _normalize_account_update_payload( + self, + account: dict[str, Any], + customer: dict[str, Any], + payload: dict[str, Any], + ) -> tuple[dict[str, Any], dict[str, Any]]: + account_specs = { + "active_status": lambda value: self._caup_yes_no(value, "Account Status"), + "current_balance_cents": lambda value: self._caup_money_cents(value, "Current Balance"), + "credit_limit_cents": lambda value: self._caup_money_cents(value, "Credit Limit"), + "cash_credit_limit_cents": lambda value: self._caup_money_cents(value, "Cash Credit Limit"), + "open_date": lambda value: self._caup_date(value, "Open Date"), + "expiration_date": lambda value: self._caup_date(value, "Expiry Date"), + "reissue_date": lambda value: self._caup_date(value, "Reissue Date"), + "current_cycle_credit_cents": lambda value: self._caup_money_cents(value, "Current Cycle Credit Limit"), + "current_cycle_debit_cents": lambda value: self._caup_money_cents(value, "Current Cycle Debit Limit"), + "zip_code": lambda value: self._caup_numeric_text(value, 5, "Account Zip"), + "group_id": lambda value: self._caup_required_text(value, 10, "Account Group"), + } + customer_specs = { + "first_name": lambda value: self._caup_alpha_text(value, 25, "First Name", required=True), + "middle_name": lambda value: self._caup_alpha_text(value, 25, "Middle Name", required=False), + "last_name": lambda value: self._caup_alpha_text(value, 25, "Last Name", required=True), + "address_line_1": lambda value: self._caup_required_text(value, 50, "Address Line 1"), + "address_line_2": lambda value: self._legacy_text(value, 50), + "address_line_3": lambda value: self._caup_alpha_text(value, 50, "City", required=True), + "state": self._caup_state, + "country": lambda value: self._caup_alpha_text(value, 3, "Country", required=True), + "zip_code": lambda value: self._caup_numeric_text(value, 5, "Zip"), + "phone_1": lambda value: self._caup_phone(value, "Phone Number 1"), + "phone_2": lambda value: self._caup_phone(value, "Phone Number 2"), + "ssn": self._caup_ssn, + "government_id": lambda value: self._caup_required_text(value, 20, "Government ID"), + "date_of_birth": lambda value: self._caup_date(value, "Date of Birth"), + "eft_account_id": lambda value: self._caup_numeric_text(value, 10, "EFT Account Id"), + "primary_card_holder": lambda value: self._caup_yes_no(value, "Primary Card Holder"), + "fico_score": self._caup_fico, + } + account_changes: dict[str, Any] = {} + for key, normalizer in account_specs.items(): + if key in payload: + account_changes[key] = normalizer(payload[key]) + + customer_payload = dict(payload.get("customer") or {}) + for external_key, internal_key in { + "customer_first_name": "first_name", + "customer_middle_name": "middle_name", + "customer_last_name": "last_name", + "customer_address_line_1": "address_line_1", + "customer_address_line_2": "address_line_2", + "customer_city": "address_line_3", + "customer_state": "state", + "customer_country": "country", + "customer_zip_code": "zip_code", + "customer_phone_1": "phone_1", + "customer_phone_2": "phone_2", + "customer_ssn": "ssn", + "customer_government_id": "government_id", + "customer_date_of_birth": "date_of_birth", + "customer_eft_account_id": "eft_account_id", + "customer_primary_card_holder": "primary_card_holder", + "customer_fico_score": "fico_score", + }.items(): + if external_key in payload: + customer_payload[internal_key] = payload[external_key] + + customer_changes: dict[str, Any] = {} + for key, normalizer in customer_specs.items(): + if key in customer_payload: + customer_changes[key] = normalizer(customer_payload[key]) + + if "state" in customer_changes and "zip_code" in customer_changes: + self._caup_state_zip_pair(customer_changes["state"], customer_changes["zip_code"]) + elif "state" in customer_changes: + self._caup_state_zip_pair(customer_changes["state"], str(customer.get("zip_code") or "")) + elif "zip_code" in customer_changes: + self._caup_state_zip_pair(str(customer.get("state") or ""), customer_changes["zip_code"]) + return account_changes, customer_changes + + def _normalize_card_account_id(self, value: Any) -> int: + text = str(value or "").strip() + if not text: + raise ValueError("Account number must be a non zero 11 digit number") + if not text.isdigit() or len(text) > 11 or int(text) == 0: + raise ValueError("Account number must be a non zero 11 digit number") + return int(text) + + def _normalize_card_number(self, value: Any) -> str: + text = str(value or "").strip() + if not text: + raise ValueError("Card number not provided") + if not text.isdigit() or len(text) != 16 or int(text) == 0: + raise ValueError("Card number if supplied must be a 16 digit number") + return text + + def _normalize_card_embossed_name(self, value: Any) -> str: + text = self._legacy_text(value, 50) + if not text: + raise ValueError("Card name not provided") + if any(not (char.isalpha() or char == " ") for char in text): + raise ValueError("Card name can only contain alphabets and spaces") + return text + + def _normalize_card_status(self, value: Any) -> str: + status = self._legacy_upper(value, 1) + if status not in {"Y", "N"}: + raise ValueError("Card Active Status must be Y or N") + return status + + def _normalize_card_expiry_parts(self, current: dict[str, Any], payload: dict[str, Any]) -> tuple[str, str]: + old_year, old_month, _old_day = str(current["expiration_date"]).split("-") + if "expiration_date" in payload and payload["expiration_date"]: + date_text = str(payload["expiration_date"]).strip()[:10] + if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_text): + raise ValueError("Invalid card expiry year") + year_text, month_text, _day_text = date_text.split("-") + else: + month_text = str(payload.get("expiration_month", old_month)).strip() + year_text = str(payload.get("expiration_year", old_year)).strip() + month = self._normalize_card_expiry_month(month_text) + year = self._normalize_card_expiry_year(year_text) + return month, year + + def _normalize_card_expiry_month(self, value: Any) -> str: + text = str(value or "").strip() + if not text.isdigit(): + raise ValueError("Card expiry month must be between 1 and 12") + month = int(text) + if not 1 <= month <= 12: + raise ValueError("Card expiry month must be between 1 and 12") + return f"{month:02d}" + + def _normalize_card_expiry_year(self, value: Any) -> str: + text = str(value or "").strip() + if not text.isdigit() or len(text) != 4: + raise ValueError("Invalid card expiry year") + year = int(text) + if not 1950 <= year <= 2099: + raise ValueError("Invalid card expiry year") + return text + + def _normalize_transaction_type_code(self, value: Any) -> str: + raw = str(value or "").strip() + if not raw: + raise ValueError("Tran Type code must be supplied.") + if not raw.isdecimal() or len(raw) > 2: + raise ValueError("Tran Type code must be numeric.") + normalized = raw.zfill(2) + if int(normalized) == 0: + raise ValueError("Tran Type code must not be zero.") + return normalized + + def _normalize_transaction_type_description(self, value: Any) -> str: + raw = str(value or "").strip() + if not raw: + raise ValueError("Transaction Desc must be supplied.") + if len(raw) > 50: + raise ValueError("Transaction Desc can have numbers or alphabets only.") + if not re.fullmatch(r"[A-Za-z0-9 ]+", raw): + raise ValueError("Transaction Desc can have numbers or alphabets only.") + return raw + + def _transaction_type_dependency_counts(self, conn: sqlite3.Connection, type_code: str) -> dict[str, int]: + tables = { + "transactions": "transactions", + "transaction_categories": "transaction_categories", + "disclosure_groups": "disclosure_groups", + "transaction_category_balances": "transaction_category_balances", + } + return { + name: int(conn.execute(f"SELECT COUNT(*) FROM {table} WHERE type_code = ?", (type_code,)).fetchone()[0]) + for name, table in tables.items() + } + + def _caup_money_cents(self, value: Any, label: str) -> int: + if isinstance(value, int): + return int(value) + text = str(value or "").strip() + if not text: + raise ValueError(f"{label} must be supplied.") + cleaned = text.replace(",", "").replace("$", "") + match = re.fullmatch(r"([+-]?)(\d+)(?:\.(\d{1,2}))?", cleaned) + if not match: + raise ValueError(f"{label} is not valid") + sign, dollars_text, cents_text = match.groups() + dollars = int(dollars_text) + cents = int((cents_text or "0").ljust(2, "0")) + amount = dollars * 100 + cents + return -amount if sign == "-" else amount + + def _caup_date(self, value: Any, label: str) -> str: + date_text = str(value or "").strip()[:10] + if not date_text: + raise ValueError(f"{label} must be supplied.") + if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_text): + raise ValueError(f"{label} is not valid") + try: + datetime.strptime(date_text, "%Y-%m-%d") + except ValueError as exc: + raise ValueError(f"{label} is not valid") from exc + return date_text + + def _caup_yes_no(self, value: Any, label: str) -> str: + text = self._legacy_upper(value, 1) + if not text: + raise ValueError(f"{label} must be supplied.") + if text not in {"Y", "N"}: + raise ValueError(f"{label} must be Y or N.") + return text + + def _caup_required_text(self, value: Any, width: int, label: str) -> str: + text = self._legacy_text(value, width) + if not text: + raise ValueError(f"{label} must be supplied.") + return text + + def _caup_numeric_text(self, value: Any, width: int, label: str) -> str: + text = self._caup_required_text(value, width, label) + if not text.isdigit(): + raise ValueError(f"{label} must be all numeric.") + if int(text) == 0: + raise ValueError(f"{label} must not be zero.") + return text + + def _caup_alpha_text(self, value: Any, width: int, label: str, *, required: bool) -> str: + text = self._legacy_text(value, width) + if not text: + if required: + raise ValueError(f"{label} must be supplied.") + return "" + if any(not (char.isalpha() or char == " ") for char in text): + raise ValueError(f"{label} can have alphabets only.") + return text + + def _caup_state(self, value: Any) -> str: + state = self._caup_alpha_text(value, 2, "State", required=True).upper() + if state not in US_STATE_CODES: + raise ValueError("State: is not a valid state code") + return state + + def _caup_state_zip_pair(self, state: str, zip_code: str) -> None: + if state and zip_code and state in US_STATE_CODES and not zip_code[:2].isdigit(): + raise ValueError("Zip must be all numeric.") + + def _caup_phone(self, value: Any, label: str) -> str: + text = self._caup_required_text(value, 15, label) + digits = re.sub(r"\D", "", text) + if len(digits) != 10: + raise ValueError(f"{label} is not valid") + return f"({digits[:3]}){digits[3:6]}-{digits[6:]}" + + def _caup_ssn(self, value: Any) -> str: + text = self._caup_numeric_text(value, 9, "SSN") + first = int(text[:3]) + if first in {0, 666} or 900 <= first <= 999: + raise ValueError("SSN: should not be 000, 666, or between 900 and 999") + if int(text[3:5]) == 0: + raise ValueError("SSN 4th & 5th chars must not be zero.") + if int(text[5:9]) == 0: + raise ValueError("SSN Last 4 chars must not be zero.") + return text + + def _caup_fico(self, value: Any) -> int: + text = self._caup_numeric_text(value, 3, "FICO Score") + score = int(text) + if not 300 <= score <= 850: + raise ValueError("FICO Score: should be between 300 and 850") + return score + + def _validate_transaction_add(self, conn, payload: dict[str, Any]) -> dict[str, Any]: + resolved = self._resolve_transaction_add_key(conn, payload) + fields = { + "type_code": self._legacy_numeric_text(payload.get("type_code"), 2, "Type CD can NOT be empty...", "Type CD must be Numeric..."), + "category_code": self._legacy_numeric_text( + payload.get("category_code"), + 4, + "Category CD can NOT be empty...", + "Category CD must be Numeric...", + ), + "source": self._legacy_required_text(payload.get("source"), 10, "Source can NOT be empty..."), + "description": self._legacy_required_text( + payload.get("description"), + 60, + "Description can NOT be empty...", + ), + "merchant_id": self._legacy_numeric_text( + payload.get("merchant_id"), + 9, + "Merchant ID can NOT be empty...", + "Merchant ID must be Numeric...", + ), + "merchant_name": self._legacy_required_text( + payload.get("merchant_name"), + 30, + "Merchant Name can NOT be empty...", + ), + "merchant_city": self._legacy_required_text( + payload.get("merchant_city"), + 25, + "Merchant City can NOT be empty...", + ), + "merchant_zip": self._legacy_required_text(payload.get("merchant_zip"), 10, "Merchant Zip can NOT be empty..."), + } + amount_cents = self._parse_transaction_add_amount(payload) + original_date = self._legacy_date(payload.get("original_timestamp") or payload.get("original_date"), "Orig Date") + processed_date = self._legacy_date(payload.get("processed_timestamp") or payload.get("processed_date"), "Proc Date") + confirm = str(payload.get("confirm") or "").strip() + if confirm in {"", "N", "n"}: + raise ValueError("Confirm to add this transaction...") + if confirm not in {"Y", "y"}: + raise ValueError("Invalid value. Valid values are (Y/N)...") + return { + **resolved, + **fields, + "amount_cents": amount_cents, + "legacy_amount": self._format_legacy_amount(amount_cents), + "original_date": original_date, + "processed_date": processed_date, + } + + def _resolve_transaction_add_key(self, conn, payload: dict[str, Any]) -> dict[str, Any]: + account_id_text = str(payload.get("account_id") or "").strip() + card_number = str(payload.get("card_number") or "").strip() + if account_id_text: + if not account_id_text.isdigit(): + raise ValueError("Account ID must be Numeric...") + account_id = int(account_id_text) + xref = conn.execute( + """ + SELECT * FROM card_xrefs + WHERE account_id = ? + ORDER BY card_number + LIMIT 1 + """, + (account_id,), + ).fetchone() + if not xref: + raise KeyError("Account ID NOT found...") + return {"account_id": account_id, "card_number": str(xref["card_number"])} + if card_number: + if not card_number.isdigit(): + raise ValueError("Card Number must be Numeric...") + xref = conn.execute("SELECT * FROM card_xrefs WHERE card_number = ?", (card_number,)).fetchone() + if not xref: + raise KeyError("Card Number NOT found...") + return {"account_id": int(xref["account_id"]), "card_number": str(xref["card_number"])} + raise ValueError("Account or Card Number must be entered...") + + def _parse_transaction_add_amount(self, payload: dict[str, Any]) -> int: + if payload.get("amount_cents") is not None and str(payload.get("amount_cents")).strip() != "": + amount_cents = int(payload["amount_cents"]) + self._format_legacy_amount(amount_cents) + return amount_cents + amount = str(payload.get("amount") or "").strip() + if not amount: + raise ValueError("Amount can NOT be empty...") + if ( + len(amount) != 12 + or amount[0] not in {"+", "-"} + or not amount[1:9].isdigit() + or amount[9] != "." + or not amount[10:12].isdigit() + ): + raise ValueError("Amount should be in format -99999999.99") + dollars = int(amount[1:9]) + cents = int(amount[10:12]) + amount_cents = dollars * 100 + cents + return -amount_cents if amount[0] == "-" else amount_cents + + def _format_legacy_amount(self, amount_cents: int) -> str: + sign = "-" if int(amount_cents) < 0 else "+" + absolute = abs(int(amount_cents)) + dollars, cents = divmod(absolute, 100) + if dollars > 99999999: + raise ValueError("Amount should be in format -99999999.99") + return f"{sign}{dollars:08d}.{cents:02d}" + + def _coerce_mq_datetime(self, value: Any = None) -> datetime: + if isinstance(value, datetime): + return value + if value: + text = str(value).strip() + for fmt, width in ( + ("%Y-%m-%dT%H:%M:%S", 19), + ("%Y-%m-%d %H:%M:%S", 19), + ("%Y-%m-%d", 10), + ): + try: + return datetime.strptime(text[:width], fmt) + except ValueError: + continue + try: + return datetime.fromisoformat(text) + except ValueError as exc: + raise ValueError("MQ date/time should be ISO-like, for example 2026-05-23T11:12:13") from exc + return datetime.now() + + def _mq_request_from_payload(self, payload: dict[str, Any], *, default_function: str) -> dict[str, Any]: + raw = payload.get("request_message") + if raw is not None: + request_message = str(raw).ljust(1000)[:1000] + function = request_message[:4].upper() + key_text = request_message[4:15] + else: + function = str(payload.get("function") or payload.get("request_type") or default_function).strip().upper() + function = function[:4].ljust(4) + key_text = self._mq_key_text( + payload.get("account_id", payload.get("account_number", payload.get("key", 0))) + ) + request_message = f"{function}{key_text}".ljust(1000)[:1000] + account_id = int(key_text) if key_text.isdigit() else 0 + return { + "function": function, + "function_display": function.rstrip(), + "account_id": account_id, + "account_id_text": key_text, + "request_message": request_message, + } + + def _mq_key_text(self, value: Any) -> str: + text = str(value or "").strip() + if not text or not text.isdigit(): + return "00000000000" + return f"{int(text):011d}"[-11:] + + def _account_mq_data(self, account: dict[str, Any]) -> dict[str, Any]: + return { + "account_id": int(account["account_id"]), + "account_id_text": f"{int(account['account_id']):011d}", + "active_status": account["active_status"], + "current_balance_cents": int(account["current_balance_cents"]), + "current_balance": money_to_display(account["current_balance_cents"]), + "credit_limit_cents": int(account["credit_limit_cents"]), + "credit_limit": money_to_display(account["credit_limit_cents"]), + "cash_credit_limit_cents": int(account["cash_credit_limit_cents"]), + "cash_credit_limit": money_to_display(account["cash_credit_limit_cents"]), + "open_date": account["open_date"], + "expiration_date": account["expiration_date"], + "reissue_date": account["reissue_date"], + "current_cycle_credit_cents": int(account["current_cycle_credit_cents"]), + "current_cycle_credit": money_to_display(account["current_cycle_credit_cents"]), + "current_cycle_debit_cents": int(account["current_cycle_debit_cents"]), + "current_cycle_debit": money_to_display(account["current_cycle_debit_cents"]), + "group_id": account["group_id"], + } + + def _format_account_mq_reply(self, account: dict[str, Any]) -> str: + data = self._account_mq_data(account) + return ( + f"ACCOUNT ID : {data['account_id_text']}" + f"ACCOUNT STATUS : {data['active_status']}" + f"BALANCE : {data['current_balance']}" + f"CREDIT LIMIT : {data['credit_limit']}" + f"CASH LIMIT : {data['cash_credit_limit']}" + f"OPEN DATE : {data['open_date']}" + f"EXPR DATE : {data['expiration_date']}" + f"REIS DATE : {data['reissue_date']}" + f"CREDIT BAL : {data['current_cycle_credit']}" + f"DEBIT BAL : {data['current_cycle_debit']}" + f"GROUP ID : {data['group_id']}" + ) + + def _invalid_account_mq_reply(self, account_id: int, function: str, *, include_function: bool) -> str: + reply = f"INVALID REQUEST PARAMETERS ACCT ID : {int(account_id):011d}" + if include_function: + reply += f"FUNCTION : {function}" + return reply + + def _legacy_date(self, value: Any, label: str) -> str: + date_text = str(value or "").strip()[:10] + if not date_text: + raise ValueError(f"{label} can NOT be empty...") + if ( + len(date_text) != 10 + or not date_text[0:4].isdigit() + or date_text[4] != "-" + or not date_text[5:7].isdigit() + or date_text[7] != "-" + or not date_text[8:10].isdigit() + ): + raise ValueError(f"{label} should be in format YYYY-MM-DD") + try: + datetime.strptime(date_text, "%Y-%m-%d") + except ValueError as exc: + raise ValueError(f"{label} - Not a valid date...") from exc + return date_text + + def _legacy_required_text(self, value: Any, width: int, empty_message: str) -> str: + text = self._legacy_text(value, width) + if not text: + raise ValueError(empty_message) + return text + + def _legacy_numeric_text(self, value: Any, width: int, empty_message: str, numeric_message: str) -> str: + text = self._legacy_required_text(value, width, empty_message) + if not text.isdigit(): + raise ValueError(numeric_message) + return text.zfill(width)[-width:] + + def _signon_failure(self, message: str, reason: str, *, user_id: str = "") -> dict[str, Any]: + return { + "legacy_transaction": "CC00", + "legacy_program": "COSGN00C", + "authenticated": False, + "reason": reason, + "user_id": user_id, + "message": message, + } + + def _normalize_user_payload(self, payload: dict[str, Any]) -> dict[str, Any]: + return { + "user_id": self._legacy_upper(payload.get("user_id"), 8), + "first_name": self._legacy_text(payload.get("first_name"), 20), + "last_name": self._legacy_text(payload.get("last_name"), 20), + "password": self._legacy_upper(payload.get("password"), 8), + "user_type": self._legacy_upper(payload.get("user_type"), 1), + } + + def _require_user_fields(self, user: dict[str, Any]) -> None: + field_labels = { + "user_id": "User ID", + "first_name": "First Name", + "last_name": "Last Name", + "password": "Password", + "user_type": "User Type", + } + for field, label in field_labels.items(): + if not str(user.get(field) or "").strip(): + raise ValueError(f"{label} can NOT be empty...") + + def _legacy_upper(self, value: Any, width: int) -> str: + return self._legacy_text(value, width).upper() + + def _legacy_text(self, value: Any, width: int) -> str: + return str(value or "").strip()[:width] + + def _decorate_money(self, row: dict[str, Any]) -> dict[str, Any]: + for key, value in list(row.items()): + if key.endswith("_cents"): + row[key[:-6]] = money_to_display(value) + return row + + def _next_transaction_id(self, conn) -> str: + last_id = conn.execute("SELECT MAX(CAST(transaction_id AS INTEGER)) FROM transactions").fetchone()[0] or 0 + return f"{int(last_id) + 1:016d}" + + def _validate_post_transaction(self, conn, payload: dict[str, Any]) -> dict[str, Any]: + card_number = str(payload.get("card_number") or "").strip() + amount_cents = int(payload.get("amount_cents") or 0) + original_date = str(payload.get("original_timestamp") or "")[:10] + xref = conn.execute("SELECT * FROM card_xrefs WHERE card_number = ?", (card_number,)).fetchone() + if not xref: + return self._posttran_reject(100, card_number=card_number) + account = conn.execute("SELECT * FROM accounts WHERE account_id = ?", (xref["account_id"],)).fetchone() + if not account: + return self._posttran_reject(101, card_number=card_number, account_id=xref["account_id"]) + temp_balance = ( + int(account["current_cycle_credit_cents"]) + - int(account["current_cycle_debit_cents"]) + + amount_cents + ) + if int(account["credit_limit_cents"]) < temp_balance: + return self._posttran_reject( + 102, + card_number=card_number, + account_id=account["account_id"], + temp_balance_cents=temp_balance, + credit_limit_cents=account["credit_limit_cents"], + ) + if original_date and str(account["expiration_date"]) < original_date: + return self._posttran_reject( + 103, + card_number=card_number, + account_id=account["account_id"], + original_date=original_date, + expiration_date=account["expiration_date"], + ) + return { + "accepted": True, + "reason_code": 0, + "reason_description": "", + "card_number": card_number, + "account_id": int(account["account_id"]), + "temp_balance_cents": temp_balance, + "temp_balance": money_to_display(temp_balance), + "credit_limit_cents": int(account["credit_limit_cents"]), + "credit_limit": money_to_display(account["credit_limit_cents"]), + } + + def _posttran_reject(self, reason_code: int, **extra: Any) -> dict[str, Any]: + return { + "accepted": False, + "reason_code": reason_code, + "reason_description": POSTTRAN_REJECT_REASONS[reason_code], + **extra, + }