first commit

This commit is contained in:
2026-07-17 13:28:28 -04:00
commit fe0288c284
31 changed files with 10756 additions and 0 deletions
+176
View File
@@ -0,0 +1,176 @@
import { app, BrowserWindow, shell, ipcMain, dialog } from 'electron'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
import os from 'node:os'
import * as pbService from './pocketbase.js'
import { parseVaccinationRecordPdf } from './parseVaccinationRecordPdf.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
process.env.APP_ROOT = path.join(__dirname, '../..')
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')
export const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL
process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
? path.join(process.env.APP_ROOT, 'public')
: RENDERER_DIST
let win = null
const preload = path.join(__dirname, '../preload/index.mjs')
const indexHtml = path.join(RENDERER_DIST, 'index.html')
async function createWindow() {
win = new BrowserWindow({
title: 'CTM Document Builder',
icon: path.join(process.env.APP_ROOT, 'assets', 'icon.ico'),
width: 900,
height: 700,
webPreferences: {
preload,
contextIsolation: true,
nodeIntegration: false,
},
})
if (VITE_DEV_SERVER_URL) {
await win.loadURL(VITE_DEV_SERVER_URL)
win.webContents.openDevTools()
} else {
await win.loadFile(indexHtml)
}
win.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https:')) shell.openExternal(url)
return { action: 'deny' }
})
}
app.whenReady().then(async () => {
await createWindow()
})
app.on('window-all-closed', () => {
win = null
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
} else {
BrowserWindow.getAllWindows()[0].focus()
}
})
ipcMain.handle('pdf:getLogo', () => {
const logoPath = app.isPackaged
? path.join(process.resourcesPath, 'assets', 'logo.png')
: path.join(process.env.APP_ROOT, 'assets', 'logo.png')
try {
if (!fs.existsSync(logoPath)) return { base64: null }
const buf = fs.readFileSync(logoPath)
return { base64: buf.toString('base64') }
} catch {
return { base64: null }
}
})
const PDF_FOOTER_TEMPLATE = `
<div style="width: 100%; font-size: 10px; color: #707070; padding: 0 0.67in; box-sizing: border-box;
display: flex; justify-content: space-between; align-items: center; font-family: Helvetica, Arial, sans-serif;">
<span class="date"></span>
<span>Page <span class="pageNumber"></span> of <span class="totalPages"></span></span>
</div>
`.trim()
async function generatePdfFromHtml(html, { landscape = false, footer = true } = {}) {
const printWin = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
},
})
const tempPath = path.join(os.tmpdir(), `ctm-print-${Date.now()}.html`)
try {
fs.writeFileSync(tempPath, html, 'utf8')
await printWin.loadFile(tempPath)
await printWin.webContents.executeJavaScript(`
(window.__pdfLayoutReady ?? Promise.all([
document.fonts.ready,
...Array.from(document.images).map((img) =>
img.complete
? Promise.resolve()
: new Promise((resolve) => {
img.onload = resolve
img.onerror = resolve
})
),
]))
`)
const pdfBuffer = await printWin.webContents.printToPDF({
printBackground: true,
preferCSSPageSize: true,
landscape,
displayHeaderFooter: true,
headerTemplate: '<div></div>',
footerTemplate: footer ? PDF_FOOTER_TEMPLATE : '<div></div>',
margins: { marginType: 'none' },
})
return pdfBuffer
} finally {
printWin.destroy()
try {
fs.unlinkSync(tempPath)
} catch {
// ignore cleanup errors
}
}
}
ipcMain.handle('pdf:generate', async (_, { html, landscape = false, footer = true }) => {
if (!html || typeof html !== 'string') {
throw new Error('PDF export requires HTML content')
}
const pdfBuffer = await generatePdfFromHtml(html, { landscape, footer })
return { base64: pdfBuffer.toString('base64') }
})
ipcMain.handle('pdf:save', async (_, { base64, defaultName = 'document.pdf' }) => {
const w = BrowserWindow.getFocusedWindow() ?? win
const { canceled, filePath } = await dialog.showSaveDialog(w, {
defaultPath: defaultName,
filters: [{ name: 'PDF', extensions: ['pdf'] }],
})
if (canceled || !filePath) return { ok: false }
const buf = Buffer.from(base64, 'base64')
fs.writeFileSync(filePath, buf)
return { ok: true, filePath }
})
ipcMain.handle('vaccinationRecord:importPdf', async () => {
const w = BrowserWindow.getFocusedWindow() ?? win
const { canceled, filePaths } = await dialog.showOpenDialog(w, {
filters: [{ name: 'PDF', extensions: ['pdf'] }],
properties: ['openFile'],
})
if (canceled || !filePaths?.[0]) return { ok: false, canceled: true }
try {
const data = await parseVaccinationRecordPdf(filePaths[0])
return { ok: true, ...data }
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return { ok: false, error: msg || 'Failed to parse PDF' }
}
})
ipcMain.handle('pb:fetchEntries', () => pbService.fetchEntries())
ipcMain.handle('pb:createEntry', (_, data) => pbService.createEntry(data))
ipcMain.handle('pb:updateEntry', (_, payload) => pbService.updateEntry(payload.id, payload))
ipcMain.handle('pb:deleteEntry', (_, { id }) => pbService.deleteEntry(id))
@@ -0,0 +1,24 @@
import fs from 'node:fs'
import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs'
import { WorkerMessageHandler } from 'pdfjs-dist/legacy/build/pdf.worker.mjs'
import { parseEncodedVaccinationRecordMetadata } from '../../src/lib/vaccinationRecordMetadata.js'
globalThis.pdfjsWorker = { WorkerMessageHandler }
/**
* @param {string} filePath
* @returns {Promise<{ patientName: string, dateOfBirth: string, notes: string, rows: object[] }>}
*/
export async function parseVaccinationRecordPdf(filePath) {
const data = new Uint8Array(fs.readFileSync(filePath))
const doc = await getDocument({ data, useSystemFonts: true }).promise
const page = await doc.getPage(1)
const content = await page.getTextContent()
const textItems = content.items.map((item) => item.str)
const metadataText =
textItems.find((s) => s.startsWith('CTM_VR:')) ??
textItems.find((s) => s.includes('CTM_VR:')) ??
textItems.join('')
return parseEncodedVaccinationRecordMetadata(metadataText)
}
+4
View File
@@ -0,0 +1,4 @@
/** Internal admin app — PocketBase connection (bundled with the desktop build). */
export const POCKETBASE_URL = 'https://ctm-pocketbase.wirediv.dev'
export const PB_ADMIN_EMAIL = 'info@wirediv.com'
export const PB_ADMIN_PASSWORD = 'Supernova99!!__'
+78
View File
@@ -0,0 +1,78 @@
import PocketBase from 'pocketbase'
import { POCKETBASE_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD } from './pocketbase-config.js'
const COLLECTION = 'instructions'
let pb = null
let authPromise = null
function getClient() {
if (!pb) {
pb = new PocketBase(POCKETBASE_URL)
// Main process may receive overlapping IPC calls (e.g. React Strict Mode).
// Default auto-cancel would abort duplicate in-flight PocketBase requests.
pb.autoCancellation(false)
}
return pb
}
function parseEntry(r) {
return {
id: r.id,
vaccine: r.vaccine ?? '',
instruction: r.instruction ?? '',
created: r.created,
updated: r.updated,
}
}
export async function ensureAuth() {
const client = getClient()
if (client.authStore.isValid) return
if (authPromise) {
await authPromise
return
}
// PocketBase v0.23+ removed /api/admins/*; superusers authenticate as a collection.
authPromise = client
.collection('_superusers')
.authWithPassword(PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD)
try {
await authPromise
} catch (err) {
authPromise = null
throw err
}
}
export async function fetchEntries() {
await ensureAuth()
const list = await getClient().collection(COLLECTION).getFullList({ sort: '-created' })
return list.map(parseEntry)
}
export async function createEntry({ vaccine, instruction }) {
await ensureAuth()
const record = await getClient().collection(COLLECTION).create({
vaccine: vaccine.trim(),
instruction: instruction.trim(),
})
return parseEntry(record)
}
export async function updateEntry(id, { instruction, vaccine, includeVaccine }) {
await ensureAuth()
const body = { instruction: instruction.trim() }
if (includeVaccine && vaccine != null) {
body.vaccine = vaccine.trim()
}
const record = await getClient().collection(COLLECTION).update(id, body)
return parseEntry(record)
}
export async function deleteEntry(id) {
await ensureAuth()
await getClient().collection(COLLECTION).delete(id)
}
+92
View File
@@ -0,0 +1,92 @@
import { ipcRenderer, contextBridge } from 'electron'
contextBridge.exposeInMainWorld('ipcRenderer', {
on: (channel, listener) => {
return ipcRenderer.on(channel, (_event, ...args) => listener(...args))
},
off: (channel, ...args) => ipcRenderer.off(channel, ...args),
send: (channel, ...args) => ipcRenderer.send(channel, ...args),
invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args),
})
contextBridge.exposeInMainWorld('api', {
pb: {
fetchEntries: () => ipcRenderer.invoke('pb:fetchEntries'),
createEntry: (data) => ipcRenderer.invoke('pb:createEntry', data),
updateEntry: (id, data) => ipcRenderer.invoke('pb:updateEntry', { id, ...data }),
deleteEntry: (id) => ipcRenderer.invoke('pb:deleteEntry', { id }),
},
})
function domReady(condition = ['complete', 'interactive']) {
return new Promise((resolve) => {
if (condition.includes(document.readyState)) {
resolve()
} else {
document.addEventListener('readystatechange', () => {
if (condition.includes(document.readyState)) resolve()
})
}
})
}
const safeDOM = {
append(parent, child) {
if (!Array.from(parent.children).includes(child)) parent.appendChild(child)
},
remove(parent, child) {
if (Array.from(parent.children).includes(child)) parent.removeChild(child)
},
}
function useLoading() {
const className = 'loaders-css__square-spin'
const styleContent = `
@keyframes square-spin {
25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }
50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }
75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }
100% { transform: perspective(100px) rotateX(0) rotateY(0); }
}
.${className} > div {
animation-fill-mode: both;
width: 50px;
height: 50px;
background: #fff;
animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;
}
.app-loading-wrap {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: #1a1b26;
z-index: 9;
}
`
const style = document.createElement('style')
const div = document.createElement('div')
style.id = 'app-loading-style'
style.textContent = styleContent
div.className = 'app-loading-wrap'
div.innerHTML = `<div class="${className}"><div></div></div>`
return {
appendLoading() {
safeDOM.append(document.head, style)
safeDOM.append(document.body, div)
},
removeLoading() {
safeDOM.remove(document.head, style)
safeDOM.remove(document.body, div)
},
}
}
const { appendLoading, removeLoading } = useLoading()
domReady().then(appendLoading)
window.onmessage = (ev) => {
if (ev.data?.payload === 'removeLoading') removeLoading()
}
setTimeout(removeLoading, 4000)