Files
pipelines/app/lib/features/chat/conversation/chat_question_card_model.dart
T

170 lines
5.9 KiB
Dart

/// Agent question forms: field visibility, values and option lists.
///
/// These rules mirror the web's `chatForms.js`. `false` and `0` are valid
/// answers, never "missing". Validation lives in `chat_question_validation.dart`
/// so this file stays a protocol model; option values are kept exactly as
/// recorded because they travel back in `chat_answer`.
library;
import '../../../core/api_gateway.dart';
const chatQuestionWaiting = 'The agent is waiting for your answer.';
const chatQuestionExpired = 'This question expired.';
const chatQuestionAnswered = 'Answer recorded.';
const chatQuestionClosed = 'Question closed.';
const chatQuestionSubmit = 'Send answer';
const chatQuestionConfirm = 'Confirm completion';
bool chatFormFieldVisible(JsonMap field, Map<String, dynamic> answers) {
if (field['hidden'] == true) return false;
final when = field['when'];
if (when is! List) return true;
for (final condition in when) {
if (condition is! Map) continue;
final key = _text(condition['key']);
final expected = condition['value'];
final actual = answers[key];
final matches = actual == expected;
if (_text(condition['op']) == 'neq' ? matches : !matches) return false;
}
return true;
}
/// A protocol-preserving field value; null means the input was cleared.
///
/// An integer answer is stored as a Dart `int`, so `"1.0"`/`"1e3"` cannot travel
/// as `1.0`/`1000.0` the way the web's `Number()` never does.
Object? chatFormFieldValue(JsonMap field, String raw) {
if (raw.isEmpty) return null;
final type = _text(field['type']);
switch (type) {
case 'boolean':
return raw == 'true';
case 'number':
case 'integer':
final parsed = num.tryParse(raw);
if (parsed == null) return double.nan;
final integral =
parsed.isFinite && parsed == parsed.roundToDouble();
return type == 'integer' && integral ? parsed.toInt() : parsed;
default:
return raw;
}
}
/// Only visible, non-external, answered fields travel in `chat_answer`.
Map<String, dynamic> chatVisibleFormAnswers(
List<JsonMap> fields,
Map<String, dynamic> answers,
) {
final result = <String, dynamic>{};
for (final field in fields) {
if (!chatFormFieldVisible(field, answers)) continue;
if (_text(field['type']) == 'external') continue;
final key = _text(field['key']);
if (!answers.containsKey(key)) continue;
result[key] = answers[key];
}
return result;
}
List<JsonMap> chatFormFields(JsonMap form) {
final fields = form['fields'];
if (fields is! List) return const [];
return [
for (final field in fields)
if (field is Map) Map<String, dynamic>.from(field),
];
}
/// A free-text edit as the protocol value. A multi-select input edits only the
/// options it already knows plus the comma-separated custom entries, matching
/// the web's question input.
Object? chatQuestionTextValue(
JsonMap field,
String raw,
Map<String, dynamic> answers,
) {
final key = _text(field['key']);
if (_text(field['type']) != 'multiselect') {
return chatFormFieldValue(field, raw);
}
final known = chatQuestionFieldOptionValues(field);
final selected = answers[key] is List
? (answers[key] as List).map((entry) => '$entry').where(known.contains)
: const <String>[];
final custom = raw
.split(',')
.map((entry) => entry.trim())
.where((entry) => entry.isNotEmpty);
return [...selected, ...custom];
}
List<String> chatQuestionFieldOptionValues(JsonMap field) => [
for (final option in chatQuestionOptions(field))
chatQuestionOptionValue(option),
];
/// The field's selectable options. The web skips an option whose recorded value
/// is empty rather than rendering a blank control.
List<JsonMap> chatQuestionOptions(JsonMap field) {
final options = field['options'];
if (options is! List) return const [];
final result = <JsonMap>[];
for (final option in options) {
if (option is! Map) continue;
final converted = Map<String, dynamic>.from(option);
if (chatQuestionOptionValue(converted).isEmpty) continue;
result.add(converted);
}
return result;
}
/// The option's exact recorded value, never trimmed: it is the protocol value
/// sent back in `chat_answer`.
String chatQuestionOptionValue(JsonMap option) =>
'${option['value'] ?? option['label'] ?? ''}';
String chatQuestionOptionLabel(JsonMap option) {
final label = _text(option['label']);
return label.isEmpty ? chatQuestionOptionValue(option) : label;
}
bool chatFormPending(JsonMap form) =>
form['resolved'] != true && form['cancelled'] != true;
/// True when an external form URL is one this app can safely show. Mirrors the
/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces.
bool chatExternalUrlIsSafe(String raw) {
if (raw.trim() != raw || RegExp(r'\s').hasMatch(raw)) return false;
final uri = Uri.tryParse(raw);
return uri != null &&
(uri.scheme == 'http' || uri.scheme == 'https') &&
uri.host.isNotEmpty;
}
/// Fold one `form` frame into the retained forms, keyed by id. A resolved or
/// cancelled update keeps the recorded answers so the card can show them
/// read-only instead of dropping evidence.
Map<String, JsonMap> chatFoldQuestionFrame(
Map<String, JsonMap> current,
JsonMap? form,
) {
if (form == null) return current;
final id = _text(form['id']);
if (id.isEmpty) return current;
final existing = current[id];
final next = <String, JsonMap>{...current};
next[id] = existing == null
? Map<String, dynamic>.from(form)
: {...existing, ...Map<String, dynamic>.from(form)};
return next;
}
/// A stable id for one confirmed answer action on a form. Reusing the same id
/// across a retry lets the send gate recognise a double tap.
String chatQuestionReplyId(String formId, {String action = ''}) =>
'chat-answer:${formId.trim()}:${action.trim().isEmpty ? 'answer' : action.trim()}';
String _text(Object? value) => '${value ?? ''}'.trim();