cadeft 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cadeft/__init__.py +1363 -0
- cadeft/__main__.py +42 -0
- cadeft/py.typed +0 -0
- cadeft-0.2.0.dist-info/METADATA +132 -0
- cadeft-0.2.0.dist-info/RECORD +10 -0
- cadeft-0.2.0.dist-info/WHEEL +5 -0
- cadeft-0.2.0.dist-info/entry_points.txt +2 -0
- cadeft-0.2.0.dist-info/licenses/LICENSE +201 -0
- cadeft-0.2.0.dist-info/licenses/NOTICE +11 -0
- cadeft-0.2.0.dist-info/top_level.txt +1 -0
cadeft/__init__.py
ADDED
|
@@ -0,0 +1,1363 @@
|
|
|
1
|
+
"""Python implementation of Payments Canada EFT Standard 005 files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__version__ = "0.2.0"
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, fields
|
|
8
|
+
from datetime import date, datetime, timedelta, timezone
|
|
9
|
+
import re
|
|
10
|
+
import unicodedata
|
|
11
|
+
from typing import Any, BinaryIO, Callable, TextIO
|
|
12
|
+
|
|
13
|
+
HEADER_RECORD = "A"
|
|
14
|
+
CREDIT_RECORD = "C"
|
|
15
|
+
DEBIT_RECORD = "D"
|
|
16
|
+
CREDIT_REVERSE_RECORD = "E"
|
|
17
|
+
DEBIT_REVERSE_RECORD = "F"
|
|
18
|
+
RETURN_CREDIT_RECORD = "I"
|
|
19
|
+
RETURN_DEBIT_RECORD = "J"
|
|
20
|
+
DEBIT_RETURN_RECORD = RETURN_DEBIT_RECORD
|
|
21
|
+
CREDIT_RETURN_RECORD = RETURN_CREDIT_RECORD
|
|
22
|
+
NOTICE_OF_CHANGE_RECORD = "S"
|
|
23
|
+
NOTICE_OF_CHANGE_HEADER = "U"
|
|
24
|
+
NOTICE_OF_CHANGE_FOOTER = "V"
|
|
25
|
+
FOOTER_RECORD = "Z"
|
|
26
|
+
|
|
27
|
+
MAX_LINE_LENGTH = 1464
|
|
28
|
+
COMMON_RECORD_DATA_LENGTH = 24
|
|
29
|
+
SEGMENT_LENGTH = 240
|
|
30
|
+
MAX_TXNS_PER_RECORD = 6
|
|
31
|
+
RecordType = str
|
|
32
|
+
TransactionType = str
|
|
33
|
+
DCSign = str
|
|
34
|
+
Transactions = list["Transaction"]
|
|
35
|
+
BaseTxnOpt = Callable[[dict[str, str]], None]
|
|
36
|
+
HeaderOpts = dict[str, str]
|
|
37
|
+
|
|
38
|
+
_RECORD_TYPES = {
|
|
39
|
+
DEBIT_RECORD,
|
|
40
|
+
CREDIT_RECORD,
|
|
41
|
+
CREDIT_REVERSE_RECORD,
|
|
42
|
+
DEBIT_REVERSE_RECORD,
|
|
43
|
+
RETURN_CREDIT_RECORD,
|
|
44
|
+
RETURN_DEBIT_RECORD,
|
|
45
|
+
}
|
|
46
|
+
_VALID_RECORD_TYPES = _RECORD_TYPES | {
|
|
47
|
+
HEADER_RECORD,
|
|
48
|
+
NOTICE_OF_CHANGE_RECORD,
|
|
49
|
+
NOTICE_OF_CHANGE_HEADER,
|
|
50
|
+
NOTICE_OF_CHANGE_FOOTER,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CadeftError(ValueError):
|
|
55
|
+
"""Base exception for parsing, validation, and serialization errors."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ParseError(CadeftError):
|
|
59
|
+
"""An EFT record could not be parsed."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ValidationError(CadeftError):
|
|
63
|
+
"""One or more EFT fields failed validation."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class EndOfFile(CadeftError):
|
|
67
|
+
"""The transaction stream has no more records."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def normalize(value: str) -> str:
|
|
71
|
+
return unicodedata.normalize("NFC", value)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def parse_num(value: str) -> int:
|
|
75
|
+
if not re.fullmatch(r"[+-]?[0-9]+", value):
|
|
76
|
+
raise ValueError(f'invalid syntax for integer: "{value}"')
|
|
77
|
+
result = int(value, 10)
|
|
78
|
+
if not -(2**63) <= result < 2**63:
|
|
79
|
+
raise ValueError(f'value out of range: "{value}"')
|
|
80
|
+
return result
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def parse_date(value: str) -> date:
|
|
84
|
+
if len(value) != 6:
|
|
85
|
+
raise ValueError("date string is not valid length")
|
|
86
|
+
try:
|
|
87
|
+
year = parse_num("20" + value[1:3])
|
|
88
|
+
day_of_year = parse_num(value[3:])
|
|
89
|
+
return date(year, 1, 1) + timedelta(days=day_of_year - 1)
|
|
90
|
+
except (ValueError, OverflowError) as exc:
|
|
91
|
+
raise ValueError(f"invalid EFT date: {value}") from exc
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def eft_date(value: date | datetime | None) -> str:
|
|
95
|
+
if value is None:
|
|
96
|
+
return "000000"
|
|
97
|
+
return f"{value.year % 100:03d}{value.timetuple().tm_yday:03d}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def zero_pad_number(value: int, width: int) -> str:
|
|
101
|
+
text = str(value)
|
|
102
|
+
if text.startswith("-"):
|
|
103
|
+
return "-" + text[1:].zfill(max(0, width - 1))
|
|
104
|
+
return text.zfill(width)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def pad_numeric(value: str, width: int) -> str:
|
|
108
|
+
return value.zfill(width)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def pad_numeric_trailing(value: str, width: int) -> str:
|
|
112
|
+
return value + "0" * max(0, width - len(value))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def pad_blanks(value: str, width: int) -> str:
|
|
116
|
+
return value + " " * max(0, width - len(value))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def abbreviate(value: str, width: int) -> str:
|
|
120
|
+
return pad_blanks(value[:width], width)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def filler(width: int) -> str:
|
|
124
|
+
return " " * max(0, width)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _as_date(value: date | datetime | str | None) -> date | datetime | None:
|
|
128
|
+
if value is None or isinstance(value, (date, datetime)):
|
|
129
|
+
return value
|
|
130
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
131
|
+
return parsed
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _json_date(value: date | datetime | None) -> str | None:
|
|
135
|
+
if value is None:
|
|
136
|
+
return None
|
|
137
|
+
if isinstance(value, datetime):
|
|
138
|
+
if value.tzinfo is None:
|
|
139
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
140
|
+
result = value.isoformat(timespec="microseconds" if value.microsecond else "seconds")
|
|
141
|
+
result = re.sub(r"(\.\d*?)0+(?=[+-]|$)", r"\1", result)
|
|
142
|
+
return result.replace("+00:00", "Z")
|
|
143
|
+
return datetime.combine(value, datetime.min.time(), timezone.utc).isoformat(
|
|
144
|
+
timespec="seconds"
|
|
145
|
+
).replace("+00:00", "Z")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class RecordHeader:
|
|
150
|
+
record_type: str = ""
|
|
151
|
+
originator_id: str = ""
|
|
152
|
+
file_creation_number: int = 0
|
|
153
|
+
record_count: int = 0
|
|
154
|
+
|
|
155
|
+
def parse(self, line: str) -> None:
|
|
156
|
+
chars = list(line)
|
|
157
|
+
if len(chars) < COMMON_RECORD_DATA_LENGTH:
|
|
158
|
+
raise ParseError("record header line too short")
|
|
159
|
+
record_type = chars[0]
|
|
160
|
+
if record_type not in {HEADER_RECORD, CREDIT_RECORD, DEBIT_RECORD, FOOTER_RECORD}:
|
|
161
|
+
raise ParseError(f"unrecognized record type {record_type}")
|
|
162
|
+
try:
|
|
163
|
+
record_count = parse_num("".join(chars[1:10]))
|
|
164
|
+
creation_number = parse_num("".join(chars[20:24]))
|
|
165
|
+
except ValueError as exc:
|
|
166
|
+
raise ParseError(str(exc)) from exc
|
|
167
|
+
self.record_type = record_type
|
|
168
|
+
self.record_count = record_count
|
|
169
|
+
self.originator_id = "".join(chars[10:20]).strip()
|
|
170
|
+
self.file_creation_number = creation_number
|
|
171
|
+
|
|
172
|
+
def build(self) -> str:
|
|
173
|
+
return (
|
|
174
|
+
abbreviate(self.record_type, 1)
|
|
175
|
+
+ zero_pad_number(self.record_count, 9)
|
|
176
|
+
+ pad_numeric(self.originator_id, 10)
|
|
177
|
+
+ zero_pad_number(self.file_creation_number, 4)
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
Build = build
|
|
181
|
+
|
|
182
|
+
def to_dict(self) -> dict[str, Any]:
|
|
183
|
+
return {
|
|
184
|
+
"type": self.record_type,
|
|
185
|
+
"originator_id": self.originator_id,
|
|
186
|
+
"file_creation_number": self.file_creation_number,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass
|
|
191
|
+
class BaseTxn:
|
|
192
|
+
txn_type: str = ""
|
|
193
|
+
amount: int = 0
|
|
194
|
+
item_trace_no: str = ""
|
|
195
|
+
institution_id: str = ""
|
|
196
|
+
stored_txn_type: str = ""
|
|
197
|
+
short_name: str = ""
|
|
198
|
+
long_name: str = ""
|
|
199
|
+
user_id: str = ""
|
|
200
|
+
cross_ref_no: str = ""
|
|
201
|
+
sundry_info: str = ""
|
|
202
|
+
settlement_code: str = ""
|
|
203
|
+
invalid_data_element_id: str = ""
|
|
204
|
+
record_type: str = ""
|
|
205
|
+
|
|
206
|
+
def to_dict(self) -> dict[str, Any]:
|
|
207
|
+
return {
|
|
208
|
+
"txn_type": self.txn_type,
|
|
209
|
+
"amount": self.amount,
|
|
210
|
+
"item_trace_no": self.item_trace_no,
|
|
211
|
+
"institution_id": self.institution_id,
|
|
212
|
+
"stored_txn_type": self.stored_txn_type,
|
|
213
|
+
"short_name": self.short_name,
|
|
214
|
+
"long_name": self.long_name,
|
|
215
|
+
"user_id": self.user_id,
|
|
216
|
+
"cross_ref_no": self.cross_ref_no,
|
|
217
|
+
"sundry_info": self.sundry_info,
|
|
218
|
+
"settlement_code": self.settlement_code,
|
|
219
|
+
"invalid_data_element_id": self.invalid_data_element_id,
|
|
220
|
+
"type": self.record_type,
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass
|
|
225
|
+
class Transaction(BaseTxn):
|
|
226
|
+
"""Shared API for a 240-character EFT transaction segment."""
|
|
227
|
+
|
|
228
|
+
date_value: date | datetime | None = None
|
|
229
|
+
account_no: str = ""
|
|
230
|
+
name: str = ""
|
|
231
|
+
return_institution_id: str = ""
|
|
232
|
+
return_account_no: str = ""
|
|
233
|
+
original_institution_id: str = ""
|
|
234
|
+
original_account_no: str = ""
|
|
235
|
+
original_item_trace_no: str = ""
|
|
236
|
+
|
|
237
|
+
RECORD_TYPE = ""
|
|
238
|
+
DATE_JSON = ""
|
|
239
|
+
ACCOUNT_JSON = ""
|
|
240
|
+
NAME_JSON = ""
|
|
241
|
+
HAS_RETURN = False
|
|
242
|
+
HAS_ORIGINAL = False
|
|
243
|
+
HAS_ORIGINAL_ITEM = False
|
|
244
|
+
HAS_INVALID_ID = False
|
|
245
|
+
DATE_ERROR = "failed to parse due date"
|
|
246
|
+
|
|
247
|
+
def __post_init__(self) -> None:
|
|
248
|
+
self.record_type = self.RECORD_TYPE
|
|
249
|
+
|
|
250
|
+
def get_type(self) -> str:
|
|
251
|
+
return self.RECORD_TYPE
|
|
252
|
+
|
|
253
|
+
def get_amount(self) -> int:
|
|
254
|
+
return self.amount
|
|
255
|
+
|
|
256
|
+
def get_base_txn(self) -> BaseTxn:
|
|
257
|
+
return BaseTxn(
|
|
258
|
+
self.txn_type, self.amount, self.item_trace_no, self.institution_id,
|
|
259
|
+
self.stored_txn_type, self.short_name, self.long_name, self.user_id,
|
|
260
|
+
self.cross_ref_no, self.sundry_info, self.settlement_code,
|
|
261
|
+
self.invalid_data_element_id, self.record_type,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def get_account_no(self) -> str:
|
|
265
|
+
return self.account_no
|
|
266
|
+
|
|
267
|
+
def get_date(self) -> date | datetime | None:
|
|
268
|
+
return self.date_value
|
|
269
|
+
|
|
270
|
+
def get_name(self) -> str:
|
|
271
|
+
return self.name
|
|
272
|
+
|
|
273
|
+
def get_return_institution_id(self) -> str:
|
|
274
|
+
return self.return_institution_id if self.HAS_RETURN else ""
|
|
275
|
+
|
|
276
|
+
def get_return_account_no(self) -> str:
|
|
277
|
+
return self.return_account_no if self.HAS_RETURN else ""
|
|
278
|
+
|
|
279
|
+
def get_original_institution_id(self) -> str:
|
|
280
|
+
return self.original_institution_id if self.HAS_ORIGINAL else ""
|
|
281
|
+
|
|
282
|
+
def get_original_account_no(self) -> str:
|
|
283
|
+
return self.original_account_no if self.HAS_ORIGINAL else ""
|
|
284
|
+
|
|
285
|
+
def get_original_item_trace_no(self) -> str:
|
|
286
|
+
return self.original_item_trace_no if self.HAS_ORIGINAL_ITEM else ""
|
|
287
|
+
|
|
288
|
+
def build(self) -> str:
|
|
289
|
+
def name_field(value: str, width: int) -> str:
|
|
290
|
+
return abbreviate(normalize(value), width)
|
|
291
|
+
|
|
292
|
+
def date_field() -> str:
|
|
293
|
+
return pad_numeric(eft_date(self.date_value), 6)
|
|
294
|
+
|
|
295
|
+
out = [
|
|
296
|
+
pad_numeric(self.txn_type, 3),
|
|
297
|
+
zero_pad_number(self.amount, 10),
|
|
298
|
+
date_field(),
|
|
299
|
+
pad_numeric(self.institution_id, 9),
|
|
300
|
+
abbreviate(self.account_no, 12),
|
|
301
|
+
pad_numeric(self.item_trace_no, 22),
|
|
302
|
+
pad_numeric(self.stored_txn_type, 3),
|
|
303
|
+
name_field(self.short_name, 15),
|
|
304
|
+
name_field(self.name, 30),
|
|
305
|
+
name_field(self.long_name, 30),
|
|
306
|
+
abbreviate(self.user_id, 10),
|
|
307
|
+
abbreviate(self.cross_ref_no, 19),
|
|
308
|
+
]
|
|
309
|
+
if self.HAS_ORIGINAL:
|
|
310
|
+
out.extend(
|
|
311
|
+
[
|
|
312
|
+
pad_numeric(self.original_institution_id, 9),
|
|
313
|
+
abbreviate(self.original_account_no, 12),
|
|
314
|
+
]
|
|
315
|
+
)
|
|
316
|
+
else:
|
|
317
|
+
out.extend(
|
|
318
|
+
[
|
|
319
|
+
pad_numeric(self.return_institution_id, 9),
|
|
320
|
+
abbreviate(self.return_account_no, 12),
|
|
321
|
+
]
|
|
322
|
+
)
|
|
323
|
+
out.append(abbreviate(self.sundry_info, 15))
|
|
324
|
+
if self.HAS_ORIGINAL_ITEM:
|
|
325
|
+
out.append(pad_numeric(self.original_item_trace_no, 22))
|
|
326
|
+
else:
|
|
327
|
+
out.append(filler(22))
|
|
328
|
+
out.append(abbreviate(self.settlement_code, 2))
|
|
329
|
+
if self.HAS_INVALID_ID:
|
|
330
|
+
out.append(pad_numeric_trailing(self.invalid_data_element_id, 11))
|
|
331
|
+
else:
|
|
332
|
+
out.append(pad_numeric("", 11))
|
|
333
|
+
return "".join(out)
|
|
334
|
+
|
|
335
|
+
def parse(self, segment: str) -> Transaction:
|
|
336
|
+
segment = normalize(segment)
|
|
337
|
+
chars = list(segment)
|
|
338
|
+
if len(chars) != SEGMENT_LENGTH:
|
|
339
|
+
raise ParseError("transaction record is not 240 characters")
|
|
340
|
+
self.txn_type = "".join(chars[0:3])
|
|
341
|
+
try:
|
|
342
|
+
self.amount = parse_num("".join(chars[3:13]))
|
|
343
|
+
except ValueError as exc:
|
|
344
|
+
raise ParseError(f"failed to parse amount: {exc}") from exc
|
|
345
|
+
try:
|
|
346
|
+
self.date_value = parse_date("".join(chars[13:19]))
|
|
347
|
+
except ValueError as exc:
|
|
348
|
+
raise ParseError(f"{self.DATE_ERROR}: {exc}") from exc
|
|
349
|
+
self.institution_id = "".join(chars[19:28])
|
|
350
|
+
self.account_no = "".join(chars[28:40]).strip()
|
|
351
|
+
self.item_trace_no = "".join(chars[40:62])
|
|
352
|
+
self.stored_txn_type = "".join(chars[62:65])
|
|
353
|
+
self.short_name = "".join(chars[65:80]).strip()
|
|
354
|
+
self.name = "".join(chars[80:110]).strip()
|
|
355
|
+
self.long_name = "".join(chars[110:140]).strip()
|
|
356
|
+
self.user_id = "".join(chars[140:150]).strip()
|
|
357
|
+
self.cross_ref_no = "".join(chars[150:169]).strip()
|
|
358
|
+
if self.HAS_ORIGINAL:
|
|
359
|
+
self.original_institution_id = "".join(chars[169:178]).strip()
|
|
360
|
+
self.original_account_no = "".join(chars[178:190]).strip()
|
|
361
|
+
else:
|
|
362
|
+
self.return_institution_id = "".join(chars[169:178]).strip()
|
|
363
|
+
self.return_account_no = "".join(chars[178:190]).strip()
|
|
364
|
+
self.sundry_info = "".join(chars[190:205]).strip()
|
|
365
|
+
if self.HAS_ORIGINAL_ITEM:
|
|
366
|
+
self.original_item_trace_no = "".join(chars[205:227]).strip()
|
|
367
|
+
self.settlement_code = "".join(chars[227:229]).strip()
|
|
368
|
+
if self.HAS_INVALID_ID:
|
|
369
|
+
self.invalid_data_element_id = "".join(chars[229:240]).strip()
|
|
370
|
+
self.record_type = self.RECORD_TYPE
|
|
371
|
+
return self
|
|
372
|
+
|
|
373
|
+
def validate(self) -> None:
|
|
374
|
+
errors: list[str] = []
|
|
375
|
+
|
|
376
|
+
def required(name: str, value: Any) -> None:
|
|
377
|
+
missing = value is None or value == ""
|
|
378
|
+
if isinstance(value, (int, float)) and value == 0:
|
|
379
|
+
missing = True
|
|
380
|
+
if missing:
|
|
381
|
+
errors.append(f"{name} is required")
|
|
382
|
+
|
|
383
|
+
def max_len(name: str, value: str, maximum: int) -> None:
|
|
384
|
+
if len(value) > maximum:
|
|
385
|
+
errors.append(f"{name} exceeds max length {maximum}")
|
|
386
|
+
|
|
387
|
+
def numeric(name: str, value: str) -> None:
|
|
388
|
+
if value and not re.fullmatch(r"[0-9]+", value):
|
|
389
|
+
errors.append(f"{name} must be numeric")
|
|
390
|
+
|
|
391
|
+
def alpha(name: str, value: str) -> None:
|
|
392
|
+
if value and not re.fullmatch(r"[A-Za-z0-9_\-\t\n\f\r ]+", value):
|
|
393
|
+
errors.append(f"{name} must contain EFT alphanumeric characters")
|
|
394
|
+
|
|
395
|
+
required("txn_type", self.txn_type)
|
|
396
|
+
numeric("txn_type", self.txn_type)
|
|
397
|
+
max_len("txn_type", self.txn_type, 3)
|
|
398
|
+
required("amount", self.amount)
|
|
399
|
+
if self.amount > 9_999_999_999:
|
|
400
|
+
errors.append("amount exceeds maximum")
|
|
401
|
+
numeric("item_trace_no", self.item_trace_no)
|
|
402
|
+
max_len("item_trace_no", self.item_trace_no, 22)
|
|
403
|
+
required("institution_id", self.institution_id)
|
|
404
|
+
numeric("institution_id", self.institution_id)
|
|
405
|
+
max_len("institution_id", self.institution_id, 9)
|
|
406
|
+
numeric("stored_txn_type", self.stored_txn_type)
|
|
407
|
+
max_len("stored_txn_type", self.stored_txn_type, 3)
|
|
408
|
+
max_len("short_name", self.short_name, 15)
|
|
409
|
+
required("long_name", self.long_name)
|
|
410
|
+
max_len("long_name", self.long_name, 30)
|
|
411
|
+
alpha("user_id", self.user_id)
|
|
412
|
+
max_len("user_id", self.user_id, 10)
|
|
413
|
+
alpha("cross_ref_no", self.cross_ref_no)
|
|
414
|
+
max_len("cross_ref_no", self.cross_ref_no, 19)
|
|
415
|
+
alpha("sundry_info", self.sundry_info)
|
|
416
|
+
max_len("sundry_info", self.sundry_info, 15)
|
|
417
|
+
alpha("settlement_code", self.settlement_code)
|
|
418
|
+
max_len("settlement_code", self.settlement_code, 2)
|
|
419
|
+
numeric("invalid_data_element_id", self.invalid_data_element_id)
|
|
420
|
+
max_len("invalid_data_element_id", self.invalid_data_element_id, 11)
|
|
421
|
+
if self.record_type not in _VALID_RECORD_TYPES:
|
|
422
|
+
errors.append("invalid record type")
|
|
423
|
+
required(self.DATE_JSON, self.date_value)
|
|
424
|
+
required(self.ACCOUNT_JSON, self.account_no)
|
|
425
|
+
max_len(self.ACCOUNT_JSON, self.account_no, 12)
|
|
426
|
+
numeric(self.ACCOUNT_JSON, self.account_no)
|
|
427
|
+
required(self.NAME_JSON, self.name)
|
|
428
|
+
max_len(self.NAME_JSON, self.name, 30)
|
|
429
|
+
if self.HAS_RETURN:
|
|
430
|
+
required("return_institution_id", self.return_institution_id)
|
|
431
|
+
max_len("return_institution_id", self.return_institution_id, 9)
|
|
432
|
+
numeric("return_institution_id", self.return_institution_id)
|
|
433
|
+
required("return_account_no", self.return_account_no)
|
|
434
|
+
max_len("return_account_no", self.return_account_no, 12)
|
|
435
|
+
alpha("return_account_no", self.return_account_no)
|
|
436
|
+
if self.HAS_ORIGINAL:
|
|
437
|
+
required("original_institution_id", self.original_institution_id)
|
|
438
|
+
max_len("original_institution_id", self.original_institution_id, 9)
|
|
439
|
+
numeric("original_institution_id", self.original_institution_id)
|
|
440
|
+
required("original_account_no", self.original_account_no)
|
|
441
|
+
max_len("original_account_no", self.original_account_no, 12)
|
|
442
|
+
alpha("original_account_no", self.original_account_no)
|
|
443
|
+
if self.HAS_ORIGINAL_ITEM:
|
|
444
|
+
required("original_item_trace_no", self.original_item_trace_no)
|
|
445
|
+
numeric("original_item_trace_no", self.original_item_trace_no)
|
|
446
|
+
max_len("original_item_trace_no", self.original_item_trace_no, 22)
|
|
447
|
+
if errors:
|
|
448
|
+
raise ValidationError("; ".join(errors))
|
|
449
|
+
|
|
450
|
+
def to_dict(self) -> dict[str, Any]:
|
|
451
|
+
result = super().to_dict()
|
|
452
|
+
result[self.DATE_JSON] = _json_date(self.date_value)
|
|
453
|
+
result[self.ACCOUNT_JSON] = self.account_no
|
|
454
|
+
result[self.NAME_JSON] = self.name
|
|
455
|
+
if self.HAS_RETURN:
|
|
456
|
+
result["return_institution_id"] = self.return_institution_id
|
|
457
|
+
result["return_account_no"] = self.return_account_no
|
|
458
|
+
if self.HAS_ORIGINAL:
|
|
459
|
+
result["original_institution_id"] = self.original_institution_id
|
|
460
|
+
result["original_account_no"] = self.original_account_no
|
|
461
|
+
if self.HAS_ORIGINAL_ITEM:
|
|
462
|
+
result["original_item_trace_no"] = self.original_item_trace_no
|
|
463
|
+
return result
|
|
464
|
+
|
|
465
|
+
# Aliases preserving the upstream CamelCase API spellings.
|
|
466
|
+
Build = build
|
|
467
|
+
Parse = parse
|
|
468
|
+
Validate = validate
|
|
469
|
+
GetType = get_type
|
|
470
|
+
GetAmount = get_amount
|
|
471
|
+
GetBaseTxn = get_base_txn
|
|
472
|
+
GetAccountNo = get_account_no
|
|
473
|
+
GetDate = get_date
|
|
474
|
+
GetName = get_name
|
|
475
|
+
GetReturnInstitutionID = get_return_institution_id
|
|
476
|
+
GetReturnAccountNo = get_return_account_no
|
|
477
|
+
GetOriginalInstitutionID = get_original_institution_id
|
|
478
|
+
GetOriginalAccountNo = get_original_account_no
|
|
479
|
+
GetOriginalItemTraceNo = get_original_item_trace_no
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
@dataclass
|
|
483
|
+
class Debit(Transaction):
|
|
484
|
+
due_date: date | datetime | None = None
|
|
485
|
+
payor_account_no: str = ""
|
|
486
|
+
payor_name: str = ""
|
|
487
|
+
return_institution_id: str = ""
|
|
488
|
+
return_account_no: str = ""
|
|
489
|
+
|
|
490
|
+
RECORD_TYPE = DEBIT_RECORD
|
|
491
|
+
DATE_JSON = "due_date"
|
|
492
|
+
ACCOUNT_JSON = "payor_account_no"
|
|
493
|
+
NAME_JSON = "payor_name"
|
|
494
|
+
HAS_RETURN = True
|
|
495
|
+
DATE_ERROR = "failed to parse due date"
|
|
496
|
+
|
|
497
|
+
def __post_init__(self) -> None:
|
|
498
|
+
self.date_value = self.due_date
|
|
499
|
+
self.account_no = self.payor_account_no
|
|
500
|
+
self.name = self.payor_name
|
|
501
|
+
super().__post_init__()
|
|
502
|
+
|
|
503
|
+
def to_dict(self) -> dict[str, Any]:
|
|
504
|
+
self.date_value, self.account_no, self.name = self.due_date, self.payor_account_no, self.payor_name
|
|
505
|
+
return super().to_dict()
|
|
506
|
+
|
|
507
|
+
def parse(self, segment: str) -> Debit:
|
|
508
|
+
super().parse(segment)
|
|
509
|
+
self.due_date, self.payor_account_no, self.payor_name = self.date_value, self.account_no, self.name
|
|
510
|
+
return self
|
|
511
|
+
|
|
512
|
+
Parse = parse
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
@dataclass
|
|
516
|
+
class Credit(Transaction):
|
|
517
|
+
date_funds_available: date | datetime | None = None
|
|
518
|
+
payee_account_no: str = ""
|
|
519
|
+
payee_name: str = ""
|
|
520
|
+
return_institution_id: str = ""
|
|
521
|
+
return_account_no: str = ""
|
|
522
|
+
|
|
523
|
+
RECORD_TYPE = CREDIT_RECORD
|
|
524
|
+
DATE_JSON = "date_funds_available"
|
|
525
|
+
ACCOUNT_JSON = "payee_account_no"
|
|
526
|
+
NAME_JSON = "payee_name"
|
|
527
|
+
HAS_RETURN = True
|
|
528
|
+
DATE_ERROR = "failed to parse date funds available"
|
|
529
|
+
|
|
530
|
+
def __post_init__(self) -> None:
|
|
531
|
+
self.date_value, self.account_no, self.name = self.date_funds_available, self.payee_account_no, self.payee_name
|
|
532
|
+
super().__post_init__()
|
|
533
|
+
|
|
534
|
+
def to_dict(self) -> dict[str, Any]:
|
|
535
|
+
self.date_value, self.account_no, self.name = self.date_funds_available, self.payee_account_no, self.payee_name
|
|
536
|
+
return super().to_dict()
|
|
537
|
+
|
|
538
|
+
def parse(self, segment: str) -> Credit:
|
|
539
|
+
super().parse(segment)
|
|
540
|
+
self.date_funds_available, self.payee_account_no, self.payee_name = self.date_value, self.account_no, self.name
|
|
541
|
+
return self
|
|
542
|
+
|
|
543
|
+
Parse = parse
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
@dataclass
|
|
547
|
+
class DebitReturn(Transaction):
|
|
548
|
+
due_date: date | datetime | None = None
|
|
549
|
+
payor_account_no: str = ""
|
|
550
|
+
payor_name: str = ""
|
|
551
|
+
original_institution_id: str = ""
|
|
552
|
+
original_account_no: str = ""
|
|
553
|
+
original_item_trace_no: str = ""
|
|
554
|
+
|
|
555
|
+
RECORD_TYPE = RETURN_DEBIT_RECORD
|
|
556
|
+
DATE_JSON = "due_date"
|
|
557
|
+
ACCOUNT_JSON = "payor_account_no"
|
|
558
|
+
NAME_JSON = "payor_name"
|
|
559
|
+
HAS_ORIGINAL = True
|
|
560
|
+
HAS_ORIGINAL_ITEM = True
|
|
561
|
+
HAS_INVALID_ID = True
|
|
562
|
+
|
|
563
|
+
def __post_init__(self) -> None:
|
|
564
|
+
self.date_value, self.account_no, self.name = self.due_date, self.payor_account_no, self.payor_name
|
|
565
|
+
super().__post_init__()
|
|
566
|
+
|
|
567
|
+
def to_dict(self) -> dict[str, Any]:
|
|
568
|
+
self.date_value, self.account_no, self.name = self.due_date, self.payor_account_no, self.payor_name
|
|
569
|
+
return super().to_dict()
|
|
570
|
+
|
|
571
|
+
def parse(self, segment: str) -> DebitReturn:
|
|
572
|
+
super().parse(segment)
|
|
573
|
+
self.due_date, self.payor_account_no, self.payor_name = self.date_value, self.account_no, self.name
|
|
574
|
+
return self
|
|
575
|
+
|
|
576
|
+
Parse = parse
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
@dataclass
|
|
580
|
+
class CreditReturn(Transaction):
|
|
581
|
+
date_funds_available: date | datetime | None = None
|
|
582
|
+
payee_account_no: str = ""
|
|
583
|
+
payee_name: str = ""
|
|
584
|
+
original_institution_id: str = ""
|
|
585
|
+
original_account_no: str = ""
|
|
586
|
+
original_item_trace_no: str = ""
|
|
587
|
+
|
|
588
|
+
RECORD_TYPE = RETURN_CREDIT_RECORD
|
|
589
|
+
DATE_JSON = "date_funds_available"
|
|
590
|
+
ACCOUNT_JSON = "payee_account_no"
|
|
591
|
+
NAME_JSON = "payee_name"
|
|
592
|
+
HAS_ORIGINAL = True
|
|
593
|
+
HAS_ORIGINAL_ITEM = True
|
|
594
|
+
HAS_INVALID_ID = True
|
|
595
|
+
DATE_ERROR = "failed to parse date funds available"
|
|
596
|
+
|
|
597
|
+
def __post_init__(self) -> None:
|
|
598
|
+
self.date_value, self.account_no, self.name = self.date_funds_available, self.payee_account_no, self.payee_name
|
|
599
|
+
super().__post_init__()
|
|
600
|
+
|
|
601
|
+
def to_dict(self) -> dict[str, Any]:
|
|
602
|
+
self.date_value, self.account_no, self.name = self.date_funds_available, self.payee_account_no, self.payee_name
|
|
603
|
+
return super().to_dict()
|
|
604
|
+
|
|
605
|
+
def parse(self, segment: str) -> CreditReturn:
|
|
606
|
+
super().parse(segment)
|
|
607
|
+
self.date_funds_available, self.payee_account_no, self.payee_name = self.date_value, self.account_no, self.name
|
|
608
|
+
return self
|
|
609
|
+
|
|
610
|
+
Parse = parse
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
@dataclass
|
|
614
|
+
class CreditReverse(Credit):
|
|
615
|
+
original_item_trace_no: str = ""
|
|
616
|
+
|
|
617
|
+
RECORD_TYPE = CREDIT_REVERSE_RECORD
|
|
618
|
+
HAS_ORIGINAL_ITEM = True
|
|
619
|
+
|
|
620
|
+
def parse(self, segment: str) -> CreditReverse:
|
|
621
|
+
Transaction.parse(self, segment)
|
|
622
|
+
self.date_funds_available, self.payee_account_no, self.payee_name = self.date_value, self.account_no, self.name
|
|
623
|
+
return self
|
|
624
|
+
|
|
625
|
+
Parse = parse
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
@dataclass
|
|
629
|
+
class DebitReverse(Debit):
|
|
630
|
+
original_item_trace_no: str = ""
|
|
631
|
+
|
|
632
|
+
RECORD_TYPE = DEBIT_REVERSE_RECORD
|
|
633
|
+
HAS_ORIGINAL_ITEM = True
|
|
634
|
+
|
|
635
|
+
def parse(self, segment: str) -> DebitReverse:
|
|
636
|
+
Transaction.parse(self, segment)
|
|
637
|
+
self.due_date, self.payor_account_no, self.payor_name = self.date_value, self.account_no, self.name
|
|
638
|
+
return self
|
|
639
|
+
|
|
640
|
+
Parse = parse
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
_TRANSACTION_CLASS = {
|
|
644
|
+
DEBIT_RECORD: Debit,
|
|
645
|
+
CREDIT_RECORD: Credit,
|
|
646
|
+
RETURN_DEBIT_RECORD: DebitReturn,
|
|
647
|
+
RETURN_CREDIT_RECORD: CreditReturn,
|
|
648
|
+
CREDIT_REVERSE_RECORD: CreditReverse,
|
|
649
|
+
DEBIT_REVERSE_RECORD: DebitReverse,
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _new_transaction(txn_record_type: str, **values: Any) -> Transaction:
|
|
654
|
+
cls = _TRANSACTION_CLASS[txn_record_type]
|
|
655
|
+
return cls(**values)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _make_base(txn_type: str, amount: int, item_trace_no: str, institution_id: str,
|
|
659
|
+
short_name: str, long_name: str, record_type: str,
|
|
660
|
+
options: dict[str, str]) -> dict[str, Any]:
|
|
661
|
+
return {
|
|
662
|
+
"txn_type": txn_type,
|
|
663
|
+
"amount": amount,
|
|
664
|
+
"item_trace_no": item_trace_no,
|
|
665
|
+
"institution_id": institution_id,
|
|
666
|
+
"stored_txn_type": options.get("stored_txn_type", "000"),
|
|
667
|
+
"short_name": short_name,
|
|
668
|
+
"long_name": long_name,
|
|
669
|
+
"user_id": options.get("user_id", ""),
|
|
670
|
+
"cross_ref_no": options.get("cross_ref_no", ""),
|
|
671
|
+
"sundry_info": options.get("sundry_info", ""),
|
|
672
|
+
"settlement_code": options.get("settlement_code", ""),
|
|
673
|
+
"invalid_data_element_id": options.get("invalid_data_element_id", ""),
|
|
674
|
+
"record_type": record_type,
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _constructor(record_type: str, txn_type: str, amount: int,
|
|
679
|
+
txn_date: date | datetime | None, institution_id: str,
|
|
680
|
+
account_no: str, item_trace_no: str, short_name: str,
|
|
681
|
+
name: str, long_name: str, bank_id: str, bank_account: str,
|
|
682
|
+
original_item_trace_no: str = "", *opts: Any,
|
|
683
|
+
**options: str) -> Transaction:
|
|
684
|
+
options = dict(options)
|
|
685
|
+
for option in opts:
|
|
686
|
+
if callable(option):
|
|
687
|
+
option(options)
|
|
688
|
+
elif isinstance(option, dict):
|
|
689
|
+
options.update(option)
|
|
690
|
+
else:
|
|
691
|
+
raise TypeError(f"unsupported transaction option: {option!r}")
|
|
692
|
+
date_key = "date_funds_available" if record_type in {
|
|
693
|
+
CREDIT_RECORD, CREDIT_REVERSE_RECORD, RETURN_CREDIT_RECORD
|
|
694
|
+
} else "due_date"
|
|
695
|
+
account_key = "payee_account_no" if record_type in {
|
|
696
|
+
CREDIT_RECORD, CREDIT_REVERSE_RECORD, RETURN_CREDIT_RECORD
|
|
697
|
+
} else "payor_account_no"
|
|
698
|
+
name_key = "payee_name" if account_key == "payee_account_no" else "payor_name"
|
|
699
|
+
values = _make_base(txn_type, amount, item_trace_no, institution_id,
|
|
700
|
+
short_name, long_name, record_type, options)
|
|
701
|
+
values.update({date_key: txn_date, account_key: account_no, name_key: name})
|
|
702
|
+
if record_type in {DEBIT_RECORD, CREDIT_RECORD, DEBIT_REVERSE_RECORD, CREDIT_REVERSE_RECORD}:
|
|
703
|
+
values["return_institution_id"] = bank_id
|
|
704
|
+
values["return_account_no"] = bank_account
|
|
705
|
+
else:
|
|
706
|
+
values["original_institution_id"] = bank_id
|
|
707
|
+
values["original_account_no"] = bank_account
|
|
708
|
+
if record_type in {DEBIT_RETURN_RECORD, CREDIT_RETURN_RECORD, DEBIT_REVERSE_RECORD, CREDIT_REVERSE_RECORD}:
|
|
709
|
+
values["original_item_trace_no"] = original_item_trace_no
|
|
710
|
+
return _new_transaction(record_type, **values)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def NewDebit(txn_type: str, amount: int, due_date: date | datetime | None,
|
|
714
|
+
institution_id: str, payor_account_no: str, item_trace_no: str,
|
|
715
|
+
originator_short_name: str, payor_name: str, originator_long_name: str,
|
|
716
|
+
return_institution_id: str, return_account_no: str, *opts: Any,
|
|
717
|
+
**options: str) -> Debit:
|
|
718
|
+
return _constructor(DEBIT_RECORD, txn_type, amount, due_date, institution_id,
|
|
719
|
+
payor_account_no, item_trace_no, originator_short_name, payor_name,
|
|
720
|
+
originator_long_name, return_institution_id, return_account_no, "",
|
|
721
|
+
*opts, **options)
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def NewCredit(txn_type: str, amount: int, date_funds_available: date | datetime | None,
|
|
725
|
+
institution_id: str, payee_account_no: str, item_trace_no: str,
|
|
726
|
+
originator_short_name: str, payee_name: str, originator_long_name: str,
|
|
727
|
+
return_institution_id: str, return_account_no: str, *opts: Any,
|
|
728
|
+
**options: str) -> Credit:
|
|
729
|
+
return _constructor(CREDIT_RECORD, txn_type, amount, date_funds_available, institution_id,
|
|
730
|
+
payee_account_no, item_trace_no, originator_short_name, payee_name,
|
|
731
|
+
originator_long_name, return_institution_id, return_account_no, "", *opts, **options)
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def NewDebitReturn(txn_type: str, amount: int, due_date: date | datetime | None,
|
|
735
|
+
institution_id: str, payor_account_no: str, item_trace_no: str,
|
|
736
|
+
originator_short_name: str, payor_name: str, originator_long_name: str,
|
|
737
|
+
original_institution_id: str, original_account_no: str,
|
|
738
|
+
original_item_trace_no: str, *opts: Any, **options: str) -> DebitReturn:
|
|
739
|
+
return _constructor(RETURN_DEBIT_RECORD, txn_type, amount, due_date, institution_id,
|
|
740
|
+
payor_account_no, item_trace_no, originator_short_name, payor_name,
|
|
741
|
+
originator_long_name, original_institution_id, original_account_no,
|
|
742
|
+
original_item_trace_no, *opts, **options)
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def NewCreditReturn(txn_type: str, amount: int, date_funds_available: date | datetime | None,
|
|
746
|
+
institution_id: str, payee_account_no: str, item_trace_no: str,
|
|
747
|
+
originator_short_name: str, payee_name: str, originator_long_name: str,
|
|
748
|
+
original_institution_id: str, original_account_no: str,
|
|
749
|
+
original_item_trace_no: str, *opts: Any, **options: str) -> CreditReturn:
|
|
750
|
+
return _constructor(RETURN_CREDIT_RECORD, txn_type, amount, date_funds_available, institution_id,
|
|
751
|
+
payee_account_no, item_trace_no, originator_short_name, payee_name,
|
|
752
|
+
originator_long_name, original_institution_id, original_account_no,
|
|
753
|
+
original_item_trace_no, *opts, **options)
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def NewCreditReverse(txn_type: str, amount: int, date_funds_available: date | datetime | None,
|
|
757
|
+
institution_id: str, payee_account_no: str, item_trace_no: str,
|
|
758
|
+
originator_short_name: str, payee_name: str, originator_long_name: str,
|
|
759
|
+
return_institution_id: str, return_account_no: str,
|
|
760
|
+
original_item_trace_no: str, *opts: Any, **options: str) -> CreditReverse:
|
|
761
|
+
return _constructor(CREDIT_REVERSE_RECORD, txn_type, amount, date_funds_available, institution_id,
|
|
762
|
+
payee_account_no, item_trace_no, originator_short_name, payee_name,
|
|
763
|
+
originator_long_name, return_institution_id, return_account_no,
|
|
764
|
+
original_item_trace_no, *opts, **options)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def NewDebitReverse(txn_type: str, amount: int, due_date: date | datetime | None,
|
|
768
|
+
institution_id: str, payor_account_no: str, item_trace_no: str,
|
|
769
|
+
originator_short_name: str, payor_name: str, originator_long_name: str,
|
|
770
|
+
return_institution_id: str, return_account_no: str,
|
|
771
|
+
original_item_trace_no: str, *opts: Any, **options: str) -> DebitReverse:
|
|
772
|
+
return _constructor(DEBIT_REVERSE_RECORD, txn_type, amount, due_date, institution_id,
|
|
773
|
+
payor_account_no, item_trace_no, originator_short_name, payor_name,
|
|
774
|
+
originator_long_name, return_institution_id, return_account_no,
|
|
775
|
+
original_item_trace_no, *opts, **options)
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
@dataclass
|
|
779
|
+
class FileHeader:
|
|
780
|
+
record_header: RecordHeader = None # type: ignore[assignment]
|
|
781
|
+
creation_date: date | datetime | None = None
|
|
782
|
+
destination_data_center: int = 0
|
|
783
|
+
communication_area: str = ""
|
|
784
|
+
currency_code: str = ""
|
|
785
|
+
|
|
786
|
+
def __post_init__(self) -> None:
|
|
787
|
+
if self.record_header is None:
|
|
788
|
+
self.record_header = RecordHeader(HEADER_RECORD, "", 0, 1)
|
|
789
|
+
|
|
790
|
+
def parse(self, line: str) -> None:
|
|
791
|
+
chars = list(line)
|
|
792
|
+
if len(chars) < 58:
|
|
793
|
+
raise ParseError("invalid header record length")
|
|
794
|
+
self.record_header = RecordHeader()
|
|
795
|
+
self.record_header.parse(line)
|
|
796
|
+
try:
|
|
797
|
+
self.creation_date = parse_date("".join(chars[24:30]))
|
|
798
|
+
self.destination_data_center = parse_num("".join(chars[30:35]))
|
|
799
|
+
except ValueError as exc:
|
|
800
|
+
raise ParseError(str(exc)) from exc
|
|
801
|
+
self.communication_area = "".join(chars[35:55]).strip()
|
|
802
|
+
self.currency_code = "".join(chars[55:58]).strip()
|
|
803
|
+
|
|
804
|
+
def build(self) -> str:
|
|
805
|
+
date_text = eft_date(self.creation_date)
|
|
806
|
+
return (
|
|
807
|
+
self.record_header.build()
|
|
808
|
+
+ date_text
|
|
809
|
+
+ zero_pad_number(self.destination_data_center, 5)
|
|
810
|
+
+ pad_blanks(self.communication_area, 20)
|
|
811
|
+
+ pad_blanks(self.currency_code, 3)
|
|
812
|
+
+ filler(1406)
|
|
813
|
+
)
|
|
814
|
+
|
|
815
|
+
def validate(self) -> None:
|
|
816
|
+
errors = []
|
|
817
|
+
rh = self.record_header
|
|
818
|
+
if rh.record_type not in _VALID_RECORD_TYPES:
|
|
819
|
+
errors.append("invalid record type")
|
|
820
|
+
if not rh.originator_id:
|
|
821
|
+
errors.append("missing originator ID")
|
|
822
|
+
if len(rh.originator_id) != 10:
|
|
823
|
+
errors.append("originator ID must be 10 characters")
|
|
824
|
+
if rh.originator_id and not re.fullmatch(r"[A-Za-z0-9_\-\t\n\f\r ]+", rh.originator_id):
|
|
825
|
+
errors.append("originator ID must be alphanumeric")
|
|
826
|
+
if rh.file_creation_number == 0 or rh.file_creation_number > 9999:
|
|
827
|
+
errors.append("invalid file creation number")
|
|
828
|
+
if self.creation_date is None:
|
|
829
|
+
errors.append("missing creation date")
|
|
830
|
+
if not 0 <= self.destination_data_center <= 99999:
|
|
831
|
+
errors.append("invalid destination data center")
|
|
832
|
+
if len(self.communication_area) > 20:
|
|
833
|
+
errors.append("communication area exceeds 20 characters")
|
|
834
|
+
if self.currency_code not in {"CAD", "USD"}:
|
|
835
|
+
errors.append("invalid currency code")
|
|
836
|
+
if errors:
|
|
837
|
+
raise ValidationError("; ".join(errors))
|
|
838
|
+
|
|
839
|
+
def to_dict(self) -> dict[str, Any]:
|
|
840
|
+
return {
|
|
841
|
+
**self.record_header.to_dict(),
|
|
842
|
+
"creation_date": _json_date(self.creation_date),
|
|
843
|
+
"destination_data_center": self.destination_data_center,
|
|
844
|
+
"communication_area": self.communication_area,
|
|
845
|
+
"currency_code": self.currency_code,
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
@property
|
|
849
|
+
def originator_id(self) -> str:
|
|
850
|
+
return self.record_header.originator_id
|
|
851
|
+
|
|
852
|
+
@originator_id.setter
|
|
853
|
+
def originator_id(self, value: str) -> None:
|
|
854
|
+
self.record_header.originator_id = value
|
|
855
|
+
|
|
856
|
+
@property
|
|
857
|
+
def record_type(self) -> str:
|
|
858
|
+
return self.record_header.record_type
|
|
859
|
+
|
|
860
|
+
@property
|
|
861
|
+
def file_creation_number(self) -> int:
|
|
862
|
+
return self.record_header.file_creation_number
|
|
863
|
+
|
|
864
|
+
Parse = parse
|
|
865
|
+
Build = build
|
|
866
|
+
Validate = validate
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def NewFileHeader(originator_id: str, file_creation_number: int,
|
|
870
|
+
creation_date: date | datetime | None, destination_data_center: int,
|
|
871
|
+
currency_code: str, *opts: Any, **options: str) -> FileHeader:
|
|
872
|
+
for option in opts:
|
|
873
|
+
if isinstance(option, dict):
|
|
874
|
+
options.update(option)
|
|
875
|
+
elif callable(option):
|
|
876
|
+
option(options)
|
|
877
|
+
else:
|
|
878
|
+
raise TypeError(f"unsupported header option: {option!r}")
|
|
879
|
+
return FileHeader(
|
|
880
|
+
RecordHeader(HEADER_RECORD, originator_id, file_creation_number, 1),
|
|
881
|
+
creation_date,
|
|
882
|
+
destination_data_center,
|
|
883
|
+
options.get("communication_area", ""),
|
|
884
|
+
currency_code,
|
|
885
|
+
)
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
@dataclass
|
|
889
|
+
class FileFooter:
|
|
890
|
+
record_header: RecordHeader = None # type: ignore[assignment]
|
|
891
|
+
total_value_debit: int = 0
|
|
892
|
+
total_count_debit: int = 0
|
|
893
|
+
total_value_credit: int = 0
|
|
894
|
+
total_count_credit: int = 0
|
|
895
|
+
total_value_reverse_debit: int = 0
|
|
896
|
+
total_count_reverse_debit: int = 0
|
|
897
|
+
total_value_reverse_credit: int = 0
|
|
898
|
+
total_count_reverse_credit: int = 0
|
|
899
|
+
|
|
900
|
+
def __post_init__(self) -> None:
|
|
901
|
+
if self.record_header is None:
|
|
902
|
+
self.record_header = RecordHeader(FOOTER_RECORD)
|
|
903
|
+
|
|
904
|
+
@classmethod
|
|
905
|
+
def from_transactions(cls, record_header: RecordHeader, txns: list[Transaction]) -> FileFooter:
|
|
906
|
+
def totals(*record_types: str) -> tuple[int, int]:
|
|
907
|
+
selected = [txn for txn in txns if txn.get_type() in record_types]
|
|
908
|
+
return sum(t.amount for t in selected), len(selected)
|
|
909
|
+
|
|
910
|
+
debit_value, debit_count = totals(DEBIT_RECORD, RETURN_DEBIT_RECORD)
|
|
911
|
+
credit_value, credit_count = totals(CREDIT_RECORD, RETURN_CREDIT_RECORD)
|
|
912
|
+
reverse_credit_value, reverse_credit_count = totals(CREDIT_REVERSE_RECORD)
|
|
913
|
+
reverse_debit_value, reverse_debit_count = totals(DEBIT_REVERSE_RECORD)
|
|
914
|
+
return cls(record_header, debit_value, debit_count, credit_value, credit_count,
|
|
915
|
+
reverse_credit_value, reverse_credit_count,
|
|
916
|
+
reverse_debit_value, reverse_debit_count)
|
|
917
|
+
|
|
918
|
+
def parse(self, line: str) -> None:
|
|
919
|
+
chars = list(line)
|
|
920
|
+
if len(chars) < 112:
|
|
921
|
+
raise ParseError("footer is too short")
|
|
922
|
+
self.record_header = RecordHeader()
|
|
923
|
+
self.record_header.parse(line)
|
|
924
|
+
offsets = [(24, 38), (38, 46), (46, 60), (60, 68),
|
|
925
|
+
(68, 82), (82, 90), (90, 104), (104, 112)]
|
|
926
|
+
values = []
|
|
927
|
+
for start, end in offsets:
|
|
928
|
+
piece = "".join(chars[start:end])
|
|
929
|
+
if not piece.strip():
|
|
930
|
+
values.append(0)
|
|
931
|
+
continue
|
|
932
|
+
try:
|
|
933
|
+
values.append(parse_num(piece))
|
|
934
|
+
except ValueError as exc:
|
|
935
|
+
raise ParseError(f"failed to parse footer total at {start}:{end}: {exc}") from exc
|
|
936
|
+
(
|
|
937
|
+
self.total_value_debit, self.total_count_debit,
|
|
938
|
+
self.total_value_credit, self.total_count_credit,
|
|
939
|
+
self.total_value_reverse_debit, self.total_count_reverse_debit,
|
|
940
|
+
self.total_value_reverse_credit, self.total_count_reverse_credit,
|
|
941
|
+
) = values
|
|
942
|
+
|
|
943
|
+
def build(self) -> str:
|
|
944
|
+
return (
|
|
945
|
+
self.record_header.build()
|
|
946
|
+
+ zero_pad_number(self.total_value_debit, 14)
|
|
947
|
+
+ zero_pad_number(self.total_count_debit, 8)
|
|
948
|
+
+ zero_pad_number(self.total_value_credit, 14)
|
|
949
|
+
+ zero_pad_number(self.total_count_credit, 8)
|
|
950
|
+
+ zero_pad_number(self.total_value_reverse_debit, 14)
|
|
951
|
+
+ zero_pad_number(self.total_count_reverse_debit, 8)
|
|
952
|
+
+ zero_pad_number(self.total_value_reverse_credit, 14)
|
|
953
|
+
+ zero_pad_number(self.total_count_reverse_credit, 8)
|
|
954
|
+
+ filler(1352)
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
def get_type(self) -> str:
|
|
958
|
+
return FOOTER_RECORD
|
|
959
|
+
|
|
960
|
+
def to_dict(self) -> dict[str, Any]:
|
|
961
|
+
return {
|
|
962
|
+
**self.record_header.to_dict(),
|
|
963
|
+
"total_value_debit": self.total_value_debit,
|
|
964
|
+
"total_count_debit": self.total_count_debit,
|
|
965
|
+
"total_value_credit": self.total_value_credit,
|
|
966
|
+
"total_count_credit": self.total_count_credit,
|
|
967
|
+
"total_value_reverse_debit": self.total_value_reverse_debit,
|
|
968
|
+
"total_count_reverse_debit": self.total_count_reverse_debit,
|
|
969
|
+
"total_value_reverse_credit": self.total_value_reverse_credit,
|
|
970
|
+
"total_count_reverse_credit": self.total_count_reverse_credit,
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
@property
|
|
974
|
+
def originator_id(self) -> str:
|
|
975
|
+
return self.record_header.originator_id
|
|
976
|
+
|
|
977
|
+
@property
|
|
978
|
+
def record_type(self) -> str:
|
|
979
|
+
return self.record_header.record_type
|
|
980
|
+
|
|
981
|
+
@property
|
|
982
|
+
def file_creation_number(self) -> int:
|
|
983
|
+
return self.record_header.file_creation_number
|
|
984
|
+
|
|
985
|
+
Parse = parse
|
|
986
|
+
Build = build
|
|
987
|
+
GetType = get_type
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def NewFileFooter(record_header: RecordHeader, txns: list[Transaction]) -> FileFooter:
|
|
991
|
+
return FileFooter.from_transactions(record_header, txns)
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
@dataclass
|
|
995
|
+
class File:
|
|
996
|
+
header: FileHeader | None = None
|
|
997
|
+
txns: list[Transaction] | None = None
|
|
998
|
+
footer: FileFooter | None = None
|
|
999
|
+
|
|
1000
|
+
def __post_init__(self) -> None:
|
|
1001
|
+
if self.txns is None:
|
|
1002
|
+
self.txns = []
|
|
1003
|
+
|
|
1004
|
+
def create(self) -> str:
|
|
1005
|
+
if self.header is None:
|
|
1006
|
+
raise CadeftError("file header is missing")
|
|
1007
|
+
current_line = 1
|
|
1008
|
+
output = [self.header.build()]
|
|
1009
|
+
current_line += 1
|
|
1010
|
+
txns = self.txns or []
|
|
1011
|
+
# Records are grouped by type. Keep first-seen type ordering for deterministic output,
|
|
1012
|
+
# matching the upstream reference implementation.
|
|
1013
|
+
grouped: dict[str, list[Transaction]] = {}
|
|
1014
|
+
for index, txn in enumerate(txns):
|
|
1015
|
+
if txn.get_type() not in _RECORD_TYPES:
|
|
1016
|
+
raise CadeftError(f"transaction[{index}] has unexpected record type: {txn.get_type()}")
|
|
1017
|
+
grouped.setdefault(txn.get_type(), []).append(txn)
|
|
1018
|
+
for record_type, entries in grouped.items():
|
|
1019
|
+
for offset in range(0, len(entries), MAX_TXNS_PER_RECORD):
|
|
1020
|
+
header = RecordHeader(record_type, self.header.record_header.originator_id,
|
|
1021
|
+
self.header.record_header.file_creation_number, current_line)
|
|
1022
|
+
built = "".join(txn.build() for txn in entries[offset:offset + MAX_TXNS_PER_RECORD])
|
|
1023
|
+
output.append("\n" + header.build() + built + filler(MAX_LINE_LENGTH - 24 - len(built)))
|
|
1024
|
+
current_line += 1
|
|
1025
|
+
output.append("\n")
|
|
1026
|
+
if self.footer is None:
|
|
1027
|
+
rh = RecordHeader(
|
|
1028
|
+
FOOTER_RECORD,
|
|
1029
|
+
self.header.record_header.originator_id,
|
|
1030
|
+
self.header.record_header.file_creation_number,
|
|
1031
|
+
current_line,
|
|
1032
|
+
)
|
|
1033
|
+
self.footer = FileFooter.from_transactions(rh, txns)
|
|
1034
|
+
else:
|
|
1035
|
+
self.footer.record_header.record_count = current_line
|
|
1036
|
+
output.append(self.footer.build())
|
|
1037
|
+
return "".join(output)
|
|
1038
|
+
|
|
1039
|
+
def validate(self) -> None:
|
|
1040
|
+
if self.header is None:
|
|
1041
|
+
raise ValidationError("file header is missing")
|
|
1042
|
+
errors = []
|
|
1043
|
+
try:
|
|
1044
|
+
self.header.validate()
|
|
1045
|
+
except ValidationError as exc:
|
|
1046
|
+
errors.append(str(exc))
|
|
1047
|
+
for index, txn in enumerate(self.txns or []):
|
|
1048
|
+
try:
|
|
1049
|
+
txn.validate()
|
|
1050
|
+
except ValidationError as exc:
|
|
1051
|
+
errors.append(f"failed to validate txn {index}: {exc}")
|
|
1052
|
+
if self.footer is not None:
|
|
1053
|
+
expected = FileFooter.from_transactions(self.footer.record_header, self.txns or [])
|
|
1054
|
+
for field_name in (
|
|
1055
|
+
"total_value_debit", "total_count_debit", "total_value_credit",
|
|
1056
|
+
"total_count_credit", "total_value_reverse_debit",
|
|
1057
|
+
"total_count_reverse_debit", "total_value_reverse_credit",
|
|
1058
|
+
"total_count_reverse_credit",
|
|
1059
|
+
):
|
|
1060
|
+
actual = getattr(self.footer, field_name)
|
|
1061
|
+
wanted = getattr(expected, field_name)
|
|
1062
|
+
if actual != wanted:
|
|
1063
|
+
errors.append(f"footer {field_name}: got {actual} want {wanted}")
|
|
1064
|
+
if errors:
|
|
1065
|
+
raise ValidationError("; ".join(errors))
|
|
1066
|
+
|
|
1067
|
+
def get_all_debit_txns(self) -> list[Debit]:
|
|
1068
|
+
return [txn for txn in self.txns or [] if isinstance(txn, Debit) and not isinstance(txn, DebitReverse)]
|
|
1069
|
+
|
|
1070
|
+
def get_all_credits(self) -> list[Credit]:
|
|
1071
|
+
return [txn for txn in self.txns or [] if isinstance(txn, Credit) and not isinstance(txn, CreditReverse)]
|
|
1072
|
+
|
|
1073
|
+
def get_all_debit_returns(self) -> list[DebitReturn]:
|
|
1074
|
+
return [txn for txn in self.txns or [] if isinstance(txn, DebitReturn)]
|
|
1075
|
+
|
|
1076
|
+
def get_all_credit_returns(self) -> list[CreditReturn]:
|
|
1077
|
+
return [txn for txn in self.txns or [] if isinstance(txn, CreditReturn)]
|
|
1078
|
+
|
|
1079
|
+
def to_dict(self) -> dict[str, Any]:
|
|
1080
|
+
result: dict[str, Any] = {}
|
|
1081
|
+
if self.header is not None:
|
|
1082
|
+
result["file_header"] = self.header.to_dict()
|
|
1083
|
+
if self.txns:
|
|
1084
|
+
result["transactions"] = [txn.to_dict() for txn in self.txns]
|
|
1085
|
+
if self.footer is not None:
|
|
1086
|
+
result["file_footer"] = self.footer.to_dict()
|
|
1087
|
+
return result
|
|
1088
|
+
|
|
1089
|
+
Create = create
|
|
1090
|
+
Validate = validate
|
|
1091
|
+
GetAllDebitTxns = get_all_debit_txns
|
|
1092
|
+
GetAllCredits = get_all_credits
|
|
1093
|
+
GetAllDebitReturns = get_all_debit_returns
|
|
1094
|
+
GetAllCreditReturns = get_all_credit_returns
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def NewFile(header: FileHeader, txns: list[Transaction]) -> File:
|
|
1098
|
+
return File(header, txns)
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def NewReader(source: str | bytes | TextIO | BinaryIO) -> Reader:
|
|
1102
|
+
return Reader(source)
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def NewFileStream(source: str | TextIO | BinaryIO) -> FileStreamer:
|
|
1106
|
+
return FileStreamer(source)
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
new_debit = NewDebit
|
|
1110
|
+
new_credit = NewCredit
|
|
1111
|
+
new_debit_return = NewDebitReturn
|
|
1112
|
+
new_credit_return = NewCreditReturn
|
|
1113
|
+
new_debit_reverse = NewDebitReverse
|
|
1114
|
+
new_credit_reverse = NewCreditReverse
|
|
1115
|
+
new_file = NewFile
|
|
1116
|
+
new_file_header = NewFileHeader
|
|
1117
|
+
new_file_footer = NewFileFooter
|
|
1118
|
+
new_reader = NewReader
|
|
1119
|
+
new_file_stream = NewFileStream
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def transaction_from_dict(value: dict[str, Any]) -> Transaction:
|
|
1123
|
+
record_type = value.get("type", "")
|
|
1124
|
+
cls = _TRANSACTION_CLASS.get(record_type)
|
|
1125
|
+
if cls is None:
|
|
1126
|
+
raise ParseError(f"unknown transaction type {record_type!r}")
|
|
1127
|
+
aliases = {field.name for field in fields(cls)}
|
|
1128
|
+
cooked = {key: val for key, val in value.items() if key in aliases}
|
|
1129
|
+
date_key = cls.DATE_JSON
|
|
1130
|
+
if date_key in cooked:
|
|
1131
|
+
cooked[date_key] = _as_date(cooked[date_key])
|
|
1132
|
+
return cls(**cooked)
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def file_from_dict(value: dict[str, Any]) -> File:
|
|
1136
|
+
header_data = value.get("file_header")
|
|
1137
|
+
header = None
|
|
1138
|
+
if header_data is not None:
|
|
1139
|
+
rh = RecordHeader(
|
|
1140
|
+
header_data.get("type", ""),
|
|
1141
|
+
header_data.get("originator_id", ""),
|
|
1142
|
+
header_data.get("file_creation_number", 0),
|
|
1143
|
+
header_data.get("record_count", 0),
|
|
1144
|
+
)
|
|
1145
|
+
header = FileHeader(
|
|
1146
|
+
rh,
|
|
1147
|
+
_as_date(header_data.get("creation_date")),
|
|
1148
|
+
header_data.get("destination_data_center", 0),
|
|
1149
|
+
header_data.get("communication_area", ""),
|
|
1150
|
+
header_data.get("currency_code", ""),
|
|
1151
|
+
)
|
|
1152
|
+
txns = [transaction_from_dict(item) for item in value.get("transactions", [])]
|
|
1153
|
+
footer_data = value.get("file_footer")
|
|
1154
|
+
footer = None
|
|
1155
|
+
if footer_data is not None:
|
|
1156
|
+
rh = RecordHeader(
|
|
1157
|
+
footer_data.get("type", ""),
|
|
1158
|
+
footer_data.get("originator_id", ""),
|
|
1159
|
+
footer_data.get("file_creation_number", 0),
|
|
1160
|
+
footer_data.get("record_count", 0),
|
|
1161
|
+
)
|
|
1162
|
+
footer = FileFooter(
|
|
1163
|
+
rh,
|
|
1164
|
+
footer_data.get("total_value_debit", 0),
|
|
1165
|
+
footer_data.get("total_count_debit", 0),
|
|
1166
|
+
footer_data.get("total_value_credit", 0),
|
|
1167
|
+
footer_data.get("total_count_credit", 0),
|
|
1168
|
+
footer_data.get("total_value_reverse_debit", 0),
|
|
1169
|
+
footer_data.get("total_count_reverse_debit", 0),
|
|
1170
|
+
footer_data.get("total_value_reverse_credit", 0),
|
|
1171
|
+
footer_data.get("total_count_reverse_credit", 0),
|
|
1172
|
+
)
|
|
1173
|
+
return File(header, txns, footer)
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
class Reader:
|
|
1177
|
+
def __init__(self, source: str | bytes | TextIO | BinaryIO):
|
|
1178
|
+
self.source = source
|
|
1179
|
+
self.file = File()
|
|
1180
|
+
|
|
1181
|
+
def read_file(self) -> File:
|
|
1182
|
+
if isinstance(self.source, bytes):
|
|
1183
|
+
text = self.source.decode("utf-8")
|
|
1184
|
+
elif isinstance(self.source, str):
|
|
1185
|
+
text = self.source
|
|
1186
|
+
else:
|
|
1187
|
+
text = self.source.read()
|
|
1188
|
+
if isinstance(text, bytes):
|
|
1189
|
+
text = text.decode("utf-8")
|
|
1190
|
+
for raw_line in text.splitlines():
|
|
1191
|
+
line = normalize(raw_line)
|
|
1192
|
+
if not line:
|
|
1193
|
+
continue
|
|
1194
|
+
record_type = line[0]
|
|
1195
|
+
if record_type == HEADER_RECORD:
|
|
1196
|
+
if len(line) < 58:
|
|
1197
|
+
raise ParseError("failed to parse header: record type A is not required length")
|
|
1198
|
+
header = FileHeader()
|
|
1199
|
+
header.parse(line)
|
|
1200
|
+
self.file.header = header
|
|
1201
|
+
elif record_type in _RECORD_TYPES:
|
|
1202
|
+
chars = list(line)
|
|
1203
|
+
if len(chars) < COMMON_RECORD_DATA_LENGTH:
|
|
1204
|
+
raise ParseError(
|
|
1205
|
+
f"txn record shorter than common header length {COMMON_RECORD_DATA_LENGTH}: got {len(chars)}"
|
|
1206
|
+
)
|
|
1207
|
+
body = chars[COMMON_RECORD_DATA_LENGTH:]
|
|
1208
|
+
if len(body) % SEGMENT_LENGTH:
|
|
1209
|
+
raise ParseError(
|
|
1210
|
+
f"record length is not valid multiple of {SEGMENT_LENGTH}, partial txn: {len(body) % SEGMENT_LENGTH}"
|
|
1211
|
+
)
|
|
1212
|
+
for offset in range(0, len(body), SEGMENT_LENGTH):
|
|
1213
|
+
segment = "".join(body[offset:offset + SEGMENT_LENGTH])
|
|
1214
|
+
if segment.strip():
|
|
1215
|
+
txn = _TRANSACTION_CLASS[record_type]()
|
|
1216
|
+
txn.parse(segment)
|
|
1217
|
+
self.file.txns.append(txn)
|
|
1218
|
+
elif record_type == FOOTER_RECORD:
|
|
1219
|
+
if len(line) < 112:
|
|
1220
|
+
raise ParseError("z record does not contain minimum amount of data")
|
|
1221
|
+
footer = FileFooter()
|
|
1222
|
+
footer.parse(line)
|
|
1223
|
+
self.file.footer = footer
|
|
1224
|
+
return self.file
|
|
1225
|
+
|
|
1226
|
+
ReadFile = read_file
|
|
1227
|
+
|
|
1228
|
+
|
|
1229
|
+
class FileStreamer:
|
|
1230
|
+
"""Stateful, single-threaded reader returning one transaction segment at a time."""
|
|
1231
|
+
|
|
1232
|
+
def __init__(self, source: str | TextIO | BinaryIO):
|
|
1233
|
+
if isinstance(source, str):
|
|
1234
|
+
self._lines = source.splitlines()
|
|
1235
|
+
else:
|
|
1236
|
+
data = source.read()
|
|
1237
|
+
if isinstance(data, bytes):
|
|
1238
|
+
data = data.decode("utf-8")
|
|
1239
|
+
self._lines = data.splitlines()
|
|
1240
|
+
self._line = 0
|
|
1241
|
+
self._segments: list[tuple[str, str]] = []
|
|
1242
|
+
|
|
1243
|
+
def get_header(self) -> FileHeader:
|
|
1244
|
+
if not self._lines:
|
|
1245
|
+
raise ParseError("failed to scan for file header")
|
|
1246
|
+
header = FileHeader()
|
|
1247
|
+
header.parse(normalize(self._lines[0]))
|
|
1248
|
+
return header
|
|
1249
|
+
|
|
1250
|
+
def get_footer(self) -> FileFooter:
|
|
1251
|
+
for line in self._lines:
|
|
1252
|
+
if line.startswith(FOOTER_RECORD):
|
|
1253
|
+
footer = FileFooter()
|
|
1254
|
+
footer.parse(normalize(line))
|
|
1255
|
+
return footer
|
|
1256
|
+
raise ParseError("failed to find footer record")
|
|
1257
|
+
|
|
1258
|
+
def scan_txn(self) -> Transaction:
|
|
1259
|
+
if self._line == 0:
|
|
1260
|
+
if not self._lines or not self._lines[0].startswith(HEADER_RECORD):
|
|
1261
|
+
raise ParseError("first line in file is not a header record")
|
|
1262
|
+
self._line = 1
|
|
1263
|
+
while not self._segments:
|
|
1264
|
+
if self._line >= len(self._lines):
|
|
1265
|
+
raise EndOfFile()
|
|
1266
|
+
line = normalize(self._lines[self._line].strip())
|
|
1267
|
+
self._line += 1
|
|
1268
|
+
if not line or line.startswith(FOOTER_RECORD):
|
|
1269
|
+
raise EndOfFile()
|
|
1270
|
+
if len(line) < COMMON_RECORD_DATA_LENGTH:
|
|
1271
|
+
raise ParseError(f"txn record at line {self._line} shorter than common header length 24")
|
|
1272
|
+
body = list(line)[COMMON_RECORD_DATA_LENGTH:]
|
|
1273
|
+
if len(body) % SEGMENT_LENGTH:
|
|
1274
|
+
raise ParseError(f"txn record at line {self._line} is not of correct length")
|
|
1275
|
+
record_type = line[0]
|
|
1276
|
+
for offset in range(0, len(body), SEGMENT_LENGTH):
|
|
1277
|
+
segment = "".join(body[offset:offset + SEGMENT_LENGTH])
|
|
1278
|
+
self._segments.append((record_type, segment))
|
|
1279
|
+
record_type, segment = self._segments.pop(0)
|
|
1280
|
+
cls = _TRANSACTION_CLASS.get(record_type)
|
|
1281
|
+
if cls is None:
|
|
1282
|
+
raise ParseError(f"unrecognized record type at line {self._line}: {record_type}")
|
|
1283
|
+
return cls().parse(segment)
|
|
1284
|
+
|
|
1285
|
+
GetHeader = get_header
|
|
1286
|
+
GetFooter = get_footer
|
|
1287
|
+
ScanTxn = scan_txn
|
|
1288
|
+
|
|
1289
|
+
|
|
1290
|
+
def NewTransaction(record_type: str, txn_type: str, amount: int,
|
|
1291
|
+
txn_date: date | datetime | None, institution_id: str,
|
|
1292
|
+
account_no: str, item_trace_no: str, short_name: str,
|
|
1293
|
+
name: str, long_name: str, bank_id: str, bank_account: str,
|
|
1294
|
+
original_item_trace_no: str = "", *opts: Any,
|
|
1295
|
+
**options: str) -> Transaction | None:
|
|
1296
|
+
if record_type not in _TRANSACTION_CLASS:
|
|
1297
|
+
return None
|
|
1298
|
+
return _constructor(record_type, txn_type, amount, txn_date, institution_id, account_no,
|
|
1299
|
+
item_trace_no, short_name, name, long_name, bank_id, bank_account,
|
|
1300
|
+
original_item_trace_no, *opts, **options)
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
new_transaction = NewTransaction
|
|
1304
|
+
|
|
1305
|
+
|
|
1306
|
+
def Ptr(value: Any) -> Any:
|
|
1307
|
+
return value
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def Arr(value: Any) -> list[Any]:
|
|
1311
|
+
return [value]
|
|
1312
|
+
|
|
1313
|
+
|
|
1314
|
+
def _option(name: str, value: str) -> Callable[[dict[str, str]], None]:
|
|
1315
|
+
return lambda options: options.__setitem__(name, value)
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
def WithUserID(value: str) -> Callable[[dict[str, str]], None]:
|
|
1319
|
+
return _option("user_id", value)
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def WithCrossRefNo(value: str) -> Callable[[dict[str, str]], None]:
|
|
1323
|
+
return _option("cross_ref_no", value)
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
def WithSundryInfo(value: str) -> Callable[[dict[str, str]], None]:
|
|
1327
|
+
return _option("sundry_info", value)
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def WithSettlementCode(value: str) -> Callable[[dict[str, str]], None]:
|
|
1331
|
+
return _option("settlement_code", value)
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def WithStoredTransactionType(value: str) -> Callable[[dict[str, str]], None]:
|
|
1335
|
+
return _option("stored_txn_type", value)
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
def WithInvalidDataElementID(value: str) -> Callable[[dict[str, str]], None]:
|
|
1339
|
+
return _option("invalid_data_element_id", value)
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
def WithDirectClearerCommunicationArea(value: str) -> dict[str, str]:
|
|
1343
|
+
return {"communication_area": value}
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
__all__ = [
|
|
1347
|
+
"Arr", "BaseTxn", "CREDIT_RECORD", "CREDIT_REVERSE_RECORD", "Credit",
|
|
1348
|
+
"CreditReturn", "CreditReverse", "CadeftError", "DEBIT_RECORD",
|
|
1349
|
+
"DEBIT_REVERSE_RECORD", "Debit", "DebitReturn", "DebitReverse", "EndOfFile",
|
|
1350
|
+
"File", "FileFooter", "FileHeader", "FileStreamer", "FOOTER_RECORD",
|
|
1351
|
+
"HEADER_RECORD", "NewCredit", "NewCreditReturn", "NewCreditReverse", "NewDebit",
|
|
1352
|
+
"NewDebitReturn", "NewDebitReverse", "NewFile", "NewFileFooter", "NewFileHeader",
|
|
1353
|
+
"NewFileStream", "NewReader", "NewTransaction", "ParseError", "Ptr", "Reader",
|
|
1354
|
+
"RecordHeader", "RecordType", "TransactionType", "DCSign", "Transactions",
|
|
1355
|
+
"BaseTxnOpt", "HeaderOpts",
|
|
1356
|
+
"RETURN_CREDIT_RECORD", "RETURN_DEBIT_RECORD", "Transaction", "ValidationError",
|
|
1357
|
+
"WithCrossRefNo", "WithDirectClearerCommunicationArea", "WithInvalidDataElementID",
|
|
1358
|
+
"WithSettlementCode", "WithStoredTransactionType", "WithSundryInfo", "WithUserID",
|
|
1359
|
+
"file_from_dict", "normalize", "parse_date", "parse_num", "transaction_from_dict",
|
|
1360
|
+
"new_credit", "new_credit_return", "new_credit_reverse", "new_debit",
|
|
1361
|
+
"new_debit_return", "new_debit_reverse", "new_file", "new_file_footer",
|
|
1362
|
+
"new_file_header", "new_file_stream", "new_reader", "new_transaction",
|
|
1363
|
+
]
|