Connecting to the shared job sheet...
The form will appear when the shared answers have loaded.
JSON definition · shared/definitions/fill-together.json
View on GitHub
{
"title": "Job sheet",
"completeText": "Finish job sheet",
"description": "Filled together by the dispatcher and the technician",
"elements": [
{
"type": "panel",
"name": "dispatch",
"title": "Dispatcher",
"elements": [
{
"type": "text",
"name": "customer",
"title": "Customer",
"isRequired": true
},
{
"type": "text",
"name": "address",
"title": "Site address"
},
{
"type": "dropdown",
"name": "job_type",
"title": "Job type",
"choices": [
"Installation",
"Repair",
"Inspection"
]
},
{
"type": "comment",
"name": "dispatch_notes",
"title": "Notes for the technician"
}
]
},
{
"type": "panel",
"name": "onsite",
"title": "Technician",
"elements": [
{
"type": "comment",
"name": "findings",
"title": "What did you find?"
},
{
"type": "checkbox",
"name": "parts",
"title": "Parts used",
"choices": [
"Filter",
"Valve",
"Pump",
"Sensor"
],
"showOtherItem": true
},
{
"type": "text",
"name": "hours",
"title": "Hours on site",
"inputType": "number",
"min": 0,
"step": 0.25
},
{
"type": "boolean",
"name": "resolved",
"title": "Issue resolved?"
}
]
}
]
}
Client · shared/client/fill-together.js · sjs:fill-together.save
View on GitHub
// Ask the relay to save once and confirm the result to every participant
function completeJobSheet(sender, options) {
completionOptions = options;
if (responseId !== null) {
sender.completedHtml = `<h3>The job sheet has been saved.</h3><p>Response ID: ${responseId}</p>`;
return options.showSaveSuccess();
}
if (!ready || ws.readyState !== WebSocket.OPEN) {
sender.completedHtml = "<h3>The job sheet hasn't been saved.</h3>";
return options.showSaveError("Reconnect to the shared session, then try again.");
}
sender.completedHtml = "<h3>Saving the job sheet...</h3>";
options.showSaveInProgress();
saveOptions = options;
setLocked(true);
ws.send(JSON.stringify({ type: "complete", data: sender.data }));
}
Client · shared/client/fill-together.js · sjs:fill-together.client
View on GitHub
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
const draft = survey?.data;
const previousSession = sessionId;
if (!collab) {
survey = new Model(message.seed);
survey.completeText = "Finish job sheet";
collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
collab.onEvent.add((_, { message }) => {
if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
});
survey.onComplete.add(completeJobSheet);
mountSurvey(survey);
}
sessionId = message.sessionId;
ready = true;
collab.apply(message);
// Restore the local draft if an empty session replaces the disconnected one
if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
form.hidden = false;
document.getElementById("collaboration-loading").hidden = true;
setLocked(false);
if (message.responseId) confirmCompletion(message.responseId, message.values);
}
Server · app/routes/fill_together.py · sjs:fill-together.server
View on GitHub
# The relay runs in this app's process, on its port, and relays JSON: it never parses the definition
@router.websocket("/ws/rooms/{record_id}")
async def fill_together(websocket: WebSocket, record_id: RecordId, user: CurrentUser, rooms: Rooms,
room_key: FillRoomKey, db: Db, name: str = "") -> None:
if user is None or room_key is None: # the demo_user cookie stands in for your real session check
await websocket.close(code=1008) # before accept(): the browser sees a refused handshake
return
await websocket.accept()
room = rooms.join(room_key, lambda: seed(db, record_id)) # the definition + the saved answers
client = room.add(websocket, display_name(name, user.name))
client.send({"type": "init", "clientId": client.id, "name": client.name, "colorIndex": room.color_index(client),
"seed": room.seed, "values": room.values, "peers": room.roster(client),
"sessionId": room.session_id, "responseId": room.response_id})
try:
async for raw in websocket.iter_text():
message = parse(raw) # objects stay objects: {} is relayed as {}
if not isinstance(message, dict):
continue
kind = message.get("type")
if kind == "complete" and isinstance(message.get("data"), dict):
await complete(room, client, message["data"], db)
elif kind == "value" and isinstance(message.get("key"), str) and room.response_id is None:
room.values[message["key"]] = message.get("value") # last write wins
room.broadcast(client, {"type": "value", "from": client.id, "key": message["key"],
"value": message.get("value")})
elif kind == "presence" and message.get("state") is not None and len(raw) <= 4096:
retain = message.get("retain") is not False # stamp identity, relay
if retain:
client.state = message["state"]
room.broadcast(client, {"type": "peer", "retain": retain, "peer": room.peer(client, message["state"])},
droppable=not retain)
# unknown types: ignore
except WebSocketDisconnect:
pass
finally:
rooms.leave(room_key, client) # peer-left to the others; the room is dropped 2 s after the last leaves
Server · app/routes/fill_together.py · sjs:fill-together.complete
View on GitHub
# Save once per room session and send the same confirmation to every participant
async def complete(room: FillRoom, sender: Participant, data: dict[str, Any], db: Connection) -> None:
async with room.lock: # two completes at once: the second waits, then finds the saved id
if room.response_id is None:
try:
room.response_id = await run_in_threadpool(insert_response, db, "job-sheet", data) # as save-response does
except Exception:
log.exception("fill-together: couldn't save the job sheet")
sender.send({"type": "save-error", "error": "Couldn't save the job sheet. Please try again."})
return
room.values = dict(data)
room.send_all({"type": "completed", "id": room.response_id, "data": room.values})