india-gst-kit 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.
- india_gst_kit-0.1.0/.github/workflows/ci.yml +16 -0
- india_gst_kit-0.1.0/.github/workflows/publish.yml +19 -0
- india_gst_kit-0.1.0/.gitignore +4 -0
- india_gst_kit-0.1.0/CONTRIBUTING.md +13 -0
- india_gst_kit-0.1.0/LICENSE +21 -0
- india_gst_kit-0.1.0/PKG-INFO +73 -0
- india_gst_kit-0.1.0/README.md +53 -0
- india_gst_kit-0.1.0/pyproject.toml +27 -0
- india_gst_kit-0.1.0/src/india_gst/__init__.py +9 -0
- india_gst_kit-0.1.0/src/india_gst/excel.py +72 -0
- india_gst_kit-0.1.0/src/india_gst/gstin.py +63 -0
- india_gst_kit-0.1.0/src/india_gst/register.py +111 -0
- india_gst_kit-0.1.0/src/india_gst/states.py +25 -0
- india_gst_kit-0.1.0/src/india_gst/tax.py +38 -0
- india_gst_kit-0.1.0/tests/test_kit.py +71 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
on: [push, pull_request]
|
|
3
|
+
jobs:
|
|
4
|
+
test:
|
|
5
|
+
runs-on: ubuntu-latest
|
|
6
|
+
strategy:
|
|
7
|
+
fail-fast: false
|
|
8
|
+
matrix:
|
|
9
|
+
python: ["3.10", "3.12", "3.13"]
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v4
|
|
12
|
+
- uses: actions/setup-python@v5
|
|
13
|
+
with:
|
|
14
|
+
python-version: ${{ matrix.python }}
|
|
15
|
+
- run: pip install -e ".[test]"
|
|
16
|
+
- run: pytest -q
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
# Publishes to PyPI when a GitHub release is published.
|
|
3
|
+
# Uses PyPI trusted publishing: no password or token is stored anywhere.
|
|
4
|
+
on:
|
|
5
|
+
release:
|
|
6
|
+
types: [published]
|
|
7
|
+
jobs:
|
|
8
|
+
pypi:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
environment: pypi
|
|
11
|
+
permissions:
|
|
12
|
+
id-token: write
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: "3.13"
|
|
18
|
+
- run: pip install build && python -m build
|
|
19
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Thanks for helping. Small pull requests are easiest to review.
|
|
4
|
+
|
|
5
|
+
1. Fork the repo and create a branch.
|
|
6
|
+
2. `pip install -e ".[test]"` then `pytest`.
|
|
7
|
+
3. Add a test for any change in behaviour.
|
|
8
|
+
4. Never commit real GSTINs, customer names or invoice data. Use the made-up sample `27AAAAA0000A1Z2` or made-up values.
|
|
9
|
+
5. Open a pull request describing what changed and why.
|
|
10
|
+
|
|
11
|
+
Good first issues are labelled `good first issue`.
|
|
12
|
+
|
|
13
|
+
GST rules change; if you spot something out of date, open an issue with a link to the CBIC or GST portal source.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hexaspace
|
|
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.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: india-gst-kit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: GSTIN validation, CGST/SGST/IGST split, GSTR-1 style sales register and a CA-ready Excel workbook, from plain Python data.
|
|
5
|
+
Author: Hexaspace
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: accounting,gst,gstin,gstr-1,hsn,india,invoice,tally,tax
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Provides-Extra: excel
|
|
15
|
+
Requires-Dist: openpyxl>=3.1; extra == 'excel'
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: openpyxl>=3.1; extra == 'test'
|
|
18
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# india-gst-kit
|
|
22
|
+
|
|
23
|
+
Small, dependency-free Python tools for Indian GST:
|
|
24
|
+
|
|
25
|
+
- **GSTIN validation**: format, state code, check digit, and a match against the customer's state
|
|
26
|
+
- **Tax split**: CGST + SGST (same state) or IGST (other state), for GST-inclusive or exclusive amounts
|
|
27
|
+
- **Sales register**: one row per invoice per GST rate (the GSTR-1 shape), B2B/B2C split, HSN summary
|
|
28
|
+
- **Checks for your CA**: missing HSN codes, GSTIN/state mismatches, unpaid invoices, advances before invoice
|
|
29
|
+
- **Excel workbook** (optional) your CA can open straight away
|
|
30
|
+
|
|
31
|
+
Works with plain dicts, so it fits any database or framework (Django, FastAPI, Flask, scripts).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install india-gst-kit # core, no dependencies
|
|
37
|
+
pip install "india-gst-kit[excel]" # + Excel export
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 30-second example
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from india_gst import validate, split, build_register
|
|
44
|
+
from india_gst.excel import to_xlsx
|
|
45
|
+
|
|
46
|
+
validate("27AAAAA0000A1Z2", state="Maharashtra") # -> "27AAAAA0000A1Z2"
|
|
47
|
+
split(1180, 18, seller_state="Gujarat", place_of_supply="Gujarat")
|
|
48
|
+
# TaxSplit(taxable=1000.0, cgst=90.0, sgst=90.0, igst=0.0, total=1180.0)
|
|
49
|
+
|
|
50
|
+
invoices = [{
|
|
51
|
+
"invoice_no": "INV-1", "invoice_date": "2026-11-02",
|
|
52
|
+
"customer": "Sample Buyer LLP", "gstin": "27AAAAA0000A1Z2", "place_of_supply": "Maharashtra",
|
|
53
|
+
"lines": [{"name": "Wardrobe", "hsn": "9403", "qty": 1, "gst_pct": 18, "amount": 1180}],
|
|
54
|
+
}]
|
|
55
|
+
reg = build_register(invoices, seller_state="Gujarat", period=("2026-11-01", "2026-11-30"))
|
|
56
|
+
open("gst-nov.xlsx", "wb").write(to_xlsx(reg, seller_name="Your Company"))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Roadmap
|
|
60
|
+
|
|
61
|
+
- 0.2: Tally Prime XML export (sales vouchers and receipts)
|
|
62
|
+
- 0.3: GSTR-1 JSON for the GST portal offline tool
|
|
63
|
+
- Credit and debit notes
|
|
64
|
+
|
|
65
|
+
Ideas and pull requests are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
66
|
+
|
|
67
|
+
## Not tax advice
|
|
68
|
+
|
|
69
|
+
This library helps prepare data. Always confirm filings with your Chartered Accountant.
|
|
70
|
+
|
|
71
|
+
## Licence
|
|
72
|
+
|
|
73
|
+
MIT. Built and used in production by [Hexaspace](https://hexaspace.in).
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# india-gst-kit
|
|
2
|
+
|
|
3
|
+
Small, dependency-free Python tools for Indian GST:
|
|
4
|
+
|
|
5
|
+
- **GSTIN validation**: format, state code, check digit, and a match against the customer's state
|
|
6
|
+
- **Tax split**: CGST + SGST (same state) or IGST (other state), for GST-inclusive or exclusive amounts
|
|
7
|
+
- **Sales register**: one row per invoice per GST rate (the GSTR-1 shape), B2B/B2C split, HSN summary
|
|
8
|
+
- **Checks for your CA**: missing HSN codes, GSTIN/state mismatches, unpaid invoices, advances before invoice
|
|
9
|
+
- **Excel workbook** (optional) your CA can open straight away
|
|
10
|
+
|
|
11
|
+
Works with plain dicts, so it fits any database or framework (Django, FastAPI, Flask, scripts).
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install india-gst-kit # core, no dependencies
|
|
17
|
+
pip install "india-gst-kit[excel]" # + Excel export
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 30-second example
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from india_gst import validate, split, build_register
|
|
24
|
+
from india_gst.excel import to_xlsx
|
|
25
|
+
|
|
26
|
+
validate("27AAAAA0000A1Z2", state="Maharashtra") # -> "27AAAAA0000A1Z2"
|
|
27
|
+
split(1180, 18, seller_state="Gujarat", place_of_supply="Gujarat")
|
|
28
|
+
# TaxSplit(taxable=1000.0, cgst=90.0, sgst=90.0, igst=0.0, total=1180.0)
|
|
29
|
+
|
|
30
|
+
invoices = [{
|
|
31
|
+
"invoice_no": "INV-1", "invoice_date": "2026-11-02",
|
|
32
|
+
"customer": "Sample Buyer LLP", "gstin": "27AAAAA0000A1Z2", "place_of_supply": "Maharashtra",
|
|
33
|
+
"lines": [{"name": "Wardrobe", "hsn": "9403", "qty": 1, "gst_pct": 18, "amount": 1180}],
|
|
34
|
+
}]
|
|
35
|
+
reg = build_register(invoices, seller_state="Gujarat", period=("2026-11-01", "2026-11-30"))
|
|
36
|
+
open("gst-nov.xlsx", "wb").write(to_xlsx(reg, seller_name="Your Company"))
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Roadmap
|
|
40
|
+
|
|
41
|
+
- 0.2: Tally Prime XML export (sales vouchers and receipts)
|
|
42
|
+
- 0.3: GSTR-1 JSON for the GST portal offline tool
|
|
43
|
+
- Credit and debit notes
|
|
44
|
+
|
|
45
|
+
Ideas and pull requests are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
46
|
+
|
|
47
|
+
## Not tax advice
|
|
48
|
+
|
|
49
|
+
This library helps prepare data. Always confirm filings with your Chartered Accountant.
|
|
50
|
+
|
|
51
|
+
## Licence
|
|
52
|
+
|
|
53
|
+
MIT. Built and used in production by [Hexaspace](https://hexaspace.in).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "india-gst-kit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "GSTIN validation, CGST/SGST/IGST split, GSTR-1 style sales register and a CA-ready Excel workbook, from plain Python data."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "Hexaspace" }]
|
|
13
|
+
keywords = ["gst", "gstin", "india", "gstr-1", "invoice", "tax", "hsn", "tally", "accounting"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
]
|
|
20
|
+
dependencies = []
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
excel = ["openpyxl>=3.1"]
|
|
24
|
+
test = ["pytest>=7", "openpyxl>=3.1"]
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/india_gst"]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""india-gst-kit: GSTIN validation, CGST/SGST/IGST split, GSTR-1 style sales register and CA workbook."""
|
|
2
|
+
from .gstin import GSTINError, check_digit, is_valid, pan_of, state_of, validate
|
|
3
|
+
from .register import build_register
|
|
4
|
+
from .states import STATE_CODES, state_code, state_name
|
|
5
|
+
from .tax import TaxSplit, split
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = ["GSTINError", "check_digit", "is_valid", "pan_of", "state_of", "validate", "build_register",
|
|
9
|
+
"STATE_CODES", "state_code", "state_name", "TaxSplit", "split"]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Write a register (from build_register) to an Excel workbook for your CA. Needs: pip install india-gst-kit[excel]"""
|
|
2
|
+
import io
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
SHEETS = [
|
|
7
|
+
("Sales register", "invoices", [("Invoice no", "invoice_no", 16), ("Invoice date", "invoice_date", 12), ("Type", "type", 6),
|
|
8
|
+
("Customer", "customer", 26), ("Customer GSTIN", "gstin", 17), ("Place of supply", "place_of_supply", 16),
|
|
9
|
+
("GST %", "gst_pct", 7), ("Taxable value", "taxable", 14), ("CGST", "cgst", 11), ("SGST", "sgst", 11),
|
|
10
|
+
("IGST", "igst", 11), ("Total at this rate", "total", 14), ("Round off", "round_off", 9),
|
|
11
|
+
("Invoice value", "invoice_value", 14), ("Paid so far", "paid_so_far", 13), ("Status", "status", 12)]),
|
|
12
|
+
("Invoice lines", "lines", [("Invoice no", "invoice_no", 16), ("Invoice date", "invoice_date", 12), ("Item", "item", 36),
|
|
13
|
+
("HSN/SAC", "hsn", 10), ("Qty", "qty", 7), ("GST %", "gst_pct", 7), ("Taxable value", "taxable", 14),
|
|
14
|
+
("CGST", "cgst", 11), ("SGST", "sgst", 11), ("IGST", "igst", 11), ("Line total", "total", 13)]),
|
|
15
|
+
("HSN summary", "hsn", [("HSN/SAC", "hsn", 12), ("GST %", "gst_pct", 7), ("Lines", "lines", 7), ("Total qty", "qty", 10),
|
|
16
|
+
("Taxable value", "taxable", 14), ("CGST", "cgst", 12), ("SGST", "sgst", 12), ("IGST", "igst", 12),
|
|
17
|
+
("Total value", "total", 14)]),
|
|
18
|
+
("Payments received", "payments", [("Receipt no", "receipt_no", 18), ("Date", "date", 12), ("Invoice no", "invoice_no", 16),
|
|
19
|
+
("Customer", "customer", 24), ("Method", "method", 13), ("Reference", "reference", 22),
|
|
20
|
+
("Amount", "amount", 13), ("Advance", "advance", 9)]),
|
|
21
|
+
("Checks for the CA", "checks", [("Check", "check", 38), ("Document", "document", 20), ("Detail", "detail", 70)]),
|
|
22
|
+
]
|
|
23
|
+
MONEY = {"taxable", "cgst", "sgst", "igst", "total", "round_off", "invoice_value", "paid_so_far", "amount"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def to_xlsx(register: dict, seller_name: str = "", seller_gstin: str = "", title: Optional[str] = None) -> bytes:
|
|
27
|
+
"""Return the workbook as bytes. Sheets: Summary, Sales register, Invoice lines, HSN summary, Payments, Checks."""
|
|
28
|
+
from openpyxl import Workbook
|
|
29
|
+
from openpyxl.styles import Alignment, Font, PatternFill
|
|
30
|
+
from openpyxl.utils import get_column_letter
|
|
31
|
+
|
|
32
|
+
wb = Workbook()
|
|
33
|
+
head, fill, fmt = Font(bold=True, color="FFFFFF"), PatternFill("solid", fgColor="1F1F1F"), "#,##,##0.00"
|
|
34
|
+
s = register["summary"]
|
|
35
|
+
ws = wb.active
|
|
36
|
+
ws.title = "Summary"
|
|
37
|
+
ws["A1"] = title or f"GST sales register {s.get('from', '')} to {s.get('to', '')}".strip()
|
|
38
|
+
ws["A1"].font = Font(bold=True, size=14)
|
|
39
|
+
rows = [("Seller", seller_name), ("GSTIN", seller_gstin), ("Prepared", datetime.now().strftime("%Y-%m-%d %H:%M")), ("", ""),
|
|
40
|
+
("Tax invoices", s["invoices"]), ("of which B2B", s["b2b"]), ("Taxable value", s["taxable"]), ("CGST", s["cgst"]),
|
|
41
|
+
("SGST", s["sgst"]), ("IGST", s["igst"]), ("Invoice value (incl. GST)", s["invoice_value"]), ("", ""),
|
|
42
|
+
("Payments", s["payments"]), ("Amount received", s["received"]), ("of which advances", s["advances"]), ("", ""),
|
|
43
|
+
("Items for the CA to check", s["checks"])]
|
|
44
|
+
for i, (k, v) in enumerate(rows, start=3):
|
|
45
|
+
ws.cell(i, 1, k).font = Font(bold=bool(k))
|
|
46
|
+
c = ws.cell(i, 2, v)
|
|
47
|
+
if isinstance(v, float):
|
|
48
|
+
c.number_format = fmt
|
|
49
|
+
ws.column_dimensions["A"].width, ws.column_dimensions["B"].width = 32, 40
|
|
50
|
+
for name, key, cols in SHEETS:
|
|
51
|
+
sh = wb.create_sheet(name)
|
|
52
|
+
for j, (label, _, w) in enumerate(cols, start=1):
|
|
53
|
+
c = sh.cell(1, j, label)
|
|
54
|
+
c.font, c.fill, c.alignment = head, fill, Alignment(wrap_text=True, vertical="center")
|
|
55
|
+
sh.column_dimensions[get_column_letter(j)].width = w
|
|
56
|
+
data = register.get(key) or []
|
|
57
|
+
for i, row in enumerate(data, start=2):
|
|
58
|
+
for j, (_, f, _) in enumerate(cols, start=1):
|
|
59
|
+
v = row.get(f)
|
|
60
|
+
if isinstance(v, bool):
|
|
61
|
+
v = "Yes" if v else "No"
|
|
62
|
+
c = sh.cell(i, j, v)
|
|
63
|
+
if f in MONEY:
|
|
64
|
+
c.number_format = fmt
|
|
65
|
+
if data:
|
|
66
|
+
sh.auto_filter.ref = f"A1:{get_column_letter(len(cols))}{len(data) + 1}"
|
|
67
|
+
else:
|
|
68
|
+
sh.cell(2, 1, "Nothing in this period")
|
|
69
|
+
sh.freeze_panes = "A2"
|
|
70
|
+
buf = io.BytesIO()
|
|
71
|
+
wb.save(buf)
|
|
72
|
+
return buf.getvalue()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""GSTIN validation: format, state code, check digit, and optional state match."""
|
|
2
|
+
import re
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from .states import STATE_CODES
|
|
6
|
+
|
|
7
|
+
GSTIN_RE = re.compile(r"^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$")
|
|
8
|
+
_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GSTINError(ValueError):
|
|
12
|
+
"""Raised when a GSTIN is invalid. The message is plain enough to show to a user."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def clean(gstin: str) -> str:
|
|
16
|
+
"""Upper-case and strip spaces."""
|
|
17
|
+
return (gstin or "").strip().upper().replace(" ", "")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def check_digit(first14: str) -> str:
|
|
21
|
+
"""Compute the 15th (check) character for the first 14 characters of a GSTIN."""
|
|
22
|
+
total = 0
|
|
23
|
+
for i, ch in enumerate(first14[:14]):
|
|
24
|
+
v = _CHARS.index(ch) * (2 if i % 2 else 1)
|
|
25
|
+
total += v // 36 + v % 36
|
|
26
|
+
return _CHARS[(36 - total % 36) % 36]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_valid(gstin: str) -> bool:
|
|
30
|
+
"""True if the GSTIN has the right format, a known state code and a correct check digit."""
|
|
31
|
+
try:
|
|
32
|
+
validate(gstin)
|
|
33
|
+
return True
|
|
34
|
+
except GSTINError:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def validate(gstin: str, state: Optional[str] = None) -> str:
|
|
39
|
+
"""Validate a GSTIN and return it cleaned.
|
|
40
|
+
|
|
41
|
+
If ``state`` (a state name) is given, the GSTIN's state must match it, because the
|
|
42
|
+
CGST/SGST vs IGST split depends on the place of supply.
|
|
43
|
+
"""
|
|
44
|
+
g = clean(gstin)
|
|
45
|
+
if not GSTIN_RE.match(g) or g[:2] not in STATE_CODES:
|
|
46
|
+
raise GSTINError("Not a valid GSTIN (15 characters, e.g. 27AAAAA0000A1Z2)")
|
|
47
|
+
if check_digit(g) != g[14]:
|
|
48
|
+
raise GSTINError("GSTIN fails the check digit; please re-check it")
|
|
49
|
+
if state is not None:
|
|
50
|
+
gst_state = STATE_CODES[g[:2]]
|
|
51
|
+
if state.strip().lower() != gst_state.lower():
|
|
52
|
+
raise GSTINError(f"GSTIN is registered in {gst_state}, not {state}")
|
|
53
|
+
return g
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def state_of(gstin: str) -> str:
|
|
57
|
+
"""Return the state name a valid GSTIN is registered in."""
|
|
58
|
+
return STATE_CODES[validate(gstin)[:2]]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pan_of(gstin: str) -> str:
|
|
62
|
+
"""Return the 10-character PAN embedded in a valid GSTIN."""
|
|
63
|
+
return validate(gstin)[2:12]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Build a GSTR-1 style sales register, HSN summary and CA checks from plain invoice data.
|
|
2
|
+
|
|
3
|
+
Input is plain dicts, so it works with any database or framework.
|
|
4
|
+
|
|
5
|
+
Invoice dict::
|
|
6
|
+
|
|
7
|
+
{
|
|
8
|
+
"invoice_no": "INV-001", "invoice_date": "2026-11-02",
|
|
9
|
+
"customer": "Asha Traders", "gstin": "27AAAAA0000A1Z2", # gstin optional (B2C if empty)
|
|
10
|
+
"place_of_supply": "Maharashtra", # state name; defaults to seller state
|
|
11
|
+
"amount_paid": 1180.0, "status": "paid", # optional
|
|
12
|
+
"lines": [{"name": "Wardrobe", "hsn": "9403", "qty": 1, "gst_pct": 18, "amount": 1180.0}],
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
Payment dict (optional)::
|
|
16
|
+
|
|
17
|
+
{"receipt_no": "R-1", "date": "2026-11-01", "invoice_no": "INV-001", "customer": "Asha Traders",
|
|
18
|
+
"method": "upi", "reference": "UTR123", "amount": 500.0, "advance": True}
|
|
19
|
+
"""
|
|
20
|
+
from typing import Iterable, Optional
|
|
21
|
+
|
|
22
|
+
from .gstin import GSTINError, validate
|
|
23
|
+
from .states import STATE_CODES
|
|
24
|
+
from .tax import split
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _r(x) -> float:
|
|
28
|
+
return round(float(x or 0) + 0.0, 2)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_register(invoices: Iterable[dict], seller_state: str, payments: Optional[Iterable[dict]] = None,
|
|
32
|
+
refunds: Optional[Iterable[dict]] = None, inclusive: bool = True,
|
|
33
|
+
period: Optional[tuple] = None) -> dict:
|
|
34
|
+
"""Return {"summary", "invoices", "lines", "hsn", "payments", "refunds", "checks"}.
|
|
35
|
+
|
|
36
|
+
``invoices`` rows in the result are one per invoice per GST rate (the GSTR-1 shape).
|
|
37
|
+
``inclusive`` says whether line amounts include GST.
|
|
38
|
+
"""
|
|
39
|
+
rows, lines, hsn, checks = [], [], {}, []
|
|
40
|
+
for inv in invoices:
|
|
41
|
+
no = inv["invoice_no"]
|
|
42
|
+
gstin = (inv.get("gstin") or "").strip()
|
|
43
|
+
pos = inv.get("place_of_supply") or seller_state
|
|
44
|
+
if gstin:
|
|
45
|
+
try:
|
|
46
|
+
gstin = validate(gstin)
|
|
47
|
+
gst_state = STATE_CODES[gstin[:2]]
|
|
48
|
+
if gst_state.lower() != pos.lower():
|
|
49
|
+
checks.append(("GSTIN state differs from place of supply", no,
|
|
50
|
+
f"GSTIN {gstin} is in {gst_state}, place of supply is {pos}"))
|
|
51
|
+
except GSTINError as e:
|
|
52
|
+
checks.append(("Invalid customer GSTIN", no, str(e)))
|
|
53
|
+
b2b = bool(gstin)
|
|
54
|
+
by_rate = {}
|
|
55
|
+
for ln in inv.get("lines", []):
|
|
56
|
+
t = split(ln["amount"], ln["gst_pct"], seller_state, pos, inclusive=inclusive).as_dict()
|
|
57
|
+
r = by_rate.setdefault(ln["gst_pct"], {"taxable": 0, "cgst": 0, "sgst": 0, "igst": 0, "total": 0})
|
|
58
|
+
for k in r:
|
|
59
|
+
r[k] += t[k]
|
|
60
|
+
lines.append({"invoice_no": no, "invoice_date": inv.get("invoice_date", ""), "item": ln.get("name", ""),
|
|
61
|
+
"hsn": ln.get("hsn") or "", "qty": ln.get("qty", 1), "gst_pct": ln["gst_pct"], **t})
|
|
62
|
+
key = (ln.get("hsn") or "MISSING", ln["gst_pct"])
|
|
63
|
+
h = hsn.setdefault(key, {"hsn": key[0], "gst_pct": key[1], "lines": 0, "qty": 0,
|
|
64
|
+
"taxable": 0, "cgst": 0, "sgst": 0, "igst": 0, "total": 0})
|
|
65
|
+
h["lines"] += 1
|
|
66
|
+
h["qty"] += float(ln.get("qty", 1) or 0)
|
|
67
|
+
for k in ("taxable", "cgst", "sgst", "igst", "total"):
|
|
68
|
+
h[k] += t[k]
|
|
69
|
+
if not ln.get("hsn"):
|
|
70
|
+
checks.append(("HSN missing", no, f"'{ln.get('name', '')}' has no HSN/SAC code"))
|
|
71
|
+
line_sum = sum(r["total"] for r in by_rate.values())
|
|
72
|
+
value = _r(inv.get("invoice_value", line_sum))
|
|
73
|
+
round_off = _r(value - line_sum)
|
|
74
|
+
top = max(by_rate) if by_rate else None
|
|
75
|
+
for rate, r in sorted(by_rate.items()):
|
|
76
|
+
rows.append({"invoice_no": no, "invoice_date": inv.get("invoice_date", ""), "type": "B2B" if b2b else "B2C",
|
|
77
|
+
"customer": inv.get("customer", ""), "gstin": gstin, "place_of_supply": pos, "gst_pct": rate,
|
|
78
|
+
**{k: _r(v) for k, v in r.items()}, "round_off": round_off if rate == top else 0.0,
|
|
79
|
+
"invoice_value": value, "paid_so_far": _r(inv.get("amount_paid", 0)),
|
|
80
|
+
"status": inv.get("status", "")})
|
|
81
|
+
if "amount_paid" in inv and _r(inv["amount_paid"]) < value - 1:
|
|
82
|
+
checks.append(("Invoice not fully paid", no, f"Paid {round(inv['amount_paid'])} of {round(value)}"))
|
|
83
|
+
|
|
84
|
+
pays = [dict(p) for p in (payments or [])]
|
|
85
|
+
for p in pays:
|
|
86
|
+
p["amount"] = _r(p.get("amount"))
|
|
87
|
+
if p.get("advance"):
|
|
88
|
+
checks.append(("Advance received before tax invoice", p.get("invoice_no") or p.get("receipt_no", ""),
|
|
89
|
+
f"Rs {round(p['amount'])} on {p.get('date', '')}: check GST on advances"))
|
|
90
|
+
refs = [dict(r) for r in (refunds or [])]
|
|
91
|
+
for r in refs:
|
|
92
|
+
if r.get("invoice_no"):
|
|
93
|
+
checks.append(("Cancelled after tax invoice", r["invoice_no"], "A credit note may be needed"))
|
|
94
|
+
|
|
95
|
+
def tot(items, k):
|
|
96
|
+
return _r(sum(i.get(k, 0) for i in items))
|
|
97
|
+
|
|
98
|
+
summary = {
|
|
99
|
+
"from": period[0] if period else "", "to": period[1] if period else "",
|
|
100
|
+
"invoices": len({i["invoice_no"] for i in rows}),
|
|
101
|
+
"b2b": len({i["invoice_no"] for i in rows if i["type"] == "B2B"}),
|
|
102
|
+
"taxable": tot(rows, "taxable"), "cgst": tot(rows, "cgst"), "sgst": tot(rows, "sgst"), "igst": tot(rows, "igst"),
|
|
103
|
+
"invoice_value": _r(sum({i["invoice_no"]: i["invoice_value"] for i in rows}.values())),
|
|
104
|
+
"payments": len(pays), "received": tot(pays, "amount"),
|
|
105
|
+
"advances": _r(sum(p["amount"] for p in pays if p.get("advance"))),
|
|
106
|
+
"refunds": len(refs), "checks": len(checks),
|
|
107
|
+
}
|
|
108
|
+
hsn_rows = [{**v, **{k: _r(v[k]) for k in ("taxable", "cgst", "sgst", "igst", "total")}}
|
|
109
|
+
for v in sorted(hsn.values(), key=lambda x: (x["hsn"], x["gst_pct"]))]
|
|
110
|
+
return {"summary": summary, "invoices": rows, "lines": lines, "hsn": hsn_rows, "payments": pays,
|
|
111
|
+
"refunds": refs, "checks": [{"check": c[0], "document": c[1], "detail": c[2]} for c in checks]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""GST state codes (first two digits of a GSTIN)."""
|
|
2
|
+
|
|
3
|
+
STATE_CODES = {
|
|
4
|
+
"01": "Jammu and Kashmir", "02": "Himachal Pradesh", "03": "Punjab", "04": "Chandigarh",
|
|
5
|
+
"05": "Uttarakhand", "06": "Haryana", "07": "Delhi", "08": "Rajasthan", "09": "Uttar Pradesh",
|
|
6
|
+
"10": "Bihar", "11": "Sikkim", "12": "Arunachal Pradesh", "13": "Nagaland", "14": "Manipur",
|
|
7
|
+
"15": "Mizoram", "16": "Tripura", "17": "Meghalaya", "18": "Assam", "19": "West Bengal",
|
|
8
|
+
"20": "Jharkhand", "21": "Odisha", "22": "Chhattisgarh", "23": "Madhya Pradesh", "24": "Gujarat",
|
|
9
|
+
"26": "Dadra and Nagar Haveli and Daman and Diu", "27": "Maharashtra", "29": "Karnataka",
|
|
10
|
+
"30": "Goa", "31": "Lakshadweep", "32": "Kerala", "33": "Tamil Nadu", "34": "Puducherry",
|
|
11
|
+
"35": "Andaman and Nicobar Islands", "36": "Telangana", "37": "Andhra Pradesh", "38": "Ladakh",
|
|
12
|
+
"97": "Other Territory",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
_BY_NAME = {v.lower(): k for k, v in STATE_CODES.items()}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def state_name(code: str) -> str:
|
|
19
|
+
"""Return the state name for a two-digit GST state code. Raises KeyError if unknown."""
|
|
20
|
+
return STATE_CODES[code]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def state_code(name: str) -> str:
|
|
24
|
+
"""Return the two-digit GST state code for a state name (case-insensitive). Raises KeyError if unknown."""
|
|
25
|
+
return _BY_NAME[name.strip().lower()]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Split a line amount into taxable value and CGST/SGST or IGST."""
|
|
2
|
+
from dataclasses import asdict, dataclass
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class TaxSplit:
|
|
7
|
+
taxable: float
|
|
8
|
+
cgst: float
|
|
9
|
+
sgst: float
|
|
10
|
+
igst: float
|
|
11
|
+
total: float
|
|
12
|
+
|
|
13
|
+
def as_dict(self) -> dict:
|
|
14
|
+
return asdict(self)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _r(x: float) -> float:
|
|
18
|
+
return round(float(x or 0) + 0.0, 2)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def split(amount: float, gst_pct: float, seller_state: str, place_of_supply: str,
|
|
22
|
+
inclusive: bool = True) -> TaxSplit:
|
|
23
|
+
"""Split one line.
|
|
24
|
+
|
|
25
|
+
- Same state (intra-state supply): CGST + SGST, half each.
|
|
26
|
+
- Different state (inter-state supply): IGST.
|
|
27
|
+
- ``inclusive=True`` means ``amount`` already includes GST (typical for B2C prices).
|
|
28
|
+
"""
|
|
29
|
+
rate = float(gst_pct) / 100
|
|
30
|
+
if inclusive:
|
|
31
|
+
taxable = amount / (1 + rate)
|
|
32
|
+
else:
|
|
33
|
+
taxable = float(amount)
|
|
34
|
+
tax = taxable * rate
|
|
35
|
+
if seller_state.strip().lower() == place_of_supply.strip().lower():
|
|
36
|
+
half = tax / 2
|
|
37
|
+
return TaxSplit(_r(taxable), _r(half), _r(half), 0.0, _r(taxable + tax))
|
|
38
|
+
return TaxSplit(_r(taxable), 0.0, 0.0, _r(tax), _r(taxable + tax))
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from india_gst import GSTINError, build_register, check_digit, is_valid, pan_of, split, state_code, state_of, validate
|
|
4
|
+
|
|
5
|
+
GOOD = "27AAAAA0000A1Z2" # made-up sample GSTIN (Maharashtra); not a real business
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_valid_gstin():
|
|
9
|
+
assert is_valid(GOOD)
|
|
10
|
+
assert validate(" 27aaaaa0000a1z2 ") == GOOD
|
|
11
|
+
assert state_of(GOOD) == "Maharashtra"
|
|
12
|
+
assert pan_of(GOOD) == "AAAAA0000A"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_bad_check_digit():
|
|
16
|
+
bad = GOOD[:14] + ("A" if GOOD[14] != "A" else "B")
|
|
17
|
+
assert not is_valid(bad)
|
|
18
|
+
with pytest.raises(GSTINError):
|
|
19
|
+
validate(bad)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_check_digit_roundtrip():
|
|
23
|
+
assert check_digit(GOOD[:14]) == GOOD[14]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_state_mismatch():
|
|
27
|
+
with pytest.raises(GSTINError):
|
|
28
|
+
validate(GOOD, state="Gujarat")
|
|
29
|
+
assert validate(GOOD, state="maharashtra") == GOOD
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_state_code():
|
|
33
|
+
assert state_code("Gujarat") == "24"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_split_intra_state_inclusive():
|
|
37
|
+
t = split(1180, 18, "Gujarat", "Gujarat")
|
|
38
|
+
assert (t.taxable, t.cgst, t.sgst, t.igst, t.total) == (1000.0, 90.0, 90.0, 0.0, 1180.0)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_split_inter_state_exclusive():
|
|
42
|
+
t = split(1000, 12, "Gujarat", "Maharashtra", inclusive=False)
|
|
43
|
+
assert (t.taxable, t.igst, t.cgst, t.total) == (1000.0, 120.0, 0.0, 1120.0)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_register():
|
|
47
|
+
invoices = [
|
|
48
|
+
{"invoice_no": "INV-1", "invoice_date": "2026-11-02", "customer": "Sample Buyer LLP", "gstin": GOOD,
|
|
49
|
+
"place_of_supply": "Maharashtra", "amount_paid": 500,
|
|
50
|
+
"lines": [{"name": "Wardrobe", "hsn": "9403", "qty": 1, "gst_pct": 18, "amount": 1180},
|
|
51
|
+
{"name": "Fitting", "hsn": "", "qty": 1, "gst_pct": 12, "amount": 112}]},
|
|
52
|
+
{"invoice_no": "INV-2", "invoice_date": "2026-11-03", "customer": "Walk-in",
|
|
53
|
+
"lines": [{"name": "Lamp", "hsn": "9405", "qty": 2, "gst_pct": 18, "amount": 590}]},
|
|
54
|
+
]
|
|
55
|
+
payments = [{"receipt_no": "R-1", "date": "2026-11-01", "invoice_no": "INV-1", "amount": 500, "advance": True}]
|
|
56
|
+
reg = build_register(invoices, seller_state="Gujarat", payments=payments, period=("2026-11-01", "2026-11-30"))
|
|
57
|
+
s = reg["summary"]
|
|
58
|
+
assert s["invoices"] == 2 and s["b2b"] == 1
|
|
59
|
+
assert s["igst"] == 192.0 and s["cgst"] == 45.0
|
|
60
|
+
assert s["invoice_value"] == 1882.0
|
|
61
|
+
kinds = {c["check"] for c in reg["checks"]}
|
|
62
|
+
assert {"HSN missing", "Invoice not fully paid", "Advance received before tax invoice"} <= kinds
|
|
63
|
+
assert any(h["hsn"] == "MISSING" for h in reg["hsn"])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_excel():
|
|
67
|
+
pytest.importorskip("openpyxl")
|
|
68
|
+
from india_gst.excel import to_xlsx
|
|
69
|
+
reg = build_register([{"invoice_no": "A", "lines": [{"name": "x", "hsn": "1", "gst_pct": 5, "amount": 105}]}], "Gujarat")
|
|
70
|
+
data = to_xlsx(reg, seller_name="Example Co")
|
|
71
|
+
assert data[:2] == b"PK"
|