新增:体重录入与历史列表接入真实数据(T2-13 体重半边)
- WeightRecordsPage:cursor 分页(加载更多/末页收起/翻页失败保留重试)、 loading/empty/error/retry 四态、下拉刷新;viewer 隐藏录入入口 - WeightFormPage:weightKg 契约区间 (0,500] 与两位小数前端校验 + 40000 兜底;称重时间转 UTC 上送;错误三层分层沿用登录纵切 - health_record 域埋点强类型封装(06 §1.4:create_started/succeeded/ failed + viewed,httpStatus 由业务码推导;viewed 按工单口径取列表曝光) - health_record_display 纯函数(体重解析/展示、疫苗状态映射、42201 规则前端拦截函数);PetsController 暴露 repository(22 号 §7 交接) - 测试 177 → 205(+28)全绿 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
import 'package:patbond_flutter/analytics/page_view_tracker.dart';
|
||||
|
||||
/// health_record 域埋点强类型封装(06 号规划 §1.4 字典 v2;后端白名单
|
||||
/// 已扩充就绪,24 号报告 §2.2)。沿用 13 号规范 §3.1 惯例:枚举编译期
|
||||
/// 锁死,业务代码禁止手拼事件名与属性。
|
||||
///
|
||||
/// T2-13 挂接创建漏斗三事件 + viewed;edit/deleted 事件的挂接随
|
||||
/// 编辑/删除交互落地(「标记完成」等)另行接线,见 25 号报告遗留。
|
||||
|
||||
/// 记录类型(06 §1.4 recordType 枚举,四类记录接口对应)。
|
||||
enum HealthRecordType {
|
||||
weight('weight'),
|
||||
vaccine('vaccine'),
|
||||
healthEvent('health_event'),
|
||||
reminder('reminder');
|
||||
|
||||
const HealthRecordType(this.value);
|
||||
|
||||
final String value;
|
||||
}
|
||||
|
||||
/// 记录创建入口(06 §1.4 entryPoint 枚举)。
|
||||
enum HealthRecordEntryPoint {
|
||||
petDetail('pet_detail'),
|
||||
recordList('record_list'),
|
||||
reminder('reminder');
|
||||
|
||||
const HealthRecordEntryPoint(this.value);
|
||||
|
||||
final String value;
|
||||
}
|
||||
|
||||
/// 创建失败原因(06 §1.4 基底 + M2 验收新增三值)。与 pet 域同款
|
||||
/// 网络归并口径:断网/超时/5xx 均并入 network_error,server_error
|
||||
/// 保留给无法归类的兜底。
|
||||
enum HealthRecordFailureReason {
|
||||
validationError('validation_error'),
|
||||
permissionDenied('permission_denied'),
|
||||
notFound('not_found'),
|
||||
rateLimited('rate_limited'),
|
||||
networkError('network_error'),
|
||||
serverError('server_error');
|
||||
|
||||
const HealthRecordFailureReason(this.value);
|
||||
|
||||
final String value;
|
||||
}
|
||||
|
||||
/// viewed 的来源(06 §1.4 source 枚举)。
|
||||
enum HealthRecordViewSource {
|
||||
recordList('record_list'),
|
||||
petDetail('pet_detail'),
|
||||
reminder('reminder');
|
||||
|
||||
const HealthRecordViewSource(this.value);
|
||||
|
||||
final String value;
|
||||
}
|
||||
|
||||
class HealthRecordAnalytics {
|
||||
HealthRecordAnalytics(this._track);
|
||||
|
||||
/// 生产传 `AnalyticsService.trackEvent`,测试传录制桩。
|
||||
final TrackEventFn _track;
|
||||
|
||||
/// 进入某类记录的创建表单并产生首次输入(每次进入记一次,表单层去重)。
|
||||
void createStarted({
|
||||
required HealthRecordType recordType,
|
||||
required HealthRecordEntryPoint entryPoint,
|
||||
}) {
|
||||
_track('health_record_create_started', {
|
||||
'recordType': recordType.value,
|
||||
'entryPoint': entryPoint.value,
|
||||
});
|
||||
}
|
||||
|
||||
/// 创建接口成功响应(漏斗事件,北极星与 H1/H3/H4 的核心数据源)。
|
||||
///
|
||||
/// [photoCount] 无照片为 0(M2 不做媒体上传,恒 0,字段随字典保留)。
|
||||
void createSucceeded({
|
||||
required HealthRecordType recordType,
|
||||
required int durationMs,
|
||||
int photoCount = 0,
|
||||
}) {
|
||||
_track('health_record_create_succeeded', {
|
||||
'recordType': recordType.value,
|
||||
'durationMs': durationMs,
|
||||
'photoCount': photoCount,
|
||||
});
|
||||
}
|
||||
|
||||
/// 创建失败:失败响应 / 超时 / 本地校验拦截。
|
||||
///
|
||||
/// [errorCode] 为业务错误码(本地校验/网络错误时缺席);
|
||||
/// [httpStatus] 由五位业务码推导(`code ~/ 100`);
|
||||
/// [attemptSeq] 为本次表单会话内第几次提交尝试(从 1 起)。
|
||||
void createFailed({
|
||||
required HealthRecordType recordType,
|
||||
required HealthRecordFailureReason reason,
|
||||
required int attemptSeq,
|
||||
int? errorCode,
|
||||
}) {
|
||||
_track('health_record_create_failed', {
|
||||
'recordType': recordType.value,
|
||||
'failureReason': reason.value,
|
||||
'attemptSeq': attemptSeq,
|
||||
'errorCode': ?errorCode,
|
||||
if (errorCode != null && errorCode >= 10000)
|
||||
'httpStatus': errorCode ~/ 100,
|
||||
});
|
||||
}
|
||||
|
||||
/// 记录曝光。06 §1.4 定义在详情页可见;M2 体重/疫苗无独立详情页,
|
||||
/// 以「列表页每次进入首个成功加载」为曝光时点(每次进入一次、
|
||||
/// 不随滚动逐条上报,防事件洪水的意图不变)。
|
||||
void viewed({
|
||||
required HealthRecordType recordType,
|
||||
required HealthRecordViewSource source,
|
||||
}) {
|
||||
_track('health_record_viewed', {
|
||||
'recordType': recordType.value,
|
||||
'source': source.value,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/// 体重 / 疫苗展示与输入解析的纯函数集合(列表 / 表单共用,可单测)。
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:patbond_flutter/core/theme/app_theme.dart';
|
||||
import 'package:patbond_flutter/features/pets/pet_models.dart';
|
||||
|
||||
/// 体重输入解析:契约区间 (0, 500]、最多两位小数(numeric(6,2))。
|
||||
/// 非法(非数字、越界、三位小数)返回 null,由表单层给 errorText。
|
||||
double? parseWeightKgInput(String raw) {
|
||||
final text = raw.trim();
|
||||
if (!RegExp(r'^\d{1,3}(\.\d{1,2})?$').hasMatch(text)) return null;
|
||||
final value = double.parse(text);
|
||||
if (value <= 0 || value > 500) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
/// 体重展示:去掉无意义尾零(4.35 → 4.35、5.00 → 5、4.50 → 4.5)。
|
||||
String formatWeightKg(double weightKg) {
|
||||
var text = weightKg.toStringAsFixed(2);
|
||||
if (text.contains('.')) {
|
||||
text = text.replaceFirst(RegExp(r'0+$'), '');
|
||||
text = text.replaceFirst(RegExp(r'\.$'), '');
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
String vaccinationStatusLabel(VaccinationStatus status) => switch (status) {
|
||||
VaccinationStatus.scheduled => '计划中',
|
||||
VaccinationStatus.completed => '已完成',
|
||||
VaccinationStatus.cancelled => '已取消',
|
||||
};
|
||||
|
||||
/// 状态标签基色(TagPill 淡染底;文字深变体由 TagPill 内置映射)。
|
||||
Color vaccinationStatusColor(VaccinationStatus status) => switch (status) {
|
||||
VaccinationStatus.scheduled => AppColors.accent,
|
||||
VaccinationStatus.completed => AppColors.success,
|
||||
VaccinationStatus.cancelled => AppColors.muted,
|
||||
};
|
||||
|
||||
/// 剂次展示:doseLabel 优先,缺席回落「第 N 针」。
|
||||
String vaccinationDoseLabel(Vaccination vaccination) =>
|
||||
vaccination.doseLabel ?? '第 ${vaccination.doseNo} 针';
|
||||
|
||||
/// 疫苗条目副行:按状态给日期语义(计划 / 接种 + 下次到期 / 取消)。
|
||||
String vaccinationDateLine(
|
||||
Vaccination vaccination,
|
||||
) => switch (vaccination.status) {
|
||||
VaccinationStatus.scheduled =>
|
||||
'计划 ${vaccination.plannedOn == null ? '未定' : dateToJson(vaccination.plannedOn!)}',
|
||||
VaccinationStatus.completed =>
|
||||
'接种 ${vaccination.administeredOn == null ? '—' : dateToJson(vaccination.administeredOn!)}'
|
||||
'${vaccination.nextDueOn == null ? '' : ' · 下次 ${dateToJson(vaccination.nextDueOn!)}'}',
|
||||
VaccinationStatus.cancelled => '已取消',
|
||||
};
|
||||
|
||||
/// 摘要疫苗进度展示:契约 null 语义——无登记为 null(不是 0/0),
|
||||
/// 调用方对 null 自行给空态文案。
|
||||
String vaccinationProgressLabel(SummaryVaccinationProgress progress) =>
|
||||
'${progress.completedDoses}/${progress.totalDoses}';
|
||||
|
||||
/// 疫苗状态-日期规则前端校验(契约 42201 规则的前置拦截;纯函数可单测):
|
||||
/// scheduled 必有 plannedOn;completed 必有 administeredOn;
|
||||
/// nextDueOn 与 administeredOn 同时存在时须 nextDueOn ≥ administeredOn。
|
||||
/// 通过返回 null,违反返回给用户的拦截文案。
|
||||
String? vaccinationDateRuleError({
|
||||
required VaccinationStatus status,
|
||||
DateTime? plannedOn,
|
||||
DateTime? administeredOn,
|
||||
DateTime? nextDueOn,
|
||||
}) {
|
||||
if (status == VaccinationStatus.scheduled && plannedOn == null) {
|
||||
return '请选择计划接种日期';
|
||||
}
|
||||
if (status == VaccinationStatus.completed && administeredOn == null) {
|
||||
return '请选择接种日期';
|
||||
}
|
||||
if (administeredOn != null &&
|
||||
nextDueOn != null &&
|
||||
nextDueOn.isBefore(
|
||||
DateTime(administeredOn.year, administeredOn.month, administeredOn.day),
|
||||
)) {
|
||||
return '下次接种日期不能早于接种日期';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -21,6 +21,10 @@ class PetsController extends ChangeNotifier {
|
||||
|
||||
final PetsRepository _repository;
|
||||
|
||||
/// 记录级页面(体重/疫苗/事件/提醒)直接经仓库取数(22 号报告 §7
|
||||
/// 交接约定:页面级状态按页自建,不膨胀本控制器)。
|
||||
PetsRepository get repository => _repository;
|
||||
|
||||
PetsLoadPhase _phase = PetsLoadPhase.initial;
|
||||
List<Pet> _pets = const [];
|
||||
ApiException? _lastError;
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||
import 'package:patbond_flutter/core/theme/app_theme.dart';
|
||||
import 'package:patbond_flutter/core/widgets/app_text_field.dart';
|
||||
import 'package:patbond_flutter/core/widgets/inline_error_banner.dart';
|
||||
import 'package:patbond_flutter/core/widgets/primary_button.dart';
|
||||
import 'package:patbond_flutter/features/pets/health_record_analytics.dart';
|
||||
import 'package:patbond_flutter/features/pets/health_record_display.dart';
|
||||
import 'package:patbond_flutter/features/pets/pet_exceptions.dart';
|
||||
import 'package:patbond_flutter/features/pets/pet_models.dart';
|
||||
import 'package:patbond_flutter/features/pets/pets_repository.dart';
|
||||
|
||||
/// 体重录入表单页(T2-13)。
|
||||
///
|
||||
/// - `weightKg` 前端校验对齐契约:(0, 500]、最多两位小数;后端 40000 兜底。
|
||||
/// - 称重时间默认「现在」,可回选日期(非今日取当日 12:00,保持
|
||||
/// measured_at DESC 排序直觉);提交前转 UTC,ISO 8601 带 Z 上送。
|
||||
/// - 错误分层沿用登录纵切:字段 errorText / InlineErrorBanner / SnackBar。
|
||||
/// - 埋点:首次输入 health_record_create_started(recordType=weight),
|
||||
/// 成功/失败按 06 §1.4 经 [HealthRecordAnalytics] 上报。
|
||||
class WeightFormPage extends StatefulWidget {
|
||||
const WeightFormPage({
|
||||
required this.repository,
|
||||
required this.petId,
|
||||
super.key,
|
||||
this.analytics,
|
||||
this.entryPoint = HealthRecordEntryPoint.recordList,
|
||||
});
|
||||
|
||||
final PetsRepository repository;
|
||||
final String petId;
|
||||
final HealthRecordAnalytics? analytics;
|
||||
final HealthRecordEntryPoint entryPoint;
|
||||
|
||||
@override
|
||||
State<WeightFormPage> createState() => _WeightFormPageState();
|
||||
}
|
||||
|
||||
class _WeightFormPageState extends State<WeightFormPage> {
|
||||
final _weightCtrl = TextEditingController();
|
||||
final _noteCtrl = TextEditingController();
|
||||
|
||||
DateTime _measuredDate = DateTime.now();
|
||||
String? _weightError;
|
||||
String? _formError;
|
||||
bool _submitting = false;
|
||||
|
||||
bool _startedFired = false;
|
||||
int _attemptSeq = 0;
|
||||
late final DateTime _openedAt;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_openedAt = DateTime.now();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_weightCtrl.dispose();
|
||||
_noteCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _markStarted() {
|
||||
if (_startedFired) return;
|
||||
_startedFired = true;
|
||||
widget.analytics?.createStarted(
|
||||
recordType: HealthRecordType.weight,
|
||||
entryPoint: widget.entryPoint,
|
||||
);
|
||||
}
|
||||
|
||||
void _trackFailed(HealthRecordFailureReason reason, [int? errorCode]) {
|
||||
widget.analytics?.createFailed(
|
||||
recordType: HealthRecordType.weight,
|
||||
reason: reason,
|
||||
attemptSeq: _attemptSeq,
|
||||
errorCode: errorCode,
|
||||
);
|
||||
}
|
||||
|
||||
String? _validateWeight() {
|
||||
final text = _weightCtrl.text.trim();
|
||||
if (text.isEmpty) return '请输入体重';
|
||||
if (parseWeightKgInput(text) == null) {
|
||||
return '体重需大于 0 且不超过 500 公斤,最多两位小数';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _showFormError(String message) {
|
||||
setState(() => _formError = message);
|
||||
SemanticsService.sendAnnouncement(
|
||||
View.of(context),
|
||||
message,
|
||||
TextDirection.ltr,
|
||||
);
|
||||
}
|
||||
|
||||
/// 称重时刻:今日取此刻,历史日期取当日 12:00(本地),提交前转 UTC。
|
||||
DateTime _measuredAt() {
|
||||
final now = DateTime.now();
|
||||
final sameDay =
|
||||
_measuredDate.year == now.year &&
|
||||
_measuredDate.month == now.month &&
|
||||
_measuredDate.day == now.day;
|
||||
final local = sameDay
|
||||
? now
|
||||
: DateTime(
|
||||
_measuredDate.year,
|
||||
_measuredDate.month,
|
||||
_measuredDate.day,
|
||||
12,
|
||||
);
|
||||
return local.toUtc();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_submitting) return;
|
||||
_attemptSeq++;
|
||||
final weightError = _validateWeight();
|
||||
if (weightError != null) {
|
||||
setState(() => _weightError = weightError);
|
||||
_trackFailed(HealthRecordFailureReason.validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_submitting = true;
|
||||
_formError = null;
|
||||
});
|
||||
try {
|
||||
final note = _noteCtrl.text.trim();
|
||||
final record = await widget.repository.createWeight(
|
||||
widget.petId,
|
||||
CreateWeightRequest(
|
||||
weightKg: parseWeightKgInput(_weightCtrl.text)!,
|
||||
measuredAt: _measuredAt(),
|
||||
note: note.isEmpty ? null : note,
|
||||
),
|
||||
);
|
||||
widget.analytics?.createSucceeded(
|
||||
recordType: HealthRecordType.weight,
|
||||
durationMs: DateTime.now().difference(_openedAt).inMilliseconds,
|
||||
);
|
||||
if (mounted) Navigator.of(context).pop(record);
|
||||
} on PetAccessDeniedException {
|
||||
if (!mounted) return;
|
||||
_showFormError('你没有权限为该宠物添加记录');
|
||||
_trackFailed(HealthRecordFailureReason.permissionDenied, 40300);
|
||||
} on PetNotFoundException {
|
||||
if (!mounted) return;
|
||||
final navigator = Navigator.of(context);
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('宠物不存在或已被删除')));
|
||||
_trackFailed(HealthRecordFailureReason.notFound, 40401);
|
||||
navigator.pop();
|
||||
} on ApiRateLimitException {
|
||||
if (!mounted) return;
|
||||
_showFormError('操作过于频繁,请稍后再试');
|
||||
_trackFailed(HealthRecordFailureReason.rateLimited);
|
||||
} on ApiBusinessException catch (error) {
|
||||
if (!mounted) return;
|
||||
final isParam = error.code == ApiCodes.paramError;
|
||||
_showFormError(isParam ? '请检查填写内容后重试' : '保存失败,请稍后重试');
|
||||
_trackFailed(
|
||||
isParam
|
||||
? HealthRecordFailureReason.validationError
|
||||
: HealthRecordFailureReason.serverError,
|
||||
error.code,
|
||||
);
|
||||
} on ApiNetworkException {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: const Text('网络异常,请检查网络后重试'),
|
||||
action: SnackBarAction(label: '重试', onPressed: _submit),
|
||||
),
|
||||
);
|
||||
_trackFailed(HealthRecordFailureReason.networkError);
|
||||
} on SessionExpiredException {
|
||||
// 会话失效:认证状态机自动回登录页。
|
||||
} finally {
|
||||
if (mounted) setState(() => _submitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
foregroundColor: AppColors.ink,
|
||||
title: const Text('记录体重'),
|
||||
centerTitle: true,
|
||||
titleTextStyle: const TextStyle(
|
||||
color: AppColors.ink,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 30),
|
||||
children: [
|
||||
AppTextField(
|
||||
label: '体重(公斤)',
|
||||
controller: _weightCtrl,
|
||||
prefixIcon: Icons.monitor_weight_outlined,
|
||||
errorText: _weightError,
|
||||
helperText: '大于 0 且不超过 500,最多两位小数',
|
||||
enabled: !_submitting,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
textInputAction: TextInputAction.next,
|
||||
onChanged: (_) {
|
||||
_markStarted();
|
||||
if (_weightError != null || _formError != null) {
|
||||
setState(() {
|
||||
_weightError = null;
|
||||
_formError = null;
|
||||
});
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
ListTile(
|
||||
shape: RoundedRectangleBorder(
|
||||
side: const BorderSide(color: AppColors.border),
|
||||
borderRadius: BorderRadius.circular(AppRadius.lg),
|
||||
),
|
||||
tileColor: AppColors.surface,
|
||||
leading: const Icon(Icons.event_outlined, color: AppColors.muted),
|
||||
title: const Text('称重日期', style: TextStyle(fontSize: 14)),
|
||||
subtitle: Text(
|
||||
dateToJson(_measuredDate),
|
||||
style: const TextStyle(color: AppColors.inkSoft, fontSize: 12),
|
||||
),
|
||||
trailing: const Icon(
|
||||
Icons.calendar_month_outlined,
|
||||
color: AppColors.muted,
|
||||
),
|
||||
enabled: !_submitting,
|
||||
onTap: () async {
|
||||
final now = DateTime.now();
|
||||
final value = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _measuredDate,
|
||||
firstDate: DateTime(1990),
|
||||
lastDate: now,
|
||||
);
|
||||
if (value != null && mounted) {
|
||||
_markStarted();
|
||||
setState(() => _measuredDate = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
AppTextField(
|
||||
label: '备注(可选,如:饭后称重)',
|
||||
controller: _noteCtrl,
|
||||
prefixIcon: Icons.sticky_note_2_outlined,
|
||||
enabled: !_submitting,
|
||||
textInputAction: TextInputAction.done,
|
||||
onChanged: (_) => _markStarted(),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
if (_formError != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
InlineErrorBanner(message: _formError!),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
PrimaryButton(
|
||||
label: '保存记录',
|
||||
isLoading: _submitting,
|
||||
onPressed: _submit,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:patbond_flutter/analytics/analytics_page_name.dart';
|
||||
import 'package:patbond_flutter/core/navigation/fade_route.dart';
|
||||
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||
import 'package:patbond_flutter/core/theme/app_theme.dart';
|
||||
import 'package:patbond_flutter/core/widgets/empty_state_illustration.dart';
|
||||
import 'package:patbond_flutter/core/widgets/inline_error_banner.dart';
|
||||
import 'package:patbond_flutter/core/widgets/record_type_dot.dart';
|
||||
import 'package:patbond_flutter/features/pets/health_record_analytics.dart';
|
||||
import 'package:patbond_flutter/features/pets/health_record_display.dart';
|
||||
import 'package:patbond_flutter/features/pets/pet_display.dart';
|
||||
import 'package:patbond_flutter/features/pets/pet_models.dart';
|
||||
import 'package:patbond_flutter/features/pets/pets_repository.dart';
|
||||
import 'package:patbond_flutter/features/pets/weight_form_page.dart';
|
||||
|
||||
enum _ListPhase { loading, ready, error }
|
||||
|
||||
/// 体重历史列表页(T2-13):cursor 分页(「加载更多」追加,末页收起),
|
||||
/// 四态齐备;新记录经 [WeightFormPage] 录入后就地插入列表头。
|
||||
///
|
||||
/// 曝光埋点:每次进入首个成功加载上报一次
|
||||
/// `health_record_viewed(recordType=weight, source=pet_detail)`
|
||||
/// (工单口径:列表曝光;不随滚动逐条上报)。
|
||||
class WeightRecordsPage extends StatefulWidget {
|
||||
const WeightRecordsPage({
|
||||
required this.repository,
|
||||
required this.petId,
|
||||
required this.canWrite,
|
||||
super.key,
|
||||
this.analytics,
|
||||
this.pageSize,
|
||||
});
|
||||
|
||||
final PetsRepository repository;
|
||||
final String petId;
|
||||
|
||||
/// owner/caregiver 可写;viewer 隐藏录入入口(40300 语义前置)。
|
||||
final bool canWrite;
|
||||
|
||||
final HealthRecordAnalytics? analytics;
|
||||
|
||||
/// 每页条数(测试注入小页验证分页;缺省走服务端默认 20)。
|
||||
final int? pageSize;
|
||||
|
||||
@override
|
||||
State<WeightRecordsPage> createState() => _WeightRecordsPageState();
|
||||
}
|
||||
|
||||
class _WeightRecordsPageState extends State<WeightRecordsPage> {
|
||||
_ListPhase _phase = _ListPhase.loading;
|
||||
List<WeightRecord> _records = const [];
|
||||
String? _nextCursor;
|
||||
bool _hasMore = false;
|
||||
bool _loadingMore = false;
|
||||
ApiException? _error;
|
||||
bool _viewedFired = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadFirstPage();
|
||||
}
|
||||
|
||||
Future<void> _loadFirstPage() async {
|
||||
setState(() {
|
||||
_phase = _ListPhase.loading;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final page = await widget.repository.listWeights(
|
||||
widget.petId,
|
||||
limit: widget.pageSize,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_records = page.items;
|
||||
_nextCursor = page.nextCursor;
|
||||
_hasMore = page.hasMore;
|
||||
_phase = _ListPhase.ready;
|
||||
});
|
||||
if (!_viewedFired) {
|
||||
_viewedFired = true;
|
||||
widget.analytics?.viewed(
|
||||
recordType: HealthRecordType.weight,
|
||||
source: HealthRecordViewSource.petDetail,
|
||||
);
|
||||
}
|
||||
} on ApiException catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = error;
|
||||
_phase = _ListPhase.error;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadMore() async {
|
||||
if (_loadingMore || !_hasMore) return;
|
||||
setState(() => _loadingMore = true);
|
||||
try {
|
||||
final page = await widget.repository.listWeights(
|
||||
widget.petId,
|
||||
limit: widget.pageSize,
|
||||
cursor: _nextCursor,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_records = [..._records, ...page.items];
|
||||
_nextCursor = page.nextCursor;
|
||||
_hasMore = page.hasMore;
|
||||
});
|
||||
} on ApiException catch (error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(petLoadErrorMessage(error))));
|
||||
} finally {
|
||||
if (mounted) setState(() => _loadingMore = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openCreate() async {
|
||||
final created = await Navigator.of(context).push<WeightRecord>(
|
||||
fadePageRoute(
|
||||
WeightFormPage(
|
||||
repository: widget.repository,
|
||||
petId: widget.petId,
|
||||
analytics: widget.analytics,
|
||||
),
|
||||
// record_form:健康记录漏斗到达段页名(06 §1.6 / §2.2)。
|
||||
settings: RouteSettings(name: AnalyticsPageName.recordForm.pageName),
|
||||
),
|
||||
);
|
||||
if (created != null && mounted) {
|
||||
setState(() {
|
||||
// 契约排序 measured_at DESC, id DESC:新记录通常最新,就地插头;
|
||||
// 补录历史日期的位置以下次刷新为准(服务端是唯一事实来源)。
|
||||
_records = [created, ..._records];
|
||||
if (_phase != _ListPhase.ready) _phase = _ListPhase.ready;
|
||||
});
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('已记录体重')));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
foregroundColor: AppColors.ink,
|
||||
title: const Text('体重记录'),
|
||||
centerTitle: true,
|
||||
titleTextStyle: const TextStyle(
|
||||
color: AppColors.ink,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
actions: [
|
||||
if (widget.canWrite && _phase == _ListPhase.ready)
|
||||
IconButton(
|
||||
tooltip: '记录体重',
|
||||
onPressed: _openCreate,
|
||||
icon: const Icon(Icons.add),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: switch (_phase) {
|
||||
_ListPhase.loading => const Center(child: CircularProgressIndicator()),
|
||||
_ListPhase.error => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
InlineErrorBanner(message: petLoadErrorMessage(_error)),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: _loadFirstPage,
|
||||
child: const Text('重试'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_ListPhase.ready when _records.isEmpty => Center(
|
||||
child: SingleChildScrollView(
|
||||
child: EmptyStateIllustration(
|
||||
icon: Icons.monitor_weight_outlined,
|
||||
title: '还没有体重记录',
|
||||
description: '定期称重,看见毛孩子的成长曲线',
|
||||
ctaLabel: widget.canWrite ? '记录第一条' : null,
|
||||
onCtaPressed: widget.canWrite ? _openCreate : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
_ListPhase.ready => _list(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list() {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _loadFirstPage,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 30),
|
||||
children: [
|
||||
for (final record in _records) ...[
|
||||
_WeightTile(record: record),
|
||||
const SizedBox(height: 10),
|
||||
],
|
||||
if (_hasMore)
|
||||
Center(
|
||||
child: _loadingMore
|
||||
? const Padding(
|
||||
padding: EdgeInsets.all(12),
|
||||
child: SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
)
|
||||
: TextButton(onPressed: _loadMore, child: const Text('加载更多')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 体重条目:RecordTypeDot(体重) + 大数值(primaryDark w800)+
|
||||
/// 日期/备注副行(05 §3.3 时间线条目形态的数值型变体)。
|
||||
class _WeightTile extends StatelessWidget {
|
||||
const _WeightTile({required this.record});
|
||||
|
||||
final WeightRecord record;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final meta = StringBuffer(formatMeasuredAt(record.measuredAt));
|
||||
if (record.note != null && record.note!.isNotEmpty) {
|
||||
meta.write(' · ${record.note}');
|
||||
}
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
const RecordTypeDot(
|
||||
type: RecordType.weight,
|
||||
size: RecordTypeDotSize.md,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${formatWeightKg(record.weightKg)} kg',
|
||||
style: const TextStyle(
|
||||
color: AppColors.primaryDark,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
meta.toString(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.inkSoft,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 称重时刻展示:本地时区 `YYYY-MM-DD HH:mm`。
|
||||
String formatMeasuredAt(DateTime measuredAt) {
|
||||
final local = measuredAt.toLocal();
|
||||
final h = local.hour.toString().padLeft(2, '0');
|
||||
final min = local.minute.toString().padLeft(2, '0');
|
||||
return '${dateToJson(local)} $h:$min';
|
||||
}
|
||||
Reference in New Issue
Block a user