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 · Endpoints/FillTogether.cs · sjs:fill-together.server
View on GitHub
// A WebSocket endpoint relays JSON between the people filling one record: answers, focus and cursors
app.Map("/ws/rooms/{recordId:regex(^[A-Za-z0-9_-]{{1,64}}$)}", async (string recordId, string? name, HttpContext context,
FillRooms rooms, RequestStorage storage, ILogger<FillRoom> log) =>
{
if (!context.WebSockets.IsWebSocketRequest) return Results.Json(new { error = "Expected a WebSocket request" }, statusCode: 400);
// Demo only: the demo_user cookie stands in for your real session check here (may this user open this record?)
if (context.User.Identity?.IsAuthenticated != true) return Results.Json(new { error = "Sign in to fill this record" }, statusCode: 403);
var database = storage.DatabasePath;
var room = await rooms.OpenAsync(RoomKey.For(storage, recordId), () => SeedAsync(database, recordId)); // the definition + the saved answers
using var socket = await context.WebSockets.AcceptWebSocketAsync();
await using var me = new Participant(socket, DisplayName(name, context.User.Identity.Name!));
room.Join(me);
me.Send(new
{
type = "init", clientId = me.Id, name = me.Name, colorIndex = FillRoom.ColorIndex(me.Slot), seed = room.Seed,
values = room.Snapshot(), peers = room.Roster(me), sessionId = room.SessionId, responseId = room.ResponseId,
});
try
{
await foreach (var raw in me.ReceiveAsync(context.RequestAborted))
{
var message = Parse(raw); // objects stay objects: {} is relayed as {}
switch (Text(message?["type"]))
{
case "complete" when message!["data"] is JsonObject data:
await CompleteAsync(room, me, data, database, log);
break;
case "value" when Text(message!["key"]) is { } key && room.ResponseId is null:
room.SetValue(key, message["value"]); // last write wins
room.Broadcast(me, new { type = "value", from = me.Id, key, value = message["value"] });
break;
case "presence" when message!["state"] is not null && raw.Length <= 4096: // stamp identity, relay
var retain = message["retain"]?.GetValueKind() != JsonValueKind.False;
if (retain) me.State = message["state"];
room.Broadcast(me, new { type = "peer", retain, peer = FillRoom.Peer(me, message["state"]) }, droppable: !retain);
break;
} // unknown types: ignore
}
}
finally
{
room.Leave(me); // peer-left; the room is dropped 2 s after the last person leaves
}
return Results.Empty;
});
Server · Endpoints/FillTogether.cs · sjs:fill-together.complete
View on GitHub
// Save once per room session and send the same confirmation to every participant
private static async Task CompleteAsync(FillRoom room, Participant from, JsonObject data, string database, ILogger log)
{
await room.Saving.WaitAsync(); // two people may finish at the same moment
try
{
if (room.ResponseId is null)
{
await using var db = SurveyDbSetup.Open(database); // a context of its own: the socket outlives the request
room.ResponseId = await StoredJson.InsertResponseAsync(db, "job-sheet", data);
room.ReplaceValues(data);
}
room.SendToAll(new { type = "completed", id = room.ResponseId, data = room.Snapshot() });
}
catch (Exception e) when (e is DbUpdateException or InvalidOperationException or IOException)
{
log.LogError(e, "Couldn't save the job sheet of room {Room}", room.Key);
from.Send(new { type = "save-error", error = "Couldn't save the job sheet. Please try again." });
}
finally
{
room.Saving.Release();
}
}