Files
workorders/web/components/work-orders/wo-form.mjs
T

222 lines
12 KiB
JavaScript

import { api } from '../../lib/api.mjs';
import { toLocalDatetime } from '../../lib/format.mjs';
const STATUSES = ['draft','assigned','scheduled','in_progress','pending_review','closed'];
const PRI_COLOR = { low:'var(--priority-low)', normal:'var(--priority-normal)', high:'var(--priority-high)', urgent:'var(--priority-urgent)' };
class WoForm extends HTMLElement {
#woId = null;
#wo = null;
#dirty = false;
static get observedAttributes() { return ['wo-id']; }
attributeChangedCallback(_, __, val) { this.#woId = val ? +val : null; if (this.shadowRoot) this.#load(); }
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.#render();
if (this.#woId) this.#load();
}
async #load() {
if (!this.#woId) return;
try { this.#wo = await api.get(`/work-orders/${this.#woId}`); } catch { /* ignore */ }
this.#render();
}
#render() {
const wo = this.#wo || {};
const isNew = !this.#woId;
const s = this.shadowRoot;
s.innerHTML = `<style>${this.#css()}</style>${this.#html(wo, isNew)}`;
this.#bind();
if (window.lucide) lucide.createIcons({ nodes: [s] });
}
#css() { return `
:host { display: block; }
.page-header { display:flex; align-items:center; gap:1rem; margin-bottom:1.25rem; }
.back-btn { background:none; border:1px solid var(--border); color:var(--text); border-radius:var(--radius); padding:.4rem .75rem; font-size:.813rem; font-weight:500; cursor:pointer; display:flex; align-items:center; gap:.3rem; transition:background .15s; }
.back-btn:hover { background:var(--surface-2); }
h1 { font-size:1.25rem; font-weight:700; color:var(--text); }
.layout { display:grid; grid-template-columns:2fr 1fr; gap:1.5rem; align-items:start; }
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:1.25rem; display:flex; flex-direction:column; gap:1rem; box-shadow:var(--shadow-sm); }
.card-title { font-size:.813rem; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:.06em; padding-bottom:.75rem; border-bottom:1px solid var(--border); }
label { display:flex; flex-direction:column; gap:.3rem; font-size:.813rem; font-weight:600; color:var(--text); }
input, select, textarea { border:1px solid var(--border); border-radius:var(--radius-sm); padding:.5rem .75rem; background:var(--surface); color:var(--text); font-size:.875rem; width:100%; transition:border-color .15s,box-shadow .15s; color-scheme:inherit; }
input:focus, select:focus, textarea:focus { outline:none; border-color:var(--teal); box-shadow:0 0 0 3px rgba(10,126,164,.15); }
textarea { resize:vertical; min-height:80px; line-height:1.6; font-family:inherit; }
.row2 { display:grid; grid-template-columns:1fr 1fr; gap:1rem; }
select { appearance:none; cursor:pointer; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748B' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right .6rem center; padding-right:2rem; }
.priority-select-wrap { position:relative; }
.pri-dot { width:8px; height:8px; border-radius:50%; position:absolute; left:.75rem; top:50%; transform:translateY(-50%); pointer-events:none; }
.priority-select { padding-left:1.75rem; }
.footer { display:flex; justify-content:flex-end; gap:.75rem; margin-top:.5rem; }
.btn { display:inline-flex; align-items:center; gap:.4rem; padding:.5rem 1rem; border:none; border-radius:var(--radius); font-size:.875rem; font-weight:600; cursor:pointer; transition:opacity .15s; }
.btn-primary { background:var(--teal); color:#fff; }
.btn-primary:hover { opacity:.88; }
.btn-ghost { background:transparent; border:1px solid var(--border); color:var(--text); }
.btn-ghost:hover { background:var(--surface-2); }
.btn:disabled { opacity:.5; cursor:not-allowed; }
.err { color:var(--danger); font-size:.813rem; text-align:right; }
@media (max-width:768px) { .layout { grid-template-columns:1fr; } .row2 { grid-template-columns:1fr; } }
`; }
#html(wo, isNew) {
const v = (field, fallback = '') => this.#esc(wo[field] ?? fallback);
return `
<div class="page-header">
<button class="back-btn" id="back"><i data-lucide="chevron-left" style="width:15px;height:15px"></i> Back</button>
<h1>${isNew ? 'New Work Order' : `Edit ${wo.wo_number || 'Work Order'}`}</h1>
</div>
<form id="wo-form">
<div class="layout">
<!-- Left: main fields -->
<div style="display:flex;flex-direction:column;gap:1rem;">
<div class="card">
<div class="card-title">Details</div>
<label>Title *<input name="title" required value="${v('title')}" placeholder="Brief description of the work"></label>
<label>Description<textarea name="description" rows="3" placeholder="What needs to be done…">${v('description')}</textarea></label>
<label>Instructions<textarea name="instructions" rows="5" placeholder="Step-by-step instructions for the field crew…">${v('instructions')}</textarea></label>
</div>
<div class="card">
<div class="card-title">Location</div>
<label>Site Name<input name="site_name" value="${v('site_name')}" placeholder="e.g. Downtown Office"></label>
<label>Address<input name="address" value="${v('address')}" placeholder="Street address"></label>
<label>Access Notes<textarea name="access_notes" rows="2" placeholder="Gate codes, road conditions, parking info…">${v('access_notes')}</textarea></label>
</div>
</div>
<!-- Right: metadata -->
<div style="display:flex;flex-direction:column;gap:1rem;">
<div class="card">
<div class="card-title">Status &amp; Priority</div>
${!isNew ? `<label>Status
<select name="status">
${STATUSES.map(s => `<option value="${s}" ${wo.status===s?'selected':''}>${s.replace('_',' ')}</option>`).join('')}
</select>
</label>` : ''}
<label>Priority
<div class="priority-select-wrap">
<span class="pri-dot" id="pri-dot" style="background:${PRI_COLOR[wo.priority||'normal']}"></span>
<select name="priority" class="priority-select">
${['low','normal','high','urgent'].map(p =>
`<option value="${p}" ${(wo.priority||'normal')===p?'selected':''}>${p.charAt(0).toUpperCase()+p.slice(1)}</option>`
).join('')}
</select>
</div>
</label>
</div>
<div class="card">
<div class="card-title">Schedule</div>
<label>Scheduled Start<input type="datetime-local" name="scheduled_start" value="${toLocalDatetime(wo.scheduled_start)}"></label>
<label>Scheduled End<input type="datetime-local" name="scheduled_end" value="${toLocalDatetime(wo.scheduled_end)}"></label>
</div>
<div class="card">
<div class="card-title">Parent</div>
<label>Parent Type
<select name="parent_type">
<option value="">None</option>
<option value="project" ${wo.parent_type==='project'?'selected':''}>Project</option>
<option value="ticket" ${wo.parent_type==='ticket'?'selected':''}>Trouble Ticket</option>
<option value="service_order" ${wo.parent_type==='service_order'?'selected':''}>Service Order</option>
</select>
</label>
<label>Parent ID<input name="parent_id" type="number" value="${wo.parent_id ?? ''}" placeholder="Reference ID"></label>
</div>
</div>
</div>
<div class="footer">
<div class="err" id="form-err"></div>
<button type="button" class="btn btn-ghost" id="cancel-btn">Cancel</button>
<button type="submit" class="btn btn-primary" id="save-btn">
<i data-lucide="save" style="width:14px;height:14px"></i>
${isNew ? 'Create Work Order' : 'Save Changes'}
</button>
</div>
</form>`;
}
#bind() {
const s = this.shadowRoot;
s.querySelector('#back')?.addEventListener('click', () => this.#goBack());
s.querySelector('#cancel-btn')?.addEventListener('click', () => this.#goBack());
// Update priority dot colour on change
s.querySelector('[name="priority"]')?.addEventListener('change', e => {
const dot = s.querySelector('#pri-dot');
if (dot) dot.style.background = PRI_COLOR[e.target.value] || PRI_COLOR.normal;
});
// Dirty tracking
s.querySelectorAll('input, select, textarea').forEach(el =>
el.addEventListener('input', () => { this.#dirty = true; }));
s.querySelector('#wo-form')?.addEventListener('submit', async e => {
e.preventDefault();
const val = n => (s.querySelector(`[name="${n}"]`)?.value ?? '').trim();
const dt = n => { const v = val(n); return v ? new Date(v).toISOString() : null; };
if (!val('title')) {
s.querySelector('#form-err').textContent = 'Title is required.';
return;
}
const body = {
title: val('title'),
description: val('description'),
instructions: val('instructions'),
priority: val('priority') || 'normal',
site_name: val('site_name'),
address: val('address'),
access_notes: val('access_notes'),
scheduled_start: dt('scheduled_start'),
scheduled_end: dt('scheduled_end'),
parent_type: val('parent_type') || null,
parent_id: val('parent_id') ? +val('parent_id') : null,
};
const btn = s.querySelector('#save-btn');
btn.disabled = true;
s.querySelector('#form-err').textContent = '';
try {
if (this.#woId) {
// Also update status if changed
const newStatus = val('status');
if (newStatus && this.#wo?.status !== newStatus) {
await api.put(`/work-orders/${this.#woId}/status`, { status: newStatus });
}
await api.put(`/work-orders/${this.#woId}`, body);
window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: 'Work order saved', type: 'success' } }));
} else {
const created = await api.post('/work-orders', body);
window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: 'Work order created', type: 'success' } }));
this.#dirty = false;
window.dispatchEvent(new CustomEvent('wo:navigate', { detail: { path: `/work-orders/${created.id}` } }));
return;
}
this.#dirty = false;
window.dispatchEvent(new CustomEvent('wo:navigate', { detail: { path: `/work-orders/${this.#woId}` } }));
} catch (err) {
s.querySelector('#form-err').textContent = err.message;
btn.disabled = false;
}
});
}
#goBack() {
if (this.#dirty && !confirm('You have unsaved changes. Leave anyway?')) return;
if (this.#woId) {
window.dispatchEvent(new CustomEvent('wo:navigate', { detail: { path: `/work-orders/${this.#woId}` } }));
} else {
window.dispatchEvent(new CustomEvent('wo:navigate', { detail: { path: '/work-orders' } }));
}
}
#esc(s) { return (s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
}
customElements.define('wo-form', WoForm);