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/Relay/FillRelay.php · sjs:fill-together.server
· run php artisan relay:fill (port 8081)
View on GitHub
// Run the relay as its own process and relay JSON: php artisan relay:fill
private array $rooms = []; // room key => Room { seed, values, clients }
public function onConnect(TcpConnection $c, Request $request): void
{
$user = $this->user($request); // may this user open this record?
$recordId = $this->recordId($request);
$roomKey = $recordId === null ? null : RoomKey::fromHandshake($request, $recordId);
if (! $user || $roomKey === null) {
$c->close();
return;
}
$room = $this->rooms[$roomKey] ??= new Room(...$this->seed($recordId)); // the definition + the saved answers
$room->cancelDrop(); // back within 2 s: keep the room
$c->context->roomKey = $roomKey;
$c->context->id = bin2hex(random_bytes(8));
$c->context->name = self::name($request->get('name'), $user->name);
$c->context->slot = $room->freeSlot();
$c->context->state = null;
$room->clients[$c->id] = $c;
$this->send($c, ['type' => 'init', 'clientId' => $c->context->id, 'name' => $c->context->name,
'colorIndex' => Room::colorIndex($c->context->slot), 'seed' => $room->seed,
'values' => $room->snapshot(), 'peers' => $room->roster($c),
'sessionId' => $room->sessionId, 'responseId' => $room->responseId]);
}
public function onMessage(TcpConnection $from, string $raw): void
{
$msg = json_decode($raw); // objects stay objects: {} is relayed as {}
$room = $this->rooms[$from->context->roomKey ?? ''] ?? null;
if (! $room || ! $msg instanceof stdClass) {
return;
}
if (($msg->type ?? '') === 'complete' && ($msg->data ?? null) instanceof stdClass) {
$this->complete($from, $room, $msg->data);
} elseif (($msg->type ?? '') === 'value' && is_string($msg->key ?? null) && $room->responseId === null) {
$room->values[$msg->key] = $msg->value ?? null;
$room->broadcast($from, ['type' => 'value', 'from' => $from->context->id, 'key' => $msg->key, 'value' => $msg->value ?? null]);
} elseif (($msg->type ?? '') === 'presence' && isset($msg->state) && strlen($raw) <= 4096) { // stamp identity, relay
$retain = ($msg->retain ?? true) !== false;
if ($retain) {
$from->context->state = $msg->state;
}
$room->broadcast($from, ['type' => 'peer', 'retain' => $retain, 'peer' => Room::peer($from, $msg->state)], droppable: ! $retain);
} // unknown types: ignore
}
public function onClose(TcpConnection $c): void
{
$room = $this->rooms[$c->context->roomKey ?? ''] ?? null;
if (! $room) {
return;
}
unset($room->clients[$c->id]);
$room->broadcast($c, ['type' => 'peer-left', 'clientId' => $c->context->id]);
if (count($room->clients) === 0) { // drop the room 2 s after the last person leaves
$room->dropTimer = Timer::add(2, fn () => count($room->clients) === 0 && $this->drop($c->context->roomKey), [], false);
}
}
Server · app/Relay/FillRelay.php · sjs:fill-together.complete
· run php artisan relay:fill (port 8081)
View on GitHub
// Save once per room session and send the same confirmation to every participant
private function complete(TcpConnection $from, Room $room, stdClass $data): void
{
try {
if ($room->responseId === null) {
if (config('surveyjs.demo_mode')) {
Sandbox::activate(explode(':', $from->context->roomKey, 2)[0]);
}
$room->responseId = StoredJson::insertResponse('job-sheet', $data);
$room->values = (array) $data;
}
foreach ($room->clients as $client) {
$this->send($client, ['type' => 'completed', 'id' => $room->responseId, 'data' => $room->snapshot()]);
}
} catch (Throwable $e) {
report($e);
$this->send($from, ['type' => 'save-error', 'error' => "Couldn't save the job sheet. Please try again."]);
}
}