Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a4be7c4cff | |||
| deb31d248f | |||
| 66374196c5 | |||
| ec54373848 | |||
| caf75fbb3f | |||
| da5d436432 | |||
| dff5fd4156 | |||
| 0c4e190952 | |||
| 01ca9a08d1 | |||
| 3b1a35b7f2 | |||
| 8587fb9378 | |||
| 572b4d8c37 | |||
| cac97f1d9c | |||
| c2d61c96cd | |||
| d70081159d | |||
| 8a944d1d20 |
@@ -5,3 +5,11 @@ SESSION_SECRET=replace-with-a-random-64-character-hex-string
|
||||
SESSION_MAX_AGE_HOURS=168 # default: 168 (7 days)
|
||||
PORT=3000
|
||||
DB_PATH=/app/data/check-printing.db
|
||||
|
||||
# OIDC / SSO (optional — omit or leave blank to disable)
|
||||
OIDC_ENABLED=false
|
||||
OIDC_DISCOVERY_URL=https://auth.example.com/.well-known/openid-configuration
|
||||
OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
OIDC_REDIRECT_URI=https://checks.example.com/api/auth/oidc/callback
|
||||
OIDC_BUTTON_LABEL=Sign in with SSO
|
||||
|
||||
@@ -1,124 +1,198 @@
|
||||
# check-printing
|
||||
|
||||
Self-hosted web app for printing checks and bank deposit slips. A containerized Node.js web app accessible on the local network.
|
||||
Self-hosted web app for printing checks and bank deposit slips on blank check stock. Runs as a containerized Node.js app accessible on your local network or behind a reverse proxy.
|
||||
|
||||
## Features
|
||||
|
||||
- Check ledger with search, filtering, and sorting
|
||||
- Precise 3-up check PDFs (three checks per 8.5" x 11" letter page, multi-page supported)
|
||||
- MICR E-13B encoding for routing/account lines (GnuMICR font, GPL-2.0)
|
||||
- Bank deposit slips with digit-column formatting and MICR line
|
||||
- Deposit reports for filing
|
||||
- Visual drag-and-drop check layout editor
|
||||
- Multi-account support with per-user access control
|
||||
- OIDC / SSO login (OpenID Connect)
|
||||
- Password reset via email (SMTP)
|
||||
- QBO CSV import for checks and deposits
|
||||
- ezCheckPrinting .mdb import
|
||||
|
||||
## Stack
|
||||
|
||||
- **Runtime:** Node.js 20
|
||||
- **Framework:** Express 4
|
||||
- **Database:** SQLite via `better-sqlite3`
|
||||
- **PDF generation:** PDFKit with embedded GnuMICR E-13B font (GPL-2.0)
|
||||
- **PDF generation:** PDFKit with embedded GnuMICR E-13B font
|
||||
- **Frontend:** Vanilla JS, no framework
|
||||
- **Container:** Docker Compose pulling from Docker Hub
|
||||
- **Container:** Docker Compose pulling from Docker Hub (`dogiakos/check-printing`)
|
||||
|
||||
## Getting started
|
||||
|
||||
### Production (Docker)
|
||||
|
||||
1. Create a `.env` file (see `.env.example`):
|
||||
|
||||
```bash
|
||||
SESSION_SECRET=$(openssl rand -hex 32)
|
||||
```
|
||||
|
||||
2. Start the container:
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
On first launch, the app detects no users are configured and opens a **setup wizard** in the browser. Create the first admin account, then configure checkwriter info, bank info, and account/routing numbers. If you have an existing ezCheckPrinting `.mdb` file, click **Import .mdb** instead.
|
||||
3. Open the app in your browser. On first launch, create the initial admin account when prompted.
|
||||
|
||||
4. Use the setup wizard to configure your first checking account (organization info, bank info, routing/account numbers), or import an existing ezCheckPrinting `.mdb` file.
|
||||
|
||||
### Development (local)
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # nodemon src/app.js
|
||||
cp .env.example .env # edit .env with your values
|
||||
npm run dev # nodemon with --env-file=.env
|
||||
```
|
||||
|
||||
## Authentication and user roles
|
||||
## Authentication
|
||||
|
||||
All access requires login. The first run prompts you to create an admin account.
|
||||
|
||||
Three roles are available:
|
||||
### Roles
|
||||
|
||||
| Role | Access |
|
||||
|------|--------|
|
||||
| **admin** | Full access to all accounts; create/edit/delete users and accounts |
|
||||
| **editor** | Read and write access to assigned accounts |
|
||||
| **viewer** | Read-only access to assigned accounts |
|
||||
| --- | --- |
|
||||
| **Admin** | Full access to all accounts; manage users, accounts, and app settings |
|
||||
| **Editor** | Read and write access to assigned accounts |
|
||||
| **Viewer** | Read-only access to assigned accounts |
|
||||
|
||||
Admins have editor access to all accounts automatically. Non-admin users are assigned per-account roles individually. User management is available in the **Users** panel (admin only). Any user can change their own password from the account menu.
|
||||
Admins have editor access to all accounts automatically. Non-admin users are assigned per-account roles individually.
|
||||
|
||||
### User management
|
||||
|
||||
Available in the **Manage Users** panel (admin only):
|
||||
|
||||
- Create, edit, and delete users
|
||||
- Assign per-account roles
|
||||
- Configure SMTP for password reset emails
|
||||
- Link/unlink OIDC identities
|
||||
|
||||
Any user can change their own password and link/unlink their OIDC identity from the account menu (click your username in the header).
|
||||
|
||||
### OIDC / SSO
|
||||
|
||||
OIDC login is configured via environment variables (see below). When enabled, a **Sign in with SSO** button appears on the login page.
|
||||
|
||||
Users must link their local account to their OIDC identity before SSO login will work. Two ways to link:
|
||||
|
||||
1. **Self-service:** Sign in with your password, click your username, then click **Link My Account** in the Single Sign-On section
|
||||
2. **Admin:** Edit a user in the Manage Users panel and set the OIDC Subject and Issuer fields
|
||||
|
||||
OIDC uses the authorization code flow with PKCE. The provider must have the redirect URI registered: `https://your-app.example.com/api/auth/oidc/callback`
|
||||
|
||||
## Multi-account support
|
||||
|
||||
The app supports multiple checking accounts in a single instance. Each account has its own check ledger, deposit records, and layout configuration. Admins can create, edit, and delete accounts. Deleting an account removes all associated checks, deposits, and layout data.
|
||||
The app supports multiple checking accounts in a single instance. Each account has its own check ledger, deposit records, and layout configuration. Use the account switcher in the header to switch between accounts. Admins can create, edit, and delete accounts.
|
||||
|
||||
## Printing
|
||||
## Checks
|
||||
|
||||
1. Select 1–3 checks from the ledger (checkbox column)
|
||||
1. Select 1 or more checks from the ledger (checkbox column)
|
||||
2. Click **Generate PDF**
|
||||
3. A 3-up 8.5"×11" PDF opens in a new tab — three 3.5" check slots per page
|
||||
4. Print from the browser; checks are marked as printed in the ledger
|
||||
3. A 3-up 8.5" x 11" PDF opens in a new tab
|
||||
4. Print from the browser; checks are marked as printed
|
||||
|
||||
Use the **Reprint** button on printed checks to regenerate without re-marking them.
|
||||
Use **Reprint** on printed checks to regenerate without re-marking.
|
||||
|
||||
Multi-page PDFs are supported when more than 3 checks are selected.
|
||||
### Check layout
|
||||
|
||||
- Page: 8.5" x 11", zero margins
|
||||
- Three check slots of 3.5" each
|
||||
- MICR line at 0.267" from bottom of each slot
|
||||
- MICR format: `A{routing}A {account}C {checkNo}A` (GnuMICR E-13B encoding)
|
||||
|
||||
## Deposit slips
|
||||
|
||||
Switch to the **Deposits** tab in the toolbar to manage bank deposits.
|
||||
1. Switch to the **Deposits** tab
|
||||
2. Click **+ New Deposit**
|
||||
3. Enter deposit date, currency, coin, and cash back amounts
|
||||
4. Add each check (check number, payee, memo, amount) -- totals update live
|
||||
5. **Save Deposit**, then click **Deposit Slip** or **Report** to generate a PDF
|
||||
|
||||
1. Click **+ New Deposit** to open the deposit entry panel
|
||||
2. Enter the deposit date, currency, coin, and cash back amounts
|
||||
3. Add each check being deposited (check number, payee, memo, amount) — totals update live
|
||||
4. Click **Save Deposit**, then **Deposit Slip** or **Report** to generate a PDF
|
||||
**Deposit Slip** generates a 3.375" x 8.5" PDF matching physical bank deposit slip stock with digit-column formatting, MICR line, and rotated totals.
|
||||
|
||||
**Deposit Slip** generates a precisely positioned 3.375" × 8.5" PDF matching physical bank deposit slip stock, including:
|
||||
**Deposit Report** generates a plain formatted ledger document for filing.
|
||||
|
||||
- Style A background (form lines and labels drawn server-side — no preprinted stock required)
|
||||
- Digit-column amount formatting
|
||||
- Routing/account line in E-13B magnetic ink character recognition font, rotated 90°
|
||||
- Rotated deposit total and check count in the left margin
|
||||
## Visual layout editor
|
||||
|
||||
**Deposit Report** generates a plain formatted ledger document listing all checks, cash totals, and the final deposit amount — suitable for filing.
|
||||
Click the **layout** button in the header (editors and above) to open the layout editor.
|
||||
|
||||
Generating a deposit slip marks the deposit as printed in the ledger.
|
||||
- Full-screen canvas with inch rulers
|
||||
- Drag any check element to reposition it
|
||||
- Position readout in inches and fractions with nudge buttons
|
||||
- Visibility toggle to hide fields from PDFs
|
||||
- Auto-saves on change
|
||||
- **Reset to Defaults** restores the built-in layout
|
||||
|
||||
## Importing from QuickBooks Online (QBO CSV)
|
||||
## Importing
|
||||
|
||||
Checks and deposits can be imported from a QuickBooks Online CSV export. Click **Import QBO CSV** in the toolbar, select the file, choose whether to import checks or deposits, and review the parsed records before confirming.
|
||||
### QuickBooks Online (QBO CSV)
|
||||
|
||||
The importer handles:
|
||||
Click **Import QBO** in the toolbar. Supports standard QBO export columns, automatic type filtering (checks vs. deposits), duplicate detection, and auto-numbering.
|
||||
|
||||
- Standard QBO export column layouts (`Date`, `Transaction Type`, `Num`, `Name`, `Memo/Description`, `Amount`, `Debit`, `Credit`)
|
||||
- Automatic type filtering — checks are matched by transaction type `Check`, deposits by `Deposit`
|
||||
- Duplicate detection — existing check numbers are skipped
|
||||
- Auto-assignment of check numbers when the source CSV has no `Num` value
|
||||
- Grouping of deposit rows by date into individual deposit records
|
||||
### ezCheckPrinting (.mdb)
|
||||
|
||||
## Importing from ezCheckPrinting (.mdb)
|
||||
**Via the UI:** Click **Import .mdb** in the toolbar, select the file, and click Import.
|
||||
|
||||
Two ways to import:
|
||||
|
||||
**Via the UI (recommended):** Click **Import .mdb** in the toolbar, select the file, and click Import. The server runs the migration and shows the log output.
|
||||
|
||||
**Via CLI** (inside the container or locally with `mdbtools` installed):
|
||||
**Via CLI** (inside the container):
|
||||
|
||||
```bash
|
||||
docker exec -it check-printing node migrations/import-mdb.js \
|
||||
--file "/app/data/YourAccount.mdb"
|
||||
|
||||
# Preview without writing:
|
||||
node migrations/import-mdb.js --file YourAccount.mdb --dry-run
|
||||
docker exec -it check-printing node migrations/import-mdb.js \
|
||||
--file "/app/data/YourAccount.mdb" --dry-run
|
||||
```
|
||||
|
||||
The script imports account config (T100), logo (Settings), check layout (T200), and check history (T104).
|
||||
|
||||
## Check layout
|
||||
|
||||
- Page: 8.5" × 11", zero margins
|
||||
- Three check slots of 3.5" each; remaining ~0.5" is tear-off strip
|
||||
- MICR line at 0.267" from bottom of each slot
|
||||
- MICR format: `A{routing}A {account}C {checkNo}A` (GnuMICR E-13B encoding)
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | `3000` | HTTP port |
|
||||
| `DB_PATH` | `/app/data/check-printing.db` | SQLite database path |
|
||||
| `SESSION_SECRET` | *(random)* | Secret for signing session cookies — set explicitly in production |
|
||||
| --- | --- | --- |
|
||||
| `SESSION_SECRET` | *(required)* | Secret for signing session cookies. Generate with `openssl rand -hex 32` |
|
||||
| `SESSION_MAX_AGE_HOURS` | `168` | Session lifetime in hours (default 7 days) |
|
||||
| `PORT` | `3000` | HTTP listen port |
|
||||
| `DB_PATH` | `/app/data/check-printing.db` | SQLite database file path |
|
||||
| `OIDC_ENABLED` | *(empty)* | Set to `true` or `1` to enable OIDC login |
|
||||
| `OIDC_DISCOVERY_URL` | *(empty)* | Provider's `.well-known/openid-configuration` URL |
|
||||
| `OIDC_CLIENT_ID` | *(empty)* | OIDC client ID |
|
||||
| `OIDC_CLIENT_SECRET` | *(empty)* | OIDC client secret |
|
||||
| `OIDC_REDIRECT_URI` | *(empty)* | Full callback URL, e.g. `https://checks.example.com/api/auth/oidc/callback` |
|
||||
| `OIDC_BUTTON_LABEL` | `Sign in with SSO` | Text shown on the SSO login button |
|
||||
|
||||
SMTP settings for password reset emails are configured in the admin UI (Manage Users > Email Settings).
|
||||
|
||||
## Docker Compose
|
||||
|
||||
```yaml
|
||||
services:
|
||||
check-printing:
|
||||
image: dogiakos/check-printing:latest
|
||||
container_name: check-printing
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3003:3000"
|
||||
volumes:
|
||||
- check-printing-data:/app/data
|
||||
environment:
|
||||
- SESSION_SECRET=${SESSION_SECRET}
|
||||
# Optional: OIDC / SSO
|
||||
- OIDC_ENABLED=${OIDC_ENABLED:-}
|
||||
- OIDC_DISCOVERY_URL=${OIDC_DISCOVERY_URL:-}
|
||||
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-}
|
||||
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET:-}
|
||||
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-}
|
||||
- OIDC_BUTTON_LABEL=${OIDC_BUTTON_LABEL:-Sign in with SSO}
|
||||
|
||||
volumes:
|
||||
check-printing-data:
|
||||
```
|
||||
|
||||
@@ -14,6 +14,13 @@ services:
|
||||
- DB_PATH=/app/data/check-printing.db
|
||||
# Required in production — generate with: openssl rand -hex 32
|
||||
- SESSION_SECRET=${SESSION_SECRET}
|
||||
# OIDC / SSO (optional — omit or leave blank to disable)
|
||||
- OIDC_ENABLED=${OIDC_ENABLED:-}
|
||||
- OIDC_DISCOVERY_URL=${OIDC_DISCOVERY_URL:-}
|
||||
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-}
|
||||
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET:-}
|
||||
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-}
|
||||
- OIDC_BUTTON_LABEL=${OIDC_BUTTON_LABEL:-Sign in with SSO}
|
||||
|
||||
volumes:
|
||||
check-printing-data:
|
||||
|
||||
Generated
+67
-6
@@ -1,19 +1,20 @@
|
||||
{
|
||||
"name": "ezcheck",
|
||||
"version": "0.1.0",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ezcheck",
|
||||
"version": "0.1.0",
|
||||
"version": "0.4.0",
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^9.4.3",
|
||||
"express": "^4.18.3",
|
||||
"express-session": "^1.19.0",
|
||||
"multer": "^2.1.1",
|
||||
"nodemailer": "^8.0.4",
|
||||
"nodemailer": "^8.0.5",
|
||||
"openid-client": "^5.7.1",
|
||||
"pdfkit": "^0.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -1391,6 +1392,15 @@
|
||||
"integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jose": {
|
||||
"version": "4.15.9",
|
||||
"resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz",
|
||||
"integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/jpeg-exif": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz",
|
||||
@@ -1417,6 +1427,18 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
@@ -1582,9 +1604,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "8.0.4",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.4.tgz",
|
||||
"integrity": "sha512-k+jf6N8PfQJ0Fe8ZhJlgqU5qJU44Lpvp2yvidH3vp1lPnVQMgi4yEEMPXg5eJS1gFIJTVq1NHBk7Ia9ARdSBdQ==",
|
||||
"version": "8.0.5",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.5.tgz",
|
||||
"integrity": "sha512-0PF8Yb1yZuQfQbq+5/pZJrtF6WQcjTd5/S4JOHs9PGFxuTqoB/icwuB44pOdURHJbRKX1PPoJZtY7R4VUoCC8w==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
@@ -1654,6 +1676,15 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
|
||||
"integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -1711,6 +1742,15 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/oidc-token-hash": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz",
|
||||
"integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^10.13.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
||||
@@ -1741,6 +1781,21 @@
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/openid-client": {
|
||||
"version": "5.7.1",
|
||||
"resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz",
|
||||
"integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jose": "^4.15.9",
|
||||
"lru-cache": "^6.0.0",
|
||||
"object-hash": "^2.2.0",
|
||||
"oidc-token-hash": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/panva"
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "0.2.9",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
|
||||
@@ -2542,6 +2597,12 @@
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"license": "ISC"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ezcheck",
|
||||
"version": "0.2.0",
|
||||
"version": "0.4.0",
|
||||
"description": "Self-hosted check printing web app",
|
||||
"main": "src/app.js",
|
||||
"scripts": {
|
||||
@@ -14,7 +14,8 @@
|
||||
"express": "^4.18.3",
|
||||
"express-session": "^1.19.0",
|
||||
"multer": "^2.1.1",
|
||||
"nodemailer": "^8.0.4",
|
||||
"nodemailer": "^8.0.5",
|
||||
"openid-client": "^5.7.1",
|
||||
"pdfkit": "^0.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -88,6 +88,18 @@ header {
|
||||
}
|
||||
|
||||
.modal-wide { width: min(720px, 96vw); }
|
||||
.modal.modal-layout-editor { width: min(1400px, 96vw); height: 92vh; max-height: 92vh; }
|
||||
.layout-editor-body { flex: 1; min-height: 0; flex-direction: column !important; padding: 0 !important; gap: 0; overflow: hidden; }
|
||||
.layout-canvas-area { flex: 1; min-height: 0; display: grid; grid-template-columns: 24px 1fr; grid-template-rows: 24px 1fr; }
|
||||
.layout-ruler-corner { background: var(--surface); border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
#layout-ruler-top { background: var(--surface); border-bottom: 1px solid var(--border); overflow: hidden; }
|
||||
#layout-ruler-left { background: var(--surface); border-right: 1px solid var(--border); overflow: hidden; }
|
||||
#layout-canvas-container { overflow: hidden; background: #d4d4d4; }
|
||||
.layout-controls { flex-shrink: 0; display: flex; align-items: center; gap: 14px; padding: 8px 16px; border-top: 1px solid var(--border); background: var(--surface); flex-wrap: wrap; }
|
||||
.layout-coord { display: flex; align-items: center; gap: 4px; }
|
||||
.layout-coord label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: var(--text-muted); white-space: nowrap; margin: 0; }
|
||||
.layout-coord input { width: 68px; }
|
||||
.layout-coord .frac { font-size: 11px; color: var(--text-muted); min-width: 28px; }
|
||||
|
||||
.qbo-tabs {
|
||||
display: flex;
|
||||
@@ -798,6 +810,56 @@ input[type="file"] {
|
||||
.login-card h2 { font-size: 16px; font-weight: 600; margin-bottom: 4px; }
|
||||
.login-sub { font-size: 12px; color: var(--text-muted); margin-bottom: 16px; }
|
||||
|
||||
.login-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 16px 0 12px;
|
||||
gap: 12px;
|
||||
}
|
||||
.login-divider::before,
|
||||
.login-divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
}
|
||||
.login-divider span {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.btn-oidc {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 10px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.btn-oidc:hover {
|
||||
background: var(--bg);
|
||||
border-color: #b0b0b0;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
|
||||
}
|
||||
.btn-oidc:active {
|
||||
background: #e8e8e8;
|
||||
}
|
||||
.btn-oidc svg {
|
||||
flex-shrink: 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* ── User management ── */
|
||||
.account-checkboxes { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
.account-checkbox-label {
|
||||
@@ -812,3 +874,8 @@ input[type="file"] {
|
||||
cursor: pointer;
|
||||
}
|
||||
.account-checkbox-label:hover { border-color: var(--primary); }
|
||||
|
||||
/* Hide layout editor button on portrait/mobile — canvas needs landscape space */
|
||||
@media (max-width: 768px), (orientation: portrait) {
|
||||
#btn-layout-editor { display: none !important; }
|
||||
}
|
||||
|
||||
+106
-2
@@ -43,6 +43,13 @@
|
||||
</div>
|
||||
<div id="login-error" class="wizard-error" hidden></div>
|
||||
<button id="btn-login-submit" class="btn-primary" style="width:100%;margin-top:8px">Sign In</button>
|
||||
<div id="oidc-login-section" hidden>
|
||||
<div class="login-divider"><span>or</span></div>
|
||||
<a id="btn-oidc-login" href="/api/auth/oidc/authorize" class="btn-oidc">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
|
||||
<span id="btn-oidc-login-label">Sign in with SSO</span>
|
||||
</a>
|
||||
</div>
|
||||
<div style="text-align:center;margin-top:8px">
|
||||
<a href="#" id="link-forgot-password" style="font-size:12px;color:var(--text-muted)">Forgot password?</a>
|
||||
</div>
|
||||
@@ -85,12 +92,13 @@
|
||||
<span class="header-brand" id="company-name">ezcheck</span>
|
||||
<select id="account-switcher" class="account-switcher" title="Switch account"></select>
|
||||
<button id="btn-account-settings" class="btn-header-icon" title="Account settings" data-admin-only>⚙</button>
|
||||
<button id="btn-layout-editor" class="btn-header-icon" title="Edit check layout" data-editor-only>⊞</button>
|
||||
<button id="btn-add-account" class="btn-header-icon" title="Add checking account" data-admin-only>+</button>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<span class="header-info">Next check: <strong id="current-check-no">—</strong><button id="btn-set-check-no" class="btn-header-inline" title="Set next check number" data-admin-only>✎</button></span>
|
||||
<button id="btn-users" class="btn-header-icon" title="Manage users" data-admin-only hidden>👥</button>
|
||||
<span id="header-username" class="header-username"></span>
|
||||
<span id="header-username" class="header-username" style="cursor:pointer" title="Account settings"></span>
|
||||
<button id="btn-logout" class="btn-header-icon" title="Sign out">↩</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -464,6 +472,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="settings-section-label">Check Position</p>
|
||||
<div class="form-group">
|
||||
<label for="as-check-position">Print checks in</label>
|
||||
<select id="as-check-position" name="check_position">
|
||||
<option value="3-per-page">All 3 slots (3 per page)</option>
|
||||
<option value="top">Top slot only</option>
|
||||
<option value="middle">Middle slot only</option>
|
||||
<option value="bottom">Bottom slot only</option>
|
||||
</select>
|
||||
<span class="field-hint">Choose which slot(s) on the page to print checks in.</span>
|
||||
</div>
|
||||
|
||||
<div id="acct-settings-error" class="wizard-error" hidden></div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -647,7 +667,7 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="users-list"></div>
|
||||
<div style="margin-top:16px;border-top:1px solid var(--border);padding-top:16px">
|
||||
<div id="user-form-section" style="margin-top:16px;border-top:1px solid var(--border);padding-top:16px">
|
||||
<h3 style="font-size:13px;font-weight:600;margin-bottom:10px" id="user-form-title">Add User</h3>
|
||||
<div class="form-row">
|
||||
<div class="form-group required">
|
||||
@@ -675,6 +695,16 @@
|
||||
<label>Account Access <span class="field-hint">(admins see all — no selection needed)</span></label>
|
||||
<div id="uf-accounts-checkboxes" class="account-checkboxes"></div>
|
||||
</div>
|
||||
<div id="uf-oidc-group" class="form-row" hidden>
|
||||
<div class="form-group">
|
||||
<label for="uf-oidc-sub">OIDC Subject <span class="field-hint">(sub claim from provider)</span></label>
|
||||
<input type="text" id="uf-oidc-sub" autocomplete="off">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="uf-oidc-issuer">OIDC Issuer <span class="field-hint">(provider URL)</span></label>
|
||||
<input type="text" id="uf-oidc-issuer" autocomplete="off">
|
||||
</div>
|
||||
</div>
|
||||
<div id="user-form-error" class="wizard-error" hidden></div>
|
||||
<div style="display:flex;gap:8px;margin-top:8px">
|
||||
<button id="btn-save-user" class="btn-primary">Add User</button>
|
||||
@@ -740,6 +770,80 @@
|
||||
<div id="cp-success" class="import-result" hidden>Password changed.</div>
|
||||
<button id="btn-change-password" class="btn-secondary" style="margin-top:8px">Change Password</button>
|
||||
</div>
|
||||
<!-- Link my OIDC identity (self-service, shown when OIDC is enabled) -->
|
||||
<div id="oidc-link-section" style="margin-top:16px;border-top:1px solid var(--border);padding-top:16px" hidden>
|
||||
<h3 style="font-size:13px;font-weight:600;margin-bottom:10px">Single Sign-On</h3>
|
||||
<p id="oidc-link-status" style="font-size:12px;color:var(--text-muted);margin-bottom:8px"></p>
|
||||
<a id="btn-oidc-link" href="/api/auth/oidc/link" class="btn-secondary" style="display:inline-block;text-decoration:none">Link My Account</a>
|
||||
<button id="btn-oidc-unlink" class="btn-ghost" style="margin-left:8px" hidden>Unlink</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Layout Editor Modal -->
|
||||
<div id="layout-editor-overlay" class="modal-overlay"></div>
|
||||
<div id="layout-editor-modal" class="modal modal-layout-editor" role="dialog" aria-labelledby="layout-editor-title">
|
||||
<div class="modal-header">
|
||||
<h2 id="layout-editor-title">Layout Editor</h2>
|
||||
<button id="btn-close-layout-editor" class="btn-icon" title="Close">×</button>
|
||||
</div>
|
||||
<div class="modal-body layout-editor-body">
|
||||
<!-- Canvas with rulers -->
|
||||
<div class="layout-canvas-area">
|
||||
<div class="layout-ruler-corner"></div>
|
||||
<div id="layout-ruler-top"></div>
|
||||
<div id="layout-ruler-left"></div>
|
||||
<div id="layout-canvas-container"><!-- SVG rendered by JS --></div>
|
||||
</div>
|
||||
<!-- Controls strip -->
|
||||
<div class="layout-controls">
|
||||
<div class="layout-coord" style="gap:6px">
|
||||
<label for="layout-field-select" style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-muted)">Field</label>
|
||||
<select id="layout-field-select" style="font-size:12px;max-width:200px"></select>
|
||||
</div>
|
||||
<label style="display:flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;white-space:nowrap">
|
||||
<input type="checkbox" id="layout-field-visible"> Visible
|
||||
</label>
|
||||
<div style="width:1px;height:24px;background:var(--border)"></div>
|
||||
<div class="layout-coord">
|
||||
<label for="layout-field-x">X</label>
|
||||
<input type="number" id="layout-field-x" step="0.0625" min="0" max="8.5">
|
||||
<span class="frac" id="layout-field-x-frac"></span>
|
||||
</div>
|
||||
<div class="layout-coord">
|
||||
<label for="layout-field-y">Y</label>
|
||||
<input type="number" id="layout-field-y" step="0.0625" min="0" max="3.5">
|
||||
<span class="frac" id="layout-field-y-frac"></span>
|
||||
</div>
|
||||
<div id="layout-end-pos-group" style="display:contents" hidden>
|
||||
<div class="layout-coord">
|
||||
<label for="layout-field-x2">End X</label>
|
||||
<input type="number" id="layout-field-x2" step="0.0625" min="0" max="8.5">
|
||||
<span class="frac" id="layout-field-x2-frac"></span>
|
||||
</div>
|
||||
<div class="layout-coord">
|
||||
<label for="layout-field-y2">End Y</label>
|
||||
<input type="number" id="layout-field-y2" step="0.0625" min="0" max="3.5">
|
||||
<span class="frac" id="layout-field-y2-frac"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="width:1px;height:24px;background:var(--border)"></div>
|
||||
<!-- Nudge cross -->
|
||||
<div style="display:flex;flex-direction:column;align-items:center;gap:2px">
|
||||
<div style="font-size:10px;text-transform:uppercase;color:var(--text-muted);letter-spacing:.04em">¹⁄₁₆"</div>
|
||||
<div style="display:grid;grid-template-columns:repeat(3,22px);grid-template-rows:repeat(3,22px);gap:2px">
|
||||
<span></span><button id="nudge-up" class="btn-sm btn-secondary" style="padding:0;display:flex;align-items:center;justify-content:center">↑</button><span></span>
|
||||
<button id="nudge-left" class="btn-sm btn-secondary" style="padding:0;display:flex;align-items:center;justify-content:center">←</button>
|
||||
<span></span>
|
||||
<button id="nudge-right" class="btn-sm btn-secondary" style="padding:0;display:flex;align-items:center;justify-content:center">→</button>
|
||||
<span></span><button id="nudge-down" class="btn-sm btn-secondary" style="padding:0;display:flex;align-items:center;justify-content:center">↓</button><span></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="layout-save-status" style="font-size:11px;color:var(--text-muted);min-width:56px"></div>
|
||||
<div style="margin-left:auto">
|
||||
<button id="btn-layout-reset" class="btn-secondary btn-sm" data-admin-only>↺ Reset to Default</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+529
-2
@@ -52,6 +52,23 @@ async function checkAuth() {
|
||||
showLoginOverlay();
|
||||
return false;
|
||||
}
|
||||
|
||||
// OIDC callback error/success detection
|
||||
if (location.hash.startsWith('#oidc-error=')) {
|
||||
const msg = decodeURIComponent(location.hash.slice('#oidc-error='.length));
|
||||
history.replaceState(null, '', location.pathname);
|
||||
showLoginSection('login-form-section');
|
||||
const errEl = document.getElementById('login-error');
|
||||
errEl.textContent = msg;
|
||||
errEl.hidden = false;
|
||||
showLoginOverlay();
|
||||
return false;
|
||||
}
|
||||
if (location.hash === '#oidc-linked') {
|
||||
history.replaceState(null, '', location.pathname);
|
||||
// Fall through to normal auth check — user is still logged in
|
||||
}
|
||||
|
||||
// Is there already a session?
|
||||
const res = await fetch('/api/auth/me');
|
||||
if (res.ok) {
|
||||
@@ -68,10 +85,27 @@ async function checkAuth() {
|
||||
} else {
|
||||
showLoginSection('login-form-section');
|
||||
}
|
||||
// Show SSO button if OIDC is enabled
|
||||
loadOidcLoginButton();
|
||||
showLoginOverlay();
|
||||
return false;
|
||||
}
|
||||
|
||||
async function loadOidcLoginButton() {
|
||||
try {
|
||||
const res = await fetch('/api/auth/oidc/config');
|
||||
if (!res.ok) return;
|
||||
const cfg = await res.json();
|
||||
const section = document.getElementById('oidc-login-section');
|
||||
if (cfg.enabled) {
|
||||
document.getElementById('btn-oidc-login-label').textContent = cfg.button_label || 'Sign in with SSO';
|
||||
section.hidden = false;
|
||||
} else {
|
||||
section.hidden = true;
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
async function submitLogin() {
|
||||
const username = document.getElementById('login-username').value.trim();
|
||||
const password = document.getElementById('login-password').value;
|
||||
@@ -158,12 +192,21 @@ function applyRoleUI() {
|
||||
let usersState = { users: [], editingId: null };
|
||||
|
||||
function openUsersModal() {
|
||||
const isAdmin = state.user && state.user.role === 'admin';
|
||||
document.getElementById('user-form-error').hidden = true;
|
||||
document.getElementById('users-title').textContent = isAdmin ? 'Manage Users' : 'My Account';
|
||||
document.getElementById('users-overlay').classList.add('open');
|
||||
document.getElementById('users-modal').classList.add('open');
|
||||
// Admin-only sections
|
||||
document.getElementById('users-list').hidden = !isAdmin;
|
||||
document.getElementById('user-form-section').hidden = !isAdmin;
|
||||
document.getElementById('smtp-settings-section').hidden = !isAdmin;
|
||||
if (isAdmin) {
|
||||
loadUsers();
|
||||
renderUfAccountCheckboxes();
|
||||
if (state.user && state.user.role === 'admin') loadSmtpSettings();
|
||||
loadSmtpSettings();
|
||||
}
|
||||
loadOidcLinkStatus();
|
||||
}
|
||||
|
||||
function closeUsersModal() {
|
||||
@@ -204,8 +247,9 @@ function renderUsersList() {
|
||||
const name = escHtml(a ? (a.company1 || `Account ${a.account_id}`) : `#${ua.account_id}`);
|
||||
return `${name} <span style="font-size:10px;color:${ua.role === 'editor' ? '#16a34a' : '#6b7280'};font-weight:600;text-transform:uppercase">${ua.role}</span>`;
|
||||
}).join(', ') : '<em style="color:var(--text-muted)">None</em>');
|
||||
const oidcTag = u.oidc_sub ? ' <span style="font-size:10px;color:#2563eb;font-weight:600" title="OIDC linked">SSO</span>' : '';
|
||||
return `<tr>
|
||||
<td><strong>${escHtml(u.username)}</strong>${isSelf ? ' <em style="color:var(--text-muted)">(you)</em>' : ''}</td>
|
||||
<td><strong>${escHtml(u.username)}</strong>${isSelf ? ' <em style="color:var(--text-muted)">(you)</em>' : ''}${oidcTag}</td>
|
||||
<td>${roleBadge(u.role)}</td>
|
||||
<td style="font-size:12px">${accountsLabel}</td>
|
||||
<td style="white-space:nowrap">
|
||||
@@ -253,6 +297,10 @@ function startUserEdit(userId) {
|
||||
document.getElementById('btn-save-user').textContent = 'Save Changes';
|
||||
document.getElementById('btn-cancel-user-edit').hidden = false;
|
||||
document.getElementById('user-form-error').hidden = true;
|
||||
// OIDC fields
|
||||
document.getElementById('uf-oidc-sub').value = u.oidc_sub || '';
|
||||
document.getElementById('uf-oidc-issuer').value = u.oidc_issuer || '';
|
||||
document.getElementById('uf-oidc-group').hidden = false;
|
||||
renderUfAccountCheckboxes();
|
||||
document.getElementById('uf-username').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
@@ -268,6 +316,10 @@ function cancelUserEdit() {
|
||||
document.getElementById('btn-save-user').textContent = 'Add User';
|
||||
document.getElementById('btn-cancel-user-edit').hidden = true;
|
||||
document.getElementById('user-form-error').hidden = true;
|
||||
// OIDC fields
|
||||
document.getElementById('uf-oidc-sub').value = '';
|
||||
document.getElementById('uf-oidc-issuer').value = '';
|
||||
document.getElementById('uf-oidc-group').hidden = true;
|
||||
renderUfAccountCheckboxes();
|
||||
}
|
||||
|
||||
@@ -296,6 +348,8 @@ async function saveUser() {
|
||||
const body = { username, email, role, accounts };
|
||||
if (password) body.password = password;
|
||||
if (usersState.editingId) {
|
||||
body.oidc_sub = document.getElementById('uf-oidc-sub').value.trim();
|
||||
body.oidc_issuer = document.getElementById('uf-oidc-issuer').value.trim();
|
||||
await apiFetch('PUT', `/api/users/${usersState.editingId}`, body);
|
||||
} else {
|
||||
await apiFetch('POST', '/api/users', body);
|
||||
@@ -909,6 +963,7 @@ function openAccountSettings() {
|
||||
f.elements.offset_up.value = a.offset_up || 0;
|
||||
f.elements.offset_down.value = a.offset_down || 0;
|
||||
document.getElementById('as-second-sig').checked = !!a.second_signature;
|
||||
document.getElementById('as-check-position').value = a.check_position || '3-per-page';
|
||||
|
||||
document.getElementById('as-logo').value = '';
|
||||
document.getElementById('as-logo-preview').hidden = true;
|
||||
@@ -947,6 +1002,7 @@ async function saveAccountSettings() {
|
||||
offset_up: parseFloat(f.elements.offset_up.value) || 0,
|
||||
offset_down: parseFloat(f.elements.offset_down.value) || 0,
|
||||
second_signature: document.getElementById('as-second-sig').checked ? 1 : 0,
|
||||
check_position: document.getElementById('as-check-position').value,
|
||||
logo_data: acctSettings.logoData || null,
|
||||
};
|
||||
|
||||
@@ -1603,6 +1659,42 @@ async function saveSmtpSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
// ── OIDC self-service linking ────────────────────────────────────────────────
|
||||
|
||||
async function loadOidcLinkStatus() {
|
||||
try {
|
||||
const cfg = await fetch('/api/auth/oidc/config').then(r => r.json());
|
||||
const section = document.getElementById('oidc-link-section');
|
||||
if (!cfg.enabled) { section.hidden = true; return; }
|
||||
section.hidden = false;
|
||||
|
||||
const me = await apiFetch('GET', '/api/auth/me');
|
||||
const statusEl = document.getElementById('oidc-link-status');
|
||||
const linkBtn = document.getElementById('btn-oidc-link');
|
||||
const unlinkBtn = document.getElementById('btn-oidc-unlink');
|
||||
|
||||
if (me.oidc_linked) {
|
||||
statusEl.textContent = 'Your account is linked to SSO.';
|
||||
linkBtn.hidden = true;
|
||||
unlinkBtn.hidden = false;
|
||||
} else {
|
||||
statusEl.textContent = 'Link your account to sign in with SSO.';
|
||||
linkBtn.hidden = false;
|
||||
unlinkBtn.hidden = true;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function unlinkOidc() {
|
||||
if (!confirm('Unlink your SSO identity? You will need to use your password to sign in.')) return;
|
||||
try {
|
||||
await apiFetch('POST', '/api/auth/oidc/unlink');
|
||||
await loadOidcLinkStatus();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Initialization ───────────────────────────────────────────────────────────
|
||||
|
||||
async function init() {
|
||||
@@ -1796,6 +1888,7 @@ async function init() {
|
||||
|
||||
// User management
|
||||
document.getElementById('btn-users').addEventListener('click', openUsersModal);
|
||||
document.getElementById('header-username').addEventListener('click', openUsersModal);
|
||||
document.getElementById('btn-close-users').addEventListener('click', closeUsersModal);
|
||||
document.getElementById('users-overlay').addEventListener('click', closeUsersModal);
|
||||
document.getElementById('users-list').addEventListener('click', e => {
|
||||
@@ -1809,13 +1902,447 @@ async function init() {
|
||||
document.getElementById('uf-role').addEventListener('change', renderUfAccountCheckboxes);
|
||||
document.getElementById('btn-change-password').addEventListener('click', changeOwnPassword);
|
||||
document.getElementById('btn-save-smtp').addEventListener('click', saveSmtpSettings);
|
||||
document.getElementById('btn-oidc-unlink').addEventListener('click', unlinkOidc);
|
||||
|
||||
// Add checking account
|
||||
document.getElementById('btn-add-account').addEventListener('click', openWizard);
|
||||
|
||||
// Layout editor
|
||||
document.getElementById('btn-layout-editor').addEventListener('click', openLayoutEditor);
|
||||
document.getElementById('btn-close-layout-editor').addEventListener('click', closeLayoutEditor);
|
||||
document.getElementById('layout-editor-overlay').addEventListener('click', closeLayoutEditor);
|
||||
document.getElementById('layout-field-select').addEventListener('change', e => selectLayoutField(parseInt(e.target.value, 10)));
|
||||
document.getElementById('layout-field-x').addEventListener('input', onLayoutSidebarChange);
|
||||
document.getElementById('layout-field-y').addEventListener('input', onLayoutSidebarChange);
|
||||
document.getElementById('layout-field-x2').addEventListener('input', onLayoutSidebarChange);
|
||||
document.getElementById('layout-field-y2').addEventListener('input', onLayoutSidebarChange);
|
||||
document.getElementById('layout-field-visible').addEventListener('change', onLayoutSidebarChange);
|
||||
document.getElementById('nudge-up').addEventListener('click', () => nudgeLayoutField( 0, -1));
|
||||
document.getElementById('nudge-down').addEventListener('click', () => nudgeLayoutField( 0, 1));
|
||||
document.getElementById('nudge-left').addEventListener('click', () => nudgeLayoutField(-1, 0));
|
||||
document.getElementById('nudge-right').addEventListener('click', () => nudgeLayoutField( 1, 0));
|
||||
document.getElementById('btn-layout-reset').addEventListener('click', resetLayoutToDefault);
|
||||
|
||||
// Initial auth check → loads app if already signed in
|
||||
const authed = await checkAuth();
|
||||
if (authed) await loadAccounts();
|
||||
}
|
||||
|
||||
// ── Layout Editor ─────────────────────────────────────────────────────────────
|
||||
|
||||
let layoutState = { fields: [], selectedId: null, scale: 80 };
|
||||
let layoutDrag = null;
|
||||
let layoutSaveTimer = null;
|
||||
|
||||
const FIELD_LABELS = {
|
||||
'Company Name': 'Account Name (line 1)',
|
||||
'Company Name2': 'Account Address (line 2)',
|
||||
'Company Name3': 'Account City/State (line 3)',
|
||||
'Company Name4': 'Account Phone/Web (line 4)',
|
||||
'Check Number': 'Check Number',
|
||||
'Date Label': 'Date Label',
|
||||
'Date': 'Date',
|
||||
'Pay To Label': '"Pay To" Label',
|
||||
'Payee Name': 'Payee Name',
|
||||
'Dollar Sign': 'Dollar Sign ($)',
|
||||
'Amount': 'Amount (numeric)',
|
||||
'Text Amount': 'Amount (written)',
|
||||
'Dollars Label': '"Dollars" Label',
|
||||
'Bank Information': 'Bank Information',
|
||||
'Bank Transit Code': 'Transit Code',
|
||||
'Payee Address': 'Payee Address',
|
||||
'Memo Label': 'Memo Label',
|
||||
'Memo': 'Memo',
|
||||
'Auth Signature Label': '"Authorized Signature" Label',
|
||||
'Payee Line': 'Line: Payee',
|
||||
'Amount Box Top': 'Line: Amount Box (top)',
|
||||
'Amount Box Left': 'Line: Amount Box (left)',
|
||||
'Amount Box Bottom': 'Line: Amount Box (bottom)',
|
||||
'Text Amount Line': 'Line: Written Amount',
|
||||
'Memo Line': 'Line: Memo',
|
||||
'Signature Line': 'Line: Signature',
|
||||
};
|
||||
const FIELD_COLORS = { Regular: '#2563eb', Text: '#16a34a', Line: '#b45309', Graph: '#7c3aed' };
|
||||
|
||||
function fieldLabel(f) { return FIELD_LABELS[f.field_name] || f.field_name; }
|
||||
function round16(v) { return Math.round(v * 16) / 16; }
|
||||
function clampIn(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
const FRAC_MAP = [
|
||||
[0,''], [1/16,'¹⁄₁₆'], [1/8,'⅛'], [3/16,'³⁄₁₆'],
|
||||
[1/4,'¼'], [5/16,'⁵⁄₁₆'], [3/8,'⅜'], [7/16,'⁷⁄₁₆'],
|
||||
[1/2,'½'], [9/16,'⁹⁄₁₆'], [5/8,'⅝'], [11/16,'¹¹⁄₁₆'],
|
||||
[3/4,'¾'], [13/16,'¹³⁄₁₆'], [7/8,'⅞'], [15/16,'¹⁵⁄₁₆'],
|
||||
];
|
||||
function toFracStr(val) {
|
||||
const w = Math.floor(val);
|
||||
const dec = val - w;
|
||||
const fr = FRAC_MAP.reduce((a, b) => Math.abs(b[0] - dec) < Math.abs(a[0] - dec) ? b : a);
|
||||
const parts = [];
|
||||
if (w) parts.push(w);
|
||||
if (fr[1]) parts.push(fr[1]);
|
||||
return (parts.length ? parts.join(' ') : '0') + '"';
|
||||
}
|
||||
function setFracEl(id, val) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = toFracStr(val || 0);
|
||||
}
|
||||
|
||||
function openLayoutEditor() {
|
||||
if (!state.activeAccountId) return;
|
||||
document.getElementById('layout-editor-overlay').classList.add('open');
|
||||
document.getElementById('layout-editor-modal').classList.add('open');
|
||||
loadLayoutFields();
|
||||
}
|
||||
|
||||
function closeLayoutEditor() {
|
||||
document.getElementById('layout-editor-overlay').classList.remove('open');
|
||||
document.getElementById('layout-editor-modal').classList.remove('open');
|
||||
layoutState = { fields: [], selectedId: null, scale: 80 };
|
||||
clearTimeout(layoutSaveTimer);
|
||||
}
|
||||
|
||||
async function loadLayoutFields() {
|
||||
try {
|
||||
layoutState.fields = await apiFetch('GET', `/api/layout/${state.activeAccountId}`);
|
||||
populateLayoutDropdown();
|
||||
requestAnimationFrame(() => {
|
||||
renderLayoutCanvas();
|
||||
if (layoutState.fields.length > 0) selectLayoutField(layoutState.fields[0].id);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to load layout fields:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function populateLayoutDropdown() {
|
||||
const sel = document.getElementById('layout-field-select');
|
||||
sel.innerHTML = layoutState.fields.map(f =>
|
||||
`<option value="${f.id}">${escHtml(fieldLabel(f))}</option>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
function svgEl(tag, attrs, text) {
|
||||
const el = document.createElementNS(SVG_NS, tag);
|
||||
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
|
||||
if (text != null) el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderLayoutCanvas() {
|
||||
const container = document.getElementById('layout-canvas-container');
|
||||
const W = container.offsetWidth;
|
||||
if (W <= 0) return;
|
||||
const SCALE = W / 8.5;
|
||||
layoutState.scale = SCALE;
|
||||
const H = 3.5 * SCALE;
|
||||
|
||||
container.innerHTML = '';
|
||||
const svg = svgEl('svg', { width: W, height: H, style: 'display:block;user-select:none' });
|
||||
|
||||
// White check background
|
||||
svg.appendChild(svgEl('rect', { x:0, y:0, width:W, height:H, fill:'#fff', stroke:'#bbb', 'stroke-width':1 }));
|
||||
|
||||
// MICR reference line
|
||||
const micrY = (3.5 - 0.267) * SCALE;
|
||||
svg.appendChild(svgEl('line', { x1:0, y1:micrY, x2:W, y2:micrY, stroke:'#ccc', 'stroke-width':1, 'stroke-dasharray':'4,4' }));
|
||||
svg.appendChild(svgEl('text', { x:4, y:micrY - 3, 'font-size':9, fill:'#bbb', 'font-family':'sans-serif' }, 'MICR'));
|
||||
|
||||
for (const f of layoutState.fields) {
|
||||
const g = createFieldSvgElement(f, SCALE, layoutState.selectedId === f.id);
|
||||
svg.appendChild(g);
|
||||
attachFieldEvents(g, f);
|
||||
}
|
||||
|
||||
container.appendChild(svg);
|
||||
renderRulers(W, H, SCALE);
|
||||
}
|
||||
|
||||
function renderRulers(W, H, scale) {
|
||||
const RULER = 24;
|
||||
const topEl = document.getElementById('layout-ruler-top');
|
||||
const leftEl = document.getElementById('layout-ruler-left');
|
||||
if (!topEl || !leftEl) return;
|
||||
|
||||
// ── Horizontal ruler (top) ──────────────────────────────────────
|
||||
const topSvg = svgEl('svg', { width: W, height: RULER, style: 'display:block' });
|
||||
topSvg.appendChild(svgEl('rect', { x:0, y:0, width:W, height:RULER, fill:'var(--surface)' }));
|
||||
|
||||
for (let n8 = 0; n8 <= Math.ceil(8.5 * 8); n8++) {
|
||||
const inches = n8 / 8;
|
||||
if (inches > 8.5) break;
|
||||
const x = inches * scale;
|
||||
const isInch = n8 % 8 === 0;
|
||||
const isHalf = n8 % 4 === 0;
|
||||
const isQtr = n8 % 2 === 0;
|
||||
const tickH = isInch ? RULER - 2 : isHalf ? 14 : isQtr ? 9 : 5;
|
||||
topSvg.appendChild(svgEl('line', { x1:x, y1:RULER, x2:x, y2:RULER - tickH, stroke:'#999', 'stroke-width': isInch ? 1 : 0.5 }));
|
||||
if (isInch && inches > 0) {
|
||||
topSvg.appendChild(svgEl('text', { x:x + 2, y:RULER - tickH - 1, 'font-size':8, fill:'#666', 'font-family':'sans-serif' }, inches + '"'));
|
||||
}
|
||||
}
|
||||
topEl.innerHTML = '';
|
||||
topEl.appendChild(topSvg);
|
||||
|
||||
// ── Vertical ruler (left) ───────────────────────────────────────
|
||||
const leftSvg = svgEl('svg', { width: RULER, height: H, style: 'display:block' });
|
||||
leftSvg.appendChild(svgEl('rect', { x:0, y:0, width:RULER, height:H, fill:'var(--surface)' }));
|
||||
|
||||
for (let n8 = 0; n8 <= Math.ceil(3.5 * 8); n8++) {
|
||||
const inches = n8 / 8;
|
||||
if (inches > 3.5) break;
|
||||
const y = inches * scale;
|
||||
const isInch = n8 % 8 === 0;
|
||||
const isHalf = n8 % 4 === 0;
|
||||
const isQtr = n8 % 2 === 0;
|
||||
const tickW = isInch ? RULER - 2 : isHalf ? 14 : isQtr ? 9 : 5;
|
||||
leftSvg.appendChild(svgEl('line', { x1:RULER, y1:y, x2:RULER - tickW, y2:y, stroke:'#999', 'stroke-width': isInch ? 1 : 0.5 }));
|
||||
if (isInch && inches > 0) {
|
||||
const t = svgEl('text', { 'font-size':8, fill:'#666', 'font-family':'sans-serif',
|
||||
'text-anchor':'end', x: RULER - tickW - 2, y: y + 3 }, inches + '"');
|
||||
leftSvg.appendChild(t);
|
||||
}
|
||||
}
|
||||
leftEl.innerHTML = '';
|
||||
leftEl.appendChild(leftSvg);
|
||||
}
|
||||
|
||||
function getFieldDisplayValue(f) {
|
||||
const a = state.account || {};
|
||||
switch (f.field_name) {
|
||||
case 'Company Name': return a.company1 || 'Company Name';
|
||||
case 'Company Name2': return a.company2 || '';
|
||||
case 'Company Name3': return a.company3 || '';
|
||||
case 'Company Name4': return a.company4 || '';
|
||||
case 'Check Number': return '1001';
|
||||
case 'Date': return '01/01/2025';
|
||||
case 'Payee Name': return 'Sample Payee';
|
||||
case 'Amount': return '1,234.56';
|
||||
case 'Text Amount': return 'One Thousand Two Hundred Thirty Four and 56/100---';
|
||||
case 'Bank Information': return [a.bank_name, a.bank_info1, a.bank_info2, a.bank_info3].filter(Boolean);
|
||||
case 'Bank Transit Code': return a.transit_code || '';
|
||||
case 'Payee Address': return ['123 Sample St', 'City, ST 12345'];
|
||||
case 'Memo': return 'Sample Memo';
|
||||
default:
|
||||
if (f.field_type === 'Text') return f.field_text || '';
|
||||
return f.field_name;
|
||||
}
|
||||
}
|
||||
|
||||
function createFieldSvgElement(f, scale, selected) {
|
||||
const g = svgEl('g', { 'data-field-id': f.id, style: `cursor:grab;opacity:${f.visible ? 1 : 0.35}` });
|
||||
const x = f.x_pos * scale;
|
||||
const y = f.y_pos * scale;
|
||||
|
||||
if (f.field_type === 'Line') {
|
||||
const x1 = f.x_pos * scale, y1 = f.y_pos * scale;
|
||||
const x2 = f.x_end_pos * scale, y2 = f.y_end_pos * scale;
|
||||
g.appendChild(svgEl('line', { x1, y1, x2, y2, stroke:'transparent', 'stroke-width':10 }));
|
||||
g.appendChild(svgEl('line', { x1, y1, x2, y2, stroke: selected ? '#2563eb' : '#333', 'stroke-width': selected ? 2 : 1.5 }));
|
||||
if (selected) {
|
||||
g.appendChild(svgEl('circle', { cx:x1, cy:y1, r:3, fill:'#2563eb' }));
|
||||
g.appendChild(svgEl('circle', { cx:x2, cy:y2, r:3, fill:'#2563eb' }));
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
if (f.field_type === 'Graph') {
|
||||
const w = Math.max(4, (f.x_end_pos - f.x_pos) * scale);
|
||||
const h = Math.max(4, (f.y_end_pos - f.y_pos) * scale);
|
||||
g.appendChild(svgEl('rect', { x, y, width:w, height:h, fill:'#f0f0f0', stroke: selected ? '#2563eb' : '#aaa', 'stroke-width':1, 'stroke-dasharray':'4,3' }));
|
||||
g.appendChild(svgEl('text', { x:x+2, y:y+10, 'font-size':7, fill:'#999', 'font-family':'sans-serif' }, '[image]'));
|
||||
return g;
|
||||
}
|
||||
|
||||
// Regular and Text fields — render actual content at proportional size
|
||||
const fontSize = Math.max(6, (f.font_size || 10) / 72 * scale);
|
||||
const fontWeight = f.font_bold ? 'bold' : 'normal';
|
||||
const displayVal = getFieldDisplayValue(f);
|
||||
const lines = Array.isArray(displayVal) ? displayVal : [String(displayVal)];
|
||||
const lineHeight = fontSize * 1.3;
|
||||
|
||||
// Invisible hit area so the element is always draggable
|
||||
const approxCharW = fontSize * 0.58;
|
||||
const hitW = Math.max(20, lines.reduce((m, l) => Math.max(m, l.length * approxCharW), 0));
|
||||
const hitH = lines.length * lineHeight + 2;
|
||||
g.appendChild(svgEl('rect', { x, y: y - fontSize, width: hitW, height: hitH, fill: 'transparent' }));
|
||||
|
||||
// Selection highlight
|
||||
if (selected) {
|
||||
g.appendChild(svgEl('rect', {
|
||||
x: x - 2, y: y - fontSize - 2,
|
||||
width: hitW + 4, height: hitH + 4,
|
||||
fill: 'rgba(37,99,235,0.06)', stroke: '#2563eb',
|
||||
'stroke-width': 1, 'stroke-dasharray': '4,3', rx: 2,
|
||||
}));
|
||||
}
|
||||
|
||||
// Text content
|
||||
if (lines.length === 1) {
|
||||
g.appendChild(svgEl('text', {
|
||||
x, y,
|
||||
'font-size': fontSize,
|
||||
'font-family': 'Helvetica, Arial, sans-serif',
|
||||
'font-weight': fontWeight,
|
||||
fill: '#111',
|
||||
}, lines[0]));
|
||||
} else {
|
||||
const textEl = svgEl('text', {
|
||||
x, y,
|
||||
'font-size': fontSize,
|
||||
'font-family': 'Helvetica, Arial, sans-serif',
|
||||
'font-weight': fontWeight,
|
||||
fill: '#111',
|
||||
});
|
||||
lines.forEach((line, i) => {
|
||||
textEl.appendChild(svgEl('tspan', { x, dy: i === 0 ? 0 : lineHeight }, line));
|
||||
});
|
||||
g.appendChild(textEl);
|
||||
}
|
||||
|
||||
return g;
|
||||
}
|
||||
|
||||
function attachFieldEvents(g, f) {
|
||||
g.addEventListener('mousedown', e => {
|
||||
selectLayoutField(f.id);
|
||||
startLayoutDrag(e, f);
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
});
|
||||
}
|
||||
|
||||
function selectLayoutField(id) {
|
||||
layoutState.selectedId = id;
|
||||
const sel = document.getElementById('layout-field-select');
|
||||
if (sel) sel.value = id;
|
||||
const f = layoutState.fields.find(x => x.id === id);
|
||||
if (f) updateLayoutSidebar(f);
|
||||
renderLayoutCanvas();
|
||||
}
|
||||
|
||||
function updateLayoutSidebar(f) {
|
||||
const fmt = x => (x || 0).toFixed(4);
|
||||
document.getElementById('layout-field-visible').checked = !!f.visible;
|
||||
document.getElementById('layout-field-x').value = fmt(f.x_pos);
|
||||
document.getElementById('layout-field-y').value = fmt(f.y_pos);
|
||||
document.getElementById('layout-field-x2').value = fmt(f.x_end_pos);
|
||||
document.getElementById('layout-field-y2').value = fmt(f.y_end_pos);
|
||||
setFracEl('layout-field-x-frac', f.x_pos);
|
||||
setFracEl('layout-field-y-frac', f.y_pos);
|
||||
setFracEl('layout-field-x2-frac', f.x_end_pos);
|
||||
setFracEl('layout-field-y2-frac', f.y_end_pos);
|
||||
document.getElementById('layout-end-pos-group').hidden =
|
||||
f.field_type !== 'Line' && f.field_type !== 'Graph';
|
||||
}
|
||||
|
||||
function onLayoutSidebarChange() {
|
||||
const f = layoutState.fields.find(x => x.id === layoutState.selectedId);
|
||||
if (!f) return;
|
||||
f.x_pos = clampIn(parseFloat(document.getElementById('layout-field-x').value) || 0, 0, 8.5);
|
||||
f.y_pos = clampIn(parseFloat(document.getElementById('layout-field-y').value) || 0, 0, 3.5);
|
||||
f.x_end_pos = clampIn(parseFloat(document.getElementById('layout-field-x2').value) || 0, 0, 8.5);
|
||||
f.y_end_pos = clampIn(parseFloat(document.getElementById('layout-field-y2').value) || 0, 0, 3.5);
|
||||
f.visible = document.getElementById('layout-field-visible').checked ? 1 : 0;
|
||||
setFracEl('layout-field-x-frac', f.x_pos);
|
||||
setFracEl('layout-field-y-frac', f.y_pos);
|
||||
setFracEl('layout-field-x2-frac', f.x_end_pos);
|
||||
setFracEl('layout-field-y2-frac', f.y_end_pos);
|
||||
renderLayoutCanvas();
|
||||
debounceLayoutSave(f);
|
||||
}
|
||||
|
||||
function startLayoutDrag(e, f) {
|
||||
layoutDrag = {
|
||||
fieldId: f.id,
|
||||
origX: f.x_pos, origY: f.y_pos,
|
||||
origX2: f.x_end_pos, origY2: f.y_end_pos,
|
||||
mouseX: e.clientX, mouseY: e.clientY,
|
||||
moveEnd: f.field_type === 'Line' || f.field_type === 'Graph',
|
||||
};
|
||||
const onMove = ev => onLayoutDragMove(ev);
|
||||
const onUp = ev => { onLayoutDragEnd(ev); document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); };
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onUp);
|
||||
}
|
||||
|
||||
function onLayoutDragMove(e) {
|
||||
if (!layoutDrag) return;
|
||||
const dx = (e.clientX - layoutDrag.mouseX) / layoutState.scale;
|
||||
const dy = (e.clientY - layoutDrag.mouseY) / layoutState.scale;
|
||||
const f = layoutState.fields.find(x => x.id === layoutDrag.fieldId);
|
||||
if (!f) return;
|
||||
f.x_pos = clampIn(round16(layoutDrag.origX + dx), 0, 8.5);
|
||||
f.y_pos = clampIn(round16(layoutDrag.origY + dy), 0, 3.5);
|
||||
if (layoutDrag.moveEnd) {
|
||||
f.x_end_pos = clampIn(round16(layoutDrag.origX2 + dx), 0, 8.5);
|
||||
f.y_end_pos = clampIn(round16(layoutDrag.origY2 + dy), 0, 3.5);
|
||||
}
|
||||
// Update just the dragged element for smooth performance
|
||||
const svg = document.querySelector('#layout-canvas-container svg');
|
||||
if (svg) {
|
||||
const old = svg.querySelector(`[data-field-id="${f.id}"]`);
|
||||
if (old) {
|
||||
const g = createFieldSvgElement(f, layoutState.scale, true);
|
||||
old.replaceWith(g);
|
||||
attachFieldEvents(g, f);
|
||||
}
|
||||
}
|
||||
updateLayoutSidebar(f);
|
||||
}
|
||||
|
||||
async function onLayoutDragEnd(e) {
|
||||
if (!layoutDrag) return;
|
||||
const id = layoutDrag.fieldId;
|
||||
layoutDrag = null;
|
||||
const f = layoutState.fields.find(x => x.id === id);
|
||||
if (f) await saveLayoutField(f);
|
||||
}
|
||||
|
||||
function nudgeLayoutField(dx, dy) {
|
||||
const f = layoutState.fields.find(x => x.id === layoutState.selectedId);
|
||||
if (!f) return;
|
||||
const S = 1 / 16;
|
||||
f.x_pos = clampIn(round16(f.x_pos + dx * S), 0, 8.5);
|
||||
f.y_pos = clampIn(round16(f.y_pos + dy * S), 0, 3.5);
|
||||
if (f.field_type === 'Line' || f.field_type === 'Graph') {
|
||||
f.x_end_pos = clampIn(round16(f.x_end_pos + dx * S), 0, 8.5);
|
||||
f.y_end_pos = clampIn(round16(f.y_end_pos + dy * S), 0, 3.5);
|
||||
}
|
||||
updateLayoutSidebar(f);
|
||||
renderLayoutCanvas();
|
||||
debounceLayoutSave(f);
|
||||
}
|
||||
|
||||
function debounceLayoutSave(f) {
|
||||
clearTimeout(layoutSaveTimer);
|
||||
layoutSaveTimer = setTimeout(() => saveLayoutField(f), 600);
|
||||
}
|
||||
|
||||
async function saveLayoutField(f) {
|
||||
try {
|
||||
await apiFetch('PUT', `/api/layout/${state.activeAccountId}/${f.id}`, {
|
||||
x_pos: f.x_pos, y_pos: f.y_pos,
|
||||
x_end_pos: f.x_end_pos, y_end_pos: f.y_end_pos,
|
||||
visible: f.visible,
|
||||
});
|
||||
const el = document.getElementById('layout-save-status');
|
||||
if (el) { el.textContent = 'Saved ✓'; setTimeout(() => { if (el) el.textContent = ''; }, 1500); }
|
||||
} catch (err) {
|
||||
const el = document.getElementById('layout-save-status');
|
||||
if (el) el.textContent = 'Save failed';
|
||||
}
|
||||
}
|
||||
|
||||
async function resetLayoutToDefault() {
|
||||
if (!confirm('Reset all layout fields to default positions? This cannot be undone.')) return;
|
||||
try {
|
||||
await apiFetch('POST', `/api/layout/${state.activeAccountId}/reset`);
|
||||
await loadLayoutFields();
|
||||
} catch (err) {
|
||||
alert('Reset failed: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
|
||||
+44
-63
@@ -10,7 +10,8 @@ const multer = require('multer');
|
||||
const session = require('express-session');
|
||||
|
||||
const db = require('./db/database');
|
||||
const { requireAuth, requireAdmin, canAccessAccount } = require('./middleware/auth');
|
||||
const { seedLayoutFields } = require('./db/database');
|
||||
const { requireAuth, requireAdmin, canAccessAccount, isEditorForAccount } = require('./middleware/auth');
|
||||
|
||||
const app = express();
|
||||
const upload = multer({ dest: os.tmpdir() });
|
||||
@@ -105,7 +106,7 @@ app.put('/api/account/:id', requireAdmin, (req, res) => {
|
||||
bank_name, bank_info1, bank_info2, bank_info3, transit_code,
|
||||
routing_number, account_number,
|
||||
offset_left, offset_right, offset_up, offset_down,
|
||||
logo_data, second_signature,
|
||||
logo_data, second_signature, check_position,
|
||||
} = req.body;
|
||||
|
||||
if (!company1 || !routing_number || !account_number) {
|
||||
@@ -116,13 +117,16 @@ app.put('/api/account/:id', requireAdmin, (req, res) => {
|
||||
return res.status(400).json({ error: 'Logo image must be smaller than 512 KB.' });
|
||||
}
|
||||
|
||||
const VALID_POSITIONS = ['3-per-page', 'top', 'middle', 'bottom'];
|
||||
const resolvedPosition = VALID_POSITIONS.includes(check_position) ? check_position : '3-per-page';
|
||||
|
||||
db.prepare(`
|
||||
UPDATE account SET
|
||||
company1 = ?, company2 = ?, company3 = ?, company4 = ?,
|
||||
bank_name = ?, bank_info1 = ?, bank_info2 = ?, bank_info3 = ?, transit_code = ?,
|
||||
routing_number = ?, account_number = ?,
|
||||
offset_left = ?, offset_right = ?, offset_up = ?, offset_down = ?,
|
||||
second_signature = ?,
|
||||
second_signature = ?, check_position = ?,
|
||||
logo_data = CASE WHEN ? IS NOT NULL THEN ? ELSE logo_data END,
|
||||
updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
@@ -132,7 +136,7 @@ app.put('/api/account/:id', requireAdmin, (req, res) => {
|
||||
routing_number, account_number,
|
||||
parseFloat(offset_left) || 0, parseFloat(offset_right) || 0,
|
||||
parseFloat(offset_up) || 0, parseFloat(offset_down) || 0,
|
||||
second_signature ? 1 : 0,
|
||||
second_signature ? 1 : 0, resolvedPosition,
|
||||
logo_data || null, logo_data || null,
|
||||
req.params.id
|
||||
);
|
||||
@@ -191,64 +195,6 @@ app.delete('/api/account/:id', requireAdmin, (req, res) => {
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Default layout fields for manually-created accounts (no .mdb import).
|
||||
// Coordinates are in inches from the top-left of each check slot (8.5" × 3.5").
|
||||
// Field names for type 'Regular' must match the keys in pdfService.resolveFieldValue.
|
||||
function seedDefaultLayoutFields(accountId) {
|
||||
const fields = [
|
||||
// Company block — top left
|
||||
{ field_name: 'Company Name', field_type: 'Regular', x_pos: 0.50, y_pos: 0.12, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica-Bold', font_size: 10, font_bold: 1, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Company Name2', field_type: 'Regular', x_pos: 0.50, y_pos: 0.30, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Company Name3', field_type: 'Regular', x_pos: 0.50, y_pos: 0.44, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Company Name4', field_type: 'Regular', x_pos: 0.50, y_pos: 0.58, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Check number — top right
|
||||
{ field_name: 'Check Number', field_type: 'Regular', x_pos: 7.20, y_pos: 0.12, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica-Bold', font_size: 10, font_bold: 1, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Date — upper right
|
||||
{ field_name: 'Date Label', field_type: 'Text', x_pos: 5.80, y_pos: 0.40, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 8, font_bold: 0, field_text: 'DATE', line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Date', field_type: 'Regular', x_pos: 6.30, y_pos: 0.40, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Pay to the order of
|
||||
{ field_name: 'Pay To Label', field_type: 'Text', x_pos: 0.30, y_pos: 0.82, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 7, font_bold: 0, field_text: 'PAY TO THE ORDER OF', line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Payee Name', field_type: 'Regular', x_pos: 2.15, y_pos: 0.80, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Amount box
|
||||
{ field_name: 'Dollar Sign', field_type: 'Text', x_pos: 6.80, y_pos: 0.80, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: '$', line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Amount', field_type: 'Regular', x_pos: 6.95, y_pos: 0.80, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica-Bold', font_size: 10, font_bold: 1, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Written amount
|
||||
{ field_name: 'Text Amount', field_type: 'Regular', x_pos: 0.30, y_pos: 1.28, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Dollars Label', field_type: 'Text', x_pos: 6.30, y_pos: 1.28, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 8, font_bold: 0, field_text: 'DOLLARS', line_thick: 1, visible: 1 },
|
||||
// Bank info block
|
||||
{ field_name: 'Bank Information', field_type: 'Regular', x_pos: 0.30, y_pos: 1.82, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 8, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Bank Transit Code', field_type: 'Regular', x_pos: 0.30, y_pos: 2.38, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 7, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Payee address — center window area (for windowed envelopes)
|
||||
{ field_name: 'Payee Address', field_type: 'Regular', x_pos: 3.50, y_pos: 1.82, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Memo
|
||||
{ field_name: 'Memo Label', field_type: 'Text', x_pos: 0.30, y_pos: 2.82, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 7, font_bold: 0, field_text: 'MEMO', line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Memo', field_type: 'Regular', x_pos: 0.72, y_pos: 2.82, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Auth signature label
|
||||
{ field_name: 'Auth Signature Label', field_type: 'Text', x_pos: 5.00, y_pos: 3.14, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 6, font_bold: 0, field_text: 'AUTHORIZED SIGNATURE', line_thick: 1, visible: 1 },
|
||||
// Lines
|
||||
{ field_name: 'Payee Line', field_type: 'Line', x_pos: 2.10, y_pos: 1.00, x_end_pos: 6.70, y_end_pos: 1.00, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Amount Box Top', field_type: 'Line', x_pos: 6.75, y_pos: 0.70, x_end_pos: 8.30, y_end_pos: 0.70, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Amount Box Left', field_type: 'Line', x_pos: 6.75, y_pos: 0.70, x_end_pos: 6.75, y_end_pos: 1.05, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Amount Box Bottom',field_type: 'Line', x_pos: 6.75, y_pos: 1.05, x_end_pos: 8.30, y_end_pos: 1.05, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Text Amount Line', field_type: 'Line', x_pos: 0.30, y_pos: 1.48, x_end_pos: 6.30, y_end_pos: 1.48, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Memo Line', field_type: 'Line', x_pos: 0.68, y_pos: 3.00, x_end_pos: 4.00, y_end_pos: 3.00, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Signature Line', field_type: 'Line', x_pos: 5.00, y_pos: 3.10, x_end_pos: 8.20, y_end_pos: 3.10, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
];
|
||||
|
||||
const stmt = db.prepare(`
|
||||
INSERT OR IGNORE INTO layout_fields
|
||||
(account_id, field_name, field_text, font_name, font_size, font_bold,
|
||||
field_type, line_thick, x_pos, y_pos, x_end_pos, y_end_pos, visible)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
db.transaction(() => {
|
||||
for (const f of fields) {
|
||||
stmt.run(accountId, f.field_name, f.field_text, f.font_name, f.font_size, f.font_bold,
|
||||
f.field_type, f.line_thick, f.x_pos, f.y_pos, f.x_end_pos, f.y_end_pos, f.visible);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// POST /api/account/setup (admin only — creates a new checking account)
|
||||
app.post('/api/account/setup', requireAdmin, (req, res) => {
|
||||
const {
|
||||
@@ -291,7 +237,7 @@ app.post('/api/account/setup', requireAdmin, (req, res) => {
|
||||
logo_data: logo_data || null,
|
||||
});
|
||||
|
||||
seedDefaultLayoutFields(result.lastInsertRowid);
|
||||
seedLayoutFields(result.lastInsertRowid);
|
||||
|
||||
res.status(201).json({ success: true, accountId: result.lastInsertRowid });
|
||||
});
|
||||
@@ -318,6 +264,41 @@ app.post('/api/import', requireAdmin, upload.single('mdbfile'), (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ── Layout editor routes ───────────────────────────────────────────────────────
|
||||
|
||||
// GET /api/layout/:accountId — all layout_fields for an account
|
||||
app.get('/api/layout/:accountId', requireAuth, (req, res) => {
|
||||
const accountId = parseInt(req.params.accountId, 10);
|
||||
if (!canAccessAccount(req.session, accountId)) return res.status(403).json({ error: 'Access denied.' });
|
||||
const fields = db.prepare('SELECT * FROM layout_fields WHERE account_id = ? ORDER BY id').all(accountId);
|
||||
res.json(fields);
|
||||
});
|
||||
|
||||
// PUT /api/layout/:accountId/:fieldId — update position/visibility of one field
|
||||
app.put('/api/layout/:accountId/:fieldId', requireAuth, (req, res) => {
|
||||
const accountId = parseInt(req.params.accountId, 10);
|
||||
const fieldId = parseInt(req.params.fieldId, 10);
|
||||
if (!isEditorForAccount(req.session, accountId)) return res.status(403).json({ error: 'Write access required.' });
|
||||
const { x_pos, y_pos, x_end_pos, y_end_pos, visible } = req.body;
|
||||
db.prepare(`
|
||||
UPDATE layout_fields SET x_pos=?, y_pos=?, x_end_pos=?, y_end_pos=?, visible=?
|
||||
WHERE id=? AND account_id=?
|
||||
`).run(
|
||||
parseFloat(x_pos) || 0, parseFloat(y_pos) || 0,
|
||||
parseFloat(x_end_pos) || 0, parseFloat(y_end_pos) || 0,
|
||||
visible ? 1 : 0, fieldId, accountId
|
||||
);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// POST /api/layout/:accountId/reset — wipe and re-seed default layout (admin only)
|
||||
app.post('/api/layout/:accountId/reset', requireAdmin, (req, res) => {
|
||||
const accountId = parseInt(req.params.accountId, 10);
|
||||
db.prepare('DELETE FROM layout_fields WHERE account_id = ?').run(accountId);
|
||||
seedLayoutFields(accountId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// Catch-all: serve index.html
|
||||
app.get('*', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, '../public/index.html'));
|
||||
|
||||
+60
-19
@@ -139,6 +139,17 @@ db.exec(`
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: add OIDC columns to users
|
||||
const usersInfo2 = db.prepare('PRAGMA table_info(users)').all();
|
||||
if (!usersInfo2.some(c => c.name === 'oidc_sub')) {
|
||||
db.exec(`
|
||||
ALTER TABLE users ADD COLUMN oidc_sub TEXT;
|
||||
ALTER TABLE users ADD COLUMN oidc_issuer TEXT;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_oidc ON users(oidc_issuer, oidc_sub)
|
||||
WHERE oidc_sub IS NOT NULL;
|
||||
`);
|
||||
}
|
||||
|
||||
// Migration: create settings table
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
@@ -147,19 +158,10 @@ db.exec(`
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: seed default layout fields for any account that has none.
|
||||
// Runs at every startup but INSERT OR IGNORE makes it idempotent.
|
||||
(function seedMissingLayoutFields() {
|
||||
const accounts = db.prepare('SELECT id FROM account').all();
|
||||
const countStmt = db.prepare('SELECT COUNT(*) AS n FROM layout_fields WHERE account_id = ?');
|
||||
const insertStmt = db.prepare(`
|
||||
INSERT OR IGNORE INTO layout_fields
|
||||
(account_id, field_name, field_text, font_name, font_size, font_bold,
|
||||
field_type, line_thick, x_pos, y_pos, x_end_pos, y_end_pos, visible)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const defaultFields = [
|
||||
// Default layout fields used for seeding and migration.
|
||||
const DEFAULT_LAYOUT_FIELDS = [
|
||||
// Logo — top left corner (Graph type, rendered as image from account.logo_data)
|
||||
{ field_name: 'Logo', field_type: 'Graph', x_pos: 0.10, y_pos: 0.08, x_end_pos: 0.45, y_end_pos: 0.58, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
// Company block — top left
|
||||
{ field_name: 'Company Name', field_type: 'Regular', x_pos: 0.50, y_pos: 0.12, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica-Bold', font_size: 10, font_bold: 1, field_text: null, line_thick: 1, visible: 1 },
|
||||
{ field_name: 'Company Name2', field_type: 'Regular', x_pos: 0.50, y_pos: 0.30, x_end_pos: 0, y_end_pos: 0, font_name: 'Helvetica', font_size: 9, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
@@ -199,18 +201,57 @@ db.exec(`
|
||||
{ field_name: 'Signature Line', field_type: 'Line', x_pos: 5.00, y_pos: 3.10, x_end_pos: 8.20, y_end_pos: 3.10, font_name: 'Helvetica', font_size: 10, font_bold: 0, field_text: null, line_thick: 1, visible: 1 },
|
||||
];
|
||||
|
||||
const seedAccount = db.transaction(accountId => {
|
||||
for (const f of defaultFields) {
|
||||
insertStmt.run(accountId, f.field_name, f.field_text, f.font_name, f.font_size, f.font_bold,
|
||||
function seedLayoutFields(accountId) {
|
||||
const insert = db.prepare(`
|
||||
INSERT OR IGNORE INTO layout_fields
|
||||
(account_id, field_name, field_text, font_name, font_size, font_bold,
|
||||
field_type, line_thick, x_pos, y_pos, x_end_pos, y_end_pos, visible)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
db.transaction(() => {
|
||||
for (const f of DEFAULT_LAYOUT_FIELDS) {
|
||||
insert.run(accountId, f.field_name, f.field_text, f.font_name, f.font_size, f.font_bold,
|
||||
f.field_type, f.line_thick, f.x_pos, f.y_pos, f.x_end_pos, f.y_end_pos, f.visible);
|
||||
}
|
||||
});
|
||||
})();
|
||||
}
|
||||
|
||||
// Migration: reset all accounts to default layout (runs once, gated by settings key).
|
||||
// Replaces any .mdb-imported or legacy layout_fields with the clean default layout.
|
||||
if (!db.prepare("SELECT value FROM settings WHERE key = 'layout_reset_v1'").get()) {
|
||||
const accounts = db.prepare('SELECT id FROM account').all();
|
||||
db.transaction(() => {
|
||||
for (const { id } of accounts) {
|
||||
if (countStmt.get(id).n === 0) {
|
||||
seedAccount(id);
|
||||
db.prepare('DELETE FROM layout_fields WHERE account_id = ?').run(id);
|
||||
seedLayoutFields(id);
|
||||
}
|
||||
db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('layout_reset_v1', '1')").run();
|
||||
})();
|
||||
}
|
||||
|
||||
// Migration: add Logo field to existing accounts that don't have one.
|
||||
(function addLogoField() {
|
||||
const accounts = db.prepare('SELECT id FROM account').all();
|
||||
const insertLogo = db.prepare(`
|
||||
INSERT OR IGNORE INTO layout_fields
|
||||
(account_id, field_name, field_text, font_name, font_size, font_bold,
|
||||
field_type, line_thick, x_pos, y_pos, x_end_pos, y_end_pos, visible)
|
||||
VALUES (?, 'Logo', NULL, 'Helvetica', 10, 0, 'Graph', 1, 0.10, 0.08, 0.45, 0.58, 1)
|
||||
`);
|
||||
for (const { id } of accounts) {
|
||||
const existing = db.prepare("SELECT id FROM layout_fields WHERE account_id = ? AND field_name = 'Logo'").get(id);
|
||||
if (!existing) insertLogo.run(id);
|
||||
}
|
||||
})();
|
||||
|
||||
// Migration: seed default layout fields for any account that has none (ongoing, idempotent).
|
||||
(function seedMissingLayoutFields() {
|
||||
const accounts = db.prepare('SELECT id FROM account').all();
|
||||
for (const { id } of accounts) {
|
||||
const { n } = db.prepare('SELECT COUNT(*) AS n FROM layout_fields WHERE account_id = ?').get(id);
|
||||
if (n === 0) seedLayoutFields(id);
|
||||
}
|
||||
})();
|
||||
|
||||
module.exports = db;
|
||||
module.exports.seedLayoutFields = seedLayoutFields;
|
||||
|
||||
+203
-1
@@ -123,7 +123,13 @@ router.get('/me', (req, res) => {
|
||||
if (!req.session || !req.session.userId) {
|
||||
return res.status(401).json({ error: 'Not authenticated.' });
|
||||
}
|
||||
res.json({ id: req.session.userId, username: req.session.username, role: req.session.role });
|
||||
const user = db.prepare('SELECT oidc_sub FROM users WHERE id = ?').get(req.session.userId);
|
||||
res.json({
|
||||
id: req.session.userId,
|
||||
username: req.session.username,
|
||||
role: req.session.role,
|
||||
oidc_linked: !!(user && user.oidc_sub),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/change-password — any logged-in user can change their own password
|
||||
@@ -200,5 +206,201 @@ router.post('/reset-password', async (req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// ── OIDC helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
function getOidcSettings() {
|
||||
return {
|
||||
enabled: process.env.OIDC_ENABLED === '1' || process.env.OIDC_ENABLED === 'true',
|
||||
discovery_url: process.env.OIDC_DISCOVERY_URL || '',
|
||||
client_id: process.env.OIDC_CLIENT_ID || '',
|
||||
client_secret: process.env.OIDC_CLIENT_SECRET || '',
|
||||
redirect_uri: process.env.OIDC_REDIRECT_URI || '',
|
||||
button_label: process.env.OIDC_BUTTON_LABEL || 'Sign in with SSO',
|
||||
};
|
||||
}
|
||||
|
||||
async function getOidcClient(settings) {
|
||||
const { Issuer } = require('openid-client');
|
||||
console.log('[oidc] discovering issuer from:', settings.discovery_url);
|
||||
const issuer = await Issuer.discover(settings.discovery_url);
|
||||
console.log('[oidc] discovered issuer:', issuer.issuer);
|
||||
const client = new issuer.Client({
|
||||
client_id: settings.client_id,
|
||||
client_secret: settings.client_secret,
|
||||
redirect_uris: [settings.redirect_uri],
|
||||
response_types: ['code'],
|
||||
});
|
||||
console.log('[oidc] client created, redirect_uri:', settings.redirect_uri);
|
||||
return client;
|
||||
}
|
||||
|
||||
// GET /api/auth/oidc/config — public, returns whether OIDC is enabled + button label
|
||||
router.get('/oidc/config', (req, res) => {
|
||||
const s = getOidcSettings();
|
||||
res.json({ enabled: s.enabled, button_label: s.button_label });
|
||||
});
|
||||
|
||||
// GET /api/auth/oidc/authorize — initiates the OIDC flow (redirect to provider)
|
||||
router.get('/oidc/authorize', async (req, res) => {
|
||||
try {
|
||||
const settings = getOidcSettings();
|
||||
console.log('[oidc] authorize: enabled=%s, discovery_url=%s, client_id=%s, redirect_uri=%s',
|
||||
settings.enabled, settings.discovery_url, settings.client_id, settings.redirect_uri);
|
||||
if (!settings.enabled) return res.status(400).json({ error: 'OIDC is not enabled.' });
|
||||
|
||||
const { generators } = require('openid-client');
|
||||
const client = await getOidcClient(settings);
|
||||
|
||||
const code_verifier = generators.codeVerifier();
|
||||
const code_challenge = generators.codeChallenge(code_verifier);
|
||||
const state = generators.state();
|
||||
const nonce = generators.nonce();
|
||||
|
||||
req.session.oidc = { code_verifier, state, nonce };
|
||||
|
||||
const authUrl = client.authorizationUrl({
|
||||
scope: 'openid email profile',
|
||||
state,
|
||||
nonce,
|
||||
code_challenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
console.log('[oidc] authorize: redirecting to:', authUrl.substring(0, 200) + '...');
|
||||
// Ensure session is persisted before redirecting (saveUninitialized is false)
|
||||
req.session.save(() => res.redirect(authUrl));
|
||||
} catch (err) {
|
||||
console.error('[oidc] authorize error:', err.message, err.stack);
|
||||
res.redirect('/#oidc-error=' + encodeURIComponent('Failed to initiate SSO login.'));
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/auth/oidc/callback — handles the provider redirect
|
||||
router.get('/oidc/callback', async (req, res) => {
|
||||
try {
|
||||
console.log('[oidc] callback: query params:', JSON.stringify(req.query));
|
||||
const settings = getOidcSettings();
|
||||
if (!settings.enabled) return res.redirect('/#oidc-error=' + encodeURIComponent('OIDC is not enabled.'));
|
||||
|
||||
const oidcSession = req.session.oidc;
|
||||
if (!oidcSession) {
|
||||
console.error('[oidc] callback: no oidc session data found — session may have expired or cookie lost');
|
||||
return res.redirect('/#oidc-error=' + encodeURIComponent('Session expired. Please try again.'));
|
||||
}
|
||||
console.log('[oidc] callback: session has oidc data, linking=%s, linkUserId=%s',
|
||||
!!oidcSession.linking, oidcSession.linkUserId || 'n/a');
|
||||
|
||||
const client = await getOidcClient(settings);
|
||||
const params = client.callbackParams(req);
|
||||
console.log('[oidc] callback: exchanging code for tokens...');
|
||||
|
||||
const tokenSet = await client.callback(settings.redirect_uri, params, {
|
||||
code_verifier: oidcSession.code_verifier,
|
||||
state: oidcSession.state,
|
||||
nonce: oidcSession.nonce,
|
||||
});
|
||||
|
||||
const claims = tokenSet.claims();
|
||||
const sub = claims.sub;
|
||||
const issuer = claims.iss;
|
||||
console.log('[oidc] callback: token exchange OK, sub=%s, iss=%s, email=%s, name=%s',
|
||||
sub, issuer, claims.email || 'n/a', claims.name || 'n/a');
|
||||
|
||||
delete req.session.oidc;
|
||||
|
||||
// Self-service linking flow
|
||||
if (oidcSession.linking && oidcSession.linkUserId) {
|
||||
console.log('[oidc] callback: linking flow for userId=%s', oidcSession.linkUserId);
|
||||
const existing = db.prepare(
|
||||
'SELECT id FROM users WHERE oidc_issuer = ? AND oidc_sub = ? AND id != ?'
|
||||
).get(issuer, sub, oidcSession.linkUserId);
|
||||
if (existing) {
|
||||
console.warn('[oidc] callback: identity already linked to userId=%s', existing.id);
|
||||
return res.redirect('/#oidc-error=' + encodeURIComponent('This identity is already linked to another account.'));
|
||||
}
|
||||
|
||||
db.prepare("UPDATE users SET oidc_sub = ?, oidc_issuer = ?, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(sub, issuer, oidcSession.linkUserId);
|
||||
console.log('[oidc] callback: linked sub=%s to userId=%s', sub, oidcSession.linkUserId);
|
||||
return res.redirect('/#oidc-linked');
|
||||
}
|
||||
|
||||
// Login flow — look up user by OIDC identity
|
||||
const user = db.prepare(
|
||||
'SELECT id, username, role FROM users WHERE oidc_issuer = ? AND oidc_sub = ?'
|
||||
).get(issuer, sub);
|
||||
|
||||
if (!user) {
|
||||
console.warn('[oidc] callback: no user found for iss=%s sub=%s — not linked', issuer, sub);
|
||||
return res.redirect('/#oidc-error=' + encodeURIComponent(
|
||||
'No account is linked to this identity. Ask an admin to link your account, or sign in with your password and link it yourself.'
|
||||
));
|
||||
}
|
||||
|
||||
console.log('[oidc] callback: login success, userId=%s, username=%s, role=%s', user.id, user.username, user.role);
|
||||
req.session.userId = user.id;
|
||||
req.session.username = user.username;
|
||||
req.session.role = user.role;
|
||||
|
||||
// Load account access into session (mirrors login behavior)
|
||||
if (user.role !== 'admin') {
|
||||
const accts = db.prepare('SELECT account_id, role FROM user_accounts WHERE user_id = ?').all(user.id);
|
||||
req.session.accounts = accts;
|
||||
}
|
||||
|
||||
res.redirect('/');
|
||||
} catch (err) {
|
||||
console.error('[oidc] callback error:', err.message, err.stack);
|
||||
res.redirect('/#oidc-error=' + encodeURIComponent('SSO login failed. Please try again.'));
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/auth/oidc/link — logged-in user initiates linking flow
|
||||
router.get('/oidc/link', async (req, res) => {
|
||||
if (!req.session || !req.session.userId) {
|
||||
return res.redirect('/#oidc-error=' + encodeURIComponent('You must be signed in to link your account.'));
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[oidc] link: userId=%s initiating linking flow', req.session.userId);
|
||||
const settings = getOidcSettings();
|
||||
if (!settings.enabled) return res.redirect('/#oidc-error=' + encodeURIComponent('OIDC is not enabled.'));
|
||||
|
||||
const { generators } = require('openid-client');
|
||||
const client = await getOidcClient(settings);
|
||||
|
||||
const code_verifier = generators.codeVerifier();
|
||||
const code_challenge = generators.codeChallenge(code_verifier);
|
||||
const state = generators.state();
|
||||
const nonce = generators.nonce();
|
||||
|
||||
req.session.oidc = { code_verifier, state, nonce, linking: true, linkUserId: req.session.userId };
|
||||
|
||||
const authUrl = client.authorizationUrl({
|
||||
scope: 'openid email profile',
|
||||
state,
|
||||
nonce,
|
||||
code_challenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
console.log('[oidc] link: redirecting to provider');
|
||||
req.session.save(() => res.redirect(authUrl));
|
||||
} catch (err) {
|
||||
console.error('[oidc] link error:', err.message, err.stack);
|
||||
res.redirect('/#oidc-error=' + encodeURIComponent('Failed to initiate SSO linking.'));
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/oidc/unlink — logged-in user removes their own OIDC link
|
||||
router.post('/oidc/unlink', (req, res) => {
|
||||
if (!req.session || !req.session.userId) {
|
||||
return res.status(401).json({ error: 'Not authenticated.' });
|
||||
}
|
||||
db.prepare("UPDATE users SET oidc_sub = NULL, oidc_issuer = NULL, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(req.session.userId);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports.validatePassword = validatePassword;
|
||||
|
||||
+20
-3
@@ -11,7 +11,7 @@ const { validatePassword } = require('./auth');
|
||||
router.use(requireAuth, requireAdmin);
|
||||
|
||||
function userWithAccounts(id) {
|
||||
const user = db.prepare('SELECT id, username, email, role, created_at FROM users WHERE id = ?').get(id);
|
||||
const user = db.prepare('SELECT id, username, email, role, oidc_sub, oidc_issuer, created_at FROM users WHERE id = ?').get(id);
|
||||
if (!user) return null;
|
||||
user.accounts = db.prepare('SELECT account_id, role FROM user_accounts WHERE user_id = ?').all(id);
|
||||
return user;
|
||||
@@ -19,7 +19,7 @@ function userWithAccounts(id) {
|
||||
|
||||
// GET /api/users
|
||||
router.get('/', (req, res) => {
|
||||
const users = db.prepare('SELECT id, username, email, role, created_at FROM users ORDER BY id ASC').all();
|
||||
const users = db.prepare('SELECT id, username, email, role, oidc_sub, oidc_issuer, created_at FROM users ORDER BY id ASC').all();
|
||||
users.forEach(u => {
|
||||
u.accounts = db.prepare('SELECT account_id, role FROM user_accounts WHERE user_id = ?').all(u.id);
|
||||
});
|
||||
@@ -60,7 +60,7 @@ router.put('/:id', async (req, res) => {
|
||||
const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.params.id);
|
||||
if (!user) return res.status(404).json({ error: 'User not found.' });
|
||||
|
||||
const { username, password, role, accounts, email } = req.body;
|
||||
const { username, password, role, accounts, email, oidc_sub, oidc_issuer } = req.body;
|
||||
|
||||
if (role && !['admin', 'editor', 'viewer'].includes(role)) {
|
||||
return res.status(400).json({ error: 'Invalid role.' });
|
||||
@@ -94,6 +94,23 @@ router.put('/:id', async (req, res) => {
|
||||
.run(hash, req.params.id);
|
||||
}
|
||||
|
||||
// OIDC linking — admin can set or clear oidc_sub/oidc_issuer
|
||||
if (oidc_sub !== undefined) {
|
||||
const newSub = oidc_sub ? oidc_sub.trim() : null;
|
||||
const newIssuer = oidc_issuer ? oidc_issuer.trim() : null;
|
||||
if (newSub && !newIssuer) {
|
||||
return res.status(400).json({ error: 'OIDC issuer is required when setting OIDC subject.' });
|
||||
}
|
||||
if (newSub) {
|
||||
const existing = db.prepare(
|
||||
'SELECT id FROM users WHERE oidc_issuer = ? AND oidc_sub = ? AND id != ?'
|
||||
).get(newIssuer, newSub, req.params.id);
|
||||
if (existing) return res.status(409).json({ error: 'This OIDC identity is already linked to another user.' });
|
||||
}
|
||||
db.prepare("UPDATE users SET oidc_sub = ?, oidc_issuer = ?, updated_at = datetime('now') WHERE id = ?")
|
||||
.run(newSub, newSub ? newIssuer : null, req.params.id);
|
||||
}
|
||||
|
||||
if (Array.isArray(accounts)) {
|
||||
db.prepare('DELETE FROM user_accounts WHERE user_id = ?').run(req.params.id);
|
||||
const effectiveRole = role || user.role;
|
||||
|
||||
@@ -387,7 +387,7 @@ function generateDepositSlip(account, deposit, items) {
|
||||
drawAmountRow(item.amount || 0, r);
|
||||
});
|
||||
|
||||
drawAmountRow(checksTotal, totalRows);
|
||||
drawAmountRow(depositTotal, totalRows);
|
||||
|
||||
// ── Rotated left strip elements ─────────────────────────────────────────
|
||||
// All elements use rotate(90): text flows downward on the page, which reads
|
||||
|
||||
@@ -131,14 +131,22 @@ function generateCheckPdf(account, checks, fields) {
|
||||
const offX = (account.offset_right - account.offset_left);
|
||||
const offY = (account.offset_down - account.offset_up);
|
||||
|
||||
// Render checks in pages of 3; add a new page for each additional group
|
||||
const pages = Math.ceil(checks.length / 3);
|
||||
// Determine slot assignment based on check_position setting
|
||||
const position = account.check_position || '3-per-page';
|
||||
const SLOT_MAP = { top: 0, middle: 1, bottom: 2 };
|
||||
const fixedSlot = SLOT_MAP[position]; // undefined for '3-per-page'
|
||||
const checksPerPage = fixedSlot !== undefined ? 1 : 3;
|
||||
|
||||
const pages = Math.ceil(checks.length / checksPerPage);
|
||||
for (let page = 0; page < pages; page++) {
|
||||
if (page > 0) doc.addPage();
|
||||
|
||||
for (let slot = 0; slot < 3; slot++) {
|
||||
const check = checks[page * 3 + slot] || null;
|
||||
const slotOriginY = slot * SLOT_HEIGHT_IN + (slot === 0 ? -0.25 : 0);
|
||||
// For fixed-slot mode, only render in the designated slot
|
||||
if (fixedSlot !== undefined && slot !== fixedSlot) continue;
|
||||
const checkIndex = fixedSlot !== undefined ? page : page * 3 + slot;
|
||||
const check = checks[checkIndex] || null;
|
||||
const slotOriginY = slot * SLOT_HEIGHT_IN;
|
||||
|
||||
// Helper: convert inches (relative to slot) to PDF points (absolute page)
|
||||
const pt = (xIn, yIn) => ({
|
||||
|
||||
Reference in New Issue
Block a user