- 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 · routes/examples/extract-from-paper.php · sjs:extract-from-paper.template
View on GitHub
// Generate a blank, fillable PDF using the same schema as extraction
Route::get('/api/work-orders/blank.pdf', function () {
$definition = DB::table('forms')->where('key', 'work-order')->value('json') ?? abort(404, 'Unknown work order form');
$pdf = SurveyJsService::post('/pdf', ['schema' => json_decode($definition)], timeout: 60);
if ($pdf->status() !== 200
|| ! str_starts_with($pdf->header('Content-Type'), 'application/pdf')
|| ! str_starts_with($pdf->body(), '%PDF-')) {
SurveyJsService::unexpected('/pdf', $pdf);
}
return response($pdf->body(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="work-order.pdf"',
'Cache-Control' => 'private, no-store',
]);
});
Server · routes/examples/extract-from-paper.php · 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
Route::post('/api/work-orders/extract', function (Request $request) {
$scan = $request->file('scan') ?? abort(400, 'Upload the scan in a field named "scan"');
abort_if(! $scan instanceof UploadedFile || ! $scan->isValid() || $scan->getSize() > 5 * 1024 * 1024, 413, 'The scan must be a file of 5 MB or less');
abort_unless(in_array($scan->getMimeType(), ['application/pdf', 'image/png', 'image/jpeg', 'image/webp', 'image/gif'], true), 400, 'The file is not a PDF, PNG, JPEG, WebP or GIF document');
$out = SurveyJsService::post('/extract', [ // JSON with base64, not multipart
'schema' => json_decode(DB::table('forms')->where('key', 'work-order')->value('json')), 'document' => base64_encode($scan->get())], timeout: 120);
$result = $out->object();
return match (true) { // nothing is saved: a person reviews the draft
$out->status() === 200 && is_object($result) && is_object($result->data ?? null) => response()->json(
['answers' => $result->data, 'confidence' => $result->confidence ?? [], 'uniqueId' => $result->uniqueId ?? null]),
$out->status() === 400 && $out->json('error') === 'INVALID_DOCUMENT' => response()->json(['error' => 'The file is not a PDF, PNG, JPEG, WebP or GIF document'], 400),
$out->status() === 503 && $out->json('error') === 'AI_NOT_CONFIGURED' => response()->json(['error' => 'The SurveyJS service has no AI provider configured'], 503),
$out->status() === 502 && $out->json('error') === 'EXTRACTION_FAILED' => response()->json(['error' => 'Could not extract the response from the document'], 502),
default => SurveyJsService::unexpected('/extract', $out, logBody: false),
};
});