// FRAZIER Finance OS — Create Invoice (2026-10-12). A standalone client
// invoice generator with the official letterhead: its own table
// (fin_created_invoices), never the Google Sheet. Sheet mode's bookkeeping
// stays sheet-only and read-only (see api/fin.php's header) — an invoice
// made here is a document to send to the client; the owner re-enters it in
// the sheet themselves if it needs to be booked.
//
// Numbering: FRZ/CI/YYYY/MM/#### (see api/lib/fin-created-invoices.php),
// deliberately different from the sheet's own INH/FN/YY/MM/### so the two
// histories can never be confused.
//
// Export: Print/Save as PDF reuses the app's .fin-print-doc convention
// (fin-kit.css) — the whole page becomes a clean white page with nothing
// but the document. "Download Word" and "Download HTML" build a standalone
// HTML string (finCiDocHtml) and save it as .doc / .html; the .doc is the
// classic HTML-with-Word-namespace trick, needs no library and opens
// directly in Word or Google Docs (File → Open).
//
// Every top-level name starts with finCi / FinCi / FIN_CI.
const FIN_CI_COMPANY = {
name: 'CV FRAZIER NETWORK',
address: 'Ruko Arcade, Jl. Pantai Indah Utara 2 Unit PB, RT.2/RW.7, Kapuk Muara, Kecamatan Penjaringan, Jkt Utara, Daerah Khusus Ibukota Jakarta 14460',
phone: '0858-8291-0012',
};
const FIN_CI_TAX_TYPES = {
pph4_2: { label: 'PPh 4(2) — withheld by client', shortLabel: 'PPh 4(2)', defaultPct: 0.5, direction: 'withheld' },
ppn: { label: 'PPN — added to total', shortLabel: 'PPN', defaultPct: 11, direction: 'added' },
none: { label: 'No tax', shortLabel: 'Tax', defaultPct: 0, direction: 'none' },
};
const FIN_CI_STATUS = {
draft: { label: 'Draft', tone: 'neutral' },
sent: { label: 'Sent', tone: 'info' },
paid: { label: 'Paid', tone: 'ok' },
void: { label: 'Void', tone: 'crit' },
};
const FIN_CI_STATUS_ORDER = ['draft', 'sent', 'paid', 'void'];
function finCiPlural(n, one, many) { return n + ' ' + (n === 1 ? one : (many || one + 's')); }
function finCiEmptyLine() { return { description: '', qty: '1', unitPrice: '' }; }
function finCiNewDraft() {
return {
clientName: '', clientAddress: '', clientContact: '',
issueDate: finTodayIso(), dueDate: '',
taxType: 'pph4_2', taxPct: String(FIN_CI_TAX_TYPES.pph4_2.defaultPct),
notes: '', lines: [finCiEmptyLine()],
};
}
function finCiDraftFromInvoice(inv) {
return {
clientName: inv.clientName || '', clientAddress: inv.clientAddress || '', clientContact: inv.clientContact || '',
issueDate: inv.issueDate, dueDate: inv.dueDate || '',
taxType: inv.taxType, taxPct: String(inv.taxPct),
notes: inv.notes || '',
lines: (inv.lines || []).map((l) => ({ description: l.description, qty: String(l.qty), unitPrice: String(l.unitPrice) })),
};
}
// ── Payment plan (2026-10-22) — one project split into N dated draft
// invoices, created together in one request (api/lib/fin-created-
// invoices.php's fin_ci_terms_create). Mirrors the backend's own split
// and clamp exactly, so the preview the owner sees before submitting is
// the real schedule, not an approximation. ─────────────────────────────
function finCiTermsNewDraft() {
return {
clientName: '', clientAddress: '', clientContact: '',
description: '', totalAmount: '', numTerms: '4', startDate: finTodayIso(),
firstTermLabel: 'dp', taxType: 'pph4_2', taxPct: String(FIN_CI_TAX_TYPES.pph4_2.defaultPct), notes: '',
};
}
// Same clamp as the backend's fin_ci_add_months: 31 Jan + 1 month = 28/29
// Feb, never a March overflow.
function finCiAddMonths(ymd, months) {
if (!ymd) return '';
const [y, m, d] = ymd.split('-').map(Number);
const base = new Date(Date.UTC(y, m - 1 + months, 1));
const lastDay = new Date(Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + 1, 0)).getUTCDate();
base.setUTCDate(Math.min(d, lastDay));
return base.getUTCFullYear() + '-' + String(base.getUTCMonth() + 1).padStart(2, '0') + '-' + String(base.getUTCDate()).padStart(2, '0');
}
function finCiTermsPreview(draft) {
const total = Math.round(Number(draft.totalAmount) || 0);
const n = Math.max(2, Math.min(24, Number(draft.numTerms) || 0));
if (total <= 0 || !n) return [];
const perTerm = Math.floor(total / n);
const remainder = total - perTerm * n;
const project = draft.description.trim() || 'Project';
const terms = [];
for (let i = 1; i <= n; i++) {
const amount = perTerm + (i === n ? remainder : 0);
const label = i === 1
? (draft.firstTermLabel === 'dp' ? project + ' — Down Payment (DP)' : project + ' — First Phase Payment (1/' + n + ')')
: project + ' — Term ' + i + ' of ' + n;
terms.push({ term: i, label, amount, issueDate: finCiAddMonths(draft.startDate, i - 1) });
}
return terms;
}
// ── Recurring templates (2026-10-22) — auto-creates a DRAFT each month,
// never sends anything (see api/lib/fin-ci-recurring.php's header: this
// app has no outbound email at all). Reuses the same line-item editor,
// tax model and compute function as a one-off invoice — a template IS an
// invoice's fields minus the dates, plus a day-of-month. ───────────────
function finCiRecEmptyLine() { return { description: '', qty: '1', unitPrice: '' }; }
function finCiRecNewDraft() {
return {
clientName: '', clientAddress: '', clientContact: '',
taxType: 'pph4_2', taxPct: String(FIN_CI_TAX_TYPES.pph4_2.defaultPct),
dayOfMonth: '1', notes: '', lines: [finCiRecEmptyLine()],
};
}
function finCiRecDraftFromTemplate(t) {
return {
clientName: t.clientName || '', clientAddress: t.clientAddress || '', clientContact: t.clientContact || '',
taxType: t.taxType, taxPct: String(t.taxPct), dayOfMonth: String(t.dayOfMonth), notes: t.notes || '',
lines: (t.lines || []).map((l) => ({ description: l.description, qty: String(l.qty), unitPrice: String(l.unitPrice) })),
};
}
// Mirrors api/lib/fin-created-invoices.php's fin_ci_compute exactly, for
// the wizard's live total box. DPP is the sum of the line items (entered at
// their real price — never grossed up from a target).
function finCiCompute(dpp, taxType, taxPct) {
const d = Math.round(Number(dpp) || 0);
const pct = Number(taxPct) || 0;
if (taxType === 'pph4_2') { const tax = Math.round(d * pct / 100); return { dpp: d, tax, total: d, nett: d - tax }; }
if (taxType === 'ppn') { const tax = Math.round(d * pct / 100); return { dpp: d, tax, total: d + tax, nett: d + tax }; }
return { dpp: d, tax: 0, total: d, nett: d };
}
function finCiLineAmount(l) { return Math.round((Number(l.qty) || 0) * (Number(l.unitPrice) || 0)); }
function finCiQty(q) {
const n = Number(q) || 0;
if (Number.isInteger(n)) return String(n);
return String(Math.round(n * 100) / 100).replace(/\.00$/, '');
}
function finCiEsc(s) {
return String(s === null || s === undefined ? '' : s)
.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
// ── Export: a standalone HTML document (used for both the .html and the
// .doc download — the .doc is this same HTML with a Word XML namespace). ──
function finCiDocHtml(invoice) {
const tax = FIN_CI_TAX_TYPES[invoice.taxType] || FIN_CI_TAX_TYPES.none;
const rows = (invoice.lines || []).map((l) => (
'