BT San Technology

16 February 2026

A preliminary price estimator on the website: calculating so customers understand the conditions

27 min read · Websites and web apps

Illustration: a tablet showing machine and tool icons beside a laptop with adjustment sliders and a finger pointing at the screen
AI-generated illustration

A customer visits a print shop's website, enters 99 pieces and sees a price of 1,485 baht. They change it to 100 pieces and the price drops to 1,200 baht. They call to ask whether the website calculated it wrong. In another case, the sales team opens a quotation sent three months ago and recalculates it, but gets a different number because someone changed a price in the formula. And on some days a customer selects two options that cannot be produced together, and the website still calculates a price as usual.

A price calculator on a website looks like a simple form, but inside it holds business rules written as code. If the rules are unclear, people can argue about the numbers forever. This article builds a small calculator in TypeScript that Node 24 runs directly, with nothing to install. It covers quantity price tiers, conflicting options, a minimum order amount, a rush fee, shipping, stacked discounts, rounding to satang, 7% VAT and price ranges. Every line of the output carries a reason in Thai, so the customer and the sales team see the same list.

The real problem: the number on the website must be explainable and reproducible

Three hypothetical situations, not any customer's project.

  • Sticker print shop: the price per piece drops once an order reaches 100 pieces, so a customer who orders 99 pieces pays more than one who orders 100. If the website does not say which price tier it used, the customer will think the system is broken. It helps if the website offers to raise the order to 100 pieces.
  • Signage and installation shop: the rush fee is a percentage of the job amount, and the member discount and the promo code can be used together. If nobody agrees on the order and a cap, the two discounts can add up to less than cost, and each salesperson calculates a different number.
  • Parts manufacturer that offers a preliminary price estimate: a quotation that has already been sent must be able to confirm the original numbers, even after material prices have changed. When a customer asks why it does not match the website from last month, sales must be able to open the rules of that day.

All three are solved by the same principle: move the rules out of the code into a data file that has a version and an effective date. Make the calculator a function whose result depends only on the input and the rules. Store money as integer satang, validate the input strictly before pricing, and attach a reason to every line.

Facts to know before writing the rules: tax and rounding

TopicWhat the source saysEffect on our code
VAT rateThe Revenue Department states that the current rate is 7 percentKeep the rate in the rules file, not in the code, because the rate can change by announcement
Discount and tax baseThe Revenue Department states that a discount or deduction reduces the tax base when it is shown clearly on the tax invoiceShow the discount as a clearly visible negative line, and calculate VAT on the amount after the discount
Half roundingMDN states that Math.round rounds a value with a fraction of exactly 0.5 toward positive infinity, so negative values round toward zeroFine for amounts that are not negative; if an amount can be negative, write your own rounding rule
Exact integersMDN states that the largest safe integer is 9,007,199,254,740,991 and that Number.isSafeInteger is available to check itCheck the quantity with isSafeInteger and set a maximum quantity the business accepts
Fractions of a satangMartin Fowler writes that amounts are usually rounded to the smallest unit of the currency, and that rounded remainders can make money disappearUse integer satang and decide exactly where rounding happens
Input validationOWASP says to validate on the server even if the browser has already validated, to define what is accepted, and to reject a bad request with a clear message instead of continuing to calculate from data that was not fully checkedAlways validate first; if it fails, do not calculate a price
Summary of the documents cited at the end of the article, as read on 2026-11-21. The detailed rules for rounding and for showing prices on a tax invoice should be confirmed by your business's accountant.

The example assumes that the prices in the rules exclude VAT and that 7% VAT is shown as a separate line at the end of the list. If your shop shows prices that already include VAT, you must reverse the formula (divide the total by 1.07 to separate the tax base) and agree with your accountant where to round. Do not let two pages on the website use different meanings of the word "price".

Overview of the example

The code is in the folder examples/website-estimate-calculator-business-rules/. It uses only Node 24 built-ins, with no npm install and no network. TypeScript runs directly with node file.ts (Node only strips the types and does not type-check them, so it does not use enum or namespace, and imports are written with the .ts extension as the Node docs specify). The business in the example is a hypothetical sticker print shop, and all numbers are hypothetical.

FilePurpose
rules.jsonTwo versions of the pricing rules (2026-01 and 2026-07) with effective dates
money.tsMoney as integer satang, percentages rounded in one place, baht formatting
validate.tsValidates the input and returns a Thai error message for every problem
estimate.tsThe calculator: returns lines with reasons, VAT shown separately, and a price range
quotes.sample.json / demo.tsSample data covering normal, edge and invalid cases, and a script that prints the results
estimate.test.tsA node:test suite with 8 cases

Step 1: the rules live in one file, with a version and an effective date

The rules file keeps its versions as a list, one block per version, each with its own effectiveFrom. The price, price tiers, options, rush fee, shipping, discounts and VAT rate all live here. Version 2026-07 in the example raises prices and adds a minimum order amount, and does not touch version 2026-01 at all. So changing a price means adding a new version, not editing an old one. Old quotations can then be recalculated to the same result as before.

rules.json
{
  "versions": [
    {
      "version": "2026-01",
      "effectiveFrom": "2026-01-01",
      "vatBp": 700,
      "minChargeSatang": 30000,
      "materials": { "paper": "กระดาษ", "vinyl": "ไวนิลสติกเกอร์" },
      "tiers": [
        { "minQty": 1, "unitSatang": 1500 },
        { "minQty": 100, "unitSatang": 1200 },
        { "minQty": 500, "unitSatang": 900 }
      ],
      "options": {
        "lamination": { "label": "เคลือบลามิเนต", "perPieceSatang": 200, "requiresMaterial": "paper", "excludes": ["waterproof"] },
        "waterproof": { "label": "กันน้ำ", "perPieceSatang": 150, "requiresMaterial": "vinyl", "excludes": ["lamination"] },
        "foil": { "label": "ปั๊มฟอยล์", "perPieceSatang": 350, "requiresMaterial": "paper", "excludes": [] },
        "diecut": { "label": "ไดคัทตามรูป", "flatSatang": 50000, "excludes": [] }
      },
      "rush": { "rateBp": 2000, "capSatang": 100000 },
      "delivery": { "pickup": 0, "bkk": 12000, "central": 25000 },
      "freeDeliveryOverSatang": 500000,
      "discounts": {
        "memberBp": 500,
        "promo": { "SPRING10": { "rateBp": 1000, "capSatang": 50000 } },
        "totalCapBp": 2000
      }
    },
    {
      "version": "2026-07",
      "effectiveFrom": "2026-07-01",
      "vatBp": 700,
      "minChargeSatang": 35000,
      "materials": { "paper": "กระดาษ", "vinyl": "ไวนิลสติกเกอร์" },
      "tiers": [
        { "minQty": 1, "unitSatang": 1600 },
        { "minQty": 100, "unitSatang": 1250 },
        { "minQty": 500, "unitSatang": 950 }
      ],
      "options": {
        "lamination": { "label": "เคลือบลามิเนต", "perPieceSatang": 200, "requiresMaterial": "paper", "excludes": ["waterproof"] },
        "waterproof": { "label": "กันน้ำ", "perPieceSatang": 150, "requiresMaterial": "vinyl", "excludes": ["lamination"] },
        "foil": { "label": "ปั๊มฟอยล์", "perPieceSatang": 400, "requiresMaterial": "paper", "excludes": [] },
        "diecut": { "label": "ไดคัทตามรูป", "flatSatang": 50000, "excludes": [] }
      },
      "rush": { "rateBp": 2500, "capSatang": 100000 },
      "delivery": { "pickup": 0, "bkk": 12000, "central": 25000 },
      "freeDeliveryOverSatang": 500000,
      "discounts": {
        "memberBp": 500,
        "promo": { "SPRING10": { "rateBp": 1000, "capSatang": 50000 } },
        "totalCapBp": 2000
      }
    }
  ]
}
rules.json: two versions of the rules, differing in price tiers, minimum order amount, foil fee and rush fee rate

Selecting a version is easy because ISO dates can be compared as strings. A quotation stores its version number and date. The current prices are never applied to an old quotation. If the date is earlier than the first version, the system rejects it instead of guessing.

estimate.ts · lines 19–22
export function rulesFor(date: string, all: Rules[] = rulesFile.versions as Rules[]): Rules | null {
  const ok = all.filter((v) => v.effectiveFrom <= date).sort((a, b) => b.effectiveFrom.localeCompare(a.effectiveFrom));
  return ok[0] ?? null;
}
estimate.ts rulesFor: selects the latest version whose effective date is not later than the quotation date

Step 2: money as satang, rounding in one place

Floating-point decimals cannot store 0.1 exactly, so adding up many lines can drift. The example stores every amount as integer satang and every percentage as basis points (7% is 700). There is only one rounding function, which rounds half up. Every line the customer sees is therefore a whole number of satang, and the lines add up to exactly the total.

money.ts
// เงินทั้งหมดเป็นจำนวนเต็มหน่วยสตางค์ (satang) ไม่ใช้ทศนิยมลอยตัว
export type Satang = number;

// เปอร์เซ็นต์เก็บเป็น basis point (1% = 100 bp) ปัดครึ่งขึ้นที่นี่ที่เดียว
// simplified: ใช้ Math.round กับจำนวนไม่ติดลบเท่านั้น; ถ้ามียอดติดลบ ต้องกำหนดกฎปัดเอง
export function pct(amount: Satang, bp: number): Satang {
  return Math.round((amount * bp) / 10000);
}

export function baht(s: Satang): string {
  const sign = s < 0 ? "-" : "";
  const abs = Math.abs(s);
  const whole = Math.floor(abs / 100).toLocaleString("en-US");
  return `${sign}${whole}.${String(abs % 100).padStart(2, "0")}`;
}
money.ts: pct rounds a percentage, and baht formats a value for display

Where you round does matter. The rule in the example is to round at each line's amount, not per piece, and to calculate VAT once from the total before VAT, not line by line. The end of demo.ts compares the two methods.

demo.ts · lines 19–27
// ปัดครั้งเดียวที่ยอดบรรทัด เทียบกับปัดทีละชิ้น (ส่วนลดสมาชิก 5% กับ 100 ชิ้น ชิ้นละ 13.50 บาท)
const line = 1350 * 100;
const once = line - pct(line, 500);
const perPiece = (1350 - pct(1350, 500)) * 100;
console.log(`\n== ปัดตอนไหน: ปัดที่ยอดบรรทัด ${baht(once)} | ปัดทีละชิ้นแล้วคูณ ${baht(perPiece)} | ต่าง ${once - perPiece} สตางค์`);
// VAT 7% ของสามบรรทัด บรรทัดละ 1.50 บาท: ปัดทีละบรรทัด เทียบกับปัดครั้งเดียวที่ยอดรวม
const lines = [150, 150, 150];
const perLine = lines.map((x) => pct(x, 700)).reduce((a, b) => a + b, 0);
console.log(`VAT ปัดทีละบรรทัด ${baht(perLine)} | VAT ปัดครั้งเดียวที่ยอดรวม ${baht(pct(450, 700))} บาท`);
demo.ts: rounding per piece compared with rounding at the line amount, and VAT per line compared with VAT once

The result: a 5% member discount on 100 stickers at 13.50 baht each comes to 1,282.50 baht when rounded at the line amount, but 1,282.00 baht when rounded per piece and then multiplied, a difference of 50 satang. And the VAT on three lines of 1.50 baht each is 0.33 baht when rounded line by line, but 0.32 baht when rounded once. The numbers are small, but if the website, the quotation and the ERP round in different ways, the totals will not match and someone has to hunt for the cause every time. Choose one rule, write it in the rules document, and make every system use it the same way.

Step 3: validate the input first, and do not calculate a price if it fails

The validator takes the selected rule version and returns all the error messages at once, without stopping at the first one. The user can then fix everything in one go (the same principle as a multi-step form; see the related article on multi-step forms). The validator covers a quantity that is 0, negative, fractional, NaN, too large, or beyond the safe integer range; an unknown option; an option that requires a different material; options that cannot be used together; a delivery area outside the service zone; and a promo code that does not exist.

validate.ts · lines 17–39
export function validate(i: QuoteInput, r: Rules): string[] {
  const e: string[] = [];
  if (!(i.material in r.materials)) e.push(`ไม่รู้จักวัสดุ "${i.material}" เลือกได้: ${Object.keys(r.materials).join(", ")}`);
  const q = typeof i.quantity === "number" ? { min: i.quantity, max: i.quantity } : i.quantity;
  const checks: [string, number][] = typeof i.quantity === "number" ? [["จำนวน", q.min]] : [["จำนวนต่ำสุด", q.min], ["จำนวนสูงสุด", q.max]];
  for (const [name, v] of checks) {
    if (!Number.isSafeInteger(v)) e.push(`${name}ต้องเป็นจำนวนเต็ม (ได้รับ ${v})`);
    else if (v < 1) e.push(`${name}ต้องไม่น้อยกว่า 1 (ได้รับ ${v})`);
    else if (v > MAX_QTY) e.push(`${name}เกิน ${MAX_QTY.toLocaleString("en-US")} ชิ้น ติดต่อเจ้าหน้าที่เพื่อขอใบเสนอราคาเฉพาะ`);
  }
  if (q.min > q.max) e.push("ช่วงจำนวนไม่ถูกต้อง: ค่าต่ำสุดมากกว่าค่าสูงสุด");
  for (const o of i.options) {
    const def = r.options[o];
    if (!def) { e.push(`ไม่รู้จักตัวเลือก "${o}"`); continue; }
    if (def.requiresMaterial && def.requiresMaterial !== i.material)
      e.push(`"${def.label}" ใช้ได้กับวัสดุ ${r.materials[def.requiresMaterial]} เท่านั้น`);
    for (const x of def.excludes) if (i.options.includes(x)) e.push(`"${def.label}" เลือกร่วมกับ "${r.options[x].label}" ไม่ได้`);
  }
  if (!["pickup", "bkk", "central", "unknown"].includes(i.zone))
    e.push(`พื้นที่จัดส่ง "${i.zone}" อยู่นอกเขตที่คำนวณอัตโนมัติ ให้เจ้าหน้าที่ประเมินค่าส่ง`);
  if (i.promo && !(i.promo in r.discounts.promo)) e.push(`รหัสโปรโมชัน "${i.promo}" ไม่ถูกต้องหรือหมดอายุ`);
  return [...new Set(e)];
}
validate.ts: checks every rule and returns Thai messages; an empty list means it passed

The validator must always run on the server. If the web page also validates, that is only a convenience for the user, because a request can be sent straight to the API without going through the form.

Step 4: price tiers, minimum order amount and rush fee

The price tiers in the example apply the tier's price to every piece. They are not graduated tiers that charge the lower price only on the extra quantity. That is why 99 pieces cost more than 100 pieces. This must be written in the reason on the line and agreed with the business owner. If you do not want this behavior, switch to graduated tiers or add a suggestion. The order of calculation is: the product, then the options, then a raise up to the minimum order amount, then the rush fee calculated on the adjusted amount, and the rush fee has a cap.

estimate.ts · lines 28–38
  const tier = [...r.tiers].reverse().find((t) => qty >= t.minQty)!;
  add("goods", `${r.materials[i.material]} ${qty} ชิ้น`, tier.unitSatang * qty, `ราคาขั้นที่เริ่มที่ ${tier.minQty} ชิ้น ชิ้นละ ${tier.unitSatang} สตางค์ ใช้กับทุกชิ้น`);
  for (const o of i.options) {
    const d = r.options[o];
    add(o, d.label, d.flatSatang ?? d.perPieceSatang! * qty, d.flatSatang ? "ค่าตั้งงานเหมา" : `ชิ้นละ ${d.perPieceSatang} สตางค์`);
  }
  let base = lines.reduce((s, l) => s + l.satang, 0);
  if (base < r.minChargeSatang) {
    add("min", "ปรับขึ้นถึงยอดขั้นต่ำ", r.minChargeSatang - base, `ยอดงานต่ำกว่าขั้นต่ำ ${r.minChargeSatang} สตางค์`);
    base = r.minChargeSatang;
  }
estimate.ts: selects the price tier, adds the options, and raises the amount to the minimum with a reason
estimate.ts · lines 39–45
  let net = base;
  if (i.rush) {
    const raw = pct(base, r.rush.rateBp);
    const fee = Math.min(raw, r.rush.capSatang);
    add("rush", "งานด่วน", fee, raw > fee ? `${r.rush.rateBp / 100}% ของยอดงาน แต่จำกัดสูงสุด ${r.rush.capSatang} สตางค์` : `${r.rush.rateBp / 100}% ของยอดงาน`);
    net += fee;
  }
estimate.ts: the rush fee is a percentage of the job amount, limited by a cap, with a reason when the cap applies

Step 5: stacked discounts, shipping and VAT

Discounts are where numbers go wrong most often. The example sets the rule that the member discount is calculated from the job amount first, and then the promo code is calculated from what remains after the member discount. The promotion has its own cap, and the total of all discounts must not exceed 20% of the job amount. If the overall cap applies, the discount line that was cut states the reason. Discounts do not reduce the rush fee or shipping, because they are calculated from the job amount only. Swapping the order gives different amounts, so tests must pin it down.

estimate.ts · lines 47–59
  const capAll = pct(base, r.discounts.totalCapBp);
  let given = 0;
  const give = (code: string, label: string, want: Satang, why: string) => {
    const amt = Math.min(want, capAll - given);
    if (amt <= 0) return;
    add(code, label, -amt, amt < want ? `${why} ถูกลดเหลือ ${amt} สตางค์ เพราะส่วนลดรวมเกินเพดาน ${r.discounts.totalCapBp / 100}%` : why);
    given += amt;
  };
  if (i.member) give("member", "ส่วนลดสมาชิก", pct(base, r.discounts.memberBp), `${r.discounts.memberBp / 100}% ของยอดงาน`);
  if (i.promo) {
    const p = r.discounts.promo[i.promo];
    give("promo", `โปรโมชัน ${i.promo}`, Math.min(pct(base - given, p.rateBp), p.capSatang), `${p.rateBp / 100}% ของยอดหลังหักส่วนลดสมาชิก สูงสุด ${p.capSatang} สตางค์`);
  }
estimate.ts: member discount first, then the promotion, and the overall cap cuts the excess

Shipping is charged by zone and is free when the amount after discounts reaches a threshold. VAT is calculated last, once, from the total before VAT.

estimate.ts · lines 60–65
  net -= given;
  const ship = base - given >= r.freeDeliveryOverSatang ? 0 : r.delivery[zone];
  add("delivery", "ค่าส่ง", ship, ship === 0 && r.delivery[zone] > 0 ? "ยอดหลังส่วนลดถึงเกณฑ์ส่งฟรี" : `โซน ${zone}`);
  net += ship;
  const vat = pct(net, r.vatBp);
  return { lines, netSatang: net, vatSatang: vat, totalSatang: net + vat };
estimate.ts: subtract the discounts, add shipping, then calculate VAT once

Step 6: a price range when the input is still uncertain

Customers often do not know the exact quantity yet, or have not chosen a delivery area. The calculator accepts the quantity as a range and accepts the delivery area as unknown. The quote function tries every value that could produce an extreme price: both ends of the range, the price tier breakpoints that fall inside the range, and every possible zone. It then reports the minimum and the maximum. Trying only the ends of the range would miss cases, because the price does not always rise with quantity (99 pieces cost more than 100 pieces).

estimate.ts · lines 72–87
export function quote(i: QuoteInput, all?: Rules[]): Quote {
  const r = rulesFor(i.quoteDate, all);
  if (!r) return { ok: false, errors: [`ไม่มีกติการาคาที่มีผลในวันที่ ${i.quoteDate}`] };
  const errors = validate(i, r);
  if (errors.length) return { ok: false, errors };
  const q = typeof i.quantity === "number" ? { min: i.quantity, max: i.quantity } : i.quantity;
  // ลองทุกค่าที่อาจทำให้ราคาสุดขอบ: ปลายช่วง และจุดเปลี่ยนขั้นที่อยู่ในช่วง
  const qtys = [q.min, q.max, ...r.tiers.map((t) => t.minQty).filter((m) => m > q.min && m < q.max)];
  const zones = i.zone === "unknown" ? ["bkk", "central"] : [i.zone];
  const all2 = qtys.flatMap((n) => zones.map((z) => price(i, n, z, r)));
  const totals = all2.map((p) => p.totalSatang);
  const lowSatang = Math.min(...totals), highSatang = Math.max(...totals);
  const exact = lowSatang === highSatang ? all2[0] : null;
  return { ok: true, version: r.version, exact, lowSatang, highSatang,
    note: exact ? "ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด" : "ช่วงราคาประมาณการ เพราะจำนวนหรือพื้นที่ส่งยังไม่แน่นอน เจ้าหน้าที่จะยืนยันราคาจริง" };
}
estimate.ts: quote combines rule version selection, validation and the price range

A real run: fourteen cases from the sample file

demo.ts reads quotes.sample.json and prints the results case by case. The cases include normal ones, a price tier boundary, the minimum order amount, the rush fee hitting its cap, stacked discounts, a price range, the same quotation dated under two different rule versions, and deliberately invalid cases.

output.txt

== A ปกติ กรุงเทพ
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 120 ชิ้น               1,440.00  ราคาขั้นที่เริ่มที่ 100 ชิ้น ชิ้นละ 1200 สตางค์ ใช้กับทุกชิ้น
  เคลือบลามิเนต                   240.00  ชิ้นละ 200 สตางค์
  ค่าส่ง                          120.00  โซน bkk
  รวมก่อน VAT                   1,800.00
  VAT 7%                          126.00
  รวมทั้งสิ้น                   1,926.00

== B ขอบขั้น 99
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 99 ชิ้น                1,485.00  ราคาขั้นที่เริ่มที่ 1 ชิ้น ชิ้นละ 1500 สตางค์ ใช้กับทุกชิ้น
  ค่าส่ง                            0.00  โซน pickup
  รวมก่อน VAT                   1,485.00
  VAT 7%                          103.95
  รวมทั้งสิ้น                   1,588.95

== C ขอบขั้น 100
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 100 ชิ้น               1,200.00  ราคาขั้นที่เริ่มที่ 100 ชิ้น ชิ้นละ 1200 สตางค์ ใช้กับทุกชิ้น
  ค่าส่ง                            0.00  โซน pickup
  รวมก่อน VAT                   1,200.00
  VAT 7%                           84.00
  รวมทั้งสิ้น                   1,284.00

== D ยอดต่ำกว่าขั้นต่ำ
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 10 ชิ้น                  150.00  ราคาขั้นที่เริ่มที่ 1 ชิ้น ชิ้นละ 1500 สตางค์ ใช้กับทุกชิ้น
  ปรับขึ้นถึงยอดขั้นต่ำ           150.00  ยอดงานต่ำกว่าขั้นต่ำ 30000 สตางค์
  ค่าส่ง                          120.00  โซน bkk
  รวมก่อน VAT                     420.00
  VAT 7%                           29.40
  รวมทั้งสิ้น                     449.40

== E งานด่วนชนเพดาน
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 1000 ชิ้น              9,000.00  ราคาขั้นที่เริ่มที่ 500 ชิ้น ชิ้นละ 900 สตางค์ ใช้กับทุกชิ้น
  ปั๊มฟอยล์                     3,500.00  ชิ้นละ 350 สตางค์
  งานด่วน                       1,000.00  20% ของยอดงาน แต่จำกัดสูงสุด 100000 สตางค์
  ค่าส่ง                            0.00  ยอดหลังส่วนลดถึงเกณฑ์ส่งฟรี
  รวมก่อน VAT                  13,500.00
  VAT 7%                          945.00
  รวมทั้งสิ้น                  14,445.00

== F ส่วนลดสมาชิก+โปรโมชัน
  กติการุ่น 2026-01 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 300 ชิ้น               3,600.00  ราคาขั้นที่เริ่มที่ 100 ชิ้น ชิ้นละ 1200 สตางค์ ใช้กับทุกชิ้น
  เคลือบลามิเนต                   600.00  ชิ้นละ 200 สตางค์
  ไดคัทตามรูป                     500.00  ค่าตั้งงานเหมา
  ส่วนลดสมาชิก                   -235.00  5% ของยอดงาน
  โปรโมชัน SPRING10              -446.50  10% ของยอดหลังหักส่วนลดสมาชิก สูงสุด 50000 สตางค์
  ค่าส่ง                          120.00  โซน bkk
  รวมก่อน VAT                   4,138.50
  VAT 7%                          289.70
  รวมทั้งสิ้น                   4,428.20

== G ช่วงจำนวน พื้นที่ยังไม่รู้
  กติการุ่น 2026-01 | ช่วงราคาประมาณการ เพราะจำนวนหรือพื้นที่ส่งยังไม่แน่นอน เจ้าหน้าที่จะยืนยันราคาจริง
  ช่วงรวม VAT: 1,412.40 ถึง 2,193.50 บาท

== H เหมือน A แต่วันที่หลังเปลี่ยนกติกา
  กติการุ่น 2026-07 | ราคาประมาณการ ไม่ใช่ใบเสนอราคา ราคาไม่รวม VAT แสดง VAT แยกบรรทัด
  กระดาษ 120 ชิ้น               1,500.00  ราคาขั้นที่เริ่มที่ 100 ชิ้น ชิ้นละ 1250 สตางค์ ใช้กับทุกชิ้น
  เคลือบลามิเนต                   240.00  ชิ้นละ 200 สตางค์
  ค่าส่ง                          120.00  โซน bkk
  รวมก่อน VAT                   1,860.00
  VAT 7%                          130.20
  รวมทั้งสิ้น                   1,990.20

== X1 ตัวเลือกขัดกัน
  ปฏิเสธ: "เคลือบลามิเนต" ใช้ได้กับวัสดุ กระดาษ เท่านั้น
  ปฏิเสธ: "เคลือบลามิเนต" เลือกร่วมกับ "กันน้ำ" ไม่ได้
  ปฏิเสธ: "กันน้ำ" เลือกร่วมกับ "เคลือบลามิเนต" ไม่ได้

== X2 จำนวนผิด
  ปฏิเสธ: จำนวนต้องไม่น้อยกว่า 1 (ได้รับ 0)

== X3 จำนวนติดลบ
  ปฏิเสธ: จำนวนต้องไม่น้อยกว่า 1 (ได้รับ -5)

== X4 จำนวนมหาศาล
  ปฏิเสธ: จำนวนเกิน 100,000 ชิ้น ติดต่อเจ้าหน้าที่เพื่อขอใบเสนอราคาเฉพาะ

== X5 ทศนิยม โซนนอกเขต โปรผิด
  ปฏิเสธ: จำนวนต้องเป็นจำนวนเต็ม (ได้รับ 1.5)
  ปฏิเสธ: ไม่รู้จักตัวเลือก "glitter"
  ปฏิเสธ: พื้นที่จัดส่ง "north" อยู่นอกเขตที่คำนวณอัตโนมัติ ให้เจ้าหน้าที่ประเมินค่าส่ง
  ปฏิเสธ: รหัสโปรโมชัน "FREE" ไม่ถูกต้องหรือหมดอายุ

== X6 วันที่ก่อนกติกาแรก
  ปฏิเสธ: ไม่มีกติการาคาที่มีผลในวันที่ 2025-12-31

== ปัดตอนไหน: ปัดที่ยอดบรรทัด 1,282.50 | ปัดทีละชิ้นแล้วคูณ 1,282.00 | ต่าง 50 สตางค์
VAT ปัดทีละบรรทัด 0.33 | VAT ปัดครั้งเดียวที่ยอดรวม 0.32 บาท
Output from a real run on 2026-11-21 with node demo.ts (Node 24), stdout only

Reading the results one by one

  1. Cases B and C: 99 pieces come to 1,588.95 baht including VAT, but 100 pieces come to 1,284.00 baht including VAT. One line says the tier starting at 1 piece was used, and the other says the tier starting at 100 pieces was used. Sales can explain this to the customer right away.
  2. Case D: a 10-piece job comes to 150 baht, so the system adds a line raising it by another 150 baht to the 300 baht minimum, with a reason. It does not hide this in the price per piece.
  3. Case E: a 20% rush fee on 12,500 baht would be 2,500 baht, but the cap is 1,000 baht. The line says it was limited, and the amount after discounts reaches the free-shipping threshold.
  4. Case F: the member discount is 235.00 baht and the promotion is 446.50 baht, calculated from the remaining amount, not 10% of the full amount. The VAT of 289.70 baht comes from the pre-VAT amount of 4,138.50 baht.
  5. Case G: a quantity of 80 to 150 pieces with an unknown delivery area gives a range of 1,412.40 to 2,193.50 baht including VAT, with a message saying it is an estimated range.
  6. Cases A and H: the same quotation dated under two different rule versions gives 1,926.00 and 1,990.20 baht, and each one states the version number used. The old version still calculates to the same result as before.
  7. Cases X1 to X6: conflicting options, quantity 0, negative, huge and fractional quantities, a zone outside the service area, a code that does not exist, and a date before the first rules are all rejected with Thai messages. None of them is priced.

The test suite

estimate.test.ts has 8 cases. Running node --test estimate.test.ts gives 8 passes. It checks the price tier boundaries (99, 100, 500), a quantity of 0, negative, fractional, NaN, huge and beyond the safe range, conflicting options, the minimum order amount and the rush fee cap, rounding to satang, the discount order and the overall cap, a price range that must cover a tier breakpoint in the middle of the range, and recalculating an old quotation.

estimate.test.ts · lines 62–75
test("ลำดับส่วนลด: สมาชิกก่อน แล้วโปรโมชันคิดจากยอดที่เหลือ และเพดานรวมตัดโปรโมชัน", () => {
  const i: QuoteInput = { ...base, quantity: 300, member: true, promo: "SPRING10", zone: "bkk" };
  const r = rulesFor("2026-03-10")!;
  const p = price(i, 300, "bkk", r);
  const member = p.lines.find((l) => l.code === "member")!.satang;
  const promo = p.lines.find((l) => l.code === "promo")!.satang;
  assert.equal(member, -pct(360000, 500));
  assert.equal(promo, -pct(360000 + member, 1000)); // คิดจากยอดหลังหักสมาชิก
  const tight: Rules = { ...r, discounts: { ...r.discounts, totalCapBp: 600 } }; // เพดานรวม 6%
  const c = price(i, 300, "bkk", tight);
  const given = -c.lines.filter((l) => l.satang < 0).reduce((s, l) => s + l.satang, 0);
  assert.equal(given, pct(360000, 600));
  assert.match(c.lines.find((l) => l.code === "promo")!.reason, /เกินเพดาน/);
});
estimate.test.ts: discount order and overall cap
estimate.test.ts · lines 85–94
test("เปลี่ยนรุ่นกติกา: ใบเสนอราคาเก่าคำนวณซ้ำได้เท่าเดิม", () => {
  const old = quote({ ...base, quantity: 120, zone: "bkk" });
  const later = quote({ ...base, quoteDate: "2026-08-10", quantity: 120, zone: "bkk" });
  assert.ok(old.ok && later.ok);
  assert.equal(old.version, "2026-01");
  assert.equal(later.version, "2026-07");
  assert.notEqual(old.lowSatang, later.lowSatang);
  assert.deepEqual(quote({ ...base, quantity: 120, zone: "bkk" }), old); // ซ้ำกี่ครั้งก็เท่าเดิม
  assert.match(errs({ quoteDate: "2025-12-31" }), /ไม่มีกติกา/);
});
estimate.test.ts: after the rule version changes, an old quotation still gives the same result

When someone changes a price or the discount order, this test suite immediately shows what the change affects. When you add a new rule version, add test cases for the new version and keep the cases for the old version.

A reason on every line, and why the final price still comes from a person or the ERP

The calculator's output is a list of lines. Each line has a name, an amount in satang and a reason in Thai. The web page shows this list to the customer. The quotation request stores the same list together with the rule version number. When sales opens it, they see the same thing the customer saw and do not have to guess where a number came from. This is the connection point to the quotation request step (see the related article on receiving quotation requests). The calculator fills in the data on the request so that sales can continue from there. It does not replace sales.

The final price still has to come from a person or the ERP because the website does not know the cost of the material bought for this lot, the actual production queue, the customer's artwork files that need fixing, that customer's credit, or any special price contract. The example's text therefore says "estimated price", not "quotation", and shows a range when it is unsure. When sales confirms the price, the binding number should be recorded as a sales document in the ERP (see the related article on sales documents in an ERP), together with the reason for any difference from the estimate.

If you use this in practice

  • Rules in a database: store rule versions as rows that cannot be edited once they take effect and can only be changed by adding a new row, with an approver and an approval date. The example reads a JSON file to show the principle.
  • Keep a snapshot: besides the version number, store the whole input and output with the request, because the calculator code itself can change. If you ever need to look back, the snapshot is the evidence of what the customer actually saw.
  • Complex pricing: if the price depends on area, size or time, add rules and tests. If there are hundreds of rules, have sales and developers review the table of test cases together.
  • Tax: the example calculates 7% VAT once from the pre-VAT amount. A business that has to issue tax invoices should have its accountant confirm the rounding method and how discounts are shown, and set the accounting system to use the same method.
  • Security and load: if you expose this as a public API, limit the call rate and the request size, so nobody can call it repeatedly to probe the whole price rule set.
  • Form: if the customer has to fill in many fields, split it into steps and show an estimated price that updates at every step, using the same validator as the server.

Hypothetical examples: adapting it to three businesses

Signage and installation shop

The price depends on the sign area, the installation height and the distance to the site. The added rule is a crane fee when the height is above a certain level. The calculator can only estimate this as a range, because someone has to visit the site first. It suits showing a price range and a message saying the real price is confirmed after a site survey.

Made-to-drawing parts manufacturer

The price depends on material, quantity and machine setup fee. Material cost changes with the market. Rule versions with effective dates keep last month's quotations verifiable. Regular customers may have their own rates stored in the ERP, so the web calculator shows the standard rate and says that regular customers get the contract price.

System installation service business

The estimate is based on the number of installation points and the cable run length. Price tiers and inter-province travel costs are in the rules, but the on-site consultant may change the number of points. A price range is therefore more important than a single number, and the request should attach the reason for every line so that the field engineer can compare it with actual conditions.

Common mistakes, and a checklist

  • Using floating-point decimals for money, so the lines do not add up to the total.
  • Rounding in different places across the website, the quotation and the accounts, which makes totals differ by a few satang and hard to trace.
  • Hard-coding prices and the VAT rate in the web page code, so every change needs a new release and leaves no history.
  • Overwriting existing rules, so old quotations cannot be recalculated.
  • Not agreeing on the discount order and the overall cap, so each salesperson calculates differently.
  • Calculating a price even though the options conflict or the quantity is zero or negative.
  • Validating the input only on the web page.
  • Showing a single number when the input is still uncertain, without saying it is an estimate.
  • Trying only the ends of the quantity range, and missing the point where the price drops in the middle of the range.
  1. Money is integer satang, and the rounding rule is written in the rules document.
  2. The rules live in one file or table, with a version, an effective date and an approver, and a version that is already in effect must not be edited.
  3. Validate the input on the server. If it fails, do not calculate a price, and reply with a message the user can act on.
  4. State whether the prices in the rules include or exclude VAT, and show VAT on its own line.
  5. Agree with the business owner on the discount order, the caps and how price tiers work.
  6. Every line has a reason in Thai, and sales and the customer see the same list.
  7. Store the rule version number and a snapshot of the input and output with the request.
  8. Have tests for price tier boundaries, abnormal quantities, conflicting options, rounding, discount order and old quotations after a version change.
  9. State clearly that it is an estimate, and have a person or the ERP confirm the price before it becomes binding.

Limits of the example: all data and prices are hypothetical. There are no other currencies, no withholding tax, no complex units of measure, no permanent storage in a database, and no rate limiting, and the VAT rule is a simple one. Use it as a learning example, not as production-ready code, and not as tax advice.

References

  1. Thai Revenue Department — Value Added Tax (rate 7 percent, discounts and the tax base) (accessed 2026-11-21)
  2. MDN — Math.round() (how .5 is rounded) (accessed 2026-11-21)
  3. MDN — Number.isSafeInteger() (accessed 2026-11-21)
  4. Martin Fowler — Money (rounding to the smallest currency unit) (accessed 2026-11-21)
  5. OWASP — Input Validation Cheat Sheet (accessed 2026-11-21)
  6. Node.js — Test runner (node:test) (accessed 2026-11-21)
  7. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer