ledger-recon-kit 0.1.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.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: ledger-recon-kit
3
+ Version: 0.1.0
4
+ Summary: Explainable reconciliation of ledger and bank statement transactions
5
+ Keywords: reconciliation,banking,accounting,finance,decimal,csv
6
+ Author: Elvin Haxverdiyev
7
+ Author-email: Elvin Haxverdiyev <elvinhaxverdiyev777@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Financial and Insurance Industry
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.15
18
+ Project-URL: Homepage, https://github.com/elvinhaxverdiyev/recon_kit
19
+ Project-URL: Repository, https://github.com/elvinhaxverdiyev/recon_kit
20
+ Project-URL: Issues, https://github.com/elvinhaxverdiyev/recon_kit/issues
21
+ Description-Content-Type: text/markdown
22
+
23
+ # ReconKit
24
+
25
+ Ledger ilə bank çıxarışını uyğunlaşdıran (reconciliation) kiçik Python kitabxanası və komanda sətri aləti.
26
+
27
+ - Heç bir xarici asılılıq yoxdur (yalnız standart kitabxana)
28
+ - Pul `Decimal` ilə, `float` heç vaxt
29
+ - Hər uyğunluğun **səbəbi və etibar skoru** var (auditor "niyə?" deyə soruşanda cavab hazırdır)
30
+ - Qeyri-müəyyən hallarda təxmin etmir, uyğunlaşdırmır (səhv uyğunluq itkin sətirdən təhlükəlidir)
31
+
32
+ ## Quraşdırma
33
+
34
+ ```bat
35
+ uv add reconkit
36
+ ```
37
+
38
+ ## CLI
39
+
40
+ ```bat
41
+ python -m reconkit run ledger.csv statement.csv --tolerance 0.05 --out hesabat
42
+ ```
43
+
44
+ | Seçim | Mənası |
45
+ |---|---|
46
+ | `--tolerance 0.05` | Məbləğ tolerantlığı (verilməsə, yalnız dəqiq qaydalar işləyir) |
47
+ | `--days 2` | Tarix pəncərəsi |
48
+ | `--invert-statement` | Çıxarışın istiqamətini çevir (nostro/vostro) |
49
+ | `--delimiter ";"` | CSV ayırıcısı |
50
+ | `--decimal-separator ","` | Onluq işarə |
51
+ | `--date-format "%d.%m.%Y"` | Tarix formatı |
52
+ | `--currency AZN` | CSV-də valyuta sütunu yoxdursa |
53
+
54
+ Çıxış kodları: `0` hamısı uyğun, `1` break var, `2` xəta.
55
+
56
+ ## Python API
57
+
58
+ ```python
59
+ from reconkit import (
60
+ AmountAndDate, AmountTolerance, ExactReference, Reconciler, load_csv,
61
+ )
62
+
63
+ ledger = load_csv("ledger.csv", id_prefix="L-")
64
+ statement = load_csv("statement.csv", id_prefix="S-")
65
+
66
+ result = Reconciler(
67
+ [ExactReference(), AmountAndDate(day_window=2), AmountTolerance("0.05")]
68
+ ).run(ledger, statement)
69
+
70
+ print(result.summary)
71
+ result.to_json("result.json")
72
+ result.breaks_to_csv("breaks.csv")
73
+ ```
74
+
75
+ ## Qaydalar
76
+
77
+ Qaydalar sırayla işləyir, ən dəqiqi birinci olmalıdır.
78
+
79
+ | Qayda | Nəyi uyğunlaşdırır | Etibar |
80
+ |---|---|---|
81
+ | `ExactReference` | reference + məbləğ + valyuta + istiqamət | 1.0 |
82
+ | `AmountAndDate` | məbləğ + valyuta + istiqamət + tarix pəncərəsi | ≤ 0.9 |
83
+ | `AmountTolerance` | məbləğ fərqi limit daxilində + tarix pəncərəsi | ≤ 0.7 |
84
+
85
+ Öz qaydanızı yazmaq üçün `Rule` sinfindən törəyin və `find_match` metodunu həyata keçirin.
86
+
87
+ ## Məhdudiyyətlər
88
+
89
+ - 1-ə-çox və çox-a-1 uyğunlaşdırma hələ yoxdur
90
+ - Tolerantlıq mütləq məbləğdir (faizlə deyil)
91
+ - MT940 / CAMT.053 formatları dəstəklənmir, yalnız CSV
92
+ - İstehsalda istifadədən əvvəl öz məlumatınızla ciddi yoxlayın
93
+
94
+ ## Təhlükəsizlik
95
+
96
+ - CSV hesabatlarında formula injection-a qarşı (`=`, `+`, `-`, `@` ilə başlayan mətn sahələri) müdafiə var
97
+ - Giriş CSV-lərində `NaN`, `Infinity` və təkrarlanan id rədd edilir
98
+
99
+ ## İnkişaf
100
+
101
+ ```bat
102
+ uv sync
103
+ uv run python -m pytest
104
+ uv run python -m ruff check .
105
+ ```
@@ -0,0 +1,15 @@
1
+ reconkit/__init__.py,sha256=47ln832a1eVm4PFz-r4C6y1R3nX5VsE80UKb21iHN9c,517
2
+ reconkit/__main__.py,sha256=0yyrJrigeLG3MIj_5SgIrYEQsQQdhQVGMVz4ULNC4gg,55
3
+ reconkit/cli.py,sha256=zoaUc9wqQ0PpRHpR35FN4uEFGenA52lGTcIJi1MKQDI,4883
4
+ reconkit/loaders.py,sha256=TxZS8CYFrZyp9PNk__DThDRF_4IWp7HDPZC8Do7Uta0,9755
5
+ reconkit/models.py,sha256=RxzZl3ZzqIujtuZvfz0NBMr_MP8R4CvgjNasvc6VZTQ,981
6
+ reconkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ reconkit/reconciler.py,sha256=xvKlPkuNl3at4YuZ2dKsvVISLs6s_yvisE-05RtNAGs,2940
8
+ reconkit/report.py,sha256=mZd7UtLvncDnms6zfcjBhOyyl9168AVzHoX-yWHZ7LQ,3487
9
+ reconkit/rules.py,sha256=m6ZPhTFQydxu8E2CJW80qbmWIetP9maps9RD7mte5sw,5663
10
+ reconkit/transforms.py,sha256=2jjxztOcEsVaC29nBu1e2xjAx1LCUaP2esras-4Njw8,673
11
+ ledger_recon_kit-0.1.0.dist-info/licenses/LICENSE,sha256=6WRa_Gi2P_YNB1BZnhF1mV5bwjQvKdO_joYI-ZAmeOM,1097
12
+ ledger_recon_kit-0.1.0.dist-info/WHEEL,sha256=3OmCxFA0ffBIsX4x0o8CdfSvZAOvO3mzEG8U_z5TvV4,80
13
+ ledger_recon_kit-0.1.0.dist-info/entry_points.txt,sha256=UbxLY-x1mHJWlq_JDJY6V6Q6nsvIiju5c2q6K21xhPY,48
14
+ ledger_recon_kit-0.1.0.dist-info/METADATA,sha256=xNRiw8tK3k_uG_5iuRp5v8Q3pdJNTqYcSYQLKjXy_2E,3658
15
+ ledger_recon_kit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.8
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ reconkit = reconkit.cli:main
3
+
@@ -0,0 +1,22 @@
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2026 Elvin Haxverdiyev
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
reconkit/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ from .loaders import CsvFormatError, load_csv
2
+ from .models import Direction, Transaction
3
+ from .reconciler import Reconciler, ReconciliationResult
4
+ from .rules import AmountAndDate, AmountTolerance, ExactReference, Match, Rule
5
+ from .transforms import invert_directions
6
+
7
+ __all__ = [
8
+ "AmountAndDate",
9
+ "AmountTolerance",
10
+ "CsvFormatError",
11
+ "Direction",
12
+ "ExactReference",
13
+ "Match",
14
+ "Reconciler",
15
+ "ReconciliationResult",
16
+ "Rule",
17
+ "Transaction",
18
+ "invert_directions",
19
+ "load_csv",
20
+ ]
reconkit/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
reconkit/cli.py ADDED
@@ -0,0 +1,209 @@
1
+
2
+ import argparse
3
+ import sys
4
+ from collections.abc import Sequence
5
+ from decimal import Decimal, InvalidOperation
6
+ from pathlib import Path
7
+
8
+ from .loaders import CsvFormatError, load_csv
9
+ from .reconciler import Reconciler
10
+ from .rules import AmountAndDate, AmountTolerance, ExactReference
11
+ from .transforms import invert_directions
12
+
13
+
14
+ def _decimal(text: str) -> Decimal:
15
+ try:
16
+ value = Decimal(text)
17
+ except InvalidOperation:
18
+ raise argparse.ArgumentTypeError(
19
+ f"ədəd deyil: {text!r}"
20
+ ) from None
21
+
22
+ if not value.is_finite() or value < 0:
23
+ raise argparse.ArgumentTypeError(
24
+ "mənfi olmayan sonlu ədəd olmalıdır"
25
+ )
26
+
27
+ return value
28
+
29
+
30
+ def _non_negative_days(text: str) -> int:
31
+ try:
32
+ value = int(text)
33
+ except ValueError:
34
+ raise argparse.ArgumentTypeError(
35
+ f"tam ədəd olmalıdır: {text!r}"
36
+ ) from None
37
+
38
+ if value < 0:
39
+ raise argparse.ArgumentTypeError(
40
+ "gün sayı mənfi ola bilməz"
41
+ )
42
+
43
+ return value
44
+
45
+
46
+ def build_parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(
48
+ prog="reconkit",
49
+ description="Ledger və bank çıxarışının uyğunlaşdırılması",
50
+ )
51
+
52
+ sub = parser.add_subparsers(
53
+ dest="command",
54
+ required=True,
55
+ )
56
+
57
+ run = sub.add_parser(
58
+ "run",
59
+ help="iki CSV faylını uyğunlaşdır",
60
+ )
61
+
62
+ run.add_argument(
63
+ "ledger",
64
+ type=Path,
65
+ help="ledger CSV faylı",
66
+ )
67
+
68
+ run.add_argument(
69
+ "statement",
70
+ type=Path,
71
+ help="bank çıxarışı CSV faylı",
72
+ )
73
+
74
+ run.add_argument(
75
+ "--tolerance",
76
+ type=_decimal,
77
+ default=Decimal(0),
78
+ help="məbləğ tolerantlığı, məsələn 0.05 (default: yoxdur)",
79
+ )
80
+
81
+ run.add_argument(
82
+ "--days",
83
+ type=_non_negative_days,
84
+ default=2,
85
+ help="tarix pəncərəsi, gün (default: 2)",
86
+ )
87
+
88
+ run.add_argument(
89
+ "--invert-statement",
90
+ action="store_true",
91
+ help="çıxarışın istiqamətini çevir (nostro/vostro üçün)",
92
+ )
93
+
94
+ run.add_argument(
95
+ "--delimiter",
96
+ default=",",
97
+ help="CSV ayırıcısı (default: ,)",
98
+ )
99
+
100
+ run.add_argument(
101
+ "--decimal-separator",
102
+ default=".",
103
+ help="onluq işarə (default: .)",
104
+ )
105
+
106
+ run.add_argument(
107
+ "--date-format",
108
+ default="%Y-%m-%d",
109
+ help="tarix formatı (default: %%Y-%%m-%%d)",
110
+ )
111
+
112
+ run.add_argument(
113
+ "--currency",
114
+ default=None,
115
+ help="CSV-də valyuta sütunu yoxdursa, istifadə olunacaq valyuta",
116
+ )
117
+
118
+ run.add_argument(
119
+ "--out",
120
+ type=Path,
121
+ default=Path("."),
122
+ help="hesabatların yazılacağı qovluq (default: cari)",
123
+ )
124
+
125
+ return parser
126
+
127
+
128
+ def main(argv: Sequence[str] | None = None) -> int:
129
+ args = build_parser().parse_args(argv)
130
+
131
+ options = {
132
+ "delimiter": args.delimiter,
133
+ "decimal_separator": args.decimal_separator,
134
+ "date_format": args.date_format,
135
+ "default_currency": args.currency,
136
+ }
137
+
138
+ try:
139
+ ledger = load_csv(
140
+ args.ledger,
141
+ id_prefix="L-",
142
+ **options,
143
+ )
144
+
145
+ statement = load_csv(
146
+ args.statement,
147
+ id_prefix="S-",
148
+ **options,
149
+ )
150
+
151
+ except (CsvFormatError, OSError) as exc:
152
+ print(f"Xəta: {exc}", file=sys.stderr)
153
+ return 2
154
+
155
+ if args.invert_statement:
156
+ statement = invert_directions(statement)
157
+
158
+ rules = [
159
+ ExactReference(),
160
+ AmountAndDate(day_window=args.days),
161
+ ]
162
+
163
+ if args.tolerance > 0:
164
+ rules.append(
165
+ AmountTolerance(
166
+ args.tolerance,
167
+ day_window=args.days,
168
+ )
169
+ )
170
+
171
+ result = Reconciler(rules).run(
172
+ ledger,
173
+ statement,
174
+ )
175
+
176
+ args.out.mkdir(
177
+ parents=True,
178
+ exist_ok=True,
179
+ )
180
+
181
+ result.to_json(args.out / "result.json")
182
+
183
+ result.matches_to_csv(
184
+ args.out / "matches.csv",
185
+ delimiter=args.delimiter,
186
+ )
187
+
188
+ result.breaks_to_csv(
189
+ args.out / "breaks.csv",
190
+ delimiter=args.delimiter,
191
+ )
192
+
193
+ summary = result.summary
194
+
195
+ print(f"Uyğunlaşdı: {summary['matched']}")
196
+ print(f"Ledger-də qalan: {summary['unmatched_left']}")
197
+ print(f"Çıxarışda qalan: {summary['unmatched_right']}")
198
+ print(f"Hesabatlar: {args.out}")
199
+
200
+ has_breaks = (
201
+ summary["unmatched_left"]
202
+ or summary["unmatched_right"]
203
+ )
204
+
205
+ return 1 if has_breaks else 0
206
+
207
+
208
+ if __name__ == "__main__":
209
+ sys.exit(main())
reconkit/loaders.py ADDED
@@ -0,0 +1,288 @@
1
+
2
+ import csv
3
+ import datetime
4
+ from collections.abc import Mapping
5
+ from decimal import Decimal, InvalidOperation
6
+ from pathlib import Path
7
+
8
+ from .models import Direction, Transaction
9
+
10
+
11
+ class CsvFormatError(ValueError):
12
+ """CSV faylında format və ya məlumat xətası."""
13
+
14
+
15
+ _REQUIRED = ("date", "amount")
16
+ _OPTIONAL = ("id", "currency", "direction", "reference", "description")
17
+
18
+ _DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
19
+ _DEFAULT_MAX_ROWS = 5_000
20
+
21
+ _DIRECTIONS = {
22
+ "debit": Direction.DEBIT,
23
+ "dr": Direction.DEBIT,
24
+ "d": Direction.DEBIT,
25
+ "credit": Direction.CREDIT,
26
+ "cr": Direction.CREDIT,
27
+ "c": Direction.CREDIT,
28
+ }
29
+
30
+
31
+ def _validate_limit(name: str, value: int | None) -> None:
32
+ if value is not None and (
33
+ isinstance(value, bool) or not isinstance(value, int) or value <= 0
34
+ ):
35
+ raise ValueError(f"{name} müsbət tam ədəd və ya None olmalıdır")
36
+
37
+
38
+ def _parse_amount(
39
+ raw: str, decimal_separator: str, thousands_separator: str | None
40
+ ) -> Decimal:
41
+ text = raw.replace("\u00a0", "").replace(" ", "")
42
+
43
+ if thousands_separator:
44
+ text = text.replace(thousands_separator, "")
45
+
46
+ if decimal_separator != ".":
47
+ text = text.replace(decimal_separator, ".")
48
+
49
+ try:
50
+ value = Decimal(text)
51
+ except InvalidOperation:
52
+ raise ValueError(f"məbləğ oxunmadı: {raw!r}") from None
53
+
54
+ if not value.is_finite():
55
+ raise ValueError(f"məbləğ sonlu ədəd olmalıdır: {raw!r}")
56
+
57
+ return value
58
+
59
+
60
+ def _parse_direction(raw: str) -> Direction:
61
+ try:
62
+ return _DIRECTIONS[raw.lower()]
63
+ except KeyError:
64
+ raise ValueError(f"istiqamət tanınmadı: {raw!r}") from None
65
+
66
+
67
+ def _cell(row: Mapping[str | None, object], header: str) -> str:
68
+ value = row.get(header)
69
+ return value.strip() if isinstance(value, str) else ""
70
+
71
+
72
+ def load_csv(
73
+ path: str | Path,
74
+ *,
75
+ columns: Mapping[str, str] | None = None,
76
+ date_format: str = "%Y-%m-%d",
77
+ delimiter: str = ",",
78
+ encoding: str = "utf-8-sig",
79
+ decimal_separator: str = ".",
80
+ thousands_separator: str | None = None,
81
+ default_currency: str | None = None,
82
+ id_prefix: str = "row-",
83
+ max_file_size: int | None = _DEFAULT_MAX_FILE_SIZE,
84
+ max_rows: int | None = _DEFAULT_MAX_ROWS,
85
+ ) -> list[Transaction]:
86
+ """CSV faylını Transaction siyahısına çevirir.
87
+
88
+ columns:
89
+ {"id": "No", "date": "Tarix", ...} kimi sütun adı xəritəsi.
90
+
91
+ max_file_size:
92
+ Maksimum fayl ölçüsü (byte). None verilərsə limit yoxdur.
93
+
94
+ max_rows:
95
+ Maksimum CSV məlumat sətirlərinin sayı. None verilərsə limit yoxdur.
96
+ """
97
+ _validate_limit("max_file_size", max_file_size)
98
+ _validate_limit("max_rows", max_rows)
99
+
100
+ if not isinstance(delimiter, str) or len(delimiter) != 1:
101
+ raise ValueError("delimiter bir simvoldan ibarət olmalıdır")
102
+
103
+ if not isinstance(decimal_separator, str) or len(decimal_separator) != 1:
104
+ raise ValueError("decimal_separator bir simvol olmalıdır")
105
+
106
+ if thousands_separator is not None and (
107
+ not isinstance(thousands_separator, str)
108
+ or len(thousands_separator) != 1
109
+ ):
110
+ raise ValueError("thousands_separator bir simvol və ya None olmalıdır")
111
+
112
+ if thousands_separator == decimal_separator:
113
+ raise ValueError(
114
+ "thousands_separator və decimal_separator fərqli olmalıdır"
115
+ )
116
+
117
+ mapping = {name: name for name in (*_REQUIRED, *_OPTIONAL)}
118
+
119
+ if columns:
120
+ unknown = set(columns) - set(mapping)
121
+ if unknown:
122
+ raise ValueError(f"naməlum sahələr: {sorted(unknown)}")
123
+
124
+ if any(not isinstance(value, str) or not value.strip() for value in columns.values()):
125
+ raise ValueError("sütun adları boş olmayan mətn olmalıdır")
126
+
127
+ mapping.update(
128
+ {key: value.strip() for key, value in columns.items()}
129
+ )
130
+
131
+ file_path = Path(path)
132
+
133
+ try:
134
+ if max_file_size is not None:
135
+ file_size = file_path.stat().st_size
136
+
137
+ if file_size > max_file_size:
138
+ raise CsvFormatError(
139
+ f"CSV faylı maksimum ölçünü keçir: "
140
+ f"{file_size} byte (limit: {max_file_size} byte)"
141
+ )
142
+
143
+ transactions: list[Transaction] = []
144
+ seen_ids: set[str] = set()
145
+
146
+ with file_path.open(newline="", encoding=encoding) as file:
147
+ reader = csv.DictReader(file, delimiter=delimiter)
148
+
149
+ raw_headers = reader.fieldnames
150
+
151
+ if not raw_headers:
152
+ raise CsvFormatError("CSV faylı boşdur və ya başlıq yoxdur")
153
+
154
+ headers = [header.strip() for header in raw_headers]
155
+
156
+ if any(not header for header in headers):
157
+ raise CsvFormatError("CSV-də boş sütun adı var")
158
+
159
+ normalized_headers = [header.casefold() for header in headers]
160
+
161
+ if len(normalized_headers) != len(set(normalized_headers)):
162
+ raise CsvFormatError(
163
+ "CSV-də təkrarlanan sütun adları var"
164
+ )
165
+
166
+ reader.fieldnames = headers
167
+
168
+ missing = [
169
+ mapping[field]
170
+ for field in _REQUIRED
171
+ if mapping[field] not in headers
172
+ ]
173
+
174
+ if missing:
175
+ raise CsvFormatError(
176
+ f"CSV-də tələb olunan sütun tapılmadı: {missing}"
177
+ )
178
+
179
+ has_id = mapping["id"] in headers
180
+ has_currency = mapping["currency"] in headers
181
+ has_direction = mapping["direction"] in headers
182
+
183
+ if not has_currency and not default_currency:
184
+ raise CsvFormatError(
185
+ "valyuta sütunu yoxdur, default_currency verilməlidir"
186
+ )
187
+
188
+ for row_count, row in enumerate(reader, start=1):
189
+ line_no = reader.line_num
190
+
191
+ if max_rows is not None and row_count > max_rows:
192
+ raise CsvFormatError(
193
+ f"CSV maksimum sətir sayını keçir: {max_rows}"
194
+ )
195
+
196
+ # Tamamilə boş sətirləri ötür.
197
+ values = [
198
+ value
199
+ for key, value in row.items()
200
+ if key is not None
201
+ ]
202
+
203
+ if not any(
204
+ isinstance(value, str) and value.strip()
205
+ for value in values
206
+ ) and None not in row:
207
+ continue
208
+
209
+ # Başlıqlardan artıq sütun varsa, DictReader onları
210
+ # None açarı altında saxlayır.
211
+ if None in row:
212
+ raise CsvFormatError(
213
+ f"sətir {line_no}: gözləniləndən artıq sütun var"
214
+ )
215
+
216
+ # Sətirdə başlıqlara uyğun olmayan əskik xanalar varsa,
217
+ # onları qəbul etmirik.
218
+ if any(value is None for value in row.values()):
219
+ raise CsvFormatError(
220
+ f"sətir {line_no}: əskik sütun və ya xana var"
221
+ )
222
+
223
+ try:
224
+ amount = _parse_amount(
225
+ _cell(row, mapping["amount"]),
226
+ decimal_separator,
227
+ thousands_separator,
228
+ )
229
+
230
+ if has_direction:
231
+ direction = _parse_direction(
232
+ _cell(row, mapping["direction"])
233
+ )
234
+ else:
235
+ direction = (
236
+ Direction.DEBIT
237
+ if amount < 0
238
+ else Direction.CREDIT
239
+ )
240
+ amount = abs(amount)
241
+
242
+ currency = (
243
+ _cell(row, mapping["currency"])
244
+ if has_currency
245
+ else (default_currency or "")
246
+ )
247
+
248
+ if not currency:
249
+ raise ValueError("valyuta boşdur")
250
+
251
+ tx_id = (
252
+ _cell(row, mapping["id"])
253
+ if has_id
254
+ else ""
255
+ ) or f"{id_prefix}{line_no}"
256
+
257
+ if tx_id in seen_ids:
258
+ raise ValueError(
259
+ f"təkrarlanan id: {tx_id!r}"
260
+ )
261
+
262
+ tx_date = datetime.datetime.strptime(
263
+ _cell(row, mapping["date"]),
264
+ date_format,
265
+ ).date()
266
+
267
+ transaction = Transaction(
268
+ id=tx_id,
269
+ date=tx_date,
270
+ amount=amount,
271
+ currency=currency,
272
+ direction=direction,
273
+ reference=_cell(row, mapping["reference"]),
274
+ description=_cell(row, mapping["description"]),
275
+ )
276
+
277
+ except ValueError as exc:
278
+ raise CsvFormatError(
279
+ f"sətir {line_no}: {exc}"
280
+ ) from exc
281
+
282
+ seen_ids.add(tx_id)
283
+ transactions.append(transaction)
284
+
285
+ return transactions
286
+
287
+ except csv.Error as exc:
288
+ raise CsvFormatError(f"CSV oxunarkən xəta baş verdi: {exc}") from exc
reconkit/models.py ADDED
@@ -0,0 +1,38 @@
1
+
2
+ import datetime
3
+ from dataclasses import dataclass
4
+ from decimal import Decimal
5
+ from enum import Enum
6
+
7
+
8
+ class Direction(str, Enum):
9
+ DEBIT = "debit"
10
+ CREDIT = "credit"
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class Transaction:
15
+ id: str
16
+ date: datetime.date
17
+ amount: Decimal
18
+ currency: str
19
+ direction: Direction
20
+ reference: str = ""
21
+ description: str = ""
22
+
23
+ def __post_init__(self) -> None:
24
+ if not isinstance(self.amount, Decimal):
25
+ raise TypeError(
26
+ "amount Decimal olmalıdır, float və ya str yox"
27
+ )
28
+
29
+ if not self.amount.is_finite():
30
+ raise ValueError(
31
+ "amount sonlu Decimal dəyəri olmalıdır"
32
+ )
33
+
34
+ if self.amount <= 0:
35
+ raise ValueError("amount müsbət olmalıdır")
36
+
37
+ # frozen olduğu üçün birbaşa mənimsətmək olmur
38
+ object.__setattr__(self, "currency", self.currency.upper())
reconkit/py.typed ADDED
File without changes
reconkit/reconciler.py ADDED
@@ -0,0 +1,86 @@
1
+ import json
2
+ from collections.abc import Iterable, Sequence
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from .models import Transaction
7
+ from .report import (
8
+ BREAK_FIELDS,
9
+ MATCH_FIELDS,
10
+ match_to_dict,
11
+ match_to_row,
12
+ transaction_to_dict,
13
+ write_csv,
14
+ )
15
+ from .rules import Match, Rule
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class ReconciliationResult:
20
+ matched: tuple[Match, ...]
21
+ unmatched_left: tuple[Transaction, ...]
22
+ unmatched_right: tuple[Transaction, ...]
23
+
24
+ @property
25
+ def summary(self) -> dict[str, int]:
26
+ return {
27
+ "matched": len(self.matched),
28
+ "unmatched_left": len(self.unmatched_left),
29
+ "unmatched_right": len(self.unmatched_right),
30
+ }
31
+
32
+ def to_dict(self) -> dict[str, object]:
33
+ return {
34
+ "summary": self.summary,
35
+ "matched": [match_to_dict(m) for m in self.matched],
36
+ "unmatched_left": [transaction_to_dict(t) for t in self.unmatched_left],
37
+ "unmatched_right": [transaction_to_dict(t) for t in self.unmatched_right],
38
+ }
39
+
40
+ def to_json(self, path: str | Path) -> None:
41
+ text = json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
42
+ Path(path).write_text(text, encoding="utf-8")
43
+
44
+ def breaks_to_csv(self, path: str | Path, delimiter: str = ",") -> None:
45
+ rows = [
46
+ {"side": "ledger", **transaction_to_dict(t)} for t in self.unmatched_left
47
+ ] + [
48
+ {"side": "statement", **transaction_to_dict(t)}
49
+ for t in self.unmatched_right
50
+ ]
51
+ write_csv(path, BREAK_FIELDS, rows, delimiter)
52
+
53
+ def matches_to_csv(self, path: str | Path, delimiter: str = ",") -> None:
54
+ rows = [match_to_row(m) for m in self.matched]
55
+ write_csv(path, MATCH_FIELDS, rows, delimiter)
56
+
57
+
58
+ class Reconciler:
59
+ def __init__(self, rules: Sequence[Rule]) -> None:
60
+ if not rules:
61
+ raise ValueError("ən azı bir qayda verilməlidir")
62
+ self._rules = tuple(rules)
63
+
64
+ def run(
65
+ self, left: Iterable[Transaction], right: Iterable[Transaction]
66
+ ) -> ReconciliationResult:
67
+ remaining_left = list(left)
68
+ remaining_right = list(right)
69
+ matches: list[Match] = []
70
+
71
+ for rule in self._rules:
72
+ still_unmatched: list[Transaction] = []
73
+ for tx in remaining_left:
74
+ match = rule.find_match(tx, remaining_right)
75
+ if match is None:
76
+ still_unmatched.append(tx)
77
+ else:
78
+ matches.append(match)
79
+ remaining_right.remove(match.right)
80
+ remaining_left = still_unmatched
81
+
82
+ return ReconciliationResult(
83
+ matched=tuple(matches),
84
+ unmatched_left=tuple(remaining_left),
85
+ unmatched_right=tuple(remaining_right),
86
+ )
reconkit/report.py ADDED
@@ -0,0 +1,134 @@
1
+
2
+ import csv
3
+ from collections.abc import Iterable, Mapping, Sequence
4
+ from pathlib import Path
5
+
6
+ from .models import Transaction
7
+ from .rules import Match
8
+
9
+ # Excel və digər cədvəl proqramlarında formula kimi işləyə bilən
10
+ # simvollar.
11
+ _FORMULA_PREFIXES = ("=", "+", "-", "@")
12
+
13
+ # Yalnız sərbəst mətn sahələri təmizlənir.
14
+ # Məbləğ fərqi "-0.05" kimi rəqəmsal sahələr dəyişdirilmir.
15
+ TEXT_FIELDS = frozenset(
16
+ {
17
+ "id",
18
+ "reference",
19
+ "description",
20
+ "left_id",
21
+ "right_id",
22
+ "reason",
23
+ "currency",
24
+ "rule",
25
+ }
26
+ )
27
+
28
+ BREAK_FIELDS = (
29
+ "side",
30
+ "id",
31
+ "date",
32
+ "amount",
33
+ "currency",
34
+ "direction",
35
+ "reference",
36
+ "description",
37
+ )
38
+
39
+ MATCH_FIELDS = (
40
+ "left_id",
41
+ "right_id",
42
+ "currency",
43
+ "left_amount",
44
+ "right_amount",
45
+ "difference",
46
+ "left_date",
47
+ "right_date",
48
+ "rule",
49
+ "confidence",
50
+ "reason",
51
+ )
52
+
53
+
54
+ def neutralize_formula(value: str) -> str:
55
+ """CSV mətn sahələrində formula injection riskini azaldır."""
56
+ if not value:
57
+ return value
58
+
59
+ # Əvvəldəki boşluq və idarəetmə simvollarını nəzərə alırıq.
60
+ # Beləliklə, məsələn, '\\n=1+1' və ' =1+1' də yoxlanılır.
61
+ stripped = value.lstrip()
62
+
63
+ if stripped.startswith(_FORMULA_PREFIXES):
64
+ return "'" + value
65
+
66
+ return value
67
+
68
+
69
+ def transaction_to_dict(tx: Transaction) -> dict[str, str]:
70
+ return {
71
+ "id": tx.id,
72
+ "date": tx.date.isoformat(),
73
+ "amount": str(tx.amount),
74
+ "currency": tx.currency,
75
+ "direction": tx.direction.value,
76
+ "reference": tx.reference,
77
+ "description": tx.description,
78
+ }
79
+
80
+
81
+ def match_to_dict(match: Match) -> dict[str, object]:
82
+ return {
83
+ "left": transaction_to_dict(match.left),
84
+ "right": transaction_to_dict(match.right),
85
+ "rule": match.rule,
86
+ "confidence": match.confidence,
87
+ "reason": match.reason,
88
+ }
89
+
90
+
91
+ def match_to_row(match: Match) -> dict[str, str]:
92
+ return {
93
+ "left_id": match.left.id,
94
+ "right_id": match.right.id,
95
+ "currency": match.left.currency,
96
+ "left_amount": str(match.left.amount),
97
+ "right_amount": str(match.right.amount),
98
+ "difference": str(match.right.amount - match.left.amount),
99
+ "left_date": match.left.date.isoformat(),
100
+ "right_date": match.right.date.isoformat(),
101
+ "rule": match.rule,
102
+ "confidence": f"{match.confidence:.2f}",
103
+ "reason": match.reason,
104
+ }
105
+
106
+
107
+ def write_csv(
108
+ path: str | Path,
109
+ fieldnames: Sequence[str],
110
+ rows: Iterable[Mapping[str, str]],
111
+ delimiter: str = ",",
112
+ ) -> None:
113
+ if len(delimiter) != 1:
114
+ raise ValueError("delimiter bir simvoldan ibarət olmalıdır")
115
+
116
+ with Path(path).open("w", newline="", encoding="utf-8-sig") as file:
117
+ writer = csv.DictWriter(
118
+ file,
119
+ fieldnames=fieldnames,
120
+ delimiter=delimiter,
121
+ )
122
+ writer.writeheader()
123
+
124
+ for row in rows:
125
+ writer.writerow(
126
+ {
127
+ key: (
128
+ neutralize_formula(value)
129
+ if key in TEXT_FIELDS and isinstance(value, str)
130
+ else value
131
+ )
132
+ for key, value in row.items()
133
+ }
134
+ )
reconkit/rules.py ADDED
@@ -0,0 +1,196 @@
1
+
2
+ from abc import ABC, abstractmethod
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from decimal import Decimal
6
+
7
+ from .models import Transaction
8
+
9
+
10
+ def _normalized_ratio(value: Decimal | int, maximum: Decimal | int) -> float:
11
+ """Dəyərin maksimum limitə nisbətini 0.0–1.0 aralığında qaytarır."""
12
+ if maximum == 0:
13
+ return 0.0
14
+
15
+ return float(value / maximum)
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Match:
20
+ left: Transaction
21
+ right: Transaction
22
+ rule: str
23
+ confidence: float
24
+ reason: str
25
+
26
+
27
+ class Rule(ABC):
28
+ """Bütün matching qaydalarının əsas interfeysi."""
29
+
30
+ name: str
31
+
32
+ @abstractmethod
33
+ def find_match(
34
+ self, left: Transaction, candidates: Sequence[Transaction]
35
+ ) -> Match | None:
36
+ """left üçün candidates arasından uyğun olanı tapır, yoxdursa None."""
37
+
38
+
39
+ class ExactReference(Rule):
40
+ name = "exact_reference"
41
+
42
+ def find_match(
43
+ self, left: Transaction, candidates: Sequence[Transaction]
44
+ ) -> Match | None:
45
+ if not left.reference:
46
+ return None
47
+
48
+ eligible = [
49
+ right
50
+ for right in candidates
51
+ if (
52
+ right.reference == left.reference
53
+ and right.amount == left.amount
54
+ and right.currency == left.currency
55
+ and right.direction == left.direction
56
+ )
57
+ ]
58
+
59
+ if not eligible or len(eligible) > 1:
60
+ return None
61
+
62
+ right = eligible[0]
63
+
64
+ return Match(
65
+ left=left,
66
+ right=right,
67
+ rule=self.name,
68
+ confidence=1.0,
69
+ reason=(
70
+ f"reference '{left.reference}', məbləğ, valyuta "
71
+ f"və istiqamət eynidir"
72
+ ),
73
+ )
74
+
75
+
76
+ class AmountAndDate(Rule):
77
+ name = "amount_and_date"
78
+
79
+ def __init__(self, day_window: int = 2) -> None:
80
+ if day_window < 0:
81
+ raise ValueError("day_window mənfi ola bilməz")
82
+
83
+ self.day_window = day_window
84
+
85
+ def find_match(
86
+ self, left: Transaction, candidates: Sequence[Transaction]
87
+ ) -> Match | None:
88
+ eligible: list[tuple[int, Transaction]] = []
89
+
90
+ for right in candidates:
91
+ if (
92
+ right.amount != left.amount
93
+ or right.currency != left.currency
94
+ or right.direction != left.direction
95
+ ):
96
+ continue
97
+
98
+ gap = abs((right.date - left.date).days)
99
+
100
+ if gap <= self.day_window:
101
+ eligible.append((gap, right))
102
+
103
+ if not eligible:
104
+ return None
105
+
106
+ eligible.sort(key=lambda pair: pair[0])
107
+ best_gap, best = eligible[0]
108
+
109
+ # Eyni dərəcədə yaxın namizədlər varsa, seçim etmirik.
110
+ if len(eligible) > 1 and eligible[1][0] == best_gap:
111
+ return None
112
+
113
+ date_ratio = _normalized_ratio(best_gap, self.day_window)
114
+ confidence = max(0.5, 0.9 - 0.4 * date_ratio)
115
+
116
+ return Match(
117
+ left=left,
118
+ right=best,
119
+ rule=self.name,
120
+ confidence=round(confidence, 4),
121
+ reason=(
122
+ f"məbləğ, valyuta və istiqamət eynidir, "
123
+ f"tarix fərqi {best_gap} gün"
124
+ ),
125
+ )
126
+
127
+
128
+ class AmountTolerance(Rule):
129
+ name = "amount_tolerance"
130
+
131
+ def __init__(self, max_diff: Decimal | str, day_window: int = 2) -> None:
132
+ if isinstance(max_diff, float):
133
+ raise TypeError("max_diff float ola bilməz, Decimal və ya str verin")
134
+
135
+ diff = Decimal(max_diff)
136
+
137
+ if not diff.is_finite():
138
+ raise ValueError("max_diff sonlu Decimal dəyəri olmalıdır")
139
+
140
+ if diff < 0:
141
+ raise ValueError("max_diff mənfi ola bilməz")
142
+
143
+ if day_window < 0:
144
+ raise ValueError("day_window mənfi ola bilməz")
145
+
146
+ self.max_diff = diff
147
+ self.day_window = day_window
148
+
149
+ def find_match(
150
+ self, left: Transaction, candidates: Sequence[Transaction]
151
+ ) -> Match | None:
152
+ eligible: list[tuple[Decimal, int, Transaction]] = []
153
+
154
+ for right in candidates:
155
+ if (
156
+ right.currency != left.currency
157
+ or right.direction != left.direction
158
+ ):
159
+ continue
160
+
161
+ diff = abs(right.amount - left.amount)
162
+ gap = abs((right.date - left.date).days)
163
+
164
+ if diff <= self.max_diff and gap <= self.day_window:
165
+ eligible.append((diff, gap, right))
166
+
167
+ if not eligible:
168
+ return None
169
+
170
+ eligible.sort(key=lambda item: (item[0], item[1]))
171
+ best_diff, best_gap, best = eligible[0]
172
+
173
+ # Eyni dərəcədə uyğun namizədlər varsa, seçim etmirik.
174
+ if len(eligible) > 1 and (
175
+ eligible[1][0], eligible[1][1]
176
+ ) == (best_diff, best_gap):
177
+ return None
178
+
179
+ amount_ratio = _normalized_ratio(best_diff, self.max_diff)
180
+ date_ratio = _normalized_ratio(best_gap, self.day_window)
181
+
182
+ confidence = max(
183
+ 0.3,
184
+ 0.7 - 0.2 * amount_ratio - 0.2 * date_ratio,
185
+ )
186
+
187
+ return Match(
188
+ left=left,
189
+ right=best,
190
+ rule=self.name,
191
+ confidence=round(confidence, 4),
192
+ reason=(
193
+ f"məbləğ fərqi {best_diff} {left.currency} "
194
+ f"(limit {self.max_diff}), tarix fərqi {best_gap} gün"
195
+ ),
196
+ )
reconkit/transforms.py ADDED
@@ -0,0 +1,21 @@
1
+ import dataclasses
2
+ from collections.abc import Iterable
3
+
4
+ from .models import Direction, Transaction
5
+
6
+ _FLIPPED = {
7
+ Direction.DEBIT: Direction.CREDIT,
8
+ Direction.CREDIT: Direction.DEBIT,
9
+ }
10
+
11
+
12
+ def invert_directions(transactions: Iterable[Transaction]) -> list[Transaction]:
13
+ """Hər əməliyyatın istiqamətini əksinə çevirir (yeni siyahı qaytarır).
14
+
15
+ Nostro/vostro hesablarında bank çıxarışı ledger-in güzgü əksidir:
16
+ bizim debet bankın kreditidir. Uyğunlaşdırmadan əvvəl çıxarışı çevirin.
17
+ """
18
+ return [
19
+ dataclasses.replace(tx, direction=_FLIPPED[tx.direction])
20
+ for tx in transactions
21
+ ]