import { getNumberFormat } from "@suphark/ui/lib/intl-cache"; import { thaiBahtText } from "@suphark/ui/lib/thai"; import { cn } from "@suphark/ui/lib/utils"; import type { ReactNode } from "react"; export interface AmountLine { label: ReactNode; value: number; /** `subtotal` = มีเส้นคั่นด้านบน (ยอดหลังหักส่วนลด ฯลฯ) */ kind?: "default" | "subtotal"; /** ข้อความเล็กใต้ป้าย เช่น "2% ของยอดรวม" */ hint?: ReactNode; } const defaultFormat = (n: number) => getNumberFormat("th-TH", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n); /** ค่าติดลบใช้เครื่องหมายลบจริง (−) ไม่ใช่ขีด — อ่านง่ายและ screen reader อ่านว่า "ลบ" */ /** ติดลบจริงหลังปัดตามที่แสดง — -0 และ -0.004 (แสดง 0.00) ไม่ใช่ค่าติดลบ */ function isNegative(value: number, format: (n: number) => string) { return value < 0 && /[1-9]/.test(format(Math.abs(value))); } /** เครื่องหมายลบอยู่หน้าสกุลเงิน: −฿100.00 (ไม่ใช่ ฿−100.00 หรือ -0.00) */ function signed(value: number, format: (n: number) => string, prefix = "") { const text = `${prefix}${format(Math.abs(value))}`; return isNegative(value, format) ? `−${text}` : text; } /** * สรุปยอดเงินท้ายเอกสาร: รายการ → ยอดย่อย → ภาษี → รวมทั้งสิ้น (+ จำนวนเงินเป็นตัวอักษร) * แอปคำนวณเอง (decimal.js ฯลฯ) — component แค่แสดง · ค่าติดลบ (ส่วนลด) เป็นสีแดง * * * * `variant="inline"` = แถวเดียวตัดบรรทัดได้ สำหรับหัวเอกสาร/แถบล่าง */ export function AmountSummary({ lines = [], total, currency = "฿", bahtText = false, format = defaultFormat, variant = "block", className, }: { lines?: ReadonlyArray; total?: { label: ReactNode; value: number }; /** สัญลักษณ์หน้ายอดรวม (ค่าเริ่มต้น ฿) — `""` = ไม่ใส่ */ currency?: string; /** แสดงยอดรวมเป็นตัวอักษรไทย (บาท/สตางค์) ใต้ยอดรวม */ bahtText?: boolean; format?: (value: number) => string; variant?: "block" | "inline"; className?: string; }) { if (variant === "inline") { return ( {lines.map((line, i) => ( // biome-ignore lint/suspicious/noArrayIndexKey: ลำดับรายการคงที่ตามที่แอปส่งมา {line.label} {signed(line.value, format)} ))} {total && ( {total.label} {signed(total.value, format, currency)} )} ); } return ( {lines.map((line, i) => ( {line.label} {line.hint && {line.hint}} {signed(line.value, format)} ))} {total && ( {total.label} {signed(total.value, format, currency)} )} {total && bahtText && ( ({thaiBahtText(total.value)}) )} ); }
({thaiBahtText(total.value)})