Skip to content

Commit daa80cd

Browse files
committed
chore(visa-base-2): add draft version of search script
1 parent a2c9339 commit daa80cd

1 file changed

Lines changed: 173 additions & 0 deletions

File tree

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
__author__ = "ipetrash"
5+
6+
7+
import enum
8+
9+
from collections import Counter
10+
from pathlib import Path
11+
from typing import Final, Any, Generator, Sized
12+
13+
# TODO:
14+
# from visa_base2_tc_counter import tc_by_counter
15+
16+
17+
# TODO: Копия из https://github.com/gil9red/SimplePyScripts/blob/2cf402b71b89a0fe5ad1081f779060e8759c3836/split_list_into_evenly_sized_chunks.py
18+
def chunks(l: Sized, n: int) -> Generator[Any, None, None]:
19+
"""Yield successive n-sized chunks from l."""
20+
for i in range(0, len(l), n):
21+
yield l[i : i + n]
22+
23+
24+
# TODO: из аргументов
25+
DIR: Path = Path(r"C:\Users\ipetrash\Desktop\IMPORT_EXPORT\Visa Base 2")
26+
27+
# NOTE: Байты F0 - F9
28+
# TODO: Мб в b"..."? вместо списка
29+
EBCDIC_DIGITS: Final[list[int]] = [0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9]
30+
ASCII_DIGITS: Final[list[int]] = [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
31+
32+
IGNORED_TC: Final[list[str]] = ["90", "91", "92", "00"]
33+
34+
class FileType(enum.Enum):
35+
CTF = enum.auto()
36+
ITF = enum.auto()
37+
REPORT = enum.auto()
38+
39+
for f in DIR.rglob("*"):
40+
if not f.is_file():
41+
continue
42+
43+
print(f"File: {f}")
44+
45+
data: bytes = f.read_bytes()
46+
47+
file_type: FileType
48+
lines: list[str]
49+
text: str
50+
51+
if data[0] in EBCDIC_DIGITS and data[1] in EBCDIC_DIGITS:
52+
try:
53+
text = data.decode("cp500")
54+
except UnicodeDecodeError:
55+
print(f"[#] Not EBCDIC: {f}")
56+
continue
57+
58+
# TODO: Проверить предположение
59+
# NOTE: Предположение, что в ITF хеш EBCDIC будет не F0 - F9
60+
# NOTE: Предположение, что в EBCDIC всегда будет ITF
61+
if data[2] in EBCDIC_DIGITS and data[3] in EBCDIC_DIGITS:
62+
file_type = FileType.CTF
63+
else:
64+
file_type = FileType.ITF
65+
66+
# TODO: Проверить предположение
67+
# NOTE: Предположение, что в EBCDIC не будет перевода строк, нужно делить по 168 или 170 байтов
68+
# print(text)
69+
lines = list(chunks(text, n=168 if file_type == FileType.CTF else 170))
70+
71+
elif data[0] in ASCII_DIGITS and data[1] in ASCII_DIGITS:
72+
try:
73+
text = data.decode("ascii")
74+
except UnicodeDecodeError:
75+
print(f"[#] Not ASCII: {f}")
76+
continue
77+
78+
lines = text.splitlines()
79+
if len(lines[0]) == 168:
80+
file_type = FileType.CTF
81+
else:
82+
file_type = FileType.ITF
83+
84+
elif data[1:8] == b"REPORT ": # NOTE: Считаем, что у отчета кодировка будет ASCII
85+
# TODO: какое название дать? Report?
86+
# file:///C:/DOC/Visa/documents-2026/BASE%20II%20Clearing%20Edit%20Package%20Reports%20Reference%20Guide%20Release%204,%20April%2023,%202026.pdf
87+
88+
# TODO: Поддержка отчета C:\Users\ipetrash\Desktop\IMPORT_EXPORT\Visa Base 2\IMPORT_TEST\REPORT EP-100A\backup\EP100A.TXT
89+
# TODO: Поиск вида отчета по названиям EP-xxxx и VX-xxxx
90+
# Примеры: EP–100A, EP–100B, ..., EP–199, EP–999
91+
# Удаление пробелов добавить
92+
# TODO: Есть 2 вида отчета - обычный и расширенный, и мы как-то определяем какой сейчас. Для инфы нужно и это учитывать
93+
print("REPORT:", data)
94+
file_type = FileType.REPORT
95+
96+
try:
97+
text = data.decode("ascii")
98+
except UnicodeDecodeError:
99+
print(f"[#] Not ASCII: {f}")
100+
continue
101+
102+
# TODO: Тут вроде бы длина строк 133
103+
lines = text.splitlines()
104+
105+
else:
106+
# TODO: Мб вообще удалить C:\Users\ipetrash\Desktop\IMPORT_EXPORT\Visa Base 2\TC33_Capture_Transaction\TWICH-11216\Testing PF3_VS_21144.csv
107+
108+
print(f"[#] Not Visa Base II format: {f}")
109+
# raise Exception(f"[#] Not Visa Base II format: {f}") # TODO:
110+
continue
111+
112+
# TODO: Проверка на валидность - если первый 2 символа не 0 - 9, то это не CTF/ITF
113+
114+
print("file_type:", file_type)
115+
print(f"Lines: {len(lines)}")
116+
# print(f"Lines ({len(lines)}):")
117+
# TODO:
118+
# print(*lines, sep="\n")
119+
120+
# TODO: Анализ lines, чтобы найти TC, TCR
121+
if file_type == FileType.REPORT:
122+
# TODO:
123+
# 1/0
124+
import sys
125+
print("[#] TODO: REPORT not supported", file=sys.stderr)
126+
else:
127+
tc_by_counter = Counter()
128+
tc_tcr_by_counter = Counter()
129+
130+
for line in lines:
131+
tc: str = line[:2]
132+
tcr: str = line[3:4] if file_type == FileType.CTF else line[5:6]
133+
134+
if tc in IGNORED_TC:
135+
continue
136+
137+
# TODO: для tc == 33 особенная логика разбора - есть те, что P17 имеют особенный идентификатор
138+
# TODO: для tc == 33 A особенная логика разбора - чтобы идентифицировать конкретные CPdd + TCR
139+
140+
tc_by_counter.update([tc])
141+
tc_tcr_by_counter.update([f"{tc}-{tcr}"])
142+
143+
# TODO: Отдельно, нужно группировать TC33 - там всякие дополнительные записи есть
144+
145+
print(" TC: " + ", ".join(f"{k}: {v}" for k, v in tc_by_counter.items()))
146+
print(" TC-TCR: " + ", ".join(f"{k}: {v}" for k, v in tc_tcr_by_counter.items()))
147+
148+
print()
149+
150+
151+
# for f in Path(r"C:\Users\ipetrash\Desktop\IMPORT_EXPORT\Visa Base 2").rglob("*"):
152+
# if not f.is_file():
153+
# continue
154+
#
155+
# try:
156+
#
157+
# text = f.read_text("ascii")
158+
# for line in text.splitlines():
159+
# if line.startswith("0109"):
160+
# print(f)
161+
# except:
162+
# continue
163+
164+
165+
# with (
166+
# open(r"C:\Users\ipetrash\Desktop\Visa Base 2\itf\errors\itf_TC54_full_TXI-15493.txt", mode="rb") as f_in,
167+
# open(r"C:\Users\ipetrash\Desktop\Visa Base 2\itf\errors\itf_TC00_full_TXI-15493.txt", mode="wb") as f_out,
168+
# ):
169+
# for line in f_in:
170+
# tc = line[:2]
171+
# if tc == b"54":
172+
# tc = b'00'
173+
# f_out.write(tc + line[2:])

0 commit comments

Comments
 (0)