← back to Filemaker Mcp
lib/fm-script-helpers.js
64 lines
// Shared helpers for scripts/sales-summary.mjs and scripts/new-invoice-monitor.mjs.
// No external dependencies — uses only Node built-ins already available in the scripts.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
/**
* Load a `.env` file adjacent to the package root into `process.env`.
* Silently skips keys already present (process env wins over file).
* Safe to call if the file is absent (launchd / shell already exports the vars).
*
* @param {string} importMetaUrl - pass `import.meta.url` from the caller
* so the root is resolved correctly regardless of cwd.
*/
export function loadEnv(importMetaUrl) {
const root = join(dirname(fileURLToPath(importMetaUrl)), '..');
try {
for (const line of readFileSync(join(root, '.env'), 'utf8').split('\n')) {
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
if (m && !(m[1] in process.env)) {
process.env[m[1]] = m[2].replace(/^["']|["']$/g, '').trim();
}
}
} catch { /* env may already be exported (e.g. launchd) */ }
}
/** @type {'America/Los_Angeles'} */
export const TZ = 'America/Los_Angeles';
/**
* Return the current Pacific-time {y, m, d} from a Date.
* Uses `en-CA` locale so formatToParts gives unambiguous year/month/day.
*
* @param {Date} d
* @returns {{ y: number, m: number, d: number }}
*/
export function ptYMD(d) {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit',
}).formatToParts(d);
const get = (type) => parts.find((x) => x.type === type).value;
return { y: +get('year'), m: +get('month'), d: +get('day') };
}
/**
* Parse a value to a finite number; returns 0 for anything non-numeric.
* @param {unknown} v
* @returns {number}
*/
export function num(v) {
const n = parseFloat(v);
return Number.isFinite(n) ? n : 0;
}
/**
* Format a number as USD, e.g. `$1,234.56`.
* @param {number} n
* @returns {string}
*/
export function money(n) {
return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}