gstreco 0.1.0__tar.gz

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.
gstreco-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ganesh Kadam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
gstreco-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: gstreco
3
+ Version: 0.1.0
4
+ Summary: Reconcile GSTR-2B with your purchase register (Tally, Busy, Zoho, Excel). Offline, free, open source.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/gbk09/gst-reco
7
+ Project-URL: Issues, https://github.com/gbk09/gst-reco/issues
8
+ Keywords: gst,gstr-2b,itc,reconciliation,india,tally,accounting
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
11
+ Classifier: Intended Audience :: Financial and Insurance Industry
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pandas>=1.5
16
+ Requires-Dist: openpyxl>=3.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # gstreco: free GSTR-2B reconciliation
22
+
23
+ Match your **GSTR-2B** from the GST portal with your **purchase register** from Tally, Busy, Zoho Books or any Excel/CSV file. You get a formatted Excel report that shows which ITC is safe, which is at risk, and which suppliers you need to follow up with.
24
+
25
+ - **Free and open source** (MIT). No limit on GSTINs or invoices.
26
+ - **Runs offline on your own computer.** Your client data is never uploaded anywhere.
27
+ - **Built by an accountant** who does this reconciliation every month.
28
+
29
+ ## What it catches
30
+
31
+ | Case | Example | Result |
32
+ |---|---|---|
33
+ | Exact match | Same GSTIN, invoice no. and amounts | Matched |
34
+ | Invoice no. typed differently | Books `1`, 2B `INV/001/26-27`; `SB-0045` vs `SB45` | Matched - inv. no. format differs |
35
+ | Wrong invoice no. in books | Books `7718`, 2B `7781`, same supplier and amounts | Probable match - check inv. no. |
36
+ | Rounding | 60 paise difference | Matched (tolerance ₹1, adjustable) |
37
+ | Amount differs | Taxable value booked ₹10,000 higher | Amount mismatch |
38
+ | GSTIN typo in books | One character wrong in supplier GSTIN | GSTIN error in books |
39
+ | Supplier hasn't filed | In books, not in 2B | Missing in GSTR-2B (**ITC at risk**) |
40
+ | Not booked | In 2B, not in books | Missing in books |
41
+ | Credit / debit notes | B2B-CDNR sheet vs debit-note vouchers | Matched separately from invoices |
42
+
43
+ It also flags invalid GSTINs in your books (checksum test), invoices the 2B marks **ITC not available**, and reverse-charge supplies.
44
+
45
+ ## The report
46
+
47
+ One Excel file with these sheets:
48
+
49
+ 1. **Summary**: ITC as per 2B and as per books, ITC at risk, and the count and tax for each status, with what to do next.
50
+ 2. **All documents**: every invoice side by side (books vs 2B) with the differences.
51
+ 3. **Missing in 2B**, **Mismatches**, **Missing in books**: filtered lists to work through.
52
+ 4. **Vendor follow-up**: one row per supplier with the tax at risk and a **ready-to-send message** listing their invoices.
53
+
54
+ ## How to use
55
+
56
+ **1. Install** (one time). You need [Python 3.10+](https://www.python.org/downloads/); tick "Add to PATH" when you install it.
57
+
58
+ ```
59
+ pip install gstreco
60
+ ```
61
+
62
+ *(Until it is published on PyPI: download this folder and run `pip install .` inside it.)*
63
+
64
+ **2. Download your files**
65
+ - **GSTR-2B:** GST portal → Returns → Returns Dashboard → GSTR-2B → Download Excel (or JSON).
66
+ - **Purchase register:** Tally Prime → Display More Reports → GST Reports → GSTR-2/Purchase Register (or Day Book filtered to purchases) → Export as Excel. Include the supplier GSTIN, supplier invoice no., date, taxable value, IGST, CGST and SGST columns.
67
+
68
+ **3. Run**
69
+
70
+ Windows, no typing: double-click **`Run GST Reco.bat`**, pick the two files, and the report opens in Excel.
71
+
72
+ Command line:
73
+
74
+ ```
75
+ python -m gstreco --gstr2b GSTR2B_Oct.xlsx --books PurchaseRegister.xlsx --period "Oct 2026"
76
+ ```
77
+
78
+ Useful options:
79
+
80
+ | Option | What it does |
81
+ |---|---|
82
+ | `--gstr2b a.xlsx b.xlsx` | Several months of 2B together (for invoices the supplier filed late) |
83
+ | `--tolerance 10` | Allow up to ₹10 difference (default ₹1) |
84
+ | `--sheet "Purchase Register"` | Choose the sheet in the books file |
85
+ | `--map inv_no="Bill Ref"` | Name a column yourself if it is not detected |
86
+ | `--out Report.xlsx` | Output file name |
87
+
88
+ Columns are detected automatically from common headings (for example *Supplier Invoice No.*, *GSTIN/UIN*, *Integrated Tax Amount*), so most Tally, Busy and Zoho exports work as they are.
89
+
90
+ ## Try it with sample data
91
+
92
+ ```
93
+ python samples/make_samples.py
94
+ python -m gstreco --gstr2b samples/GSTR2B_sample_Oct2026.xlsx --books samples/Purchase_Register_sample.xlsx --period "Oct 2026" --out Sample_Report.xlsx
95
+ ```
96
+
97
+ The sample suppliers and GSTINs are fictitious.
98
+
99
+ ## How matching works
100
+
101
+ Each pass only looks at invoices that are still unmatched:
102
+
103
+ 1. Same GSTIN and same invoice number, ignoring spaces, `/ - .` and case.
104
+ 2. Same GSTIN and same **core number**, ignoring prefixes, leading zeros and the financial year (`26-27`, `2026-27`). It is used only when the match is unique on both sides.
105
+ 3. Same GSTIN, same taxable value and tax (within tolerance), dates within 45 days, unique both ways. This gives a *probable* match, for you to verify.
106
+ 4. Same invoice number where the books GSTIN is 1–2 characters off or has the same PAN. This is a GSTIN typo.
107
+
108
+ ## Contributing
109
+
110
+ Issues and pull requests are welcome, especially sample exports from other software (Busy, Marg, Zoho, SAP) with the data removed, and new edge cases. Run the tests with `pip install -e .[dev]` and then `pytest`.
111
+
112
+ ## Disclaimer
113
+
114
+ This is a helper tool. Always check the results before you claim ITC or file returns. It is not tax advice.
@@ -0,0 +1,94 @@
1
+ # gstreco: free GSTR-2B reconciliation
2
+
3
+ Match your **GSTR-2B** from the GST portal with your **purchase register** from Tally, Busy, Zoho Books or any Excel/CSV file. You get a formatted Excel report that shows which ITC is safe, which is at risk, and which suppliers you need to follow up with.
4
+
5
+ - **Free and open source** (MIT). No limit on GSTINs or invoices.
6
+ - **Runs offline on your own computer.** Your client data is never uploaded anywhere.
7
+ - **Built by an accountant** who does this reconciliation every month.
8
+
9
+ ## What it catches
10
+
11
+ | Case | Example | Result |
12
+ |---|---|---|
13
+ | Exact match | Same GSTIN, invoice no. and amounts | Matched |
14
+ | Invoice no. typed differently | Books `1`, 2B `INV/001/26-27`; `SB-0045` vs `SB45` | Matched - inv. no. format differs |
15
+ | Wrong invoice no. in books | Books `7718`, 2B `7781`, same supplier and amounts | Probable match - check inv. no. |
16
+ | Rounding | 60 paise difference | Matched (tolerance ₹1, adjustable) |
17
+ | Amount differs | Taxable value booked ₹10,000 higher | Amount mismatch |
18
+ | GSTIN typo in books | One character wrong in supplier GSTIN | GSTIN error in books |
19
+ | Supplier hasn't filed | In books, not in 2B | Missing in GSTR-2B (**ITC at risk**) |
20
+ | Not booked | In 2B, not in books | Missing in books |
21
+ | Credit / debit notes | B2B-CDNR sheet vs debit-note vouchers | Matched separately from invoices |
22
+
23
+ It also flags invalid GSTINs in your books (checksum test), invoices the 2B marks **ITC not available**, and reverse-charge supplies.
24
+
25
+ ## The report
26
+
27
+ One Excel file with these sheets:
28
+
29
+ 1. **Summary**: ITC as per 2B and as per books, ITC at risk, and the count and tax for each status, with what to do next.
30
+ 2. **All documents**: every invoice side by side (books vs 2B) with the differences.
31
+ 3. **Missing in 2B**, **Mismatches**, **Missing in books**: filtered lists to work through.
32
+ 4. **Vendor follow-up**: one row per supplier with the tax at risk and a **ready-to-send message** listing their invoices.
33
+
34
+ ## How to use
35
+
36
+ **1. Install** (one time). You need [Python 3.10+](https://www.python.org/downloads/); tick "Add to PATH" when you install it.
37
+
38
+ ```
39
+ pip install gstreco
40
+ ```
41
+
42
+ *(Until it is published on PyPI: download this folder and run `pip install .` inside it.)*
43
+
44
+ **2. Download your files**
45
+ - **GSTR-2B:** GST portal → Returns → Returns Dashboard → GSTR-2B → Download Excel (or JSON).
46
+ - **Purchase register:** Tally Prime → Display More Reports → GST Reports → GSTR-2/Purchase Register (or Day Book filtered to purchases) → Export as Excel. Include the supplier GSTIN, supplier invoice no., date, taxable value, IGST, CGST and SGST columns.
47
+
48
+ **3. Run**
49
+
50
+ Windows, no typing: double-click **`Run GST Reco.bat`**, pick the two files, and the report opens in Excel.
51
+
52
+ Command line:
53
+
54
+ ```
55
+ python -m gstreco --gstr2b GSTR2B_Oct.xlsx --books PurchaseRegister.xlsx --period "Oct 2026"
56
+ ```
57
+
58
+ Useful options:
59
+
60
+ | Option | What it does |
61
+ |---|---|
62
+ | `--gstr2b a.xlsx b.xlsx` | Several months of 2B together (for invoices the supplier filed late) |
63
+ | `--tolerance 10` | Allow up to ₹10 difference (default ₹1) |
64
+ | `--sheet "Purchase Register"` | Choose the sheet in the books file |
65
+ | `--map inv_no="Bill Ref"` | Name a column yourself if it is not detected |
66
+ | `--out Report.xlsx` | Output file name |
67
+
68
+ Columns are detected automatically from common headings (for example *Supplier Invoice No.*, *GSTIN/UIN*, *Integrated Tax Amount*), so most Tally, Busy and Zoho exports work as they are.
69
+
70
+ ## Try it with sample data
71
+
72
+ ```
73
+ python samples/make_samples.py
74
+ python -m gstreco --gstr2b samples/GSTR2B_sample_Oct2026.xlsx --books samples/Purchase_Register_sample.xlsx --period "Oct 2026" --out Sample_Report.xlsx
75
+ ```
76
+
77
+ The sample suppliers and GSTINs are fictitious.
78
+
79
+ ## How matching works
80
+
81
+ Each pass only looks at invoices that are still unmatched:
82
+
83
+ 1. Same GSTIN and same invoice number, ignoring spaces, `/ - .` and case.
84
+ 2. Same GSTIN and same **core number**, ignoring prefixes, leading zeros and the financial year (`26-27`, `2026-27`). It is used only when the match is unique on both sides.
85
+ 3. Same GSTIN, same taxable value and tax (within tolerance), dates within 45 days, unique both ways. This gives a *probable* match, for you to verify.
86
+ 4. Same invoice number where the books GSTIN is 1–2 characters off or has the same PAN. This is a GSTIN typo.
87
+
88
+ ## Contributing
89
+
90
+ Issues and pull requests are welcome, especially sample exports from other software (Busy, Marg, Zoho, SAP) with the data removed, and new edge cases. Run the tests with `pip install -e .[dev]` and then `pytest`.
91
+
92
+ ## Disclaimer
93
+
94
+ This is a helper tool. Always check the results before you claim ITC or file returns. It is not tax advice.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gstreco"
7
+ version = "0.1.0"
8
+ description = "Reconcile GSTR-2B with your purchase register (Tally, Busy, Zoho, Excel). Offline, free, open source."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ dependencies = ["pandas>=1.5", "openpyxl>=3.0"]
13
+ keywords = ["gst", "gstr-2b", "itc", "reconciliation", "india", "tally", "accounting"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Office/Business :: Financial :: Accounting",
17
+ "Intended Audience :: Financial and Insurance Industry",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/gbk09/gst-reco"
22
+ Issues = "https://github.com/gbk09/gst-reco/issues"
23
+
24
+ [project.optional-dependencies]
25
+ dev = ["pytest"]
26
+
27
+ [project.scripts]
28
+ gstreco = "gstreco.cli:main"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """gstreco: reconcile GSTR-2B with your purchase register. Runs offline; your data never leaves your computer."""
2
+ from .matcher import reconcile
3
+ from .readers import read_gstr2b, read_books
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["reconcile", "read_gstr2b", "read_books", "__version__"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,69 @@
1
+ """Command line: gstreco --gstr2b 2B.xlsx --books purchase_register.xlsx"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+ from . import __version__
11
+ from .matcher import STATUS_ORDER, reconcile
12
+ from .readers import read_books, read_gstr2b
13
+ from .report import summary_figures, write_report
14
+
15
+
16
+ def main(argv=None) -> int:
17
+ p = argparse.ArgumentParser(
18
+ prog="gstreco",
19
+ description="Reconcile GSTR-2B with your purchase register. Runs offline on your computer.")
20
+ p.add_argument("--gstr2b", nargs="+", required=True,
21
+ help="GSTR-2B file(s) from the GST portal (.xlsx or .json). Give several months if needed.")
22
+ p.add_argument("--books", nargs="+", required=True,
23
+ help="Purchase register (.xlsx/.xls/.csv) from Tally, Busy, Zoho, etc.")
24
+ p.add_argument("--sheet", help="Sheet name of the purchase register (default: first sheet)")
25
+ p.add_argument("--out", default="GST_Reconciliation.xlsx", help="Output Excel file")
26
+ p.add_argument("--period", default="", help='Period label for the report, e.g. "Oct 2026"')
27
+ p.add_argument("--tolerance", type=float, default=1.0, help="Allowed difference in Rs (default 1)")
28
+ p.add_argument("--map", action="append", default=[], metavar="FIELD=COLUMN",
29
+ help='Name a books column yourself, e.g. --map inv_no="Bill Ref". '
30
+ "Fields: gstin, name, inv_no, inv_date, taxable, igst, cgst, sgst, cess")
31
+ p.add_argument("--version", action="version", version=f"gstreco {__version__}")
32
+ a = p.parse_args(argv)
33
+ for stream in (sys.stdout, sys.stderr):
34
+ try:
35
+ stream.reconfigure(errors="replace")
36
+ except AttributeError:
37
+ pass
38
+
39
+ mapping = {}
40
+ for m in a.map:
41
+ if "=" not in m:
42
+ p.error(f"--map needs FIELD=COLUMN, got {m!r}")
43
+ k, v = m.split("=", 1)
44
+ mapping[k.strip()] = v.strip()
45
+
46
+ try:
47
+ t = pd.concat([read_gstr2b(f) for f in a.gstr2b], ignore_index=True)
48
+ b = pd.concat([read_books(f, a.sheet, mapping or None) for f in a.books], ignore_index=True)
49
+ except (ValueError, FileNotFoundError) as e:
50
+ print(f"Error: {e}", file=sys.stderr)
51
+ return 2
52
+
53
+ print(f"Read {len(t)} documents from GSTR-2B and {len(b)} from books.")
54
+ result = reconcile(t, b, tolerance=a.tolerance)
55
+ files = tuple(Path(f).name for f in [*a.gstr2b, *a.books])
56
+ write_report(result, a.out, period=a.period, files=files, tolerance=a.tolerance)
57
+
58
+ counts = result["Status"].value_counts()
59
+ for s in STATUS_ORDER:
60
+ if counts.get(s):
61
+ print(f" {s:<36}{counts[s]:>5}")
62
+ for label, value in summary_figures(result).items():
63
+ print(f" {label:<52} Rs {value:>14,.2f}")
64
+ print(f"Report saved: {Path(a.out).resolve()}")
65
+ return 0
66
+
67
+
68
+ if __name__ == "__main__":
69
+ raise SystemExit(main())
@@ -0,0 +1,43 @@
1
+ """GSTIN validation helpers."""
2
+ import re
3
+
4
+ _CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5
+ _PATTERN = re.compile(r"^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$")
6
+
7
+
8
+ def checksum_char(first14: str) -> str:
9
+ """Return the 15th (check) character for the first 14 characters of a GSTIN."""
10
+ total = 0
11
+ for i, ch in enumerate(first14):
12
+ product = _CHARS.index(ch) * (2 if i % 2 else 1)
13
+ total += product // 36 + product % 36
14
+ return _CHARS[(36 - total % 36) % 36]
15
+
16
+
17
+ def clean(gstin) -> str:
18
+ if gstin is None:
19
+ return ""
20
+ s = str(gstin).strip().upper().replace(" ", "")
21
+ return "" if s in ("NAN", "NONE") else s
22
+
23
+
24
+ def is_valid(gstin) -> bool:
25
+ g = clean(gstin)
26
+ return bool(_PATTERN.match(g)) and checksum_char(g[:14]) == g[14]
27
+
28
+
29
+ def pan(gstin) -> str:
30
+ g = clean(gstin)
31
+ return g[2:12] if len(g) == 15 else ""
32
+
33
+
34
+ def is_close(a, b) -> bool:
35
+ """True when two GSTINs look like the same supplier with a typo (same PAN, or <=2 chars differ)."""
36
+ a, b = clean(a), clean(b)
37
+ if not a or not b or a == b:
38
+ return False
39
+ if pan(a) and pan(a) == pan(b):
40
+ return True
41
+ if len(a) == len(b):
42
+ return sum(x != y for x, y in zip(a, b)) <= 2
43
+ return False
@@ -0,0 +1,213 @@
1
+ """Match purchase-register documents with GSTR-2B documents.
2
+
3
+ Passes, in order (each only looks at documents still unmatched):
4
+ 1. Same GSTIN + same invoice number (ignoring spaces, / - . and case)
5
+ 2. Same GSTIN + same core number (ignoring prefixes, leading zeros and the financial year,
6
+ so "INV/001/26-27" matches "1")
7
+ 3. Same GSTIN + same taxable value and tax within tolerance, date close: probable match
8
+ 4. Same invoice number but the GSTIN in the books has a typo (same PAN or 1-2 characters off)
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ import pandas as pd
15
+
16
+ from .gstin import is_close, is_valid
17
+
18
+ MATCHED = "Matched"
19
+ FORMAT_DIFF = "Matched - inv. no. format differs"
20
+ PROBABLE = "Probable match - check inv. no."
21
+ MISMATCH = "Amount mismatch"
22
+ GSTIN_ERR = "GSTIN error in books"
23
+ MISSING_2B = "Missing in GSTR-2B"
24
+ MISSING_BOOKS = "Missing in books"
25
+
26
+ STATUS_ORDER = [MATCHED, FORMAT_DIFF, PROBABLE, MISMATCH, GSTIN_ERR, MISSING_2B, MISSING_BOOKS]
27
+
28
+ _FY = re.compile(r"(?<!\d)(?:20)?(\d{2})\s*[-/]\s*(?:20)?(\d{2})(?!\d)")
29
+
30
+
31
+ def norm_exact(inv) -> str:
32
+ return re.sub(r"[^A-Z0-9]", "", str(inv).upper())
33
+
34
+
35
+ def norm_core(inv) -> str:
36
+ """Numeric core of an invoice number: drop the FY (26-27 / 2026-27), prefixes and leading zeros."""
37
+ s = str(inv).upper()
38
+ pos = 0
39
+ while (m := _FY.search(s, pos)): # step one char at a time so "12/2026-27" still finds "2026-27"
40
+ if int(m.group(2)) == (int(m.group(1)) + 1) % 100:
41
+ s = s[:m.start()] + " " + s[m.end():]
42
+ pos = m.start()
43
+ else:
44
+ pos = m.start() + 1
45
+ nums = [n.lstrip("0") or "0" for n in re.findall(r"\d+", s)]
46
+ return "-".join(nums) if nums else norm_exact(inv)
47
+
48
+
49
+ def _tax(r) -> float:
50
+ return r["igst"] + r["cgst"] + r["sgst"] + r["cess"]
51
+
52
+
53
+ def _family(doc_type) -> str:
54
+ return "CN" if doc_type == "CN" else "INV"
55
+
56
+
57
+ def _amounts_close(b, t, tol) -> bool:
58
+ return abs(abs(b["taxable"]) - abs(t["taxable"])) <= tol and abs(abs(_tax(b)) - abs(_tax(t))) <= tol
59
+
60
+
61
+ def _days_apart(a, b):
62
+ if pd.isna(a) or pd.isna(b):
63
+ return None
64
+ return abs((pd.Timestamp(a) - pd.Timestamp(b)).days)
65
+
66
+
67
+ def reconcile(gstr2b: pd.DataFrame, books: pd.DataFrame, tolerance: float = 1.0,
68
+ date_window: int = 45) -> pd.DataFrame:
69
+ """Return one row per document with a Status column and side-by-side books / 2B figures."""
70
+ B = books.to_dict("records")
71
+ T = gstr2b.to_dict("records")
72
+ b_free = set(range(len(B)))
73
+ t_free = set(range(len(T)))
74
+ pairs: list[tuple[int, int, str]] = []
75
+
76
+ def take(bi, ti, how):
77
+ pairs.append((bi, ti, how))
78
+ b_free.discard(bi)
79
+ t_free.discard(ti)
80
+
81
+ def index(keyfn):
82
+ idx: dict = {}
83
+ for ti in sorted(t_free):
84
+ idx.setdefault(keyfn(T[ti]), []).append(ti)
85
+ return idx
86
+
87
+ # Pass 1: exact invoice number
88
+ key1 = lambda r: (r["gstin"], norm_exact(r["inv_no"]), _family(r["doc_type"]))
89
+ idx = index(key1)
90
+ for bi in sorted(b_free):
91
+ cands = [t for t in idx.get(key1(B[bi]), []) if t in t_free]
92
+ if cands:
93
+ take(bi, cands[0], "exact")
94
+
95
+ # Pass 2: core number, only when unique on both sides
96
+ key2 = lambda r: (r["gstin"], norm_core(r["inv_no"]), _family(r["doc_type"]))
97
+ idx = index(key2)
98
+ b_count: dict = {}
99
+ for bi in b_free:
100
+ b_count[key2(B[bi])] = b_count.get(key2(B[bi]), 0) + 1
101
+ for bi in sorted(b_free):
102
+ k = key2(B[bi])
103
+ cands = [t for t in idx.get(k, []) if t in t_free]
104
+ if len(cands) == 1 and b_count[k] == 1:
105
+ take(bi, cands[0], "core")
106
+
107
+ # Pass 3: same supplier, same amounts, close dates, unique both ways
108
+ def amount_cands(bi):
109
+ out = []
110
+ for ti in t_free:
111
+ b, t = B[bi], T[ti]
112
+ if b["gstin"] != t["gstin"] or _family(b["doc_type"]) != _family(t["doc_type"]):
113
+ continue
114
+ if not _amounts_close(b, t, tolerance) or abs(_tax(b)) < 0.01:
115
+ continue
116
+ d = _days_apart(b["inv_date"], t["inv_date"])
117
+ if d is not None and d > date_window:
118
+ continue
119
+ out.append(ti)
120
+ return out
121
+
122
+ proposals = {bi: amount_cands(bi) for bi in sorted(b_free)}
123
+ claimed: dict = {}
124
+ for bi, c in proposals.items():
125
+ if len(c) == 1:
126
+ claimed.setdefault(c[0], []).append(bi)
127
+ for ti, bis in claimed.items():
128
+ if len(bis) == 1:
129
+ take(bis[0], ti, "amount")
130
+
131
+ # Pass 4: GSTIN typo in books
132
+ idx = {}
133
+ for ti in t_free:
134
+ idx.setdefault(norm_exact(T[ti]["inv_no"]), []).append(ti)
135
+ for bi in sorted(b_free):
136
+ cands = [t for t in idx.get(norm_exact(B[bi]["inv_no"]), [])
137
+ if t in t_free and is_close(B[bi]["gstin"], T[t]["gstin"])]
138
+ if len(cands) == 1:
139
+ take(bi, cands[0], "gstin")
140
+
141
+ rows = []
142
+ for bi, ti, how in pairs:
143
+ rows.append(_row(B[bi], T[ti], how, tolerance))
144
+ for bi in sorted(b_free):
145
+ rows.append(_row(B[bi], None, None, tolerance))
146
+ for ti in sorted(t_free):
147
+ rows.append(_row(None, T[ti], None, tolerance))
148
+
149
+ out = pd.DataFrame(rows)
150
+ out["_order"] = out["Status"].map({s: i for i, s in enumerate(STATUS_ORDER)})
151
+ out = out.sort_values(["_order", "Supplier name", "Supplier GSTIN"], kind="stable").drop(columns="_order")
152
+ return out.reset_index(drop=True)
153
+
154
+
155
+ def _row(b, t, how, tol) -> dict:
156
+ remarks = []
157
+ if b is not None and t is not None:
158
+ if how == "gstin":
159
+ status = GSTIN_ERR
160
+ remarks.append(f"Books GSTIN {b['gstin']} vs 2B GSTIN {t['gstin']}")
161
+ elif not _amounts_close(b, t, tol):
162
+ status = MISMATCH
163
+ else:
164
+ status = {"exact": MATCHED, "core": FORMAT_DIFF, "amount": PROBABLE}[how]
165
+ if how in ("core", "amount") and norm_exact(b["inv_no"]) != norm_exact(t["inv_no"]):
166
+ remarks.append(f"Inv. no. books '{b['inv_no']}' vs 2B '{t['inv_no']}'")
167
+ d = _days_apart(b["inv_date"], t["inv_date"])
168
+ if d:
169
+ remarks.append(f"Inv. date differs by {d} day(s)")
170
+ elif b is not None:
171
+ status = MISSING_2B
172
+ remarks.append("ITC at risk: supplier has not filed / not reported in GSTR-1")
173
+ else:
174
+ status = MISSING_BOOKS
175
+ remarks.append("In GSTR-2B but not booked: check if bill received / to be booked")
176
+
177
+ if b is not None and b["gstin"] and not is_valid(b["gstin"]):
178
+ remarks.append("Books GSTIN is not a valid GSTIN")
179
+ if t is not None:
180
+ if str(t.get("itc_avail", "")).strip().upper() in ("NO", "N"):
181
+ remarks.append("2B says ITC NOT available")
182
+ if str(t.get("rcm", "")).strip().upper() in ("YES", "Y"):
183
+ remarks.append("Reverse charge supply")
184
+
185
+ src = t if t is not None else b
186
+ btax = _tax(b) if b is not None else None
187
+ ttax = _tax(t) if t is not None else None
188
+ diff = lambda x, y: round(x - y, 2) if x is not None and y is not None else None
189
+ btx = b["taxable"] if b is not None else None
190
+ ttx = t["taxable"] if t is not None else None
191
+ return {
192
+ "Status": status,
193
+ "Supplier GSTIN": t["gstin"] if t is not None else b["gstin"],
194
+ "Supplier name": (t["name"] if t is not None and t["name"] else (b["name"] if b is not None else "")),
195
+ "Doc type": {"INV": "Invoice", "CN": "Credit note", "DN": "Debit note"}.get(src["doc_type"], src["doc_type"]),
196
+ "Inv. no. (books)": b["inv_no"] if b is not None else "",
197
+ "Inv. no. (2B)": t["inv_no"] if t is not None else "",
198
+ "Inv. date (books)": b["inv_date"] if b is not None else pd.NaT,
199
+ "Inv. date (2B)": t["inv_date"] if t is not None else pd.NaT,
200
+ "Taxable (books)": btx,
201
+ "Taxable (2B)": ttx,
202
+ "Taxable diff": diff(btx, ttx),
203
+ "Total tax (books)": round(btax, 2) if btax is not None else None,
204
+ "Total tax (2B)": round(ttax, 2) if ttax is not None else None,
205
+ "Tax diff": diff(btax, ttax),
206
+ "IGST (books)": b["igst"] if b is not None else None,
207
+ "IGST (2B)": t["igst"] if t is not None else None,
208
+ "CGST (books)": b["cgst"] if b is not None else None,
209
+ "CGST (2B)": t["cgst"] if t is not None else None,
210
+ "SGST (books)": b["sgst"] if b is not None else None,
211
+ "SGST (2B)": t["sgst"] if t is not None else None,
212
+ "Remarks": "; ".join(remarks),
213
+ }
@@ -0,0 +1,237 @@
1
+ """Read GSTR-2B (portal Excel or JSON) and purchase registers (Tally, Busy, Zoho or any Excel/CSV).
2
+
3
+ Every reader returns a DataFrame with the same standard columns:
4
+ gstin, name, inv_no, inv_date, doc_type, taxable, igst, cgst, sgst, cess,
5
+ inv_value, itc_avail, rcm, source
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from pathlib import Path
12
+
13
+ import pandas as pd
14
+
15
+ from .gstin import clean as clean_gstin
16
+
17
+ AMOUNTS = ["taxable", "igst", "cgst", "sgst", "cess", "inv_value"]
18
+ STANDARD = ["gstin", "name", "inv_no", "inv_date", "doc_type", *AMOUNTS, "itc_avail", "rcm", "source"]
19
+
20
+ # Header synonyms, best first. Headers are compared lower-case with only a-z and 0-9 kept,
21
+ # so "Integrated Tax(₹)" becomes "integratedtax".
22
+ SYNONYMS: dict[str, list[str]] = {
23
+ "gstin": ["gstinofsupplier", "suppliergstin", "partygstin", "vendorgstin", "gstinuin", "gstin",
24
+ "gstinno", "gstno", "gstnumber", "ctin"],
25
+ "name": ["tradelegalname", "suppliername", "partyname", "vendorname", "tradename", "legalname",
26
+ "particulars", "ledgername", "partyaccount", "name"],
27
+ "inv_no": ["invoicenumber", "supplierinvoiceno", "supplierinvoicenumber", "suppliersinvoiceno",
28
+ "notenumber", "invoiceno", "billno", "billnumber", "documentnumber", "docno",
29
+ "referenceno", "refno", "reference", "vouchernumber", "voucherno", "vchno"],
30
+ "inv_date": ["invoicedate", "supplierinvoicedate", "notedate", "billdate", "documentdate",
31
+ "docdate", "date"],
32
+ "note_type": ["notetype", "documenttype", "doctype"],
33
+ "taxable": ["taxablevalue", "taxableamount", "assessablevalue", "taxable"],
34
+ "igst": ["integratedtax", "integratedtaxamount", "igst", "igstamount"],
35
+ "cgst": ["centraltax", "centraltaxamount", "cgst", "cgstamount"],
36
+ "sgst": ["stateuttax", "statetax", "statetaxamount", "stateuttaxamount", "sgst", "sgstamount",
37
+ "sgstutgst", "utgst"],
38
+ "cess": ["cess", "cessamount", "compensationcess"],
39
+ "inv_value": ["invoicevalue", "notevalue", "grosstotal", "invoiceamount", "billamount", "totalvalue",
40
+ "totalamount"],
41
+ "itc_avail": ["itcavailability", "itceligibility"],
42
+ "rcm": ["supplyattractreversecharge", "reversecharge"],
43
+ }
44
+
45
+
46
+ def _norm_header(value) -> str:
47
+ if value is None or (isinstance(value, float) and pd.isna(value)):
48
+ return ""
49
+ return re.sub(r"[^a-z0-9]", "", str(value).lower())
50
+
51
+
52
+ def _field_for(header) -> tuple[str, int] | None:
53
+ """Map one header cell to (field, priority). Lower priority number = better match."""
54
+ h = _norm_header(header)
55
+ if not h:
56
+ return None
57
+ # also try without a currency suffix: "Taxable Amount (Rs)" -> "taxableamount"
58
+ for cand in (h, re.sub(r"(inrs|rs|inr)$", "", h)):
59
+ for field, names in SYNONYMS.items():
60
+ if cand in names:
61
+ return field, names.index(cand)
62
+ return None
63
+
64
+
65
+ def _detect_columns(raw: pd.DataFrame, overrides: dict[str, str] | None = None):
66
+ """Find the header row(s) and return ({field: column index}, first data row)."""
67
+ scan = min(len(raw), 25)
68
+ best_row, best_hits = None, 0
69
+ for r in range(scan):
70
+ hits = len({f[0] for f in (_field_for(v) for v in raw.iloc[r]) if f})
71
+ if hits > best_hits:
72
+ best_row, best_hits = r, hits
73
+ if best_row is None or best_hits < 3:
74
+ raise ValueError("Could not find the header row. Make sure the sheet has columns like "
75
+ "GSTIN, Invoice number, Taxable value, IGST/CGST/SGST.")
76
+
77
+ chosen: dict[str, tuple[int, int]] = {} # field -> (priority, column)
78
+ used_next_row = False
79
+ for col in range(raw.shape[1]):
80
+ for r in (best_row, best_row - 1, best_row + 1): # handles the portal's two-row headers
81
+ if 0 <= r < len(raw):
82
+ hit = _field_for(raw.iat[r, col])
83
+ if hit:
84
+ field, prio = hit
85
+ if field not in chosen or prio < chosen[field][0]:
86
+ chosen[field] = (prio, col)
87
+ if r == best_row + 1:
88
+ used_next_row = True
89
+ break
90
+ cols = {f: c for f, (_, c) in chosen.items()}
91
+
92
+ if overrides:
93
+ headers = {col: [_norm_header(raw.iat[r, col]) for r in range(scan)] for col in range(raw.shape[1])}
94
+ for field, wanted in overrides.items():
95
+ w = _norm_header(wanted)
96
+ match = [c for c, hs in headers.items() if w in hs]
97
+ if not match:
98
+ raise ValueError(f"Column '{wanted}' (for {field}) not found.")
99
+ cols[field] = match[0]
100
+
101
+ missing = [f for f in ("gstin", "inv_no") if f not in cols]
102
+ if missing:
103
+ raise ValueError(f"Could not find column(s) for: {', '.join(missing)}. "
104
+ "Use the --map option to name them, e.g. --map inv_no=\"Bill Ref\".")
105
+ if not any(f in cols for f in ("igst", "cgst", "sgst", "taxable")):
106
+ raise ValueError("Could not find any amount columns (Taxable value, IGST, CGST, SGST).")
107
+ return cols, best_row + (2 if used_next_row else 1)
108
+
109
+
110
+ def _to_amount(series: pd.Series) -> pd.Series:
111
+ s = series.astype("string").str.replace(r"[,₹\s]", "", regex=True)
112
+ s = s.str.replace(r"^\((.*)\)$", r"-\1", regex=True) # (123) -> -123
113
+ return pd.to_numeric(s, errors="coerce").fillna(0.0).astype(float)
114
+
115
+
116
+ def _to_date(series: pd.Series) -> pd.Series:
117
+ out = []
118
+ for v in series:
119
+ if v is None or (isinstance(v, float) and pd.isna(v)) or str(v).strip() == "":
120
+ out.append(pd.NaT)
121
+ elif isinstance(v, (pd.Timestamp,)) or hasattr(v, "year"):
122
+ out.append(pd.Timestamp(v))
123
+ else:
124
+ out.append(pd.to_datetime(str(v).strip(), dayfirst=True, errors="coerce"))
125
+ return pd.Series(out, index=series.index, dtype="datetime64[ns]")
126
+
127
+
128
+ def _standardise(raw: pd.DataFrame, cols: dict[str, int], start: int, source: str) -> pd.DataFrame:
129
+ data = raw.iloc[start:].reset_index(drop=True)
130
+ out = pd.DataFrame(index=data.index)
131
+ for field in ("gstin", "name", "inv_no", "note_type", "itc_avail", "rcm"):
132
+ if field in cols:
133
+ out[field] = data.iloc[:, cols[field]].astype("string").str.strip().fillna("")
134
+ else:
135
+ out[field] = ""
136
+ out["gstin"] = out["gstin"].map(clean_gstin)
137
+ out["inv_date"] = _to_date(data.iloc[:, cols["inv_date"]]) if "inv_date" in cols else pd.NaT
138
+ for field in AMOUNTS:
139
+ out[field] = _to_amount(data.iloc[:, cols[field]]) if field in cols else 0.0
140
+ out["source"] = [f"{source} row {start + i + 1}" for i in range(len(out))]
141
+
142
+ # Keep only real document rows (drop blanks, sub-totals, grand totals).
143
+ out = out[(out["inv_no"] != "") & (out["gstin"].str.len() >= 10)]
144
+ out = out[~out["inv_no"].str.lower().str.contains("total")]
145
+
146
+ note = out["note_type"].str.lower()
147
+ out["doc_type"] = "INV"
148
+ out.loc[note.str.contains("debit"), "doc_type"] = "DN"
149
+ out.loc[note.str.contains("credit"), "doc_type"] = "CN"
150
+ out.loc[(out["doc_type"] == "INV") & (out["taxable"] < 0), "doc_type"] = "CN"
151
+ return out
152
+
153
+
154
+ def _aggregate(df: pd.DataFrame) -> pd.DataFrame:
155
+ """One row per document (the portal lists one line per tax rate)."""
156
+ if df.empty:
157
+ return pd.DataFrame(columns=STANDARD)
158
+ agg = {f: "sum" for f in AMOUNTS if f != "inv_value"}
159
+ agg.update({"inv_value": "max", "name": "first", "inv_date": "first", "itc_avail": "first",
160
+ "rcm": "first", "source": "first"})
161
+ g = df.groupby(["gstin", "inv_no", "doc_type"], as_index=False, sort=False).agg(agg)
162
+ return g[STANDARD].reset_index(drop=True)
163
+
164
+
165
+ def _read_table(path: Path, sheet=None) -> pd.DataFrame:
166
+ if path.suffix.lower() in (".csv", ".txt"):
167
+ return pd.read_csv(path, header=None, dtype=object)
168
+ return pd.read_excel(path, sheet_name=sheet if sheet is not None else 0, header=None, dtype=object)
169
+
170
+
171
+ def read_books(path, sheet=None, mapping: dict[str, str] | None = None) -> pd.DataFrame:
172
+ """Read a purchase register exported from Tally, Busy, Zoho Books or any Excel/CSV."""
173
+ path = Path(path)
174
+ raw = _read_table(path, sheet)
175
+ cols, start = _detect_columns(raw, mapping)
176
+ return _aggregate(_standardise(raw, cols, start, path.name))
177
+
178
+
179
+ def _read_2b_json(path: Path) -> pd.DataFrame:
180
+ doc = json.loads(path.read_text(encoding="utf-8"))
181
+ data = doc.get("data", doc)
182
+ docdata = data.get("docdata", data)
183
+ rows = []
184
+
185
+ def add(supplier, d, number_key, date_key, value_key, doc_type):
186
+ items = d.get("items") or [d]
187
+ sign = -1 if doc_type == "CN" else 1
188
+ rows.append({
189
+ "gstin": clean_gstin(supplier.get("ctin")), "name": supplier.get("trdnm", ""),
190
+ "inv_no": str(d.get(number_key, "")).strip(),
191
+ "inv_date": pd.to_datetime(d.get(date_key), dayfirst=True, errors="coerce"),
192
+ "doc_type": doc_type,
193
+ "taxable": sign * sum(float(i.get("txval", 0) or 0) for i in items),
194
+ "igst": sign * sum(float(i.get("igst", 0) or 0) for i in items),
195
+ "cgst": sign * sum(float(i.get("cgst", 0) or 0) for i in items),
196
+ "sgst": sign * sum(float(i.get("sgst", 0) or 0) for i in items),
197
+ "cess": sign * sum(float(i.get("cess", 0) or 0) for i in items),
198
+ "inv_value": sign * float(d.get(value_key, 0) or 0),
199
+ "itc_avail": d.get("itcavl", ""), "rcm": d.get("rev", ""), "source": path.name,
200
+ })
201
+
202
+ for s in docdata.get("b2b", []):
203
+ for inv in s.get("inv", []):
204
+ add(s, inv, "inum", "dt", "val", "INV")
205
+ for s in docdata.get("cdnr", []):
206
+ for nt in s.get("nt", []):
207
+ add(s, nt, "ntnum", "dt", "val", "CN" if str(nt.get("typ", "C")).upper().startswith("C") else "DN")
208
+ df = pd.DataFrame(rows, columns=STANDARD)
209
+ return _aggregate(df) if not df.empty else df
210
+
211
+
212
+ def read_gstr2b(path) -> pd.DataFrame:
213
+ """Read a GSTR-2B downloaded from the GST portal (Excel or JSON). B2B invoices and credit/debit notes."""
214
+ path = Path(path)
215
+ if path.suffix.lower() == ".json":
216
+ return _read_2b_json(path)
217
+ if path.suffix.lower() in (".csv", ".txt"):
218
+ raw = _read_table(path)
219
+ cols, start = _detect_columns(raw)
220
+ return _aggregate(_standardise(raw, cols, start, path.name))
221
+
222
+ sheets = pd.ExcelFile(path).sheet_names
223
+ wanted = [s for s in sheets if re.sub(r"[^a-z0-9]", "", s.lower()) in ("b2b", "b2bcdnr")]
224
+ if not wanted:
225
+ wanted = [sheets[0]]
226
+ frames = []
227
+ for sheet in wanted:
228
+ raw = pd.read_excel(path, sheet_name=sheet, header=None, dtype=object)
229
+ cols, start = _detect_columns(raw)
230
+ df = _standardise(raw, cols, start, f"{path.name} [{sheet}]")
231
+ if "cdnr" in sheet.lower():
232
+ # The portal shows note amounts as positive; credit notes reduce ITC.
233
+ cn = df["doc_type"] == "CN"
234
+ df.loc[cn, AMOUNTS] = -df.loc[cn, AMOUNTS].abs()
235
+ frames.append(df)
236
+ frames = [f for f in frames if not f.empty]
237
+ return _aggregate(pd.concat(frames, ignore_index=True)) if frames else pd.DataFrame(columns=STANDARD)
@@ -0,0 +1,182 @@
1
+ """Write the reconciliation to a formatted Excel workbook."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime
5
+
6
+ import pandas as pd
7
+ from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
8
+ from openpyxl.utils import get_column_letter
9
+
10
+ from .matcher import (FORMAT_DIFF, GSTIN_ERR, MATCHED, MISMATCH, MISSING_2B, MISSING_BOOKS, PROBABLE,
11
+ STATUS_ORDER)
12
+
13
+ NAVY = "1B2F4B"
14
+ TEAL = "0E7C86"
15
+ STATUS_FILL = {
16
+ MATCHED: "E3F4EA", FORMAT_DIFF: "E3F4EA", PROBABLE: "FFF4D6", MISMATCH: "FDE2E1",
17
+ GSTIN_ERR: "FDE2E1", MISSING_2B: "FDE2E1", MISSING_BOOKS: "E6EEF8",
18
+ }
19
+ ACTIONS = {
20
+ MATCHED: "No action. ITC can be claimed.",
21
+ FORMAT_DIFF: "Same invoice, number typed differently. Optionally correct the number in books.",
22
+ PROBABLE: "Same supplier and amounts but different invoice no. Verify with the bill.",
23
+ MISMATCH: "Amounts differ. Check the bill; ask supplier to amend GSTR-1 or correct books.",
24
+ GSTIN_ERR: "Invoice found under a different GSTIN. Correct the supplier GSTIN in books.",
25
+ MISSING_2B: "ITC at risk. Ask supplier to file / report the invoice in GSTR-1.",
26
+ MISSING_BOOKS: "In 2B but not booked. Check if bill received; book it or note as not ours.",
27
+ }
28
+ MONEY = '#,##0.00;[Red]-#,##0.00'
29
+ THIN = Side(style="thin", color="D0D7E2")
30
+
31
+
32
+ def _ftax(series) -> float:
33
+ return float(pd.to_numeric(series, errors="coerce").fillna(0).sum())
34
+
35
+
36
+ def summary_figures(result: pd.DataFrame) -> dict:
37
+ by = result.groupby("Status")
38
+ tax_b = lambda s: _ftax(by.get_group(s)["Total tax (books)"]) if s in by.groups else 0.0
39
+ tax_t = lambda s: _ftax(by.get_group(s)["Total tax (2B)"]) if s in by.groups else 0.0
40
+ not_avail = result["Remarks"].str.contains("ITC NOT available", na=False)
41
+ return {
42
+ "ITC as per GSTR-2B": _ftax(result["Total tax (2B)"]),
43
+ "ITC as per books": _ftax(result["Total tax (books)"]),
44
+ "ITC matched (as per 2B)": sum(tax_t(s) for s in (MATCHED, FORMAT_DIFF, PROBABLE)),
45
+ "ITC at risk: in books, missing in 2B": tax_b(MISSING_2B),
46
+ "In 2B but not booked": tax_t(MISSING_BOOKS),
47
+ "Net difference on amount mismatches (books - 2B)": tax_b(MISMATCH) - tax_t(MISMATCH),
48
+ "ITC marked 'not available' in 2B": _ftax(result.loc[not_avail, "Total tax (2B)"]),
49
+ }
50
+
51
+
52
+ def vendor_followup(result: pd.DataFrame, period: str = "") -> pd.DataFrame:
53
+ issues = result[result["Status"].isin([MISSING_2B, MISMATCH])] # GSTIN errors are fixed in our own books
54
+ rows = []
55
+ for gstin, g in issues.groupby("Supplier GSTIN", sort=False):
56
+ name = g["Supplier name"].iloc[0] or gstin
57
+ lines = []
58
+ for _, r in g.iterrows():
59
+ inv = r["Inv. no. (books)"] or r["Inv. no. (2B)"]
60
+ d = r["Inv. date (books)"]
61
+ dt = f" dt {pd.Timestamp(d):%d-%m-%Y}" if pd.notna(d) else ""
62
+ tax = r["Total tax (books)"] or 0
63
+ what = {MISSING_2B: "not reflecting",
64
+ MISMATCH: f"tax differs by Rs {abs(r['Tax diff'] or 0):,.2f}"}[r["Status"]]
65
+ lines.append(f"{inv}{dt} (tax Rs {tax:,.2f}) - {what}")
66
+ at_risk = _ftax(g.loc[g["Status"] == MISSING_2B, "Total tax (books)"]) + \
67
+ _ftax(g.loc[g["Status"] == MISMATCH, "Tax diff"].abs())
68
+ p = f" for {period}" if period else ""
69
+ msg = (f"Dear {name}, while reconciling our GSTR-2B{p}, the following invoice(s) from you "
70
+ f"need attention: " + "; ".join(lines) +
71
+ ". Kindly file / amend your GSTR-1 at the earliest so that we can claim the ITC. Thank you.")
72
+ rows.append({"Supplier name": name, "Supplier GSTIN": gstin, "Invoices": len(g),
73
+ "Issues": ", ".join(sorted(set(g["Status"]), key=STATUS_ORDER.index)),
74
+ "ITC at risk / difference": round(at_risk, 2),
75
+ "Invoice details": "\n".join(lines), "Message to supplier": msg})
76
+ out = pd.DataFrame(rows, columns=["Supplier name", "Supplier GSTIN", "Invoices", "Issues",
77
+ "ITC at risk / difference", "Invoice details", "Message to supplier"])
78
+ return out.sort_values("ITC at risk / difference", ascending=False).reset_index(drop=True)
79
+
80
+
81
+ def _style_table(ws, df: pd.DataFrame, start_row: int = 1, status_col: str | None = "Status",
82
+ freeze: bool = True):
83
+ head_font = Font(bold=True, color="FFFFFF")
84
+ head_fill = PatternFill("solid", fgColor=NAVY)
85
+ for c in range(1, len(df.columns) + 1):
86
+ cell = ws.cell(row=start_row, column=c)
87
+ cell.font, cell.fill = head_font, head_fill
88
+ cell.alignment = Alignment(wrap_text=True, vertical="center")
89
+ ws.row_dimensions[start_row].height = 32
90
+ for i, col in enumerate(df.columns, start=1):
91
+ letter = get_column_letter(i)
92
+ is_money = pd.api.types.is_numeric_dtype(df[col]) and col not in ("Invoices", "Count")
93
+ is_date = "date" in col.lower()
94
+ width = max([len(str(col))] + [len(str(v)) for v in df[col].head(200)]) + 2
95
+ if col in ("Remarks", "Message to supplier"):
96
+ width = 60
97
+ elif col == "Invoice details":
98
+ width = 55
99
+ ws.column_dimensions[letter].width = min(max(width, 10), 60)
100
+ for r in range(start_row + 1, start_row + 1 + len(df)):
101
+ cell = ws.cell(row=r, column=i)
102
+ cell.border = Border(bottom=THIN)
103
+ cell.alignment = Alignment(vertical="top")
104
+ if is_money:
105
+ cell.number_format = MONEY
106
+ elif is_date:
107
+ cell.number_format = "dd-mm-yyyy"
108
+ if col in ("Remarks", "Invoice details", "Message to supplier"):
109
+ cell.alignment = Alignment(wrap_text=True, vertical="top")
110
+ if status_col and status_col in df.columns:
111
+ sc = list(df.columns).index(status_col) + 1
112
+ for r in range(start_row + 1, start_row + 1 + len(df)):
113
+ cell = ws.cell(row=r, column=sc)
114
+ color = STATUS_FILL.get(cell.value)
115
+ if color:
116
+ cell.fill = PatternFill("solid", fgColor=color)
117
+ cell.font = Font(bold=True)
118
+ if not freeze:
119
+ return
120
+ ws.freeze_panes = ws.cell(row=start_row + 1, column=3 if status_col else 2)
121
+ if len(df):
122
+ ws.auto_filter.ref = f"A{start_row}:{get_column_letter(len(df.columns))}{start_row + len(df)}"
123
+
124
+
125
+ def write_report(result: pd.DataFrame, path, period: str = "", files: tuple[str, ...] = (),
126
+ tolerance: float = 1.0) -> None:
127
+ figures = summary_figures(result)
128
+ followup = vendor_followup(result, period)
129
+ status_rows = []
130
+ for s in STATUS_ORDER:
131
+ g = result[result["Status"] == s]
132
+ status_rows.append({"Status": s, "Count": len(g),
133
+ "Tax as per books": round(_ftax(g["Total tax (books)"]), 2),
134
+ "Tax as per 2B": round(_ftax(g["Total tax (2B)"]), 2),
135
+ "What to do": ACTIONS[s]})
136
+ status_df = pd.DataFrame(status_rows)
137
+
138
+ with pd.ExcelWriter(path, engine="openpyxl") as xw:
139
+ # Summary
140
+ pd.DataFrame().to_excel(xw, sheet_name="Summary", index=False)
141
+ ws = xw.sheets["Summary"]
142
+ ws["A1"] = "GSTR-2B vs Purchase Register Reconciliation"
143
+ ws["A1"].font = Font(bold=True, size=16, color=NAVY)
144
+ ws["A2"] = (f"Period: {period} | " if period else "") + \
145
+ f"Generated {datetime.now():%d-%m-%Y %H:%M} | Tolerance Rs {tolerance:,.2f}"
146
+ ws["A2"].font = Font(italic=True, color="555555")
147
+ if files:
148
+ ws["A3"] = "Files: " + ", ".join(files)
149
+ ws["A3"].font = Font(italic=True, color="555555")
150
+ r = 5
151
+ ws.cell(row=r, column=1, value="KEY FIGURES (Rs)").font = Font(bold=True, color=TEAL, size=12)
152
+ for label, value in figures.items():
153
+ r += 1
154
+ ws.cell(row=r, column=1, value=label)
155
+ c = ws.cell(row=r, column=2, value=round(value, 2))
156
+ c.number_format = MONEY
157
+ c.font = Font(bold=True)
158
+ if label.startswith("ITC at risk"):
159
+ ws.cell(row=r, column=1).font = Font(bold=True, color="B42318")
160
+ c.font = Font(bold=True, color="B42318")
161
+ r += 2
162
+ ws.cell(row=r, column=1, value="BY STATUS").font = Font(bold=True, color=TEAL, size=12)
163
+ r += 1
164
+ status_df.to_excel(xw, sheet_name="Summary", index=False, startrow=r - 1)
165
+ _style_table(ws, status_df, start_row=r, freeze=False)
166
+ ws.column_dimensions["A"].width = 48
167
+ ws.column_dimensions["B"].width = 16
168
+ ws.column_dimensions["E"].width = 80
169
+
170
+ sheets = [
171
+ ("All documents", result),
172
+ ("Missing in 2B", result[result["Status"] == MISSING_2B]),
173
+ ("Mismatches", result[result["Status"].isin([MISMATCH, GSTIN_ERR, PROBABLE, FORMAT_DIFF])]),
174
+ ("Missing in books", result[result["Status"] == MISSING_BOOKS]),
175
+ ]
176
+ for name, df in sheets:
177
+ df = df.reset_index(drop=True)
178
+ df.to_excel(xw, sheet_name=name, index=False)
179
+ _style_table(xw.sheets[name], df)
180
+
181
+ followup.to_excel(xw, sheet_name="Vendor follow-up", index=False)
182
+ _style_table(xw.sheets["Vendor follow-up"], followup, status_col=None)
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: gstreco
3
+ Version: 0.1.0
4
+ Summary: Reconcile GSTR-2B with your purchase register (Tally, Busy, Zoho, Excel). Offline, free, open source.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/gbk09/gst-reco
7
+ Project-URL: Issues, https://github.com/gbk09/gst-reco/issues
8
+ Keywords: gst,gstr-2b,itc,reconciliation,india,tally,accounting
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
11
+ Classifier: Intended Audience :: Financial and Insurance Industry
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pandas>=1.5
16
+ Requires-Dist: openpyxl>=3.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # gstreco: free GSTR-2B reconciliation
22
+
23
+ Match your **GSTR-2B** from the GST portal with your **purchase register** from Tally, Busy, Zoho Books or any Excel/CSV file. You get a formatted Excel report that shows which ITC is safe, which is at risk, and which suppliers you need to follow up with.
24
+
25
+ - **Free and open source** (MIT). No limit on GSTINs or invoices.
26
+ - **Runs offline on your own computer.** Your client data is never uploaded anywhere.
27
+ - **Built by an accountant** who does this reconciliation every month.
28
+
29
+ ## What it catches
30
+
31
+ | Case | Example | Result |
32
+ |---|---|---|
33
+ | Exact match | Same GSTIN, invoice no. and amounts | Matched |
34
+ | Invoice no. typed differently | Books `1`, 2B `INV/001/26-27`; `SB-0045` vs `SB45` | Matched - inv. no. format differs |
35
+ | Wrong invoice no. in books | Books `7718`, 2B `7781`, same supplier and amounts | Probable match - check inv. no. |
36
+ | Rounding | 60 paise difference | Matched (tolerance ₹1, adjustable) |
37
+ | Amount differs | Taxable value booked ₹10,000 higher | Amount mismatch |
38
+ | GSTIN typo in books | One character wrong in supplier GSTIN | GSTIN error in books |
39
+ | Supplier hasn't filed | In books, not in 2B | Missing in GSTR-2B (**ITC at risk**) |
40
+ | Not booked | In 2B, not in books | Missing in books |
41
+ | Credit / debit notes | B2B-CDNR sheet vs debit-note vouchers | Matched separately from invoices |
42
+
43
+ It also flags invalid GSTINs in your books (checksum test), invoices the 2B marks **ITC not available**, and reverse-charge supplies.
44
+
45
+ ## The report
46
+
47
+ One Excel file with these sheets:
48
+
49
+ 1. **Summary**: ITC as per 2B and as per books, ITC at risk, and the count and tax for each status, with what to do next.
50
+ 2. **All documents**: every invoice side by side (books vs 2B) with the differences.
51
+ 3. **Missing in 2B**, **Mismatches**, **Missing in books**: filtered lists to work through.
52
+ 4. **Vendor follow-up**: one row per supplier with the tax at risk and a **ready-to-send message** listing their invoices.
53
+
54
+ ## How to use
55
+
56
+ **1. Install** (one time). You need [Python 3.10+](https://www.python.org/downloads/); tick "Add to PATH" when you install it.
57
+
58
+ ```
59
+ pip install gstreco
60
+ ```
61
+
62
+ *(Until it is published on PyPI: download this folder and run `pip install .` inside it.)*
63
+
64
+ **2. Download your files**
65
+ - **GSTR-2B:** GST portal → Returns → Returns Dashboard → GSTR-2B → Download Excel (or JSON).
66
+ - **Purchase register:** Tally Prime → Display More Reports → GST Reports → GSTR-2/Purchase Register (or Day Book filtered to purchases) → Export as Excel. Include the supplier GSTIN, supplier invoice no., date, taxable value, IGST, CGST and SGST columns.
67
+
68
+ **3. Run**
69
+
70
+ Windows, no typing: double-click **`Run GST Reco.bat`**, pick the two files, and the report opens in Excel.
71
+
72
+ Command line:
73
+
74
+ ```
75
+ python -m gstreco --gstr2b GSTR2B_Oct.xlsx --books PurchaseRegister.xlsx --period "Oct 2026"
76
+ ```
77
+
78
+ Useful options:
79
+
80
+ | Option | What it does |
81
+ |---|---|
82
+ | `--gstr2b a.xlsx b.xlsx` | Several months of 2B together (for invoices the supplier filed late) |
83
+ | `--tolerance 10` | Allow up to ₹10 difference (default ₹1) |
84
+ | `--sheet "Purchase Register"` | Choose the sheet in the books file |
85
+ | `--map inv_no="Bill Ref"` | Name a column yourself if it is not detected |
86
+ | `--out Report.xlsx` | Output file name |
87
+
88
+ Columns are detected automatically from common headings (for example *Supplier Invoice No.*, *GSTIN/UIN*, *Integrated Tax Amount*), so most Tally, Busy and Zoho exports work as they are.
89
+
90
+ ## Try it with sample data
91
+
92
+ ```
93
+ python samples/make_samples.py
94
+ python -m gstreco --gstr2b samples/GSTR2B_sample_Oct2026.xlsx --books samples/Purchase_Register_sample.xlsx --period "Oct 2026" --out Sample_Report.xlsx
95
+ ```
96
+
97
+ The sample suppliers and GSTINs are fictitious.
98
+
99
+ ## How matching works
100
+
101
+ Each pass only looks at invoices that are still unmatched:
102
+
103
+ 1. Same GSTIN and same invoice number, ignoring spaces, `/ - .` and case.
104
+ 2. Same GSTIN and same **core number**, ignoring prefixes, leading zeros and the financial year (`26-27`, `2026-27`). It is used only when the match is unique on both sides.
105
+ 3. Same GSTIN, same taxable value and tax (within tolerance), dates within 45 days, unique both ways. This gives a *probable* match, for you to verify.
106
+ 4. Same invoice number where the books GSTIN is 1–2 characters off or has the same PAN. This is a GSTIN typo.
107
+
108
+ ## Contributing
109
+
110
+ Issues and pull requests are welcome, especially sample exports from other software (Busy, Marg, Zoho, SAP) with the data removed, and new edge cases. Run the tests with `pip install -e .[dev]` and then `pytest`.
111
+
112
+ ## Disclaimer
113
+
114
+ This is a helper tool. Always check the results before you claim ITC or file returns. It is not tax advice.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/gstreco/__init__.py
5
+ src/gstreco/__main__.py
6
+ src/gstreco/cli.py
7
+ src/gstreco/gstin.py
8
+ src/gstreco/matcher.py
9
+ src/gstreco/readers.py
10
+ src/gstreco/report.py
11
+ src/gstreco.egg-info/PKG-INFO
12
+ src/gstreco.egg-info/SOURCES.txt
13
+ src/gstreco.egg-info/dependency_links.txt
14
+ src/gstreco.egg-info/entry_points.txt
15
+ src/gstreco.egg-info/requires.txt
16
+ src/gstreco.egg-info/top_level.txt
17
+ tests/test_reco.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ gstreco = gstreco.cli:main
@@ -0,0 +1,5 @@
1
+ pandas>=1.5
2
+ openpyxl>=3.0
3
+
4
+ [dev]
5
+ pytest
@@ -0,0 +1 @@
1
+ gstreco
@@ -0,0 +1,88 @@
1
+ import json
2
+ import subprocess
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import pandas as pd
7
+ import pytest
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0, str(ROOT / "src"))
11
+
12
+ from gstreco import read_books, read_gstr2b, reconcile # noqa: E402
13
+ from gstreco.gstin import checksum_char, is_close, is_valid # noqa: E402
14
+ from gstreco.matcher import norm_core, norm_exact # noqa: E402
15
+ from gstreco.report import write_report # noqa: E402
16
+
17
+ SAMPLES = ROOT / "samples"
18
+
19
+
20
+ @pytest.fixture(scope="session", autouse=True)
21
+ def samples():
22
+ subprocess.run([sys.executable, str(SAMPLES / "make_samples.py")], check=True, capture_output=True)
23
+
24
+
25
+ def test_gstin_checksum():
26
+ g = "27AAACS1234A1Z"
27
+ full = g + checksum_char(g)
28
+ assert is_valid(full)
29
+ assert not is_valid(full[:-1] + ("0" if full[-1] != "0" else "1"))
30
+ assert not is_valid("27AAACS1234A1Z")
31
+ assert is_close(full, full[:3] + "B" + full[4:])
32
+
33
+
34
+ @pytest.mark.parametrize("a,b", [("INV/001/26-27", "1"), ("SB-0045", "SB45"), ("2026-27/0912", "912"),
35
+ ("A/12/2026-27", "a-12")])
36
+ def test_core_number(a, b):
37
+ assert norm_core(a) == norm_core(b)
38
+
39
+
40
+ def test_core_keeps_real_numbers():
41
+ assert norm_core("INV-12") != norm_core("INV-13")
42
+ assert norm_exact("ab/1-2") == "AB12"
43
+
44
+
45
+ def test_sample_reconciliation(tmp_path):
46
+ t = read_gstr2b(SAMPLES / "GSTR2B_sample_Oct2026.xlsx")
47
+ b = read_books(SAMPLES / "Purchase_Register_sample.xlsx")
48
+ assert len(t) == 32 and len(b) == 33
49
+ r = reconcile(t, b)
50
+ counts = r["Status"].value_counts().to_dict()
51
+ assert counts == {
52
+ "Matched": 23, "Matched - inv. no. format differs": 2, "Probable match - check inv. no.": 1,
53
+ "Amount mismatch": 2, "GSTIN error in books": 1, "Missing in GSTR-2B": 4, "Missing in books": 3,
54
+ }
55
+ assert any("ITC NOT available" in x for x in r["Remarks"])
56
+ cn = r[r["Doc type"] == "Credit note"]
57
+ assert len(cn) == 1 and cn["Status"].iloc[0] == "Matched"
58
+ out = tmp_path / "report.xlsx"
59
+ write_report(r, out, period="Oct 2026")
60
+ sheets = pd.ExcelFile(out).sheet_names
61
+ assert sheets == ["Summary", "All documents", "Missing in 2B", "Mismatches", "Missing in books",
62
+ "Vendor follow-up"]
63
+
64
+
65
+ def test_json_2b_and_csv_books(tmp_path):
66
+ g = "27AAACS1234A1Z"
67
+ g += checksum_char(g)
68
+ doc = {"data": {"docdata": {"b2b": [{"ctin": g, "trdnm": "Test Supplier", "inv": [
69
+ {"inum": "T/0007/26-27", "dt": "05-10-2026", "val": 1180,
70
+ "items": [{"txval": 1000, "igst": 0, "cgst": 90, "sgst": 90, "cess": 0}]},
71
+ {"inum": "T/8", "dt": "06-10-2026", "val": 590, "items": [{"txval": 500, "cgst": 45, "sgst": 45}]},
72
+ ]}]}}}
73
+ j = tmp_path / "2b.json"
74
+ j.write_text(json.dumps(doc), encoding="utf-8")
75
+ csv = tmp_path / "books.csv"
76
+ csv.write_text("Bill Ref,Party GSTIN,Bill Date,Taxable,CGST,SGST\n7,%s,05/10/2026,\"1,000.00\",90,90\n" % g,
77
+ encoding="utf-8")
78
+ r = reconcile(read_gstr2b(j), read_books(csv, mapping={"inv_no": "Bill Ref"}))
79
+ assert sorted(r["Status"]) == ["Matched - inv. no. format differs", "Missing in books"]
80
+
81
+
82
+ def test_cli(tmp_path):
83
+ out = tmp_path / "cli.xlsx"
84
+ res = subprocess.run([sys.executable, "-m", "gstreco", "--gstr2b", str(SAMPLES / "GSTR2B_sample_Oct2026.xlsx"),
85
+ "--books", str(SAMPLES / "Purchase_Register_sample.xlsx"), "--out", str(out)],
86
+ capture_output=True, text=True, env={**__import__("os").environ, "PYTHONPATH": str(ROOT / "src")})
87
+ assert res.returncode == 0, res.stderr
88
+ assert out.exists()