Initialize work order management system with database schema, API handlers, web client, and Docker configuration.

This commit is contained in:
2026-05-16 16:15:53 -04:00
parent c135722339
commit f904431ec3
28 changed files with 2171 additions and 0 deletions
+84
View File
@@ -0,0 +1,84 @@
import { setToken } from './lib/api.mjs';
import './components/wo-list.mjs';
import './components/wo-form.mjs';
// ── Keycloak init ─────────────────────────────────────────────────────────────
const keycloak = new Keycloak({
url: window.KEYCLOAK_URL || 'http://localhost:8180',
realm: window.KEYCLOAK_REALM || 'workorders',
clientId: window.KEYCLOAK_CLIENT_ID || 'workorders-app',
});
keycloak.init({
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
})
.then(authenticated => {
if (!authenticated) { keycloak.login(); return; }
setToken(keycloak.token);
// Refresh token before it expires
setInterval(async () => {
try { await keycloak.updateToken(60); setToken(keycloak.token); }
catch { keycloak.login(); }
}, 30_000);
window.addEventListener('auth:expired', () => keycloak.login());
renderApp(keycloak);
})
.catch(() => document.getElementById('app').innerHTML =
'<p style="color:red;padding:2rem">Failed to connect to authentication server.</p>');
// ── App shell ─────────────────────────────────────────────────────────────────
function renderApp(kc) {
const app = document.getElementById('app');
const userName = kc.tokenParsed?.name || kc.tokenParsed?.preferred_username || 'User';
// Nav
const nav = document.createElement('nav');
nav.innerHTML = `
<span class="brand">Work Orders</span>
<span class="spacer"></span>
<span class="user-info">${userName}</span>
<button id="logout" style="background:transparent;border:1px solid rgba(255,255,255,.4);color:#fff;padding:.3rem .8rem;font-size:.85rem">Logout</button>`;
document.body.insertBefore(nav, app);
nav.querySelector('#logout').addEventListener('click', () => kc.logout());
showList();
app.addEventListener('wo:select', e => showDetail(e.detail.id));
app.addEventListener('wo:cancel', () => showList());
app.addEventListener('wo:saved', () => showList());
document.addEventListener('keydown', e => { if (e.key === 'Escape') showList(); });
}
function showList() {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header">
<h1>Work Orders</h1>
<button id="new-wo">+ New Work Order</button>
</div>
<wo-list id="wo-list"></wo-list>`;
app.querySelector('#new-wo').addEventListener('click', showCreate);
}
function showCreate() {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header"><h1>New Work Order</h1></div>
<div class="card"><wo-form></wo-form></div>`;
}
function showDetail(id) {
const app = document.getElementById('app');
app.innerHTML = `
<div class="page-header">
<h1>Edit Work Order</h1>
<button id="back" class="secondary">← Back</button>
</div>
<div class="card"><wo-form wo-id="${id}"></wo-form></div>`;
app.querySelector('#back').addEventListener('click', showList);
}
+115
View File
@@ -0,0 +1,115 @@
import { api } from '../lib/api.mjs';
class WoForm extends HTMLElement {
#woId = null;
#wo = null;
static get observedAttributes() { return ['wo-id']; }
attributeChangedCallback(_, __, val) { this.#woId = val ? +val : null; this.#load(); }
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.#render();
if (this.#woId) this.#load();
}
async #load() {
if (!this.#woId) return;
this.#wo = await api.get(`/work-orders/${this.#woId}`);
this.#render();
}
#render() {
const wo = this.#wo ?? {};
this.shadowRoot.innerHTML = `
<style>
:host { display: block; }
form { display: grid; gap: 1rem; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
label { display: flex; flex-direction: column; gap: .3rem; font-size: .9rem; font-weight: 600; color: #1a2e3b; }
input, select, textarea {
border: 1px solid #e2ebf0; border-radius: 8px;
padding: .5rem .75rem; font-size: .95rem; background: #fff; color: #1a2e3b;
}
input:focus, select:focus, textarea:focus { outline: none; border-color: #0a7ea4; }
textarea { resize: vertical; min-height: 80px; }
.actions { display: flex; gap: .75rem; justify-content: flex-end; }
button {
padding: .5rem 1.25rem; border: none; border-radius: 8px;
font-weight: 600; cursor: pointer;
}
.btn-primary { background: #0a7ea4; color: #fff; }
.btn-cancel { background: transparent; border: 1px solid #e2ebf0; color: #1a2e3b; }
.error { color: #c0392b; font-size: .85rem; }
</style>
<form>
<label>Title *<input name="title" required value="${wo.title || ''}"></label>
<div class="row">
<label>Priority
<select name="priority">
${['low','normal','high','urgent'].map(p =>
`<option value="${p}" ${wo.priority===p?'selected':''}>${p}</option>`).join('')}
</select>
</label>
<label>Site Name<input name="site_name" value="${wo.site_name || ''}"></label>
</div>
<label>Address<input name="address" value="${wo.address || ''}"></label>
<div class="row">
<label>Scheduled Start<input type="datetime-local" name="scheduled_start"
value="${wo.scheduled_start ? wo.scheduled_start.slice(0,16) : ''}"></label>
<label>Scheduled End<input type="datetime-local" name="scheduled_end"
value="${wo.scheduled_end ? wo.scheduled_end.slice(0,16) : ''}"></label>
</div>
<label>Description<textarea name="description">${wo.description || ''}</textarea></label>
<label>Instructions<textarea name="instructions">${wo.instructions || ''}</textarea></label>
<label>Access Notes<textarea name="access_notes">${wo.access_notes || ''}</textarea></label>
<div class="error" id="err"></div>
<div class="actions">
<button type="button" class="btn-cancel" id="cancel">Cancel</button>
<button type="submit" class="btn-primary">${this.#woId ? 'Save Changes' : 'Create Work Order'}</button>
</div>
</form>`;
this.shadowRoot.querySelector('#cancel').addEventListener('click', () =>
this.dispatchEvent(new CustomEvent('wo:cancel', { bubbles: true, composed: true })));
this.shadowRoot.querySelector('form').addEventListener('submit', async e => {
e.preventDefault();
// Read fields directly — Shadow DOM + FormData has unreliable browser support
const val = name => (this.shadowRoot.querySelector(`[name="${name}"]`)?.value ?? '').trim();
// datetime-local gives "YYYY-MM-DDTHH:MM"; convert to full ISO so Go can parse it
const dt = name => { const v = val(name); return v ? new Date(v).toISOString() : null; };
const body = {
title: val('title'),
priority: val('priority') || 'normal',
site_name: val('site_name'),
address: val('address'),
scheduled_start: dt('scheduled_start'),
scheduled_end: dt('scheduled_end'),
description: val('description'),
instructions: val('instructions'),
access_notes: val('access_notes'),
};
if (!body.title) {
this.shadowRoot.querySelector('#err').textContent = 'Title is required.';
return;
}
this.shadowRoot.querySelector('#err').textContent = '';
try {
const wo = this.#woId
? await api.put(`/work-orders/${this.#woId}`, body)
: await api.post('/work-orders', body);
this.dispatchEvent(new CustomEvent('wo:saved',
{ detail: { wo }, bubbles: true, composed: true }));
} catch (err) {
this.shadowRoot.querySelector('#err').textContent = err.message;
}
});
}
}
customElements.define('wo-form', WoForm);
+66
View File
@@ -0,0 +1,66 @@
import { api } from '../lib/api.mjs';
class WoList extends HTMLElement {
#data = [];
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.#load();
}
async #load() {
const status = this.getAttribute('filter-status') || '';
this.#data = await api.get(`/work-orders?status=${status}`) ?? [];
this.#render();
}
refresh() { this.#load(); }
#render() {
this.shadowRoot.innerHTML = `
<style>
:host { display: block; }
.empty { color: #64748b; text-align: center; padding: 3rem; }
.grid { display: grid; gap: .75rem; }
.card {
background: #fff; border: 1px solid #e2ebf0;
border-radius: 8px; padding: 1rem 1.25rem;
cursor: pointer; display: grid;
grid-template-columns: 1fr auto; gap: .25rem 1rem;
transition: box-shadow .15s;
}
.card:hover { box-shadow: 0 4px 12px rgba(0,0,0,.08); }
.wo-num { font-size: .75rem; color: #64748b; }
.title { font-weight: 600; }
.meta { font-size: .8rem; color: #64748b; }
.badge { display:inline-block; padding:.2rem .6rem; border-radius:999px;
font-size:.7rem; font-weight:700; text-transform:uppercase;
align-self: start; margin-top:.25rem; }
.draft { background:#e2e8f0; color:#475569; }
.assigned { background:#dbeafe; color:#1d4ed8; }
.scheduled { background:#fef3c7; color:#92400e; }
.in_progress { background:#d1fae5; color:#065f46; }
.pending_review { background:#ede9fe; color:#5b21b6; }
.closed { background:#f3f4f6; color:#6b7280; }
</style>
${this.#data.length === 0
? '<div class="empty">No work orders found.</div>'
: `<div class="grid">${this.#data.map(wo => `
<div class="card" data-id="${wo.id}">
<div>
<div class="wo-num">${wo.wo_number}</div>
<div class="title">${wo.title}</div>
<div class="meta">${wo.site_name || '—'} · ${wo.steps_done}/${wo.step_count} steps</div>
</div>
<span class="badge ${wo.status}">${wo.status.replace('_',' ')}</span>
</div>`).join('')}
</div>`}`;
this.shadowRoot.querySelectorAll('.card').forEach(c =>
c.addEventListener('click', () =>
this.dispatchEvent(new CustomEvent('wo:select',
{ detail: { id: +c.dataset.id }, bubbles: true, composed: true }))));
}
}
customElements.define('wo-list', WoList);
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Work Orders</title>
<link rel="stylesheet" href="/styles/reset.css">
<link rel="stylesheet" href="/styles/global.css">
<!-- Keycloak JS adapter (served by Keycloak itself) -->
<script src="http://localhost:8180/js/keycloak.js"></script>
</head>
<body>
<div id="app">
<p style="padding:2rem;color:#64748b">Connecting to authentication server...</p>
</div>
<script type="module" src="/app.mjs"></script>
</body>
</html>
+33
View File
@@ -0,0 +1,33 @@
const BASE = '/api';
let _token = '';
export function setToken(t) { _token = t; }
export function getToken() { return _token; }
async function request(method, path, body, isForm = false) {
const headers = { Authorization: `Bearer ${_token}` };
if (!isForm && body) headers['Content-Type'] = 'application/json';
const res = await fetch(BASE + path, {
method,
headers,
body: body ? (isForm ? body : JSON.stringify(body)) : undefined,
});
if (res.status === 401) {
window.dispatchEvent(new CustomEvent('auth:expired'));
return null;
}
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
return json.data;
}
export const api = {
get: (path) => request('GET', path),
post: (path, body) => request('POST', path, body),
put: (path, body) => request('PUT', path, body),
delete: (path) => request('DELETE', path),
upload: (path, form) => request('POST', path, form, true),
};
+104
View File
@@ -0,0 +1,104 @@
:root {
--navy: #0d2137;
--accent: #0a7ea4;
--accent-lt: #14b8d4;
--surface: #ffffff;
--bg: #f0f6fa;
--border: #e2ebf0;
--text: #1a2e3b;
--muted: #64748b;
--danger: #c0392b;
--success: #1d9d6c;
--warning: #e07b39;
--radius: 8px;
--shadow: 0 2px 8px rgba(0,0,0,.08);
font-family: Calibri, 'Segoe UI', system-ui, sans-serif;
font-size: 16px;
color: var(--text);
background: var(--bg);
}
body { min-height: 100vh; }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
button {
cursor: pointer;
border: none;
border-radius: var(--radius);
padding: .5rem 1rem;
background: var(--accent);
color: #fff;
font-weight: 600;
transition: opacity .15s;
}
button:hover { opacity: .85; }
button.secondary {
background: transparent;
border: 1px solid var(--border);
color: var(--text);
}
input, select, textarea {
border: 1px solid var(--border);
border-radius: var(--radius);
padding: .5rem .75rem;
width: 100%;
background: var(--surface);
color: var(--text);
transition: border-color .15s;
}
input:focus, select:focus, textarea:focus {
outline: none;
border-color: var(--accent);
}
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.25rem;
box-shadow: var(--shadow);
}
.badge {
display: inline-block;
padding: .2rem .6rem;
border-radius: 999px;
font-size: .75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .04em;
}
.badge-draft { background: #e2e8f0; color: #475569; }
.badge-assigned { background: #dbeafe; color: #1d4ed8; }
.badge-scheduled { background: #fef3c7; color: #92400e; }
.badge-in_progress { background: #d1fae5; color: #065f46; }
.badge-pending_review { background: #ede9fe; color: #5b21b6; }
.badge-closed { background: #f3f4f6; color: #6b7280; }
#app { max-width: 1200px; margin: 0 auto; padding: 0 1rem; }
nav {
background: var(--navy);
color: #fff;
padding: .75rem 1.5rem;
display: flex;
align-items: center;
gap: 1.5rem;
}
nav .brand { font-weight: 700; font-size: 1.1rem; color: #fff; }
nav a { color: rgba(255,255,255,.8); font-size: .9rem; }
nav a:hover { color: #fff; text-decoration: none; }
nav .spacer { flex: 1; }
nav .user-info { font-size: .85rem; color: rgba(255,255,255,.7); }
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 0 1rem;
}
.page-header h1 { font-size: 1.4rem; }
+6
View File
@@ -0,0 +1,6 @@
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { -webkit-text-size-adjust: 100%; }
body { line-height: 1.5; -webkit-font-smoothing: antialiased; }
img, svg { display: block; max-width: 100%; }
input, button, textarea, select { font: inherit; }
p, h1, h2, h3, h4, h5, h6 { overflow-wrap: break-word; }