enhanced questionnaire version handling and handling uploads from outdated questionnaires through automatic revisioning and checks
Some checks failed
PHPUnit / test (push) Has been cancelled
Some checks failed
PHPUnit / test (push) Has been cancelled
This commit is contained in:
@ -1,8 +1,11 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/questionnaire_structure.php';
|
||||
|
||||
/**
|
||||
* Validate Android app questionnaire submit payloads before persisting answers.
|
||||
*
|
||||
* @param array<string, mixed>|null $manifest Structure manifest for legacy revision submits
|
||||
* @return list<array{questionID: string, code: string, message: string}>
|
||||
*/
|
||||
function qdb_validate_app_submit_payload(
|
||||
@ -12,7 +15,8 @@ function qdb_validate_app_submit_payload(
|
||||
array $shortIdMap,
|
||||
array $shortIdToType,
|
||||
array $symptomParentMap,
|
||||
array $optionMap
|
||||
array $optionMap,
|
||||
?array $manifest = null
|
||||
): array {
|
||||
$errors = [];
|
||||
|
||||
@ -124,8 +128,13 @@ function qdb_validate_app_submit_payload(
|
||||
}
|
||||
}
|
||||
|
||||
if ($manifest !== null) {
|
||||
return array_merge($errors, qdb_validate_required_answers_from_manifest($manifest, $answeredShort));
|
||||
}
|
||||
|
||||
$qStmt = $pdo->prepare(
|
||||
'SELECT questionID, type, isRequired, configJson FROM question WHERE questionnaireID = :qn'
|
||||
'SELECT questionID, type, isRequired, configJson FROM question
|
||||
WHERE questionnaireID = :qn AND ' . qdb_active_questions_clause('question')
|
||||
);
|
||||
$qStmt->execute([':qn' => $qnID]);
|
||||
foreach ($qStmt->fetchAll(PDO::FETCH_ASSOC) as $qRow) {
|
||||
@ -169,3 +178,44 @@ function qdb_validate_app_submit_payload(
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{questionID: string, code: string, message: string}>
|
||||
*/
|
||||
function qdb_validate_required_answers_from_manifest(array $manifest, array $answeredShort): array {
|
||||
$errors = [];
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (!is_array($qEntry) || empty($qEntry['isRequired'])) {
|
||||
continue;
|
||||
}
|
||||
$shortId = (string)($qEntry['shortId'] ?? '');
|
||||
$type = (string)($qEntry['type'] ?? '');
|
||||
if ($shortId === '') {
|
||||
continue;
|
||||
}
|
||||
if ($type === 'glass_scale_question') {
|
||||
foreach ($qEntry['symptoms'] ?? [] as $symptomKey) {
|
||||
$sk = trim((string)$symptomKey);
|
||||
if ($sk === '') {
|
||||
continue;
|
||||
}
|
||||
if (empty($answeredShort[$sk])) {
|
||||
$errors[] = [
|
||||
'questionID' => $sk,
|
||||
'code' => 'MISSING_ANSWER',
|
||||
'message' => 'Required symptom is not answered',
|
||||
];
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (empty($answeredShort[$shortId])) {
|
||||
$errors[] = [
|
||||
'questionID' => $shortId,
|
||||
'code' => 'MISSING_ANSWER',
|
||||
'message' => 'Required question is not answered',
|
||||
];
|
||||
}
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
414
lib/questionnaire_structure.php
Normal file
414
lib/questionnaire_structure.php
Normal file
@ -0,0 +1,414 @@
|
||||
<?php
|
||||
/**
|
||||
* Questionnaire structure revisions: bump, snapshot manifests, retire questions.
|
||||
*/
|
||||
|
||||
function qdb_active_questions_clause(string $alias = 'question'): string {
|
||||
return "COALESCE($alias.retiredAt, 0) = 0";
|
||||
}
|
||||
|
||||
function qdb_active_options_clause(string $alias = 'answer_option'): string {
|
||||
return "COALESCE($alias.retiredAt, 0) = 0";
|
||||
}
|
||||
|
||||
function qdb_questionnaire_structure_revision(PDO $pdo, string $qnID): int {
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT COALESCE(structureRevision, 1) FROM questionnaire WHERE questionnaireID = :id'
|
||||
);
|
||||
$stmt->execute([':id' => $qnID]);
|
||||
$rev = $stmt->fetchColumn();
|
||||
return $rev !== false ? max(1, (int)$rev) : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
function qdb_build_structure_manifest(PDO $pdo, string $qnID, bool $includeRetired = false): array {
|
||||
$where = 'questionnaireID = :qn';
|
||||
if (!$includeRetired) {
|
||||
$where .= ' AND ' . qdb_active_questions_clause('question');
|
||||
}
|
||||
$qStmt = $pdo->prepare(
|
||||
"SELECT questionID, type, isRequired, configJson, defaultText, retiredAt
|
||||
FROM question WHERE $where ORDER BY orderIndex"
|
||||
);
|
||||
$qStmt->execute([':qn' => $qnID]);
|
||||
$questions = [];
|
||||
foreach ($qStmt->fetchAll(PDO::FETCH_ASSOC) as $qRow) {
|
||||
$fullId = $qRow['questionID'];
|
||||
$shortId = qdb_question_local_id($fullId, $qnID);
|
||||
$config = json_decode($qRow['configJson'] ?? '{}', true) ?: [];
|
||||
$qKey = qdb_question_key($config, $qRow['defaultText']);
|
||||
|
||||
$optWhere = 'questionID = :qid';
|
||||
if (!$includeRetired) {
|
||||
$optWhere .= ' AND ' . qdb_active_options_clause('answer_option');
|
||||
}
|
||||
$aoStmt = $pdo->prepare(
|
||||
"SELECT defaultText, points FROM answer_option WHERE $optWhere ORDER BY orderIndex"
|
||||
);
|
||||
$aoStmt->execute([':qid' => $fullId]);
|
||||
$options = [];
|
||||
foreach ($aoStmt->fetchAll(PDO::FETCH_ASSOC) as $ao) {
|
||||
$options[] = [
|
||||
'key' => $ao['defaultText'],
|
||||
'points' => (int)$ao['points'],
|
||||
];
|
||||
}
|
||||
|
||||
$entry = [
|
||||
'questionID' => $fullId,
|
||||
'shortId' => $shortId,
|
||||
'questionKey'=> $qKey,
|
||||
'type' => $qRow['type'] ?? '',
|
||||
'isRequired' => (int)($qRow['isRequired'] ?? 0) === 1,
|
||||
'options' => $options,
|
||||
];
|
||||
if ($includeRetired && (int)($qRow['retiredAt'] ?? 0) > 0) {
|
||||
$entry['retired'] = true;
|
||||
}
|
||||
if (($qRow['type'] ?? '') === 'glass_scale_question' && !empty($config['symptoms'])) {
|
||||
$entry['symptoms'] = array_values(array_map('strval', (array)$config['symptoms']));
|
||||
}
|
||||
$questions[] = $entry;
|
||||
}
|
||||
|
||||
return [
|
||||
'questionnaireID' => $qnID,
|
||||
'structureRevision' => qdb_questionnaire_structure_revision($pdo, $qnID),
|
||||
'questions' => $questions,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
function qdb_load_structure_manifest(PDO $pdo, string $qnID, int $revision): ?array {
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT manifestJson FROM questionnaire_structure_snapshot
|
||||
WHERE questionnaireID = :qn AND structureRevision = :rev'
|
||||
);
|
||||
$stmt->execute([':qn' => $qnID, ':rev' => $revision]);
|
||||
$json = $stmt->fetchColumn();
|
||||
if ($json === false || $json === '') {
|
||||
return null;
|
||||
}
|
||||
$decoded = json_decode((string)$json, true);
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
|
||||
function qdb_save_structure_snapshot(PDO $pdo, string $qnID, int $revision, array $manifest): void {
|
||||
$json = json_encode($manifest, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if ($json === false) {
|
||||
$json = '{}';
|
||||
}
|
||||
$pdo->prepare(
|
||||
'INSERT INTO questionnaire_structure_snapshot (questionnaireID, structureRevision, createdAt, manifestJson)
|
||||
VALUES (:qn, :rev, :ts, :mj)
|
||||
ON CONFLICT(questionnaireID, structureRevision) DO UPDATE SET
|
||||
manifestJson = excluded.manifestJson,
|
||||
createdAt = excluded.createdAt'
|
||||
)->execute([
|
||||
':qn' => $qnID,
|
||||
':rev' => $revision,
|
||||
':ts' => time(),
|
||||
':mj' => $json,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfill revision-1 snapshots for questionnaires missing any snapshot row.
|
||||
*/
|
||||
function qdb_backfill_structure_snapshots(PDO $pdo): bool {
|
||||
$ids = $pdo->query('SELECT questionnaireID FROM questionnaire')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$changed = false;
|
||||
foreach ($ids as $qnID) {
|
||||
$qnID = (string)$qnID;
|
||||
$chk = $pdo->prepare(
|
||||
'SELECT 1 FROM questionnaire_structure_snapshot
|
||||
WHERE questionnaireID = :qn LIMIT 1'
|
||||
);
|
||||
$chk->execute([':qn' => $qnID]);
|
||||
if ($chk->fetchColumn()) {
|
||||
continue;
|
||||
}
|
||||
$rev = qdb_questionnaire_structure_revision($pdo, $qnID);
|
||||
$manifest = qdb_build_structure_manifest($pdo, $qnID, true);
|
||||
$manifest['structureRevision'] = $rev;
|
||||
qdb_save_structure_snapshot($pdo, $qnID, $rev, $manifest);
|
||||
$changed = true;
|
||||
}
|
||||
return $changed;
|
||||
}
|
||||
|
||||
function qdb_bump_structure_revision(PDO $pdo, string $qnID, string $reason = ''): int {
|
||||
$current = qdb_questionnaire_structure_revision($pdo, $qnID);
|
||||
$manifest = qdb_build_structure_manifest($pdo, $qnID, false);
|
||||
$manifest['structureRevision'] = $current;
|
||||
qdb_save_structure_snapshot($pdo, $qnID, $current, $manifest);
|
||||
|
||||
$newRev = $current + 1;
|
||||
$pdo->prepare(
|
||||
'UPDATE questionnaire SET structureRevision = :rev, structureChangedAt = :ts WHERE questionnaireID = :qn'
|
||||
)->execute([':rev' => $newRev, ':ts' => time(), ':qn' => $qnID]);
|
||||
|
||||
return $newRev;
|
||||
}
|
||||
|
||||
function qdb_questionnaire_id_for_question(PDO $pdo, string $questionID): ?string {
|
||||
$stmt = $pdo->prepare('SELECT questionnaireID FROM question WHERE questionID = :qid');
|
||||
$stmt->execute([':qid' => $questionID]);
|
||||
$id = $stmt->fetchColumn();
|
||||
return $id !== false ? (string)$id : null;
|
||||
}
|
||||
|
||||
function qdb_option_has_client_data(PDO $pdo, string $answerOptionID): bool {
|
||||
$stmt = $pdo->prepare('SELECT 1 FROM client_answer WHERE answerOptionID = :id LIMIT 1');
|
||||
$stmt->execute([':id' => $answerOptionID]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
return true;
|
||||
}
|
||||
$chk = $pdo->query(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'client_answer_submission' LIMIT 1"
|
||||
);
|
||||
if (!$chk || !$chk->fetchColumn()) {
|
||||
return false;
|
||||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT 1 FROM client_answer_submission WHERE answerOptionID = :id LIMIT 1'
|
||||
);
|
||||
$stmt->execute([':id' => $answerOptionID]);
|
||||
return (bool)$stmt->fetchColumn();
|
||||
}
|
||||
|
||||
function qdb_question_has_client_data(PDO $pdo, string $questionID): bool {
|
||||
$stmt = $pdo->prepare('SELECT 1 FROM client_answer WHERE questionID = :qid LIMIT 1');
|
||||
$stmt->execute([':qid' => $questionID]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
return true;
|
||||
}
|
||||
$chk = $pdo->query(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'client_answer_submission' LIMIT 1"
|
||||
);
|
||||
if (!$chk || !$chk->fetchColumn()) {
|
||||
return false;
|
||||
}
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT 1 FROM client_answer_submission WHERE questionID = :qid LIMIT 1'
|
||||
);
|
||||
$stmt->execute([':qid' => $questionID]);
|
||||
return (bool)$stmt->fetchColumn();
|
||||
}
|
||||
|
||||
function qdb_retire_question(PDO $pdo, string $questionID, int $revision): void {
|
||||
$pdo->prepare(
|
||||
'UPDATE question SET retiredAt = :ts, retiredInRevision = :rev
|
||||
WHERE questionID = :qid AND COALESCE(retiredAt, 0) = 0'
|
||||
)->execute([':ts' => time(), ':rev' => $revision, ':qid' => $questionID]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build submit maps from a structure manifest (current or legacy).
|
||||
*
|
||||
* @return array{
|
||||
* shortIdMap: array<string, string>,
|
||||
* shortIdToType: array<string, string>,
|
||||
* optionMap: array<string, array<string, array{answerOptionID: string, points: int}>>,
|
||||
* symptomParentMap: array<string, string>,
|
||||
* freeTextMaxLen: array<string, int>,
|
||||
* manifestQuestionIds: list<string>
|
||||
* }
|
||||
*/
|
||||
function qdb_submit_maps_from_manifest(PDO $pdo, string $qnID, array $manifest): array {
|
||||
$shortIdMap = [];
|
||||
$shortIdToType = [];
|
||||
$optionMap = [];
|
||||
$symptomParentMap = [];
|
||||
$freeTextMaxLen = [];
|
||||
$manifestQuestionIds = [];
|
||||
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (!is_array($qEntry)) {
|
||||
continue;
|
||||
}
|
||||
$fullId = (string)($qEntry['questionID'] ?? '');
|
||||
$shortId = (string)($qEntry['shortId'] ?? '');
|
||||
if ($fullId === '' || $shortId === '') {
|
||||
continue;
|
||||
}
|
||||
$type = (string)($qEntry['type'] ?? '');
|
||||
$shortIdMap[$shortId] = $fullId;
|
||||
$shortIdToType[$shortId] = $type;
|
||||
$manifestQuestionIds[] = $fullId;
|
||||
|
||||
if ($type === 'free_text') {
|
||||
$cfgStmt = $pdo->prepare('SELECT configJson FROM question WHERE questionID = :qid');
|
||||
$cfgStmt->execute([':qid' => $fullId]);
|
||||
$cfgJson = $cfgStmt->fetchColumn();
|
||||
$cfg = json_decode($cfgJson ?: '{}', true) ?: [];
|
||||
$freeTextMaxLen[$fullId] = max(1, min((int)($cfg['maxLength'] ?? 500), 10000));
|
||||
}
|
||||
|
||||
$optionMap[$fullId] = [];
|
||||
foreach ($qEntry['options'] ?? [] as $opt) {
|
||||
if (!is_array($opt)) {
|
||||
continue;
|
||||
}
|
||||
$key = (string)($opt['key'] ?? '');
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
$aoStmt = $pdo->prepare(
|
||||
'SELECT answerOptionID, points FROM answer_option
|
||||
WHERE questionID = :qid AND defaultText = :k LIMIT 1'
|
||||
);
|
||||
$aoStmt->execute([':qid' => $fullId, ':k' => $key]);
|
||||
$aoRow = $aoStmt->fetch(PDO::FETCH_ASSOC);
|
||||
$optionMap[$fullId][$key] = [
|
||||
'answerOptionID' => $aoRow ? (string)$aoRow['answerOptionID'] : '',
|
||||
'points' => $aoRow ? (int)$aoRow['points'] : (int)($opt['points'] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
if ($type === 'glass_scale_question') {
|
||||
foreach ($qEntry['symptoms'] ?? [] as $symptomKey) {
|
||||
$sk = trim((string)$symptomKey);
|
||||
if ($sk !== '') {
|
||||
$symptomParentMap[$sk] = $fullId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($symptomParentMap === []) {
|
||||
$symptomParentMap = qdb_glass_symptom_parent_map($pdo, $qnID);
|
||||
}
|
||||
|
||||
return [
|
||||
'shortIdMap' => $shortIdMap,
|
||||
'shortIdToType' => $shortIdToType,
|
||||
'optionMap' => $optionMap,
|
||||
'symptomParentMap' => $symptomParentMap,
|
||||
'freeTextMaxLen' => $freeTextMaxLen,
|
||||
'manifestQuestionIds' => $manifestQuestionIds,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build submit maps from active DB questions (current revision).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
function qdb_submit_maps_from_active_questions(PDO $pdo, string $qnID): array {
|
||||
$manifest = qdb_build_structure_manifest($pdo, $qnID, false);
|
||||
$manifest['structureRevision'] = qdb_questionnaire_structure_revision($pdo, $qnID);
|
||||
return qdb_submit_maps_from_manifest($pdo, $qnID, $manifest);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{field: string, header: string, questionID: string, type: string}>
|
||||
*/
|
||||
function qdb_result_columns_from_manifest(array $manifest): array {
|
||||
$cols = [];
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (!is_array($qEntry)) {
|
||||
continue;
|
||||
}
|
||||
$fullId = (string)($qEntry['questionID'] ?? '');
|
||||
$shortId = (string)($qEntry['shortId'] ?? '');
|
||||
$qKey = (string)($qEntry['questionKey'] ?? '');
|
||||
$type = (string)($qEntry['type'] ?? '');
|
||||
if ($fullId === '') {
|
||||
continue;
|
||||
}
|
||||
$header = $qKey !== '' ? $qKey : ($shortId !== '' ? $shortId : $fullId);
|
||||
$cols[] = [
|
||||
'field' => $header,
|
||||
'header' => $header,
|
||||
'questionID' => $fullId,
|
||||
'type' => $type,
|
||||
];
|
||||
if ($type === 'glass_scale_question') {
|
||||
foreach ($qEntry['symptoms'] ?? [] as $symptomKey) {
|
||||
$sk = trim((string)$symptomKey);
|
||||
if ($sk === '') {
|
||||
continue;
|
||||
}
|
||||
$cols[] = [
|
||||
'field' => $sk,
|
||||
'header' => $sk,
|
||||
'questionID' => $fullId,
|
||||
'type' => 'glass_symptom',
|
||||
'symptomKey' => $sk,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return $cols;
|
||||
}
|
||||
|
||||
function qdb_compute_questionnaire_score_from_manifest(
|
||||
PDO $pdo,
|
||||
string $clientCode,
|
||||
array $manifest
|
||||
): int {
|
||||
require_once __DIR__ . '/scoring.php';
|
||||
$qnID = (string)($manifest['questionnaireID'] ?? '');
|
||||
if ($qnID === '') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$questionIDs = [];
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (is_array($qEntry) && !empty($qEntry['questionID'])) {
|
||||
$questionIDs[] = (string)$qEntry['questionID'];
|
||||
}
|
||||
}
|
||||
if ($questionIDs === []) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$ph = implode(',', array_fill(0, count($questionIDs), '?'));
|
||||
$aStmt = $pdo->prepare(
|
||||
"SELECT ca.questionID, ca.answerOptionID, ca.freeTextValue, ca.numericValue,
|
||||
ao.defaultText AS optionKey
|
||||
FROM client_answer ca
|
||||
LEFT JOIN answer_option ao ON ao.answerOptionID = ca.answerOptionID
|
||||
WHERE ca.clientCode = ? AND ca.questionID IN ($ph)"
|
||||
);
|
||||
$aStmt->execute(array_merge([$clientCode], $questionIDs));
|
||||
$answersByQuestion = [];
|
||||
foreach ($aStmt->fetchAll(PDO::FETCH_ASSOC) as $a) {
|
||||
$answersByQuestion[$a['questionID']] = $a;
|
||||
}
|
||||
|
||||
$total = 0;
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (!is_array($qEntry)) {
|
||||
continue;
|
||||
}
|
||||
$fullId = (string)($qEntry['questionID'] ?? '');
|
||||
$type = (string)($qEntry['type'] ?? '');
|
||||
$optionPoints = [];
|
||||
foreach ($qEntry['options'] ?? [] as $opt) {
|
||||
if (is_array($opt) && isset($opt['key'])) {
|
||||
$optionPoints[(string)$opt['key']] = (int)($opt['points'] ?? 0);
|
||||
}
|
||||
}
|
||||
$qRow = [
|
||||
'questionID' => $fullId,
|
||||
'type' => $type,
|
||||
'configJson' => json_encode(
|
||||
['symptoms' => $qEntry['symptoms'] ?? []],
|
||||
JSON_UNESCAPED_UNICODE
|
||||
),
|
||||
];
|
||||
$total += qdb_score_points_for_question(
|
||||
$pdo,
|
||||
$qRow,
|
||||
$answersByQuestion[$fullId] ?? null,
|
||||
$optionPoints
|
||||
);
|
||||
}
|
||||
return $total;
|
||||
}
|
||||
@ -19,6 +19,8 @@ function qdb_read_db_open(): array {
|
||||
}
|
||||
|
||||
[$pdo, $memfdPath, $memfdFd] = qdb_read_materialize_decrypted_db();
|
||||
// Materialize may persist a migration (updates QDB_PATH mtime); refresh signature before caching.
|
||||
$signature = qdb_read_cache_signature();
|
||||
qdb_read_cache_store($signature, $pdo, $memfdPath, $memfdFd);
|
||||
return [$pdo, QDB_READONLY_CACHE_HANDLE, null];
|
||||
}
|
||||
|
||||
@ -3,6 +3,110 @@
|
||||
* Questionnaire submission versioning (archive each coach upload).
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/questionnaire_structure.php';
|
||||
|
||||
/**
|
||||
* Build display columns from a stored structure manifest (historical submissions).
|
||||
*
|
||||
* @return array{questions: array, resultColumns: array, optionTextMap: array, stringLabelCache: array}
|
||||
*/
|
||||
function qdb_display_context_from_manifest(PDO $pdo, array $manifest): array {
|
||||
$stringLabelCache = [];
|
||||
$resultColumns = [];
|
||||
$questions = [];
|
||||
$optionTextMap = [];
|
||||
|
||||
foreach ($manifest['questions'] ?? [] as $qEntry) {
|
||||
if (!is_array($qEntry)) {
|
||||
continue;
|
||||
}
|
||||
$fullId = (string)($qEntry['questionID'] ?? '');
|
||||
if ($fullId === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$qStmt = $pdo->prepare(
|
||||
'SELECT questionID, defaultText, type, orderIndex, configJson FROM question WHERE questionID = :id'
|
||||
);
|
||||
$qStmt->execute([':id' => $fullId]);
|
||||
$qRow = $qStmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$qRow) {
|
||||
$symptoms = $qEntry['symptoms'] ?? [];
|
||||
$qRow = [
|
||||
'questionID' => $fullId,
|
||||
'defaultText' => (string)($qEntry['questionKey'] ?? $qEntry['shortId'] ?? $fullId),
|
||||
'type' => (string)($qEntry['type'] ?? ''),
|
||||
'orderIndex' => 0,
|
||||
'configJson' => json_encode(
|
||||
['symptoms' => is_array($symptoms) ? $symptoms : []],
|
||||
JSON_UNESCAPED_UNICODE
|
||||
),
|
||||
];
|
||||
}
|
||||
$questions[] = $qRow;
|
||||
|
||||
$cfg = json_decode($qRow['configJson'] ?? '{}', true) ?: [];
|
||||
$type = $qRow['type'] ?? '';
|
||||
if ($type === 'glass_scale_question') {
|
||||
$symptoms = $cfg['symptoms'] ?? $qEntry['symptoms'] ?? [];
|
||||
if (is_array($symptoms) && $symptoms !== []) {
|
||||
foreach ($symptoms as $symptomKey) {
|
||||
$sk = trim((string)$symptomKey);
|
||||
if ($sk === '') {
|
||||
continue;
|
||||
}
|
||||
$resultColumns[] = [
|
||||
'header' => qdb_string_german_label($pdo, $sk, $stringLabelCache),
|
||||
'questionID' => $fullId,
|
||||
'symptomKey' => $sk,
|
||||
'kind' => 'glass_symptom',
|
||||
'question' => $qRow,
|
||||
];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$resultColumns[] = [
|
||||
'header' => qdb_question_german_label($pdo, $qRow),
|
||||
'questionID' => $fullId,
|
||||
'symptomKey' => null,
|
||||
'kind' => 'question',
|
||||
'question' => $qRow,
|
||||
];
|
||||
|
||||
$aoStmt = $pdo->prepare('SELECT answerOptionID, defaultText FROM answer_option WHERE questionID = :qid');
|
||||
$aoStmt->execute([':qid' => $fullId]);
|
||||
$dbOptions = $aoStmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
if ($dbOptions !== []) {
|
||||
foreach ($dbOptions as $ao) {
|
||||
$optionTextMap[$ao['answerOptionID']] = qdb_option_german_label(
|
||||
$pdo,
|
||||
$ao['answerOptionID'],
|
||||
$ao['defaultText']
|
||||
);
|
||||
}
|
||||
} else {
|
||||
foreach ($qEntry['options'] ?? [] as $opt) {
|
||||
if (!is_array($opt)) {
|
||||
continue;
|
||||
}
|
||||
$key = (string)($opt['key'] ?? '');
|
||||
if ($key !== '') {
|
||||
$optionTextMap[$key] = $key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'questions' => $questions,
|
||||
'resultColumns' => $resultColumns,
|
||||
'optionTextMap' => $optionTextMap,
|
||||
'stringLabelCache' => $stringLabelCache,
|
||||
];
|
||||
}
|
||||
|
||||
function qdb_next_submission_version(PDO $pdo, string $clientCode, string $questionnaireID): int {
|
||||
$stmt = $pdo->prepare(
|
||||
'SELECT COALESCE(MAX(version), 0) + 1 FROM questionnaire_submission
|
||||
@ -24,11 +128,21 @@ function qdb_record_submission_after_submit(
|
||||
?int $completedAt,
|
||||
int $sumPoints,
|
||||
string $assignedByCoach,
|
||||
int $structureRevision = 1,
|
||||
?array $structureManifest = null,
|
||||
?array $questionIdsToCopy = null,
|
||||
?int $submittedAt = null
|
||||
): string {
|
||||
$version = qdb_next_submission_version($pdo, $clientCode, $questionnaireID);
|
||||
$submissionID = bin2hex(random_bytes(16));
|
||||
$submittedAtValue = $submittedAt ?? $completedAt ?? time();
|
||||
$snapshotJson = '{}';
|
||||
if ($structureManifest !== null) {
|
||||
$encoded = json_encode($structureManifest, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if ($encoded !== false) {
|
||||
$snapshotJson = $encoded;
|
||||
}
|
||||
}
|
||||
|
||||
$cq = $pdo->prepare(
|
||||
'SELECT status FROM completed_questionnaire WHERE clientCode = :cc AND questionnaireID = :qn'
|
||||
@ -40,11 +154,13 @@ function qdb_record_submission_after_submit(
|
||||
'INSERT INTO questionnaire_submission (
|
||||
submissionID, clientCode, questionnaireID, version, submittedAt,
|
||||
submittedByUserID, submittedByRole, assignedByCoach,
|
||||
status, startedAt, completedAt, sumPoints
|
||||
status, startedAt, completedAt, sumPoints,
|
||||
structureRevision, structureSnapshotJson
|
||||
) VALUES (
|
||||
:sid, :cc, :qn, :ver, :sat,
|
||||
:uid, :role, :abc,
|
||||
:st, :sa, :ca, :sp
|
||||
:st, :sa, :ca, :sp,
|
||||
:srev, :snap
|
||||
)'
|
||||
)->execute([
|
||||
':sid' => $submissionID,
|
||||
@ -59,17 +175,31 @@ function qdb_record_submission_after_submit(
|
||||
':sa' => $startedAt,
|
||||
':ca' => $completedAt,
|
||||
':sp' => $sumPoints,
|
||||
':srev' => max(1, $structureRevision),
|
||||
':snap' => $snapshotJson,
|
||||
]);
|
||||
|
||||
$copy = $pdo->prepare(
|
||||
'INSERT INTO client_answer_submission (submissionID, questionID, answerOptionID, freeTextValue, numericValue, answeredAt)
|
||||
SELECT :sid, questionID, answerOptionID, freeTextValue, numericValue, answeredAt
|
||||
FROM client_answer
|
||||
WHERE clientCode = :cc AND questionID IN (
|
||||
SELECT questionID FROM question WHERE questionnaireID = :qn
|
||||
)'
|
||||
);
|
||||
$copy->execute([':sid' => $submissionID, ':cc' => $clientCode, ':qn' => $questionnaireID]);
|
||||
if ($questionIdsToCopy !== null && $questionIdsToCopy !== []) {
|
||||
$questionIdsToCopy = array_values(array_unique(array_filter($questionIdsToCopy, 'is_string')));
|
||||
$ph = implode(',', array_fill(0, count($questionIdsToCopy), '?'));
|
||||
$copy = $pdo->prepare(
|
||||
"INSERT INTO client_answer_submission (submissionID, questionID, answerOptionID, freeTextValue, numericValue, answeredAt)
|
||||
SELECT ?, questionID, answerOptionID, freeTextValue, numericValue, answeredAt
|
||||
FROM client_answer
|
||||
WHERE clientCode = ? AND questionID IN ($ph)"
|
||||
);
|
||||
$copy->execute(array_merge([$submissionID, $clientCode], $questionIdsToCopy));
|
||||
} else {
|
||||
$copy = $pdo->prepare(
|
||||
'INSERT INTO client_answer_submission (submissionID, questionID, answerOptionID, freeTextValue, numericValue, answeredAt)
|
||||
SELECT :sid, questionID, answerOptionID, freeTextValue, numericValue, answeredAt
|
||||
FROM client_answer
|
||||
WHERE clientCode = :cc AND questionID IN (
|
||||
SELECT questionID FROM question WHERE questionnaireID = :qn
|
||||
)'
|
||||
);
|
||||
$copy->execute([':sid' => $submissionID, ':cc' => $clientCode, ':qn' => $questionnaireID]);
|
||||
}
|
||||
|
||||
return $submissionID;
|
||||
}
|
||||
@ -169,6 +299,7 @@ function qdb_export_all_versions_rows(
|
||||
SELECT qs.submissionID, qs.version, qs.submittedAt, qs.submittedByUserID, qs.submittedByRole,
|
||||
qs.completedAt AS submissionCompletedAt, qs.sumPoints AS submissionSumPoints,
|
||||
qs.startedAt AS submissionStartedAt, qs.status AS submissionStatus,
|
||||
qs.structureRevision, qs.structureSnapshotJson,
|
||||
cl.clientCode, cl.coachID,
|
||||
co.username AS coachUsername,
|
||||
sv.username AS supervisorUsername
|
||||
@ -184,16 +315,7 @@ function qdb_export_all_versions_rows(
|
||||
$stmt->execute($params);
|
||||
$submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$questionIDs = array_column($questions, 'questionID');
|
||||
$qPlaceholders = !empty($questionIDs)
|
||||
? implode(',', array_fill(0, count($questionIDs), '?'))
|
||||
: "'__none__'";
|
||||
|
||||
$answerStmt = $pdo->prepare("
|
||||
SELECT questionID, answerOptionID, freeTextValue, numericValue
|
||||
FROM client_answer_submission
|
||||
WHERE submissionID = ? AND questionID IN ($qPlaceholders)
|
||||
");
|
||||
$defaultQuestionIDs = array_column($questions, 'questionID');
|
||||
|
||||
$userMap = [];
|
||||
$userStmt = $pdo->query('SELECT userID, username FROM users');
|
||||
@ -203,32 +325,46 @@ function qdb_export_all_versions_rows(
|
||||
|
||||
$rows = [];
|
||||
foreach ($submissions as $s) {
|
||||
$row = [
|
||||
'submissionID' => $s['submissionID'],
|
||||
'version' => (string)(int)$s['version'],
|
||||
'submittedAt' => $s['submittedAt'] ? date('Y-m-d H:i', (int)$s['submittedAt']) : '',
|
||||
'submittedByRole'=> $s['submittedByRole'] ?? '',
|
||||
'submittedBy' => $userMap[$s['submittedByUserID'] ?? ''] ?? ($s['submittedByUserID'] ?? ''),
|
||||
'clientCode' => $s['clientCode'],
|
||||
'coach' => $s['coachUsername'] ?? $s['coachID'],
|
||||
'supervisor' => $s['supervisorUsername'] ?? '',
|
||||
'status' => $s['submissionStatus'] ?? '',
|
||||
'sumPoints' => $s['submissionSumPoints'] ?? '',
|
||||
'startedAt' => $s['submissionStartedAt'] ? date('Y-m-d H:i', (int)$s['submissionStartedAt']) : '',
|
||||
'completedAt' => $s['submissionCompletedAt'] ? date('Y-m-d H:i', (int)$s['submissionCompletedAt']) : '',
|
||||
];
|
||||
|
||||
$bindParams = array_merge([$s['submissionID']], $questionIDs);
|
||||
$answerStmt->execute($bindParams);
|
||||
$answerMap = [];
|
||||
foreach ($answerStmt->fetchAll(PDO::FETCH_ASSOC) as $a) {
|
||||
$answerMap[$a['questionID']] = $a;
|
||||
$snap = json_decode($s['structureSnapshotJson'] ?? '{}', true) ?: [];
|
||||
if (!empty($snap['questions'])) {
|
||||
$snapCtx = qdb_display_context_from_manifest($pdo, $snap);
|
||||
$submissionColumns = $snapCtx['resultColumns'];
|
||||
$submissionOptionMap = $snapCtx['optionTextMap'];
|
||||
$submissionQuestionIDs = array_column($snapCtx['questions'], 'questionID');
|
||||
} else {
|
||||
$submissionColumns = $resultColumns;
|
||||
$submissionOptionMap = $optionTextMap;
|
||||
$submissionQuestionIDs = $defaultQuestionIDs;
|
||||
}
|
||||
|
||||
foreach ($resultColumns as $col) {
|
||||
$row = [
|
||||
'submissionID' => $s['submissionID'],
|
||||
'version' => (string)(int)$s['version'],
|
||||
'structureRevision' => (string)max(1, (int)($s['structureRevision'] ?? 1)),
|
||||
'submittedAt' => $s['submittedAt'] ? date('Y-m-d H:i', (int)$s['submittedAt']) : '',
|
||||
'submittedByRole' => $s['submittedByRole'] ?? '',
|
||||
'submittedBy' => $userMap[$s['submittedByUserID'] ?? ''] ?? ($s['submittedByUserID'] ?? ''),
|
||||
'clientCode' => $s['clientCode'],
|
||||
'coach' => $s['coachUsername'] ?? $s['coachID'],
|
||||
'supervisor' => $s['supervisorUsername'] ?? '',
|
||||
'status' => $s['submissionStatus'] ?? '',
|
||||
'sumPoints' => $s['submissionSumPoints'] ?? '',
|
||||
'startedAt' => $s['submissionStartedAt'] ? date('Y-m-d H:i', (int)$s['submissionStartedAt']) : '',
|
||||
'completedAt' => $s['submissionCompletedAt'] ? date('Y-m-d H:i', (int)$s['submissionCompletedAt']) : '',
|
||||
];
|
||||
|
||||
$answerMap = qdb_load_client_answer_map(
|
||||
$pdo,
|
||||
$s['clientCode'],
|
||||
$submissionQuestionIDs,
|
||||
'client_answer_submission',
|
||||
$s['submissionID']
|
||||
);
|
||||
|
||||
foreach ($submissionColumns as $col) {
|
||||
$qid = $col['questionID'];
|
||||
$a = $answerMap[$qid] ?? null;
|
||||
$row[$col['header']] = qdb_results_column_cell_value($col, $a, $optionTextMap);
|
||||
$row[$col['header']] = qdb_results_column_cell_value($col, $a, $submissionOptionMap);
|
||||
}
|
||||
$rows[] = $row;
|
||||
}
|
||||
@ -671,7 +807,8 @@ function qdb_client_detail(PDO $pdo, array $tokenRec, string $clientCode): array
|
||||
);
|
||||
|
||||
$subStmt = $pdo->prepare(
|
||||
'SELECT submissionID, version, submittedAt, status, sumPoints, completedAt
|
||||
'SELECT submissionID, version, submittedAt, status, sumPoints, completedAt,
|
||||
structureRevision, structureSnapshotJson
|
||||
FROM questionnaire_submission
|
||||
WHERE clientCode = :cc AND questionnaireID = :qn
|
||||
ORDER BY version DESC'
|
||||
@ -679,19 +816,33 @@ function qdb_client_detail(PDO $pdo, array $tokenRec, string $clientCode): array
|
||||
$subStmt->execute([':cc' => $clientCode, ':qn' => $qnID]);
|
||||
$submissions = [];
|
||||
foreach ($subStmt->fetchAll(PDO::FETCH_ASSOC) as $s) {
|
||||
$snap = json_decode($s['structureSnapshotJson'] ?? '{}', true) ?: [];
|
||||
if (!empty($snap['questions'])) {
|
||||
$snapCtx = qdb_display_context_from_manifest($pdo, $snap);
|
||||
$versionColumns = $snapCtx['resultColumns'];
|
||||
$versionOptionMap = $snapCtx['optionTextMap'];
|
||||
$versionStringCache = $snapCtx['stringLabelCache'];
|
||||
$versionQuestionIDs = array_column($snapCtx['questions'], 'questionID');
|
||||
} else {
|
||||
$versionColumns = $resultColumns;
|
||||
$versionOptionMap = $optionTextMap;
|
||||
$versionStringCache = $stringLabelCache;
|
||||
$versionQuestionIDs = $questionIDs;
|
||||
}
|
||||
|
||||
$subMap = qdb_load_client_answer_map(
|
||||
$pdo,
|
||||
$clientCode,
|
||||
$questionIDs,
|
||||
$versionQuestionIDs,
|
||||
'client_answer_submission',
|
||||
$s['submissionID']
|
||||
);
|
||||
$versionAnswers = qdb_answers_display_rows(
|
||||
$pdo,
|
||||
$resultColumns,
|
||||
$versionColumns,
|
||||
$subMap,
|
||||
$optionTextMap,
|
||||
$stringLabelCache,
|
||||
$versionOptionMap,
|
||||
$versionStringCache,
|
||||
$liveMap
|
||||
);
|
||||
$changedCount = count(array_filter(
|
||||
@ -699,14 +850,15 @@ function qdb_client_detail(PDO $pdo, array $tokenRec, string $clientCode): array
|
||||
static fn($r) => !empty($r['changedFromLive'])
|
||||
));
|
||||
$submissions[] = [
|
||||
'submissionID' => $s['submissionID'],
|
||||
'version' => (int)$s['version'],
|
||||
'submittedAt' => $s['submittedAt'] ? date('Y-m-d H:i', (int)$s['submittedAt']) : '',
|
||||
'status' => $s['status'] ?? '',
|
||||
'sumPoints' => $s['sumPoints'] !== null ? (int)$s['sumPoints'] : null,
|
||||
'completedAt' => $s['completedAt'] ? date('Y-m-d H:i', (int)$s['completedAt']) : '',
|
||||
'changedCount' => $changedCount,
|
||||
'answers' => $versionAnswers,
|
||||
'submissionID' => $s['submissionID'],
|
||||
'version' => (int)$s['version'],
|
||||
'structureRevision' => max(1, (int)($s['structureRevision'] ?? 1)),
|
||||
'submittedAt' => $s['submittedAt'] ? date('Y-m-d H:i', (int)$s['submittedAt']) : '',
|
||||
'status' => $s['status'] ?? '',
|
||||
'sumPoints' => $s['sumPoints'] !== null ? (int)$s['sumPoints'] : null,
|
||||
'completedAt' => $s['completedAt'] ? date('Y-m-d H:i', (int)$s['completedAt']) : '',
|
||||
'changedCount' => $changedCount,
|
||||
'answers' => $versionAnswers,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user