from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Iterable POS_OVERPUNCH = { "{": "0", "A": "1", "B": "2", "C": "3", "D": "4", "E": "5", "F": "6", "G": "7", "H": "8", "I": "9", } NEG_OVERPUNCH = { "}": "0", "J": "1", "K": "2", "L": "3", "M": "4", "N": "5", "O": "6", "P": "7", "Q": "8", "R": "9", } @dataclass(frozen=True) class Field: name: str start: int length: int kind: str = "text" scale: int = 0 CUSTOMER_FIELDS = [ Field("customer_id", 0, 9, "int"), Field("first_name", 9, 25), Field("middle_name", 34, 25), Field("last_name", 59, 25), Field("address_line_1", 84, 50), Field("address_line_2", 134, 50), Field("address_line_3", 184, 50), Field("state", 234, 2), Field("country", 236, 3), Field("zip_code", 239, 10), Field("phone_1", 249, 15), Field("phone_2", 264, 15), Field("ssn", 279, 9), Field("government_id", 288, 20), Field("date_of_birth", 308, 10), Field("eft_account_id", 318, 10), Field("primary_card_holder", 328, 1), Field("fico_score", 329, 3, "int"), ] ACCOUNT_FIELDS = [ Field("account_id", 0, 11, "int"), Field("active_status", 11, 1), Field("current_balance_cents", 12, 12, "money", 2), Field("credit_limit_cents", 24, 12, "money", 2), Field("cash_credit_limit_cents", 36, 12, "money", 2), Field("open_date", 48, 10), Field("expiration_date", 58, 10), Field("reissue_date", 68, 10), Field("current_cycle_credit_cents", 78, 12, "money", 2), Field("current_cycle_debit_cents", 90, 12, "money", 2), Field("zip_code", 102, 10), Field("group_id", 112, 10), ] CARD_FIELDS = [ Field("card_number", 0, 16), Field("account_id", 16, 11, "int"), Field("cvv", 27, 3), Field("embossed_name", 30, 50), Field("expiration_date", 80, 10), Field("active_status", 90, 1), ] CARD_XREF_FIELDS = [ Field("card_number", 0, 16), Field("customer_id", 16, 9, "int"), Field("account_id", 25, 11, "int"), ] TRANSACTION_FIELDS = [ Field("transaction_id", 0, 16), Field("type_code", 16, 2), Field("category_code", 18, 4), Field("source", 22, 10), Field("description", 32, 100), Field("amount_cents", 132, 11, "money", 2), Field("merchant_id", 143, 9), Field("merchant_name", 152, 50), Field("merchant_city", 202, 50), Field("merchant_zip", 252, 10), Field("card_number", 262, 16), Field("original_timestamp", 278, 26), Field("processed_timestamp", 304, 26), ] TRANSACTION_TYPE_FIELDS = [ Field("type_code", 0, 2), Field("description", 2, 50), ] TRANSACTION_CATEGORY_FIELDS = [ Field("type_code", 0, 2), Field("category_code", 2, 4), Field("description", 6, 50), ] DISCLOSURE_GROUP_FIELDS = [ Field("group_id", 0, 10), Field("type_code", 10, 2), Field("category_code", 12, 4), Field("interest_rate_basis_points", 16, 6, "money", 2), ] TRANSACTION_CATEGORY_BALANCE_FIELDS = [ Field("account_id", 0, 11, "int"), Field("type_code", 11, 2), Field("category_code", 13, 4), Field("balance_cents", 17, 11, "money", 2), ] USER_FIELDS = [ Field("user_id", 0, 8), Field("first_name", 8, 20), Field("last_name", 28, 20), Field("password", 48, 8), Field("user_type", 56, 1), ] PAUTSUM0_MARKER = b"\xd7\xc1\xe4\xe3\xe2\xe4\xd4\xf0" PAUTDTL1_MARKER = b"\xd7\xc1\xe4\xe3\xc4\xe3\xd3\xf1" IMS_UNLOAD_SEGMENT_DATA_OFFSET = 29 def parse_overpunch_int(raw: str) -> int: text = raw.strip() if not text: return 0 last = text[-1] sign = 1 if last in POS_OVERPUNCH: text = text[:-1] + POS_OVERPUNCH[last] elif last in NEG_OVERPUNCH: text = text[:-1] + NEG_OVERPUNCH[last] sign = -1 elif last in "+-": sign = -1 if last == "-" else 1 text = text[:-1] return sign * int(text or "0") def parse_money(raw: str, scale: int = 2) -> int: return parse_overpunch_int(raw) if scale == 2 else parse_overpunch_int(raw) def money_to_display(cents: int | None) -> str: cents = int(cents or 0) sign = "-" if cents < 0 else "" value = abs(cents) return f"{sign}{value // 100}.{value % 100:02d}" def parse_fixed_width(line: str, fields: Iterable[Field]) -> dict[str, object]: out: dict[str, object] = {} for field in fields: raw = line[field.start : field.start + field.length] if field.kind == "int": out[field.name] = int(raw.strip() or "0") elif field.kind == "money": out[field.name] = parse_money(raw, field.scale) else: out[field.name] = raw.rstrip() return out def fixed_lines(path: Path, width: int | None = None, encoding: str = "utf-8") -> list[str]: text = path.read_text(encoding=encoding) lines = text.splitlines() if width and len(lines) == 1 and len(lines[0]) > width: joined = lines[0] return [joined[index : index + width] for index in range(0, len(joined), width)] return [line for line in lines if line] def parse_ascii_file(path: Path, fields: Iterable[Field], width: int) -> list[dict[str, object]]: return [parse_fixed_width(line.ljust(width), fields) for line in fixed_lines(path, width=width)] def parse_user_security(path: Path) -> list[dict[str, object]]: raw = path.read_bytes() decoded = raw.decode("cp037") records: list[dict[str, object]] = [] for index in range(0, len(decoded), 80): chunk = decoded[index : index + 80] if not chunk.strip(): continue records.append(parse_fixed_width(chunk.ljust(80), USER_FIELDS)) return records def parse_packed_decimal(raw: bytes) -> int: digits: list[str] = [] sign = 1 for index, byte in enumerate(raw): high = byte >> 4 low = byte & 0x0F if index == len(raw) - 1: if high > 9 or low not in (0x0C, 0x0D, 0x0F): raise ValueError(f"invalid packed decimal byte: {byte:02x}") digits.append(str(high)) sign = -1 if low == 0x0D else 1 else: if high > 9 or low > 9: raise ValueError(f"invalid packed decimal byte: {byte:02x}") digits.extend((str(high), str(low))) return sign * int("".join(digits) or "0") def parse_comp(raw: bytes) -> int: return int.from_bytes(raw, "big", signed=True) def _ebcdic_text(raw: bytes) -> str: return raw.decode("cp037", errors="replace").replace("\x00", "").rstrip() def _iter_ims_unload_segments(raw: bytes): markers: list[tuple[int, str]] = [] for marker, name in ((PAUTSUM0_MARKER, "summary"), (PAUTDTL1_MARKER, "detail")): start = 0 while True: offset = raw.find(marker, start) if offset < 0: break markers.append((offset, name)) start = offset + 1 for offset, name in sorted(markers): length = 100 if name == "summary" else 200 data_start = offset + IMS_UNLOAD_SEGMENT_DATA_OFFSET yield offset, name, raw[data_start : data_start + length] def _parse_pending_authorization_summary(raw: bytes, sequence_no: int) -> dict[str, object]: offset = 0 account_id = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 customer_id = int(_ebcdic_text(raw[offset : offset + 9]) or "0") offset += 9 auth_status = _ebcdic_text(raw[offset : offset + 1]) offset += 1 account_statuses = [] for _ in range(5): account_statuses.append(_ebcdic_text(raw[offset : offset + 2])) offset += 2 credit_limit_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 cash_limit_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 credit_balance_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 cash_balance_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 approved_auth_count = parse_comp(raw[offset : offset + 2]) offset += 2 declined_auth_count = parse_comp(raw[offset : offset + 2]) offset += 2 approved_auth_amount_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 declined_auth_amount_cents = parse_packed_decimal(raw[offset : offset + 6]) offset += 6 return { "account_id": account_id, "customer_id": customer_id, "sequence_no": sequence_no, "auth_status": auth_status, "account_status_1": account_statuses[0], "account_status_2": account_statuses[1], "account_status_3": account_statuses[2], "account_status_4": account_statuses[3], "account_status_5": account_statuses[4], "credit_limit_cents": credit_limit_cents, "cash_limit_cents": cash_limit_cents, "credit_balance_cents": credit_balance_cents, "cash_balance_cents": cash_balance_cents, "approved_auth_count": approved_auth_count, "declined_auth_count": declined_auth_count, "approved_auth_amount_cents": approved_auth_amount_cents, "declined_auth_amount_cents": declined_auth_amount_cents, } def _parse_pending_authorization_detail(raw: bytes, account_id: int, sequence_no: int) -> dict[str, object]: offset = 0 authorization_key = raw[offset : offset + 8] auth_date_key = parse_packed_decimal(raw[offset : offset + 3]) offset += 3 auth_time_key = parse_packed_decimal(raw[offset : offset + 5]) offset += 5 def text_field(length: int) -> str: nonlocal offset value = _ebcdic_text(raw[offset : offset + length]) offset += length return value detail: dict[str, object] = { "account_id": account_id, "sequence_no": sequence_no, "authorization_key": authorization_key.hex(), "auth_date_key": auth_date_key, "auth_time_key": auth_time_key, "auth_yyddd": 99999 - auth_date_key, "auth_orig_date": text_field(6), "auth_orig_time": text_field(6), "card_number": text_field(16), "auth_type": text_field(4), "card_expiry_date": text_field(4), "message_type": text_field(6), "message_source": text_field(6), "auth_id_code": text_field(6), "auth_resp_code": text_field(2), "auth_resp_reason": text_field(4), "processing_code": text_field(6), } detail["transaction_amount_cents"] = parse_packed_decimal(raw[offset : offset + 7]) offset += 7 detail["approved_amount_cents"] = parse_packed_decimal(raw[offset : offset + 7]) offset += 7 detail.update( { "merchant_category_code": text_field(4), "acqr_country_code": text_field(3), "pos_entry_mode": text_field(2), "merchant_id": text_field(15), "merchant_name": text_field(22), "merchant_city": text_field(13), "merchant_state": text_field(2), "merchant_zip": text_field(9), "transaction_id": text_field(15), "match_status": text_field(1), "auth_fraud": text_field(1), "fraud_rpt_date": text_field(8), } ) return detail def parse_pending_authorizations(path: Path) -> dict[str, list[dict[str, object]]]: raw = path.read_bytes() summaries: list[dict[str, object]] = [] details: list[dict[str, object]] = [] current_account_id: int | None = None for _, segment_name, segment_data in _iter_ims_unload_segments(raw): try: if segment_name == "summary": summary = _parse_pending_authorization_summary(segment_data, len(summaries) + 1) account_id = int(summary["account_id"]) if account_id <= 0 or account_id > 99_999_999_999 or int(summary["customer_id"]) <= 0: continue summaries.append(summary) current_account_id = account_id elif current_account_id is not None: detail = _parse_pending_authorization_detail(segment_data, current_account_id, len(details) + 1) if not str(detail["card_number"]).isdigit() or not str(detail["auth_orig_date"]).isdigit(): continue details.append(detail) except (ValueError, UnicodeDecodeError): continue return {"summaries": summaries, "details": details}