- Source file
- Document ID
- Answers to review
Review the draft before submitting.
Source document · Open document
JSON definition · shared/definitions/extract-from-paper.json
View on GitHub
{
"title": "Work order",
"description": "Completed on paper by the technician and scanned at the office",
"elements": [
{
"type": "text",
"name": "customer_name",
"title": "Customer name"
},
{
"type": "text",
"name": "site_address",
"title": "Site address"
},
{
"type": "text",
"name": "visit_date",
"title": "Visit date",
"inputType": "date"
},
{
"type": "radiogroup",
"name": "work_type",
"title": "Type of work",
"choices": [
{
"value": "installation",
"text": "Installation"
},
{
"value": "repair",
"text": "Repair"
},
{
"value": "inspection",
"text": "Inspection"
}
]
},
{
"type": "checkbox",
"name": "parts",
"title": "Parts replaced",
"choices": [
{
"value": "filter",
"text": "Filter"
},
{
"value": "valve",
"text": "Valve"
},
{
"value": "pump",
"text": "Pump"
},
{
"value": "sensor",
"text": "Sensor"
}
]
},
{
"type": "text",
"name": "hours",
"title": "Hours on site",
"inputType": "number"
},
{
"type": "boolean",
"name": "resolved",
"title": "Issue resolved"
},
{
"type": "text",
"name": "technician",
"title": "Technician"
},
{
"type": "comment",
"name": "notes",
"title": "Notes"
}
]
}
Client · shared/client/extract-from-paper.js · sjs:extract-from-paper.client
View on GitHub
// Extract a draft without saving it and validate the response before replacing any answers
async function extract(file, signal) {
const body = new FormData();
body.append("scan", file);
const response = await fetch("/api/work-orders/extract", { method: "POST", body, signal });
if (!response.ok) throw await responseError(response, "Couldn't extract the answers. Try again or enter the answers directly in the form.");
const result = await response.json();
if (!result.answers || typeof result.answers !== "object" || Array.isArray(result.answers) || !Array.isArray(result.confidence)) {
throw new Error("The extraction result couldn't be read. Try again or enter the answers directly in the form.");
}
return result;
}
Client · shared/client/extract-from-paper.js · sjs:extract-from-paper.save
View on GitHub
// Save only after human review and confirm the response ID returned by the backend
survey.onComplete.add(async (sender, options) => {
lock(true, true);
sender.completedHtml = "<h3>Saving the reviewed response...</h3>";
options.showSaveInProgress();
try {
const data = Object.fromEntries(sender.getAllQuestions()
.filter(q => q !== reviewed).map(q => [q.valueName || q.name, q.isEmpty() ? null : q.value]));
const response = await fetch("/api/responses", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ formId: "work-order", data })
});
if (!response.ok) throw await responseError(response, "Couldn't save the reviewed response. Please try again.");
const { id } = await response.json();
if (!Number.isInteger(id) || id < 1) throw new Error("The server didn't confirm a saved response. Please try again.");
setStoredQuery({ id });
sender.completedHtml = `<h3>The reviewed response has been saved.</h3><p>Response ID: ${id}</p>`;
showStatus(`Reviewed response #${id} saved.`);
options.showSaveSuccess();
} catch (error) {
sender.completedHtml = "<h3>The reviewed response hasn't been saved.</h3>";
options.showSaveError(error instanceof TypeError ? "Couldn't save the reviewed response. Please try again." : error.message);
} finally { lock(false); }
});
Server · Endpoints/ExtractFromPaper.cs · sjs:extract-from-paper.template
View on GitHub
// Generate a blank, fillable PDF using the same schema as extraction
app.MapGet("/api/work-orders/blank.pdf", async (SurveyDb db, SurveyJsService service, HttpResponse response) =>
{
var definition = await db.Forms.Where(f => f.Key == "work-order").Select(f => f.Json).SingleOrDefaultAsync();
if (definition is null) return Results.Json(new { error = "Unknown work order form" }, statusCode: 404);
var pdf = await service.PostAsync("/pdf", new { schema = JsonNode.Parse(definition) }, TimeSpan.FromSeconds(60));
if (pdf.Status != 200 || !pdf.HasContentType("application/pdf") || !pdf.BodyStartsWith("%PDF-"))
throw service.Unexpected("/pdf", pdf);
response.Headers.ContentDisposition = "attachment; filename=\"work-order.pdf\"";
response.Headers.CacheControl = "private, no-store";
return Results.Bytes(pdf.Body, "application/pdf");
});
Server · Endpoints/ExtractFromPaper.cs · sjs:extract-from-paper.server
View on GitHub
// POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
app.MapPost("/api/work-orders/extract", async (IFormFile? scan, SurveyDb db, SurveyJsService service, CancellationToken aborted) =>
{
if (scan is null) return Results.Json(new { error = "Upload the scan in a field named \"scan\"" }, statusCode: 400);
if (scan.Length > 5 * 1024 * 1024) return Results.Json(new { error = "The scan must be a file of 5 MB or less" }, statusCode: 413);
var bytes = await FileType.ReadAllBytesAsync(scan, aborted);
if (FileType.Detect(bytes) is null) // its first bytes, not the client's content type
return Results.Json(new { error = "The file is not a PDF, PNG, JPEG, WebP or GIF document" }, statusCode: 400);
var definition = await db.Forms.Where(f => f.Key == "work-order").Select(f => f.Json).SingleAsync();
var output = await service.PostAsync("/extract", // JSON with base64, not multipart
new { schema = JsonNode.Parse(definition), document = Convert.ToBase64String(bytes) }, TimeSpan.FromSeconds(120));
return output switch // nothing is saved: a person reviews the draft
{
{ Status: 200, Object: { } result } when result["data"] is JsonObject data =>
Results.Json(new { answers = data, confidence = result["confidence"] ?? new JsonArray(), uniqueId = result["uniqueId"] }),
{ Status: 400, Error: "INVALID_DOCUMENT" } => Results.Json(new { error = "The file is not a PDF, PNG, JPEG, WebP or GIF document" }, statusCode: 400),
{ Status: 503, Error: "AI_NOT_CONFIGURED" } => Results.Json(new { error = "The SurveyJS service has no AI provider configured" }, statusCode: 503),
{ Status: 502, Error: "EXTRACTION_FAILED" } => Results.Json(new { error = "Could not extract the response from the document" }, statusCode: 502),
_ => throw service.Unexpected("/extract", output, logBody: false),
};
}).DisableAntiforgery(); // called with fetch() from the same origin; with cookie auth, validate a token or use an Authorization header