India GST split
BodyPicks the tax head from the place of supply against the state code in the supplier's GSTIN, never from the billing address or a typed state name: the same state gets CGST plus SGST (UTGST in a Union Territory without a legislature) at half the rate each, a different state gets IGST at the full rate. Supplies to an SEZ and exports are always inter-state; under a letter of undertaking they carry IGST at nil and the Rule 46 mention. Each half is rounded to the paisa on its own, so an odd paisa can make CGST plus SGST differ from IGST on the same base, which is correct. Prints place of supply as 'State (code)', the mandatory 'Reverse charge: Yes/No', an HSN/SAC-wise summary, the round-off to the nearest rupee, and the total in words in lakh and crore. Under reverse charge the tax is shown but not added to the amount payable. All of it is worked out by a deriver that ships with it.
npx dxcl add india-gst-split Preview data
the JSON this preview was built with{
"seller": {
"gstin": "26AAACR5055K1Z5",
"stateCode": "26"
},
"placeOfSupply": {
"stateCode": "26",
"stateName": "Dadra and Nagar Haveli and Daman and Diu"
},
"customer": {
"isSez": false
},
"supply": {
"exportUnderLut": false,
"reverseCharge": false
},
"lines": [
{
"hsnSac": "84714190",
"taxableMinor": 12345678950,
"rate": 18
},
{
"hsnSac": "998314",
"taxableMinor": 4567890125,
"rate": 18
},
{
"hsnSac": "84714190",
"taxableMinor": 9999999,
"rate": 18
},
{
"hsnSac": "30049099",
"taxableMinor": 234567891,
"rate": 5
},
{
"hsnSac": "71023910",
"taxableMinor": 9876543,
"rate": 0.25
}
]
} Rendered preview
the component rendered on its ownResolved nodes
what a renderer receives — 1 nodesindia-gst-split section The files
what installing writes; the selected file is the componentnodes/india-gst-split.node.tsx import { Cell, type Nodes, Paragraph, Row, Section, Table, useDeriver, useState } from "docxcelerate/template";
import indiaGstSplit from "../derivers/india-gst-split.deriver.ts";
/**
* The GST block of an Indian tax invoice: place of supply, the reverse-charge
* declaration, the HSN/SAC-wise tax summary under the right tax heads, the
* round-off, the total payable and that total in words.
*
* Decisions already made for you:
*
* - The tax head comes from comparing two state codes: the supplier's, read
* from the first two digits of its GSTIN, and the place of supply. The
* billing address and any typed state name play no part.
* - The same code gets CGST plus SGST at half the rate each, or CGST plus UTGST
* in a Union Territory without a legislature (Delhi, Jammu and Kashmir and
* Puducherry have one, so they get SGST). A different code gets IGST at the
* full rate.
* - A supply to an SEZ, or an export (place-of-supply code 96), is always
* inter-state. Under a letter of undertaking it carries IGST at nil and the
* Rule 46 "without payment of integrated tax" mention; without one it carries
* IGST at the full rate and the "on payment" mention.
* - Each half of an intra-state tax is rounded to the paisa on its own, so an
* odd paisa makes CGST plus SGST differ by one paisa from IGST on the same
* base. That is correct; the base is never split after rounding.
* - "Reverse charge: Yes/No" always prints. Under reverse charge the tax is
* shown but left out of the amount payable.
* - The total is rounded to the nearest rupee on its own visible line, and is
* written in lakh and crore, never million and billion.
*
* Everything is decided in one deriver, because GSTIN prefixes, grouping, sums
* and rounding cannot be computed from request data at publish time. The node
* only picks a table and interpolates finished strings.
*
* Not checked: the GSTIN check digit, whether a GSTIN is live, whether the rate
* is the right one for the HSN code, and whether the LUT is current.
*
* Installed by `dxcl add india-gst-split`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface IndiaGstSplitData {
seller: {
/**
* The supplier's GSTIN, 15 characters. Trimmed and upper-cased, then
* printed by nothing here: its first two digits are the supplier's state
* code, and that is the only state this component believes. Required:
* the deriver throws when it is missing, not 15 characters of [0-9A-Z],
* or does not start with a known state code (01 to 38, or 97). An
* unregistered supplier cannot charge GST, so there is no fallback.
*/
gstin: string;
/**
* The supplier's state code as your system holds it, two digits: "27".
* Optional, and only a cross-check: when given and it differs from the
* GSTIN's first two digits, the deriver throws rather than pick one.
*/
stateCode?: string;
};
placeOfSupply: {
/**
* Two-digit GST state code of the place of supply: "27", "07", or "96"
* for a supply outside India (an export). Required: throws when missing
* or not one of 01 to 38, 96 or 97. A number such as 7 is not accepted;
* pass "07".
*/
stateCode: string;
/**
* The state's name as it should print: "Maharashtra". Printed as
* "Maharashtra (27)". Trimmed. Required: throws when missing or blank,
* because Rule 46 makes the place of supply mandatory. Never used to
* decide anything.
*/
stateName: string;
};
/** Missing entirely means "not an SEZ". */
customer?: {
/**
* Whether the recipient is an SEZ unit or developer receiving for
* authorised operations. True makes the supply inter-state whatever the
* state codes say. Missing or anything but `true` means false. Throws
* with place of supply "96": an SEZ is in India.
*/
isSez?: boolean;
};
supply: {
/**
* Whether this zero-rated supply (an export or a supply to an SEZ) is
* made under a bond or letter of undertaking without payment of IGST.
* True prints IGST at nil with the LUT mention. Missing means false.
* Throws when true on a supply that is neither an export nor to an SEZ,
* because that would print nil tax on a taxable domestic supply.
*/
exportUnderLut?: boolean;
/**
* Whether tax is payable by the recipient on reverse charge. Printed as
* "Reverse charge: Yes" or "No" on every invoice. True shows the tax but
* leaves it out of the amount payable. Required, and must be a boolean:
* the deriver throws when it is missing, because the field is mandatory
* and guessing "No" is how it goes wrong.
*/
reverseCharge: boolean;
};
/**
* The invoice's lines, as far as tax is concerned. At least one is
* required: an empty or missing list throws. Lines sharing an HSN/SAC
* code and a rate are summed into one summary row.
*/
lines: Array<{
/**
* The HSN (goods) or SAC (services) code, digits only, 4, 6 or 8 long:
* "84714190", "998314". Trimmed. Throws otherwise, including when a code
* was stored as a number and lost its leading zero.
*/
hsnSac: string;
/**
* The line's taxable value in paise, an integer: 1234550 is
* ₹12,345.50. Negative is allowed (a discount line, or a credit note) and
* is taxed as the mirror image of its positive. Throws when it is not a
* safe integer.
*/
taxableMinor: number;
/**
* The full GST rate in percent, 0 or above, at most two decimal places:
* 18, 5, 0.25, 0, 40. Not checked against a list of slabs, because the
* slabs change. Throws when negative, not finite, or with a third
* decimal place.
*/
rate: number;
}>;
}
/** The GST block of an Indian tax invoice, decided from the place of supply. */
export const IndiaGstSplit: Nodes = async () => {
const [seller] = useState((data: IndiaGstSplitData) => data.seller);
const [placeOfSupply] = useState((data: IndiaGstSplitData) => data.placeOfSupply);
const [customer] = useState((data: IndiaGstSplitData) => data.customer);
const [supply] = useState((data: IndiaGstSplitData) => data.supply);
const [lines] = useState((data: IndiaGstSplitData) => data.lines);
// After every other hook; it runs for every invoice and has no placeholder.
const split = await useDeriver(indiaGstSplit, [seller, placeOfSupply, customer, supply, lines]);
return (
<Section id="india-gst-split" title="GST summary">
<Paragraph id="gst-split-place-of-supply">Place of supply: {split.placeOfSupply}</Paragraph>
<Paragraph id="gst-split-reverse-charge">Reverse charge: {split.reverseCharge}</Paragraph>
{split.intraState
? (
<Table
id="gst-split-intra"
columns={[
{ width: 20 },
{ width: "auto", align: "right" },
{ width: 13, align: "right" },
{ width: "auto", align: "right" },
{ width: 13, align: "right" },
{ width: "auto", align: "right" },
{ width: "auto", align: "right" },
]}
>
<Row id="gst-split-intra-header" header>
<Cell>HSN/SAC</Cell>
<Cell>Taxable value</Cell>
<Cell>CGST rate</Cell>
<Cell>CGST</Cell>
<Cell>{split.stateTaxLabel} rate</Cell>
<Cell>{split.stateTaxLabel}</Cell>
<Cell>Total tax</Cell>
</Row>
{split.rows.map((row) => (
<Row id="gst-split-intra-row">
<Cell>{row.hsnSac}</Cell>
<Cell>{row.taxable}</Cell>
<Cell>{row.halfRate}</Cell>
<Cell>{row.centralTax}</Cell>
<Cell>{row.halfRate}</Cell>
<Cell>{row.stateTax}</Cell>
<Cell>{row.totalTax}</Cell>
</Row>
))}
<Row id="gst-split-intra-total">
<Cell>Total</Cell>
<Cell>{split.taxableTotal}</Cell>
<Cell>{""}</Cell>
<Cell>{split.centralTaxTotal}</Cell>
<Cell>{""}</Cell>
<Cell>{split.stateTaxTotal}</Cell>
<Cell>{split.taxTotal}</Cell>
</Row>
</Table>
)
: (
<Table
id="gst-split-inter"
columns={[{ width: 20 }, { width: "auto", align: "right" }, { width: 16, align: "right" }, {
width: "auto",
align: "right",
}]}
>
<Row id="gst-split-inter-header" header>
<Cell>HSN/SAC</Cell>
<Cell>Taxable value</Cell>
<Cell>IGST rate</Cell>
<Cell>IGST</Cell>
</Row>
{split.rows.map((row) => (
<Row id="gst-split-inter-row">
<Cell>{row.hsnSac}</Cell>
<Cell>{row.taxable}</Cell>
<Cell>{row.rate}</Cell>
<Cell>{row.integratedTax}</Cell>
</Row>
))}
<Row id="gst-split-inter-total">
<Cell>Total</Cell>
<Cell>{split.taxableTotal}</Cell>
<Cell>{""}</Cell>
<Cell>{split.integratedTaxTotal}</Cell>
</Row>
</Table>
)}
{split.zeroRatedMention && <Paragraph id="gst-split-zero-rated">{split.zeroRatedMention}</Paragraph>}
{split.reverseChargeNote && (
<Paragraph id="gst-split-reverse-charge-note">{split.reverseChargeNote}</Paragraph>
)}
<Paragraph id="gst-split-round-off">Round off: {split.roundOff}</Paragraph>
<Paragraph id="gst-split-grand-total">Total amount payable: {split.grandTotal}</Paragraph>
<Paragraph id="gst-split-in-words">Amount in words: {split.grandTotalInWords}</Paragraph>
</Section>
);
}; derivers/india-gst-split.deriver.ts import { deriver } from "docxcelerate/template";
/**
* Works out the whole GST block of an Indian tax invoice. Installed by
* `dxcl add india-gst-split`.
*
* It is self-contained on purpose: it travels to the engine as source text, so
* a module-level constant or helper would be a ReferenceError there. The state
* codes, the number-to-words function and the formatters live inside `run`.
* Money is integer paise throughout; no step multiplies a rounded figure.
*/
export default deriver({
name: "indiaGstSplit",
run: (seller: unknown, placeOfSupply: unknown, customer: unknown, supply: unknown, lines: unknown) => {
// deno-lint-ignore no-explicit-any
const sel = seller as any;
// deno-lint-ignore no-explicit-any
const pos = placeOfSupply as any;
// deno-lint-ignore no-explicit-any
const cus = customer as any;
// deno-lint-ignore no-explicit-any
const sup = supply as any;
// deno-lint-ignore no-explicit-any
const items = lines as any;
const validCode = (code: string) => {
const n = Number(code);
return /^\d{2}$/.test(code) && ((n >= 1 && n <= 38) || n === 97);
};
if (typeof sel?.gstin !== "string") throw new Error("seller.gstin must be a 15-character GSTIN");
const gstin = sel.gstin.trim().toUpperCase();
if (!/^[0-9A-Z]{15}$/.test(gstin)) throw new Error("seller.gstin must be a 15-character GSTIN");
const supplierCode = gstin.slice(0, 2);
if (!validCode(supplierCode)) throw new Error("seller.gstin must start with a known state code");
if (sel.stateCode !== undefined && sel.stateCode !== supplierCode) {
throw new Error("seller.stateCode does not match the state code in seller.gstin");
}
const posCode = pos?.stateCode;
if (typeof posCode !== "string" || !(validCode(posCode) || posCode === "96")) {
throw new Error("placeOfSupply.stateCode must be a two-digit state code (01 to 38, 96 or 97)");
}
if (typeof pos.stateName !== "string" || pos.stateName.trim() === "") {
throw new Error("placeOfSupply.stateName is required");
}
const sez = cus?.isSez === true;
const export_ = posCode === "96";
if (sez && export_) throw new Error("customer.isSez cannot be true with place of supply 96");
const zeroRated = sez || export_;
if (typeof sup?.reverseCharge !== "boolean") throw new Error("supply.reverseCharge must be a boolean");
const reverseCharge: boolean = sup.reverseCharge;
const lut = sup.exportUnderLut === true;
if (lut && !zeroRated) {
throw new Error("supply.exportUnderLut applies only to an export or a supply to an SEZ");
}
if (!Array.isArray(items) || items.length === 0) throw new Error("lines must have at least one line");
const intraState = !zeroRated && supplierCode === posCode;
const stateTaxLabel = !intraState
? ""
: ["04", "25", "26", "31", "35", "38", "97"].includes(posCode)
? "UTGST"
: "SGST";
const groups = new Map<string, { hsnSac: string; rate: number; taxable: number }>();
for (const [i, line] of items.entries()) {
const hsnSac = typeof line?.hsnSac === "string" ? line.hsnSac.trim() : "";
if (!/^(\d{4}|\d{6}|\d{8})$/.test(hsnSac)) {
throw new Error(`lines[${i}].hsnSac must be a 4, 6 or 8 digit HSN/SAC code`);
}
if (!Number.isSafeInteger(line.taxableMinor)) {
throw new Error(`lines[${i}].taxableMinor must be an integer number of paise`);
}
const rate = line.rate;
if (
typeof rate !== "number" || !Number.isFinite(rate) || rate < 0 ||
Math.abs(rate * 100 - Math.round(rate * 100)) > 1e-6
) {
throw new Error(`lines[${i}].rate must be 0 or more, with at most two decimal places`);
}
const key = hsnSac + "|" + rate;
const group = groups.get(key);
if (group) group.taxable += line.taxableMinor;
else groups.set(key, { hsnSac, rate, taxable: line.taxableMinor });
if (!Number.isSafeInteger(groups.get(key)!.taxable)) throw new Error(`lines[${i}] overflows the safe integer range`);
}
// Half away from zero, so a credit note mirrors its invoice. `+ 0` drops -0.
const roundDiv = (n: number, d: number) => Math.sign(n) * Math.floor((Math.abs(n) + d / 2) / d) + 0;
const money = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
const signed = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", signDisplay: "exceptZero" });
const fmt = (paise: number) => money.format(paise / 100);
let taxableSum = 0;
let centralSum = 0;
let stateSum = 0;
let integratedSum = 0;
const rows = [...groups.values()].map((g) => {
const bp = Math.round(g.rate * 100);
const n = g.taxable * bp;
if (Math.abs(n) > Number.MAX_SAFE_INTEGER) throw new Error(`tax on ${g.hsnSac} overflows the safe integer range`);
// Each half is rounded on its own; the base is never split after rounding.
const half = intraState ? roundDiv(n, 20000) : 0;
const igst = intraState || lut ? 0 : roundDiv(n, 10000);
taxableSum += g.taxable;
centralSum += half;
stateSum += half;
integratedSum += igst;
return {
hsnSac: g.hsnSac,
taxable: fmt(g.taxable),
rate: lut ? "Nil" : bp / 100 + "%",
halfRate: intraState ? bp / 200 + "%" : "",
centralTax: intraState ? fmt(half) : "",
stateTax: intraState ? fmt(half) : "",
integratedTax: intraState ? "" : fmt(igst),
totalTax: fmt(intraState ? half * 2 : igst),
};
});
const taxSum = centralSum + stateSum + integratedSum;
const unrounded = taxableSum + (reverseCharge ? 0 : taxSum);
const grand = roundDiv(unrounded, 100) * 100;
const ones = [
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
"Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
];
const tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
const words = (n: number): string => {
if (n === 0) return "Zero";
if (n < 20) return ones[n];
if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? " " + ones[n % 10] : "");
const [unit, name] = n >= 1e7
? [1e7, "Crore"]
: n >= 1e5
? [1e5, "Lakh"]
: n >= 1e3
? [1e3, "Thousand"]
: [100, "Hundred"];
const rest = n % unit;
return words(Math.floor(n / unit)) + " " + name + (rest ? " " + words(rest) : "");
};
const taxTotal = fmt(taxSum);
const zeroRatedMention = !zeroRated
? ""
: (export_ ? "SUPPLY MEANT FOR EXPORT" : "SUPPLY TO SEZ UNIT OR SEZ DEVELOPER FOR AUTHORISED OPERATIONS") +
(lut ? " UNDER BOND OR LETTER OF UNDERTAKING WITHOUT PAYMENT OF INTEGRATED TAX" : " ON PAYMENT OF INTEGRATED TAX");
return {
intraState,
stateTaxLabel,
placeOfSupply: pos.stateName.trim() + " (" + posCode + ")",
reverseCharge: reverseCharge ? "Yes" : "No",
zeroRatedMention,
reverseChargeNote: reverseCharge
? `Tax of ${taxTotal} is payable by the recipient under reverse charge and is not included in the amount payable.`
: "",
rows,
taxableTotal: fmt(taxableSum),
centralTaxTotal: fmt(centralSum),
stateTaxTotal: fmt(stateSum),
integratedTaxTotal: fmt(integratedSum),
taxTotal,
roundOff: signed.format((grand - unrounded) / 100),
grandTotal: fmt(grand),
grandTotalInWords: (grand < 0 ? "Minus " : "") + "Rupees " + words(Math.abs(grand) / 100) + " Only",
};
},
});