Files
co-lite/solvway-admin-portal/app/lib/xlsx.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

88 lines
4.0 KiB
TypeScript

export interface XlsxColumn { key: string; title: string }
// Excel also rejects edge apostrophes, empty names and the reserved name "History" (exceljs throws on it).
function safeSheetName(name: string): string {
const n = name.replace(/[*?:\\/[\]]/g, '-').slice(0, 31).replace(/^'+|'+$/g, '') || 'Sheet1'
return n.toLowerCase() === 'history' ? `${n} 1` : n
}
export interface XlsxListValidation { column: string; values: string[] }
// A decimal string ("-78.00", money from toFixed) becomes a number so the sheet can sum it. Digit-only
// strings are identifiers (codes, IC numbers, "0123") and stay text, as does anything over 15 significant
// digits (9 integer + 6 decimal), which a double would round.
const DECIMAL = /^-?(0|[1-9]\d{0,8})\.(\d{1,6})$/
function cellValue(value: unknown): { value: string | number | null; numFmt?: string } {
if (value === null || value === undefined || value === '') return { value: null }
if (typeof value === 'number') return { value }
const s = String(value)
const m = DECIMAL.exec(s)
if (!m) return { value: s }
return { value: Number(s), numFmt: '0.' + '0'.repeat(m[2].length) }
}
// Strings are written as text cells, never formulas, so a member-typed "=..." cannot run when opened.
export async function toXlsx(
rows: Record<string, unknown>[],
columns: XlsxColumn[],
sheetName: string,
opts?: { listValidations?: XlsxListValidation[] },
): Promise<Uint8Array> {
// Loaded on export only: exceljs is large and only the click needs it.
const { default: ExcelJS } = await import('exceljs')
const wb = new ExcelJS.Workbook()
// Sheet names can be admin-edited copy; Excel forbids * ? : \ / [ ] and caps them at 31 characters.
const ws = wb.addWorksheet(safeSheetName(sheetName), { views: [{ state: 'frozen', ySplit: 1 }] })
const header = ws.addRow(columns.map(c => c.title))
header.font = { bold: true }
const widths = columns.map(c => c.title.length)
for (const row of rows) {
const cells = columns.map(c => cellValue(row[c.key]))
const added = ws.addRow(cells.map(c => c.value))
cells.forEach((c, i) => {
if (c.numFmt) added.getCell(i + 1).numFmt = c.numFmt
widths[i] = Math.max(widths[i], String(row[columns[i].key] ?? '').length)
})
}
// ponytail: width = character count, capped at 60; wide scripts (CJK) may still clip.
// Minimum 10: exceljs does not write a width equal to its default (9), which Excel then renders narrower.
widths.forEach((w, i) => { ws.getColumn(i + 1).width = Math.min(Math.max(w + 2, 10), 60) })
// Dropdowns read from a hidden Lists sheet, so a long list is not capped by Excel's 255-character inline limit.
// ponytail: rows 2..1000 and at most 26 lists (columns A..Z); widen when a template needs more
const lists = (opts?.listValidations ?? []).filter(v => v.values.length > 0)
if (lists.length) {
const listsWs = wb.addWorksheet('Lists', { state: 'hidden' })
lists.forEach((v, li) => {
const listCol = String.fromCharCode(65 + li)
v.values.forEach((value, ri) => { listsWs.getCell(`${listCol}${ri + 1}`).value = value })
const target = columns.findIndex(c => c.key === v.column)
if (target < 0) return
const formulae = [`Lists!$${listCol}$1:$${listCol}$${v.values.length}`]
for (let row = 2; row <= 1000; row++) {
ws.getCell(row, target + 1).dataValidation = { type: 'list', allowBlank: true, formulae }
}
})
}
return new Uint8Array(await wb.xlsx.writeBuffer())
}
export function downloadXlsx(filename: string, bytes: Uint8Array): void {
const blob = new Blob([bytes as BlobPart], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
// Deferred: revoking synchronously after click() can cancel the download in some browsers.
setTimeout(() => URL.revokeObjectURL(url), 0)
}