优化行为

This commit is contained in:
gs committed 2026-09-26 21:47:16 +08:00
1 parent 1ed38c6648
commit 80c73fd46c
44 files changed
+2691 -147

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ node_modules/
dist/ dist/
target/ target/
*.tsbuildinfo *.tsbuildinfo
pnpm-lock.yaml
# Environment Variables & Secrets # Environment Variables & Secrets
.env .env
+1 -1
View File
@@ -16,7 +16,7 @@ Baby Tracker 是一款专为**新生儿家庭(尤其顺产出院头几周)**
1. **核心场景深度聚焦**: 1. **核心场景深度聚焦**:
- **喂养记录**: - **喂养记录**:
- **母乳亲喂**:支持左/右侧开始、实时秒级分侧独立计时与无缝切换;提供快捷预设时长(10/15/20/30分钟)一键记录并自动按侧别推导起止时间;数据库具备结构化独立字段 `left_duration_minutes` 与 `right_duration_minutes`; - **母乳亲喂**:支持左/右侧开始、实时秒级分侧独立计时与无缝切换;提供快捷预设时长(10/15/20/30分钟)一键记录并自动按侧别推导起止时间;数据库具备结构化独立字段 `left_duration_minutes` 与 `right_duration_minutes`;
- **瓶喂记录**:奶量步进调节极简化展示,默认数值与用户偏好配置实时联动。 - **挤出母乳记录**:奶量步进调节极简化展示,默认数值与用户偏好配置实时联动。
- **睡眠记录**:入睡计时、醒来打卡、睡眠时长自动推导计算。 - **睡眠记录**:入睡计时、醒来打卡、睡眠时长自动推导计算。
- **排泄观察**:小便(嘘嘘)、大便(便便)次数记录与性状特征观察。 - **排泄观察**:小便(嘘嘘)、大便(便便)次数记录与性状特征观察。
2. **贴心的人性化导航(双字对仗)**: 2. **贴心的人性化导航(双字对仗)**:
+43 -2
View File
@@ -2,7 +2,9 @@ import type {
ApiResponse, ApiResponse,
BabyProfile, BabyProfile,
CareRecord, CareRecord,
CareQuickRule,
CreateBabyPayload, CreateBabyPayload,
CreateFamilyPayload,
CreateManualRecordPayload, CreateManualRecordPayload,
CreateMemberPayload, CreateMemberPayload,
DailySummary, DailySummary,
@@ -10,6 +12,7 @@ import type {
FamilyInfo, FamilyInfo,
FamilyMember, FamilyMember,
FeedingMethod, FeedingMethod,
JoinFamilyPayload,
ServerTimeInfo, ServerTimeInfo,
UpdateCareRecordPayload, UpdateCareRecordPayload,
UpdateFamilyPayload, UpdateFamilyPayload,
@@ -35,8 +38,23 @@ export function getCurrentBaby() {
return request<BabyProfile>('/api/v1/babies/current') return request<BabyProfile>('/api/v1/babies/current')
} }
export function getFamilyContext() { export function getFamilyContext(familyId?: string) {
return request<FamilyContext>('/api/v1/families/current-context') const query = familyId ? `?familyId=${encodeURIComponent(familyId)}` : ''
return request<FamilyContext>(`/api/v1/families/current-context${query}`)
}
export function createFamily(payload: CreateFamilyPayload) {
return request<FamilyContext>('/api/v1/families', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function joinFamily(payload: JoinFamilyPayload) {
return request<FamilyContext>('/api/v1/families/join', {
method: 'POST',
body: JSON.stringify(payload)
})
} }
export function updateCurrentBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) { export function updateCurrentBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
@@ -95,6 +113,25 @@ export function deleteMember(familyId: string, memberId: string) {
}) })
} }
export function getQuickRules(familyId?: string) {
const query = familyId ? `?familyId=${encodeURIComponent(familyId)}` : ''
return request<CareQuickRule[]>(`/api/v1/families/quick-rules${query}`)
}
export function saveQuickRule(payload: Omit<CareQuickRule, 'ruleId'> & { ruleId?: string }) {
return request<CareQuickRule>('/api/v1/families/quick-rules', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function deleteQuickRule(ruleId: string) {
return request<void>('/api/v1/families/quick-rules/delete', {
method: 'POST',
body: JSON.stringify({ ruleId })
})
}
export function getDailySummary(babyId: string) { export function getDailySummary(babyId: string) {
return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`) return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`)
} }
@@ -116,6 +153,8 @@ export function createFeeding(payload: {
endTime?: string endTime?: string
leftDurationMinutes?: number leftDurationMinutes?: number
rightDurationMinutes?: number rightDurationMinutes?: number
effectiveFeedingMinutes?: number
pauseSegmentsJson?: string
operatorName: string operatorName: string
remark?: string remark?: string
note?: string note?: string
@@ -147,6 +186,8 @@ export function endFeeding(payload: {
breastSide?: 'left' | 'right' breastSide?: 'left' | 'right'
leftDurationMinutes?: number leftDurationMinutes?: number
rightDurationMinutes?: number rightDurationMinutes?: number
effectiveFeedingMinutes?: number
pauseSegmentsJson?: string
operatorName: string operatorName: string
remark?: string remark?: string
note?: string note?: string
@@ -1,8 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import { showToast } from 'vant' import { showConfirmDialog, showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import type { ActionPreferences } from '../../types/domain' import type { ActionPreferences, CareQuickAction, CareQuickRule } from '../../types/domain'
const store = useCareStore() const store = useCareStore()
@@ -15,8 +15,22 @@ const actionForm = reactive<ActionPreferences>({
autoBurpReminder: true autoBurpReminder: true
}) })
const editingRuleId = ref<string | null>(null)
const ruleForm = reactive({
name: '',
actions: ['diaper', 'feeding', 'sleep'] as CareQuickAction[],
diaperOffsetMinutes: 0,
feedingOffsetMinutes: 5,
sleepAfterFeedingMinutes: 5,
enabled: true,
sortOrder: 100
})
const enabledRules = computed(() => store.quickRules.filter(rule => rule.enabled))
onMounted(() => { onMounted(() => {
syncActionForm() syncActionForm()
store.reloadQuickRules()
}) })
function syncActionForm() { function syncActionForm() {
@@ -27,30 +41,124 @@ function saveActions() {
store.savePreferences(actionForm) store.savePreferences(actionForm)
showToast({ message: '照护行为偏好已更新', type: 'success' }) showToast({ message: '照护行为偏好已更新', type: 'success' })
} }
function resetRuleForm() {
editingRuleId.value = null
ruleForm.name = ''
ruleForm.actions = ['diaper', 'feeding', 'sleep']
ruleForm.diaperOffsetMinutes = 0
ruleForm.feedingOffsetMinutes = 5
ruleForm.sleepAfterFeedingMinutes = 5
ruleForm.enabled = true
ruleForm.sortOrder = 100
}
function editRule(rule: CareQuickRule) {
editingRuleId.value = rule.ruleId
ruleForm.name = rule.name
ruleForm.actions = [...rule.actions]
ruleForm.diaperOffsetMinutes = rule.diaperOffsetMinutes
ruleForm.feedingOffsetMinutes = rule.feedingOffsetMinutes
ruleForm.sleepAfterFeedingMinutes = rule.sleepAfterFeedingMinutes
ruleForm.enabled = rule.enabled
ruleForm.sortOrder = rule.sortOrder
}
function toggleAction(action: CareQuickAction) {
if (ruleForm.actions.includes(action)) {
ruleForm.actions = ruleForm.actions.filter(item => item !== action)
} else {
ruleForm.actions = [...ruleForm.actions, action]
}
}
function actionText(actions: CareQuickAction[]) {
const map: Record<CareQuickAction, string> = {
diaper: '换尿布',
feeding: '喂奶',
sleep: '睡觉'
}
return actions.map(action => map[action]).join('、')
}
async function saveQuickRule() {
if (!ruleForm.name.trim()) {
showToast('请填写常用补记名称')
return
}
if (!ruleForm.actions.length) {
showToast('至少选择一个照护动作')
return
}
const payload = {
familyId: store.context?.family.familyId || '',
name: ruleForm.name.trim(),
actions: ruleForm.actions,
diaperOffsetMinutes: ruleForm.diaperOffsetMinutes || 0,
feedingOffsetMinutes: ruleForm.feedingOffsetMinutes || 0,
sleepAfterFeedingMinutes: ruleForm.sleepAfterFeedingMinutes || 0,
enabled: ruleForm.enabled,
sortOrder: ruleForm.sortOrder || 100
}
if (editingRuleId.value) {
await store.updateQuickRule(editingRuleId.value, payload)
showToast({ message: '常用补记已更新', type: 'success' })
} else {
await store.addQuickRule(payload)
showToast({ message: '常用补记已添加', type: 'success' })
}
resetRuleForm()
}
async function removeRule(rule: CareQuickRule) {
try {
await showConfirmDialog({
title: '删除常用补记',
message: `确定删除“${rule.name}”吗?`
})
await store.deleteQuickRule(rule.ruleId)
if (editingRuleId.value === rule.ruleId) {
resetRuleForm()
}
showToast({ message: '已删除', type: 'success' })
} catch {
// cancel
}
}
</script> </script>
<template> <template>
<section class="panel form-panel"> <div class="action-mobile-page">
<section class="panel action-mobile-card">
<div class="action-card-head">
<div> <div>
<span class="eyebrow">照护行为偏好</span> <span class="eyebrow">照护习惯</span>
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">自定义默认喂养、睡眠及操作习惯</p> <h3>默认记录偏好</h3>
</div>
<button class="mini-save-btn" type="button" @click="saveActions">保存</button>
</div> </div>
<label> <div class="mobile-setting-block">
默认喂养方式 <div class="mobile-setting-title">
<select v-model="actionForm.defaultFeedingMethod"> <strong>默认喂养方式</strong>
<option value="breastfeed">亲喂 (母乳)</option> <span>今日页和补记会优先使用</span>
<option value="bottle">瓶喂 (母乳)</option> </div>
<option value="formula">配方奶</option> <div class="mobile-option-grid">
<option value="mixed">混合喂养</option> <button type="button" class="mobile-option" :class="{ active: actionForm.defaultFeedingMethod === 'breastfeed' }" @click="actionForm.defaultFeedingMethod = 'breastfeed'">亲喂</button>
</select> <button type="button" class="mobile-option" :class="{ active: actionForm.defaultFeedingMethod === 'bottle' }" @click="actionForm.defaultFeedingMethod = 'bottle'">挤出母乳</button>
</label> <button type="button" class="mobile-option" :class="{ active: actionForm.defaultFeedingMethod === 'formula' }" @click="actionForm.defaultFeedingMethod = 'formula'">配方奶</button>
<button type="button" class="mobile-option" :class="{ active: actionForm.defaultFeedingMethod === 'mixed' }" @click="actionForm.defaultFeedingMethod = 'mixed'">混合喂养</button>
</div>
</div>
<label> <div class="mobile-setting-block">
默认单次瓶喂奶量 (ml) <div class="mobile-setting-title">
<div style="display: flex; gap: 8px; align-items: center;"> <strong>挤出母乳默认奶量</strong>
<span>ml</span>
</div>
<div class="amount-mobile-row">
<input v-model.number="actionForm.defaultBottleAmount" type="number" min="10" max="300" step="5" /> <input v-model.number="actionForm.defaultBottleAmount" type="number" min="10" max="300" step="5" />
<div class="chip-group" style="margin: 0;"> <div class="amount-chip-grid">
<button <button
v-for="amt in [30, 60, 90, 120]" v-for="amt in [30, 60, 90, 120]"
:key="amt" :key="amt"
@@ -63,42 +171,116 @@ function saveActions() {
</button> </button>
</div> </div>
</div> </div>
</div>
<div class="mobile-setting-block">
<div class="mobile-setting-title">
<strong>亲喂优先侧</strong>
<span>开始计时时默认侧</span>
</div>
<div class="mobile-option-grid two">
<button type="button" class="mobile-option" :class="{ active: actionForm.defaultBreastSide === 'left' }" @click="actionForm.defaultBreastSide = 'left'">左侧优先</button>
<button type="button" class="mobile-option" :class="{ active: actionForm.defaultBreastSide === 'right' }" @click="actionForm.defaultBreastSide = 'right'">右侧优先</button>
</div>
</div>
<div class="mobile-setting-block">
<div class="mobile-setting-title">
<strong>睡眠记录</strong>
<span>选择常用方式</span>
</div>
<div class="mobile-option-grid two">
<button type="button" class="mobile-option" :class="{ active: actionForm.defaultSleepMode === 'timer' }" @click="actionForm.defaultSleepMode = 'timer'">开始/醒来</button>
<button type="button" class="mobile-option" :class="{ active: actionForm.defaultSleepMode === 'manual' }" @click="actionForm.defaultSleepMode = 'manual'">补记完成</button>
</div>
</div>
<div class="mobile-switch-list">
<label class="mobile-switch-row">
<span>
<strong>记录成功反馈</strong>
<small>快速操作成功后轻提示</small>
</span>
<input v-model="actionForm.quickFeedbackToast" type="checkbox" />
</label> </label>
<label class="mobile-switch-row">
<label> <span>
默认亲喂优先侧 <strong>喂奶后拍嗝提醒</strong>
<select v-model="actionForm.defaultBreastSide"> <small>亲喂/挤出母乳结束后提示</small>
<option value="left">左侧优先 (Left)</option> </span>
<option value="right">右侧优先 (Right)</option> <input v-model="actionForm.autoBurpReminder" type="checkbox" />
</select>
</label> </label>
<label>
睡眠默认模式
<select v-model="actionForm.defaultSleepMode">
<option value="timer">计时器模式(开始/醒来两步计时)</option>
<option value="manual">快捷录入模式(记录已完成的睡眠)</option>
</select>
</label>
<div style="border-top: 1px solid #f0ece5; padding-top: 12px; display: grid; gap: 12px;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<strong style="font-size: 14px; display: block;">记录成功温馨反馈</strong>
<span style="font-size: 12px; color: #65707d;">快速操作成功后弹出轻提示</span>
</div> </div>
<input v-model="actionForm.quickFeedbackToast" type="checkbox" style="width: 22px; height: 22px;" />
</div>
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<strong style="font-size: 14px; display: block;">亲喂/瓶喂后拍嗝提醒</strong>
<span style="font-size: 12px; color: #65707d;">每次喂养结束后友好提示竖抱拍嗝</span>
</div>
<input v-model="actionForm.autoBurpReminder" type="checkbox" style="width: 22px; height: 22px;" />
</div>
</div>
<button class="save-button" @click="saveActions">保存行为偏好设置</button>
</section> </section>
<section class="panel action-mobile-card">
<div class="action-card-head">
<div>
<span class="eyebrow">常用补记</span>
<h3>一组照护动作</h3>
</div>
</div>
<div class="quick-rule-card active">
<strong>完整照护</strong>
<span>系统内置:换尿布、喂奶、睡觉</span>
</div>
<div v-if="enabledRules.length" class="quick-rule-list">
<div v-for="rule in enabledRules" :key="rule.ruleId" class="quick-rule-card mobile-rule-card">
<div>
<strong>{{ rule.name }}</strong>
<span>{{ actionText(rule.actions) }}</span>
</div>
<div class="item-actions">
<button class="edit-button" type="button" @click="editRule(rule)">编辑</button>
<button class="delete-button" type="button" @click="removeRule(rule)">删除</button>
</div>
</div>
</div>
<div class="quick-rule-editor mobile-rule-editor">
<strong>{{ editingRuleId ? '编辑常用补记' : '添加常用补记' }}</strong>
<label>
名称
<input v-model="ruleForm.name" placeholder="例如:夜里只喂奶" />
</label>
<label>
包含哪些事
<div class="mobile-option-grid three">
<button type="button" class="mobile-option" :class="{ active: ruleForm.actions.includes('diaper') }" @click="toggleAction('diaper')">换尿布</button>
<button type="button" class="mobile-option" :class="{ active: ruleForm.actions.includes('feeding') }" @click="toggleAction('feeding')">喂奶</button>
<button type="button" class="mobile-option" :class="{ active: ruleForm.actions.includes('sleep') }" @click="toggleAction('sleep')">睡觉</button>
</div>
</label>
<div class="mobile-offset-list">
<label>
换尿布偏移
<input v-model.number="ruleForm.diaperOffsetMinutes" type="number" min="0" max="120" />
<span>分钟</span>
</label>
<label>
喂奶偏移
<input v-model.number="ruleForm.feedingOffsetMinutes" type="number" min="0" max="120" />
<span>分钟</span>
</label>
<label>
喂完多久睡
<input v-model.number="ruleForm.sleepAfterFeedingMinutes" type="number" min="0" max="120" />
<span>分钟</span>
</label>
</div>
<div class="modal-actions">
<button v-if="editingRuleId" class="secondary-button" type="button" @click="resetRuleForm">取消</button>
<button class="save-button" type="button" @click="saveQuickRule">
{{ editingRuleId ? '保存' : '添加' }}
</button>
</div>
</div>
</section>
</div>
</template> </template>
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import { getLocalDateStr } from '../../utils/format' import { getLocalDateStr } from '../../utils/format'
@@ -16,6 +16,7 @@ const babyForm = reactive({
// 添加宝宝弹窗 // 添加宝宝弹窗
const showAddBabyModal = ref(false) const showAddBabyModal = ref(false)
const showEditBabyModal = ref(false)
const newBabyForm = reactive({ const newBabyForm = reactive({
name: '', name: '',
gender: 'boy', gender: 'boy',
@@ -24,6 +25,23 @@ const newBabyForm = reactive({
isDefault: false isDefault: false
}) })
const currentGenderLabel = computed(() => {
if (!store.baby) return '-'
return store.baby.gender === 'girl' ? '女宝' : '男宝'
})
const currentDeliveryLabel = computed(() => {
if (!store.baby) return '-'
if (store.baby.deliveryType === 'c_section') return '剖宫产'
if (store.baby.deliveryType === 'unknown') return '暂不设置'
return '顺产'
})
const currentBabySummary = computed(() => {
if (!store.baby) return '-'
return `${store.baby.birthDate} · ${currentGenderLabel.value} · ${currentDeliveryLabel.value}`
})
onMounted(() => { onMounted(() => {
syncBabyForm() syncBabyForm()
}) })
@@ -52,9 +70,15 @@ async function saveBaby() {
birthDate: babyForm.birthDate, birthDate: babyForm.birthDate,
deliveryType: babyForm.deliveryType deliveryType: babyForm.deliveryType
}) })
showEditBabyModal.value = false
showToast({ message: '宝宝档案已更新', type: 'success' }) showToast({ message: '宝宝档案已更新', type: 'success' })
} }
function openEditBabyModal() {
syncBabyForm()
showEditBabyModal.value = true
}
// 打开添加宝宝弹窗 // 打开添加宝宝弹窗
function openAddBabyModal() { function openAddBabyModal() {
newBabyForm.name = '' newBabyForm.name = ''
@@ -99,39 +123,67 @@ async function handleSetDefaultBaby(babyId: string) {
</script> </script>
<template> <template>
<section class="panel"> <section class="panel baby-overview-panel">
<div class="timeline-header-actions"> <div class="timeline-header-actions">
<div> <div>
<span class="eyebrow">宝宝管理</span> <span class="eyebrow">家庭里的宝宝</span>
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">选择或维护宝宝档案</p>
</div> </div>
<button class="primary-pill-button" @click="openAddBabyModal"> <button class="icon-text-button" type="button" @click="openAddBabyModal">
+ 添加宝宝 添加
</button> </button>
</div> </div>
<!-- 宝宝切换卡片 --> <div v-if="store.baby" class="baby-profile compact">
<div class="chip-group" style="margin-bottom: 16px;"> <div>
<span class="eyebrow">当前照护</span>
<strong>{{ store.baby.name }}</strong>
<p>{{ store.baby.ageText }}</p>
</div>
<button class="icon-text-button" type="button" @click="openEditBabyModal">改</button>
</div>
<div v-if="store.baby" class="baby-compact-row">
<span>宝宝档案</span>
<strong>{{ currentBabySummary }}</strong>
</div>
<div class="baby-list">
<button <button
v-for="b in store.babies" v-for="b in store.babies"
:key="b.babyId" :key="b.babyId"
class="chip" class="baby-list-item"
:class="{ active: store.baby?.babyId === b.babyId }" :class="{ active: store.baby?.babyId === b.babyId }"
type="button"
@click="store.selectBaby(b.babyId)" @click="store.selectBaby(b.babyId)"
> >
{{ b.name }} ({{ b.ageText }}) <span>
<span v-if="b.isDefault" class="tag-badge default">默认</span> <strong>{{ b.name }}</strong>
<small>{{ b.ageText }}</small>
</span>
<em v-if="b.isDefault">默认</em>
</button> </button>
</div> </div>
<div v-if="store.baby && store.babies.length > 1 && !store.baby.isDefault" style="margin-bottom: 16px;"> <div v-if="store.baby && store.babies.length > 1 && !store.baby.isDefault" class="baby-default-action">
<button class="secondary-button" style="font-size: 13px;" @click="handleSetDefaultBaby(store.baby.babyId)"> <button class="secondary-button" type="button" @click="handleSetDefaultBaby(store.baby.babyId)">
设为全局默认宝宝 设为当前默认宝宝
</button> </button>
</div> </div>
<!-- 当前宝宝修改表单 --> <van-popup
<div class="form-panel" style="border-top: 1px solid #f0ece5; padding-top: 16px;"> v-model:show="showEditBabyModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header">
<h3>修改宝宝档案</h3>
<button class="close-btn" type="button" @click="showEditBabyModal = false">×</button>
</div>
<div class="modal-form">
<label> <label>
宝宝昵称 宝宝昵称
<input v-model="babyForm.name" placeholder="请输入宝宝名字或乳名" /> <input v-model="babyForm.name" placeholder="请输入宝宝名字或乳名" />
@@ -150,15 +202,19 @@ async function handleSetDefaultBaby(babyId: string) {
<label> <label>
分娩方式 分娩方式
<select v-model="babyForm.deliveryType"> <select v-model="babyForm.deliveryType">
<option value="natural">顺产 (Natural)</option> <option value="natural">顺产</option>
<option value="c_section">剖宫产 (C-Section)</option> <option value="c_section">剖宫产</option>
<option value="unknown">暂不设置</option> <option value="unknown">暂不设置</option>
</select> </select>
</label> </label>
<button class="save-button" @click="saveBaby">保存宝宝信息</button> <div class="modal-actions">
<button class="secondary-button" type="button" @click="showEditBabyModal = false">取消</button>
<button class="save-button" type="button" @click="saveBaby">保存宝宝档案</button>
</div> </div>
</div>
</div>
</van-popup>
<!-- 弹窗:添加新宝宝 -->
<van-popup <van-popup
v-model:show="showAddBabyModal" v-model:show="showAddBabyModal"
position="bottom" position="bottom"
@@ -1,15 +1,33 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
const store = useCareStore() const store = useCareStore()
const showEditModal = ref(false)
const showCreateModal = ref(false)
const showJoinModal = ref(false)
const familyForm = reactive({ const familyForm = reactive({
name: '', name: '',
inviteCode: '' inviteCode: ''
}) })
const createFamilyForm = reactive({
name: '',
roleName: '宝妈',
inviteCode: ''
})
const joinFamilyForm = reactive({
inviteCode: '',
roleName: '宝妈'
})
const family = computed(() => store.context?.family)
const familyName = computed(() => family.value?.name || '新生儿照护家庭')
const inviteCode = computed(() => family.value?.inviteCode || '暂未设置')
onMounted(() => { onMounted(() => {
syncFamilyForm() syncFamilyForm()
}) })
@@ -34,12 +52,74 @@ async function saveFamily() {
name: familyForm.name.trim(), name: familyForm.name.trim(),
inviteCode: familyForm.inviteCode.trim() inviteCode: familyForm.inviteCode.trim()
}) })
showEditModal.value = false
showToast({ message: '家庭信息已保存', type: 'success' }) showToast({ message: '家庭信息已保存', type: 'success' })
} catch (err: any) { } catch (err: any) {
showToast(err.message || '保存失败') showToast(err.message || '保存失败')
} }
} }
function startEdit() {
syncFamilyForm()
showEditModal.value = true
}
function openCreateFamilyModal() {
createFamilyForm.name = ''
createFamilyForm.roleName = store.operatorName || '宝妈'
createFamilyForm.inviteCode = ''
showCreateModal.value = true
}
function openJoinFamilyModal() {
joinFamilyForm.inviteCode = ''
joinFamilyForm.roleName = store.operatorName || '宝妈'
showJoinModal.value = true
}
async function submitCreateFamily() {
if (!createFamilyForm.name.trim()) {
showToast('请输入家庭名称')
return
}
if (!createFamilyForm.roleName.trim()) {
showToast('请输入你的称谓')
return
}
try {
await store.createFamily({
name: createFamilyForm.name.trim(),
roleName: createFamilyForm.roleName.trim(),
inviteCode: createFamilyForm.inviteCode.trim() || undefined
})
showCreateModal.value = false
showToast({ message: '家庭已创建', type: 'success' })
} catch (err: any) {
showToast(err.message || '创建失败')
}
}
async function submitJoinFamily() {
if (!joinFamilyForm.inviteCode.trim()) {
showToast('请输入成员加入码')
return
}
if (!joinFamilyForm.roleName.trim()) {
showToast('请输入你的称谓')
return
}
try {
await store.joinFamily({
inviteCode: joinFamilyForm.inviteCode.trim(),
roleName: joinFamilyForm.roleName.trim()
})
showJoinModal.value = false
showToast({ message: '已加入家庭', type: 'success' })
} catch (err: any) {
showToast(err.message || '加入失败')
}
}
function generateInviteCode() { function generateInviteCode() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
let res = 'BT' let res = 'BT'
@@ -48,43 +128,144 @@ function generateInviteCode() {
} }
familyForm.inviteCode = res familyForm.inviteCode = res
} }
async function copyInviteCode() {
if (!family.value?.inviteCode) {
showToast('暂无成员加入码')
return
}
try {
await navigator.clipboard.writeText(family.value.inviteCode)
showToast({ message: '成员加入码已复制', type: 'success' })
} catch {
showToast('复制失败,请手动复制')
}
}
</script> </script>
<template> <template>
<section class="panel form-panel"> <section class="panel family-overview-panel">
<div class="family-profile">
<div> <div>
<span class="eyebrow">家庭基础设置</span> <span class="eyebrow">家庭核心信息</span>
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">维护家庭名称与成员共享邀请码</p> <strong>{{ familyName }}</strong>
<p>家庭编号:{{ family?.familyId || '-' }}</p>
</div>
<button class="icon-text-button" type="button" aria-label="编辑家庭资料" @click="startEdit">
改
</button>
</div> </div>
<div class="family-compact-row">
<span>成员加入码</span>
<button type="button" @click="copyInviteCode">
<strong>{{ inviteCode }}</strong>
<small>复制</small>
</button>
</div>
<div class="family-onboarding-actions">
<button type="button" @click="openCreateFamilyModal">新建家庭</button>
<button type="button" @click="openJoinFamilyModal">加入家庭</button>
</div>
<van-popup
v-model:show="showEditModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header">
<h3>修改家庭资料</h3>
<button class="close-btn" type="button" @click="showEditModal = false">×</button>
</div>
<div class="modal-form">
<label> <label>
家庭名称 家庭名称
<input v-model="familyForm.name" placeholder="例如:新生儿照护家庭、幸福小家" /> <input v-model="familyForm.name" placeholder="例如:新生儿照护家庭、幸福小家" />
</label> </label>
<label> <label>
家庭邀请码 成员加入码
<div style="display: flex; gap: 8px;"> <div style="display: flex; gap: 8px;">
<input v-model="familyForm.inviteCode" placeholder="共享邀请码" style="flex: 1;" /> <input v-model="familyForm.inviteCode" placeholder="给家人加入使用" style="flex: 1;" />
<button class="secondary-button" type="button" @click="generateInviteCode">随机生成</button> <button class="secondary-button" type="button" @click="generateInviteCode">随机生成</button>
</div> </div>
</label> </label>
<div class="settings-list" style="margin: 8px 0;"> <div class="modal-actions">
<div> <button class="secondary-button" type="button" @click="showEditModal = false">取消</button>
<span>家庭编号</span> <button class="save-button" type="button" @click="saveFamily">保存家庭信息</button>
<strong>{{ store.context?.family.familyId || '-' }}</strong>
</div>
<div>
<span>宝宝总数</span>
<strong>{{ store.babies.length }} 个宝宝</strong>
</div>
<div>
<span>成员人数</span>
<strong>{{ store.members.length }} 位成员</strong>
</div> </div>
</div> </div>
</div>
</van-popup>
<button class="save-button" @click="saveFamily">保存家庭信息</button> <van-popup
v-model:show="showCreateModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header">
<h3>新建家庭</h3>
<button class="close-btn" type="button" @click="showCreateModal = false">×</button>
</div>
<div class="modal-form">
<label>
家庭名称
<input v-model="createFamilyForm.name" placeholder="例如:新生儿照护家庭" />
</label>
<label>
我的称谓
<input v-model="createFamilyForm.roleName" placeholder="例如:宝妈、宝爸" />
</label>
<label>
成员加入码
<input v-model="createFamilyForm.inviteCode" placeholder="可不填,系统自动生成" />
</label>
<div class="modal-actions">
<button class="secondary-button" type="button" @click="showCreateModal = false">取消</button>
<button class="save-button" type="button" @click="submitCreateFamily">创建家庭</button>
</div>
</div>
</div>
</van-popup>
<van-popup
v-model:show="showJoinModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header">
<h3>加入家庭</h3>
<button class="close-btn" type="button" @click="showJoinModal = false">×</button>
</div>
<div class="modal-form">
<label>
成员加入码
<input v-model="joinFamilyForm.inviteCode" placeholder="输入家人分享的加入码" />
</label>
<label>
我的称谓
<input v-model="joinFamilyForm.roleName" placeholder="例如:宝妈、宝爸" />
</label>
<div class="modal-actions">
<button class="secondary-button" type="button" @click="showJoinModal = false">取消</button>
<button class="save-button" type="button" @click="submitJoinFamily">加入家庭</button>
</div>
</div>
</div>
</van-popup>
</section> </section>
</template> </template>
@@ -270,7 +270,7 @@ async function submitEdit() {
喂养方式 喂养方式
<select v-model="editForm.feedingMethod"> <select v-model="editForm.feedingMethod">
<option value="breastfeed">亲喂 (母乳)</option> <option value="breastfeed">亲喂 (母乳)</option>
<option value="bottle">瓶喂 (母乳)</option> <option value="bottle">挤出母乳</option>
<option value="formula">配方奶</option> <option value="formula">配方奶</option>
<option value="mixed">混合喂养</option> <option value="mixed">混合喂养</option>
</select> </select>
@@ -1,12 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { reactive, watch } from 'vue' import { computed, reactive, ref, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import type { ExcretionType, FeedingMethod, RecordType } from '../../types/domain' import type { CareQuickRule, CreateManualRecordPayload, ExcretionType, FeedingMethod, RecordType } from '../../types/domain'
import { getLocalDateStr, getLocalTimeStr } from '../../utils/format' import { getLocalDateStr, getLocalTimeStr } from '../../utils/format'
const props = defineProps<{ const props = defineProps<{
show: boolean show: boolean
initialMode?: ManualMode
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -18,7 +19,57 @@ const store = useCareStore()
const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香'] const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香']
type ManualMode = 'quick' | 'detail'
type DiaperChoice = 'pee' | 'poop' | 'both'
type FeedingQuickChoice = 'breastfeed20' | 'breastfeed10' | 'bottle' | 'formula'
type Draft = Omit<CreateManualRecordPayload, 'babyId'> & {
draftId: string
title: string
}
const mode = ref<ManualMode>('quick')
const selectedRuleId = ref('system_full_care')
const drafts = ref<Draft[]>([])
const savingQuick = ref(false)
const timePresets = [
{ label: '刚刚', minutesAgo: 0 },
{ label: '10分钟前', minutesAgo: 10 },
{ label: '20分钟前', minutesAgo: 20 },
{ label: '半小时前', minutesAgo: 30 }
]
const initialNow = store.getServerNow() const initialNow = store.getServerNow()
const quickForm = reactive({
date: getLocalDateStr(initialNow),
time: getLocalTimeStr(initialNow),
diaper: 'pee' as DiaperChoice,
feeding: 'breastfeed20' as FeedingQuickChoice,
operatorName: store.operatorName,
note: ''
})
const systemQuickRule: CareQuickRule = {
ruleId: 'system_full_care',
familyId: 'system',
name: '完整照护',
actions: ['diaper', 'feeding', 'sleep'],
diaperOffsetMinutes: 0,
feedingOffsetMinutes: 5,
sleepAfterFeedingMinutes: 5,
enabled: true,
sortOrder: 0
}
const quickRules = computed<CareQuickRule[]>(() => [
systemQuickRule,
...store.quickRules.filter(rule => rule.enabled)
])
const selectedRule = computed(() => quickRules.value.find(rule => rule.ruleId === selectedRuleId.value) || quickRules.value[0])
const ruleNeedsDiaper = computed(() => selectedRule.value.actions.includes('diaper'))
const ruleNeedsFeeding = computed(() => selectedRule.value.actions.includes('feeding'))
const ruleNeedsSleep = computed(() => selectedRule.value.actions.includes('sleep'))
const manualForm = reactive({ const manualForm = reactive({
recordType: 'feeding' as RecordType, recordType: 'feeding' as RecordType,
startDate: getLocalDateStr(initialNow), startDate: getLocalDateStr(initialNow),
@@ -40,9 +91,227 @@ const manualForm = reactive({
watch(() => props.show, (newVal) => { watch(() => props.show, (newVal) => {
if (newVal) { if (newVal) {
initForm() initForm()
initQuickForm()
} }
}) })
function initQuickForm() {
const now = store.getServerNow()
quickForm.date = getLocalDateStr(now)
quickForm.time = getLocalTimeStr(now)
quickForm.operatorName = store.operatorName
quickForm.diaper = 'pee'
quickForm.feeding = defaultFeedingChoice()
quickForm.note = ''
selectedRuleId.value = quickRules.value[0]?.ruleId || 'system_full_care'
drafts.value = []
mode.value = props.initialMode || 'quick'
}
function defaultFeedingChoice(): FeedingQuickChoice {
const method = store.preferences.defaultFeedingMethod
if (method === 'bottle') return 'bottle'
if (method === 'formula') return 'formula'
return 'breastfeed20'
}
function applyTimePreset(minutesAgo: number) {
const base = new Date(store.getServerNow().getTime() - minutesAgo * 60000)
quickForm.date = getLocalDateStr(base)
quickForm.time = getLocalTimeStr(base)
}
function addMinutes(date: Date, minutes: number): Date {
return new Date(date.getTime() + minutes * 60000)
}
function toPayloadTime(date: Date): string {
return `${getLocalDateStr(date)}T${getLocalTimeStr(date)}:00`
}
function draftId() {
return `draft_${Date.now()}_${Math.random().toString(16).slice(2)}`
}
function buildFeedingDraft(start: Date): Draft {
const operatorName = quickForm.operatorName || store.operatorName
const baseNote = quickForm.note.trim() || null
if (quickForm.feeding === 'bottle' || quickForm.feeding === 'formula') {
const amount = store.preferences.defaultBottleAmount || (quickForm.feeding === 'bottle' ? 30 : 60)
return {
draftId: draftId(),
title: quickForm.feeding === 'bottle' ? `挤出母乳 ${amount}ml` : `配方奶 ${amount}ml`,
recordType: 'feeding',
startTime: toPayloadTime(start),
endTime: null,
durationMinutes: null,
leftDurationMinutes: null,
rightDurationMinutes: null,
feedingMethod: quickForm.feeding,
amountMl: amount,
excretionType: null,
operatorName,
note: baseNote
}
}
const duration = quickForm.feeding === 'breastfeed10' ? 10 : 20
const end = addMinutes(start, duration)
return {
draftId: draftId(),
title: `亲喂 ${duration}分钟`,
recordType: 'feeding',
startTime: toPayloadTime(start),
endTime: toPayloadTime(end),
durationMinutes: duration,
leftDurationMinutes: Math.floor(duration / 2),
rightDurationMinutes: Math.ceil(duration / 2),
feedingMethod: 'breastfeed',
amountMl: null,
excretionType: null,
operatorName,
note: baseNote
}
}
function buildSleepDraft(start: Date): Draft {
return {
draftId: draftId(),
title: '开始睡觉',
recordType: 'sleep',
startTime: toPayloadTime(start),
endTime: null,
durationMinutes: null,
leftDurationMinutes: null,
rightDurationMinutes: null,
feedingMethod: null,
amountMl: null,
excretionType: null,
operatorName: quickForm.operatorName || store.operatorName,
note: quickForm.note.trim() || null
}
}
function buildExcretionDraft(type: ExcretionType, start: Date): Draft {
return {
draftId: draftId(),
title: type === 'pee' ? '小便' : '大便',
recordType: 'excretion',
startTime: toPayloadTime(start),
endTime: null,
durationMinutes: null,
leftDurationMinutes: null,
rightDurationMinutes: null,
feedingMethod: null,
amountMl: null,
excretionType: type,
operatorName: quickForm.operatorName || store.operatorName,
note: quickForm.note.trim() || null
}
}
function generateDrafts() {
if (!quickForm.date || !quickForm.time) {
showToast('请选择大概时间')
return
}
const anchor = new Date(`${quickForm.date}T${quickForm.time}:00`)
if (isNaN(anchor.getTime())) {
showToast('时间格式不正确')
return
}
const nextDrafts: Draft[] = []
if (ruleNeedsDiaper.value) {
const diaperTime = addMinutes(anchor, selectedRule.value.diaperOffsetMinutes || 0)
if (quickForm.diaper === 'pee' || quickForm.diaper === 'both') {
nextDrafts.push(buildExcretionDraft('pee', diaperTime))
}
if (quickForm.diaper === 'poop' || quickForm.diaper === 'both') {
nextDrafts.push(buildExcretionDraft('poop', diaperTime))
}
}
let feedingEnd = anchor
if (ruleNeedsFeeding.value) {
const feedingStart = addMinutes(anchor, selectedRule.value.feedingOffsetMinutes || 0)
const feedingDraft = buildFeedingDraft(feedingStart)
nextDrafts.push(feedingDraft)
feedingEnd = feedingDraft.endTime ? new Date(feedingDraft.endTime) : addMinutes(feedingStart, 15)
}
if (ruleNeedsSleep.value) {
const sleepStart = ruleNeedsFeeding.value
? addMinutes(feedingEnd, selectedRule.value.sleepAfterFeedingMinutes || 0)
: anchor
nextDrafts.push(buildSleepDraft(sleepStart))
}
drafts.value = nextDrafts
}
function removeDraft(id: string) {
drafts.value = drafts.value.filter(item => item.draftId !== id)
}
function updateDraftStart(draft: Draft, value: string) {
if (!value) return
const oldStart = new Date(draft.startTime)
const oldEnd = draft.endTime ? new Date(draft.endTime) : null
draft.startTime = `${quickForm.date}T${value}:00`
if (oldEnd && !isNaN(oldStart.getTime()) && !isNaN(oldEnd.getTime())) {
const durationMs = oldEnd.getTime() - oldStart.getTime()
draft.endTime = toPayloadTime(new Date(new Date(draft.startTime).getTime() + durationMs))
}
}
function updateDraftDuration(draft: Draft, value: number | null) {
if (!value || value <= 0) return
draft.durationMinutes = value
if (draft.feedingMethod === 'breastfeed') {
draft.leftDurationMinutes = Math.floor(value / 2)
draft.rightDurationMinutes = Math.ceil(value / 2)
}
draft.endTime = toPayloadTime(addMinutes(new Date(draft.startTime), value))
draft.title = draft.feedingMethod === 'breastfeed' ? `亲喂 ${value}分钟` : draft.title
}
function updateDraftAmount(draft: Draft, value: number | null) {
if (!value || value <= 0) return
draft.amountMl = value
draft.title = draft.feedingMethod === 'formula' ? `配方奶 ${value}ml` : `挤出母乳 ${value}ml`
}
async function submitDrafts() {
if (!drafts.value.length) {
showToast('请先生成补记明细')
return
}
savingQuick.value = true
try {
await store.manualLogMany(drafts.value.map(({ draftId: _draftId, title: _title, ...payload }) => payload))
emit('update:show', false)
emit('success')
showToast({ message: `已补记 ${drafts.value.length} 条照护记录`, type: 'success' })
} catch (err: any) {
showToast(err.message || '补记失败')
} finally {
savingQuick.value = false
}
}
function draftStartTime(draft: Draft) {
return draft.startTime.split('T')[1]?.slice(0, 5) || ''
}
function quickRuleActionText(rule: CareQuickRule) {
const names: string[] = []
if (rule.actions.includes('diaper')) names.push('换尿布')
if (rule.actions.includes('feeding')) names.push('喂奶')
if (rule.actions.includes('sleep')) names.push('睡觉')
return names.join('、')
}
function initForm() { function initForm() {
const now = store.getServerNow() const now = store.getServerNow()
manualForm.recordType = 'feeding' manualForm.recordType = 'feeding'
@@ -183,7 +452,133 @@ async function submitManual() {
<button class="close-btn" type="button" @click="emit('update:show', false)">×</button> <button class="close-btn" type="button" @click="emit('update:show', false)">×</button>
</div> </div>
<div class="modal-form"> <div class="manual-mode-tabs">
<button type="button" :class="{ active: mode === 'quick' }" @click="mode = 'quick'">常用补记</button>
<button type="button" :class="{ active: mode === 'detail' }" @click="mode = 'detail'">补一条详细记录</button>
</div>
<div v-if="mode === 'quick'" class="quick-manual-panel">
<label class="quick-section">
系统内置
<div class="quick-rule-grid">
<button
v-for="rule in quickRules"
:key="rule.ruleId"
type="button"
class="quick-rule-card"
:class="{ active: selectedRuleId === rule.ruleId }"
@click="selectedRuleId = rule.ruleId; drafts = []"
>
<strong>{{ rule.name }}</strong>
<span>{{ quickRuleActionText(rule) }}</span>
</button>
</div>
</label>
<div class="quick-config-hint">
家庭里的其他常用补记,可在「家庭 · 行为」中添加和调整。
</div>
<div class="quick-section">
<span class="quick-label">大概时间</span>
<div class="quick-time-presets">
<button
v-for="preset in timePresets"
:key="preset.label"
type="button"
class="chip sm"
@click="applyTimePreset(preset.minutesAgo); drafts = []"
>
{{ preset.label }}
</button>
</div>
<div class="quick-two-cols">
<label>
日期
<input v-model="quickForm.date" type="date" @change="drafts = []" />
</label>
<label>
时间
<input v-model="quickForm.time" type="time" @change="drafts = []" />
</label>
</div>
</div>
<label v-if="ruleNeedsDiaper" class="quick-section">
尿布里有
<div class="chip-group">
<button type="button" class="chip" :class="{ active: quickForm.diaper === 'pee' }" @click="quickForm.diaper = 'pee'; drafts = []">小便</button>
<button type="button" class="chip" :class="{ active: quickForm.diaper === 'poop' }" @click="quickForm.diaper = 'poop'; drafts = []">大便</button>
<button type="button" class="chip" :class="{ active: quickForm.diaper === 'both' }" @click="quickForm.diaper = 'both'; drafts = []">都有</button>
</div>
</label>
<label v-if="ruleNeedsFeeding" class="quick-section">
喂奶大概
<div class="chip-group">
<button type="button" class="chip" :class="{ active: quickForm.feeding === 'breastfeed20' }" @click="quickForm.feeding = 'breastfeed20'; drafts = []">亲喂20分钟</button>
<button type="button" class="chip" :class="{ active: quickForm.feeding === 'breastfeed10' }" @click="quickForm.feeding = 'breastfeed10'; drafts = []">亲喂10分钟</button>
<button type="button" class="chip" :class="{ active: quickForm.feeding === 'bottle' }" @click="quickForm.feeding = 'bottle'; drafts = []">挤出母乳默认量</button>
<button type="button" class="chip" :class="{ active: quickForm.feeding === 'formula' }" @click="quickForm.feeding = 'formula'; drafts = []">配方奶默认量</button>
</div>
</label>
<label class="quick-section">
记录人
<input v-model="quickForm.operatorName" placeholder="例如:宝妈、宝爸" @input="drafts = []" />
</label>
<label class="quick-section">
备注说明
<input v-model="quickForm.note" placeholder="选填,例如:状态好" @input="drafts = []" />
</label>
<button class="save-button" type="button" @click="generateDrafts">
生成明细
</button>
<div v-if="drafts.length" class="draft-panel">
<div class="draft-panel-title">
<strong>请确认这些明细</strong>
<span>{{ selectedRule.name }}</span>
</div>
<article v-for="draft in drafts" :key="draft.draftId" class="draft-card">
<div class="draft-card-header">
<strong>{{ draft.title }}</strong>
<button type="button" class="delete-button" @click="removeDraft(draft.draftId)">删除</button>
</div>
<div class="draft-fields">
<label>
时间
<input :value="draftStartTime(draft)" type="time" @input="updateDraftStart(draft, ($event.target as HTMLInputElement).value)" />
</label>
<label v-if="draft.recordType === 'excretion'">
类型
<select v-model="draft.excretionType">
<option value="pee">小便</option>
<option value="poop">大便</option>
</select>
</label>
<label v-if="draft.recordType === 'feeding' && draft.feedingMethod === 'breastfeed'">
亲喂分钟
<input :value="draft.durationMinutes || 20" type="number" min="1" max="180" @input="updateDraftDuration(draft, Number(($event.target as HTMLInputElement).value))" />
</label>
<label v-if="draft.recordType === 'feeding' && draft.feedingMethod !== 'breastfeed'">
奶量 ml
<input :value="draft.amountMl || 30" type="number" min="5" max="400" step="5" @input="updateDraftAmount(draft, Number(($event.target as HTMLInputElement).value))" />
</label>
</div>
</article>
<div class="modal-actions">
<button class="secondary-button" type="button" @click="drafts = []">重新生成</button>
<button class="save-button" type="button" :disabled="savingQuick" @click="submitDrafts">
{{ savingQuick ? '保存中...' : `保存 ${drafts.length} 条记录` }}
</button>
</div>
</div>
</div>
<div v-else class="modal-form">
<!-- 记录类型选择 --> <!-- 记录类型选择 -->
<label> <label>
记录类型 记录类型
@@ -233,7 +628,7 @@ async function submitManual() {
喂养方式 喂养方式
<select v-model="manualForm.feedingMethod"> <select v-model="manualForm.feedingMethod">
<option value="breastfeed">亲喂 (母乳)</option> <option value="breastfeed">亲喂 (母乳)</option>
<option value="bottle">瓶喂 (母乳)</option> <option value="bottle">挤出母乳</option>
<option value="formula">配方奶</option> <option value="formula">配方奶</option>
<option value="mixed">混合喂养</option> <option value="mixed">混合喂养</option>
</select> </select>
+6 -10
View File
@@ -7,7 +7,7 @@ import MemberSettingsTab from '../components/settings/MemberSettingsTab.vue'
import ActionSettingsTab from '../components/settings/ActionSettingsTab.vue' import ActionSettingsTab from '../components/settings/ActionSettingsTab.vue'
const store = useCareStore() const store = useCareStore()
const activeTab = ref('baby') const activeTab = ref('family')
const currentBabyLabel = computed(() => const currentBabyLabel = computed(() =>
store.baby ? `${store.baby.name} · ${store.baby.ageText}` : '未选择宝宝' store.baby ? `${store.baby.name} · ${store.baby.ageText}` : '未选择宝宝'
@@ -27,22 +27,18 @@ onMounted(async () => {
</header> </header>
<van-tabs v-model:active="activeTab" shrink animated swipeable> <van-tabs v-model:active="activeTab" shrink animated swipeable>
<!-- Tab 1: 宝宝维护 --> <!-- 家庭入口:一个家庭下管理多个宝宝与家庭资料 -->
<van-tab title="宝宝" name="baby"> <van-tab title="家庭" name="family">
<FamilySettingsTab />
<BabySettingsTab /> <BabySettingsTab />
</van-tab> </van-tab>
<!-- Tab 2: 家庭维护 --> <!-- 成员维护 -->
<van-tab title="家庭" name="family">
<FamilySettingsTab />
</van-tab>
<!-- Tab 3: 成员维护 -->
<van-tab title="成员" name="members"> <van-tab title="成员" name="members">
<MemberSettingsTab /> <MemberSettingsTab />
</van-tab> </van-tab>
<!-- Tab 4: 行为偏好维护 --> <!-- 行为偏好维护 -->
<van-tab title="行为" name="actions"> <van-tab title="行为" name="actions">
<ActionSettingsTab /> <ActionSettingsTab />
</van-tab> </van-tab>
+11 -5
View File
@@ -25,6 +25,7 @@ const sortOrder = ref<'desc' | 'asc'>('desc')
// 补录弹窗控制 // 补录弹窗控制
const showManualModal = ref(false) const showManualModal = ref(false)
const manualInitialMode = ref<'quick' | 'detail'>('quick')
// 编辑弹窗控制 // 编辑弹窗控制
const showEditModal = ref(false) const showEditModal = ref(false)
@@ -74,7 +75,8 @@ function toggleSortOrder() {
sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc' sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
} }
function openManualModal() { function openManualModal(mode: 'quick' | 'detail' = 'quick') {
manualInitialMode.value = mode
showManualModal.value = true showManualModal.value = true
} }
@@ -181,8 +183,11 @@ const totalCount = computed(() => records.value.length)
<span class="sort-icon">{{ sortOrder === 'desc' ? '↓' : '↑' }}</span> <span class="sort-icon">{{ sortOrder === 'desc' ? '↓' : '↑' }}</span>
{{ sortOrder === 'desc' ? '时间倒序' : '时间正序' }} {{ sortOrder === 'desc' ? '时间倒序' : '时间正序' }}
</button> </button>
<button class="primary-pill-button" @click="openManualModal"> <button class="primary-pill-button" @click="openManualModal('quick')">
+ 补录 + 补记照护
</button>
<button class="secondary-pill-button" @click="openManualModal('detail')">
补单次
</button> </button>
</div> </div>
</div> </div>
@@ -277,12 +282,13 @@ const totalCount = computed(() => records.value.length)
</p> </p>
<div style="display: flex; gap: 10px; justify-content: center;"> <div style="display: flex; gap: 10px; justify-content: center;">
<button v-if="filterDate" class="secondary-btn" @click="clearFilter">查看全部日期</button> <button v-if="filterDate" class="secondary-btn" @click="clearFilter">查看全部日期</button>
<button class="primary-pill-button" @click="openManualModal">+ 补录记录</button> <button class="primary-pill-button" @click="openManualModal('quick')">+ 补记照护</button>
<button class="secondary-pill-button" @click="openManualModal('detail')">补单次</button>
</div> </div>
</div> </div>
<!-- 弹窗:补录记录维护组件 --> <!-- 弹窗:补录记录维护组件 -->
<TimelineManualModal v-model:show="showManualModal" @success="handleRecordChanged" /> <TimelineManualModal v-model:show="showManualModal" :initial-mode="manualInitialMode" @success="handleRecordChanged" />
<!-- 弹窗:编辑记录维护组件 --> <!-- 弹窗:编辑记录维护组件 -->
<TimelineEditModal v-model:show="showEditModal" :record="selectedRecord" @success="handleRecordChanged" /> <TimelineEditModal v-model:show="showEditModal" :record="selectedRecord" @success="handleRecordChanged" />
+21 -10
View File
@@ -15,7 +15,7 @@ const currentFeedingTab = ref<FeedingTabType>(
const feedingTabOptions = [ const feedingTabOptions = [
{ value: 'breastfeed' as FeedingTabType, label: '亲喂' }, { value: 'breastfeed' as FeedingTabType, label: '亲喂' },
{ value: 'bottle' as FeedingTabType, label: '瓶喂' }, { value: 'bottle' as FeedingTabType, label: '挤出母乳' },
{ value: 'formula' as FeedingTabType, label: '配方奶' }, { value: 'formula' as FeedingTabType, label: '配方奶' },
{ value: 'mixed' as FeedingTabType, label: '混合喂养' } { value: 'mixed' as FeedingTabType, label: '混合喂养' }
] ]
@@ -191,6 +191,7 @@ async function handleOneClickBreastfeeding() {
endTime, endTime,
leftDurationMinutes: leftDur, leftDurationMinutes: leftDur,
rightDurationMinutes: rightDur, rightDurationMinutes: rightDur,
effectiveFeedingMinutes: dur,
breastSide: breastSideMode.value breastSide: breastSideMode.value
}), }),
`已记录亲喂 ${dur}分钟(${startStr} ~ ${endStr})` `已记录亲喂 ${dur}分钟(${startStr} ~ ${endStr})`
@@ -268,7 +269,7 @@ async function handleOneClickBreastfeeding() {
<h2>喂养</h2> <h2>喂养</h2>
<span v-if="store.bfTimerActive" class="bf-live-badge">亲喂进行中</span> <span v-if="store.bfTimerActive" class="bf-live-badge">亲喂进行中</span>
</div> </div>
<p>支持亲喂、瓶喂、配方奶与混合喂养多模式快捷记录。</p> <p>支持亲喂、挤出母乳、配方奶与混合喂养多模式快捷记录。</p>
</div> </div>
<!-- 四大喂养方式切换 Tab --> <!-- 四大喂养方式切换 Tab -->
@@ -302,7 +303,7 @@ async function handleOneClickBreastfeeding() {
<div class="bf-card-header"> <div class="bf-card-header">
<span class="bf-card-title">左侧</span> <span class="bf-card-title">左侧</span>
<span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'left' ? 'timing' : 'paused'"> <span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'left' ? 'timing' : 'paused'">
{{ store.bfActiveSide === 'left' ? '计时中' : '已暂计' }} {{ store.bfActiveSide === 'left' ? (store.bfPaused ? '暂停中' : '计时中') : '已暂计' }}
</span> </span>
<span v-else class="bf-status-tag idle"> <span v-else class="bf-status-tag idle">
{{ breastSide === 'left' ? '优先起始' : '点击选择' }} {{ breastSide === 'left' ? '优先起始' : '点击选择' }}
@@ -337,7 +338,7 @@ async function handleOneClickBreastfeeding() {
<div class="bf-card-header"> <div class="bf-card-header">
<span class="bf-card-title">右侧</span> <span class="bf-card-title">右侧</span>
<span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'right' ? 'timing' : 'paused'"> <span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'right' ? 'timing' : 'paused'">
{{ store.bfActiveSide === 'right' ? '计时中' : '已暂计' }} {{ store.bfActiveSide === 'right' ? (store.bfPaused ? '暂停中' : '计时中') : '已暂计' }}
</span> </span>
<span v-else class="bf-status-tag idle"> <span v-else class="bf-status-tag idle">
{{ breastSide === 'right' ? '优先起始' : '点击选择' }} {{ breastSide === 'right' ? '优先起始' : '点击选择' }}
@@ -364,7 +365,7 @@ async function handleOneClickBreastfeeding() {
<!-- 计时汇总横条 --> <!-- 计时汇总横条 -->
<div v-if="store.bfTimerActive" class="bf-summary-bar"> <div v-if="store.bfTimerActive" class="bf-summary-bar">
<span>本次亲喂总计:<strong>{{ formatTotalBfTime() }}</strong></span> <span>本次亲喂总计:<strong>{{ formatTotalBfTime() }}</strong></span>
<small>(左侧 {{ formatSec(store.bfLeftSeconds) }} · 右侧 {{ formatSec(store.bfRightSeconds) }})</small> <small>(左侧 {{ formatSec(store.bfLeftSeconds) }} · 右侧 {{ formatSec(store.bfRightSeconds) }}{{ store.bfPaused ? ' · 已暂停' : '' }})</small>
</div> </div>
<!-- 未在计时状态下的亲喂模式与时长配置 --> <!-- 未在计时状态下的亲喂模式与时长配置 -->
@@ -455,9 +456,19 @@ async function handleOneClickBreastfeeding() {
round round
type="warning" type="warning"
:disabled="operating" :disabled="operating"
@click="store.switchBreastfeedSide(store.bfActiveSide === 'left' ? 'right' : 'left')" @click="store.bfPaused ? store.resumeBreastfeedTimer(store.bfActiveSide === 'left' ? 'right' : 'left') : store.switchBreastfeedSide(store.bfActiveSide === 'left' ? 'right' : 'left')"
> >
⇄ 切换到{{ store.bfActiveSide === 'left' ? '右侧' : '左侧' }} ⇄ {{ store.bfPaused ? '切换并继续' : '切换到' }}{{ store.bfActiveSide === 'left' ? '右侧' : '左侧' }}
</van-button>
<van-button
block
round
plain
type="primary"
:disabled="operating"
@click="store.bfPaused ? store.resumeBreastfeedTimer() : store.pauseBreastfeedTimer()"
>
{{ store.bfPaused ? '继续亲喂' : '暂停一会' }}
</van-button> </van-button>
<van-button <van-button
block block
@@ -472,7 +483,7 @@ async function handleOneClickBreastfeeding() {
</div> </div>
</div> </div>
<!-- Tab 2: 瓶喂 --> <!-- Tab 2: 挤出母乳 -->
<div v-show="currentFeedingTab === 'bottle'" class="feeding-tab-content"> <div v-show="currentFeedingTab === 'bottle'" class="feeding-tab-content">
<div class="amount-row"> <div class="amount-row">
<span>母乳奶量 (ml)</span> <span>母乳奶量 (ml)</span>
@@ -496,9 +507,9 @@ async function handleOneClickBreastfeeding() {
type="success" type="success"
:loading="operating" :loading="operating"
:disabled="operating" :disabled="operating"
@click="runWithTip(() => store.logFeeding('bottle', bottleAmount), `已记录瓶喂 ${bottleAmount}ml`)" @click="runWithTip(() => store.logFeeding('bottle', bottleAmount), `已记录挤出母乳 ${bottleAmount}ml`)"
> >
记录瓶喂 记录挤出母乳
</van-button> </van-button>
</div> </div>
+189 -5
View File
@@ -1,9 +1,11 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { import {
createBaby, createBaby,
createFamily as apiCreateFamily,
createFeeding, createFeeding,
createManualRecord, createManualRecord,
createMember, createMember,
deleteQuickRule as apiDeleteQuickRule,
createPee, createPee,
createPoop, createPoop,
deleteMember, deleteMember,
@@ -11,26 +13,32 @@ import {
endSleep, endSleep,
getDailySummary, getDailySummary,
getFamilyContext, getFamilyContext,
getQuickRules,
getServerTime,
joinFamily as apiJoinFamily,
setDefaultBaby as apiSetDefaultBaby, setDefaultBaby as apiSetDefaultBaby,
saveQuickRule as apiSaveQuickRule,
startFeeding, startFeeding,
startSleep, startSleep,
updateBaby, updateBaby,
updateCurrentBaby, updateCurrentBaby,
updateFamily, updateFamily,
updateMember, updateMember,
updateRecord, updateRecord
getServerTime
} from '../api/client' } from '../api/client'
import type { import type {
ActionPreferences, ActionPreferences,
BabyProfile, BabyProfile,
CareQuickRule,
CreateBabyPayload, CreateBabyPayload,
CreateFamilyPayload,
CreateManualRecordPayload, CreateManualRecordPayload,
CreateMemberPayload, CreateMemberPayload,
DailySummary, DailySummary,
FamilyContext, FamilyContext,
FamilyMember, FamilyMember,
FeedingMethod, FeedingMethod,
JoinFamilyPayload,
UpdateCareRecordPayload, UpdateCareRecordPayload,
UpdateFamilyPayload, UpdateFamilyPayload,
UpdateMemberPayload UpdateMemberPayload
@@ -59,6 +67,22 @@ function loadInitialPreferences(): ActionPreferences {
let bfTicker: ReturnType<typeof setInterval> | null = null let bfTicker: ReturnType<typeof setInterval> | null = null
interface BreastfeedPauseSegment {
startTime: string
endTime: string
durationSeconds: number
}
function toLocalDateTimeString(date: Date) {
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const hh = String(date.getHours()).padStart(2, '0')
const mm = String(date.getMinutes()).padStart(2, '0')
const ss = String(date.getSeconds()).padStart(2, '0')
return `${y}-${m}-${d}T${hh}:${mm}:${ss}`
}
function startBfTicker(store: any) { function startBfTicker(store: any) {
if (bfTicker) return if (bfTicker) return
bfTicker = setInterval(() => { bfTicker = setInterval(() => {
@@ -66,6 +90,7 @@ function startBfTicker(store: any) {
stopBfTicker() stopBfTicker()
return return
} }
if (store.bfPaused) return
const now = Date.now() const now = Date.now()
const delta = Math.max(0, Math.floor((now - store.bfLastTickTime) / 1000)) const delta = Math.max(0, Math.floor((now - store.bfLastTickTime) / 1000))
if (delta > 0) { if (delta > 0) {
@@ -93,14 +118,19 @@ export const useCareStore = defineStore('care', {
babies: [] as BabyProfile[], babies: [] as BabyProfile[],
members: [] as FamilyMember[], members: [] as FamilyMember[],
selectedBabyId: localStorage.getItem('selectedBabyId') || '', selectedBabyId: localStorage.getItem('selectedBabyId') || '',
activeFamilyId: localStorage.getItem('activeFamilyId') || '',
baby: null as BabyProfile | null, baby: null as BabyProfile | null,
summary: null as DailySummary | null, summary: null as DailySummary | null,
operatorName: localStorage.getItem('operatorName') || '宝妈', operatorName: localStorage.getItem('operatorName') || '宝妈',
preferences: loadInitialPreferences() as ActionPreferences, preferences: loadInitialPreferences() as ActionPreferences,
quickRules: [] as CareQuickRule[],
bfTimerActive: false, bfTimerActive: false,
bfActiveSide: 'left' as 'left' | 'right', bfActiveSide: 'left' as 'left' | 'right',
bfLeftSeconds: 0, bfLeftSeconds: 0,
bfRightSeconds: 0, bfRightSeconds: 0,
bfPaused: false,
bfPauseStartedAt: 0,
bfPauseSegments: [] as BreastfeedPauseSegment[],
bfLastTickTime: 0, bfLastTickTime: 0,
serverOffsetMs: 0, serverOffsetMs: 0,
loading: false, loading: false,
@@ -125,9 +155,16 @@ export const useCareStore = defineStore('care', {
this.error = '' this.error = ''
try { try {
await this.syncServerTime() await this.syncServerTime()
this.context = await getFamilyContext() this.context = await getFamilyContext(this.activeFamilyId)
this.activeFamilyId = this.context.family.familyId
localStorage.setItem('activeFamilyId', this.activeFamilyId)
this.babies = this.context.babies this.babies = this.context.babies
this.members = this.context.members this.members = this.context.members
this.quickRules = await getQuickRules(this.context.family.familyId)
if (this.selectedBabyId && !this.babies.some(baby => baby.babyId === this.selectedBabyId)) {
this.selectedBabyId = ''
localStorage.removeItem('selectedBabyId')
}
if (!this.selectedBabyId && this.babies[0]) { if (!this.selectedBabyId && this.babies[0]) {
this.selectedBabyId = this.babies[0].babyId this.selectedBabyId = this.babies[0].babyId
} }
@@ -144,6 +181,48 @@ export const useCareStore = defineStore('care', {
this.loading = false this.loading = false
} }
}, },
applyFamilyContext(context: FamilyContext) {
this.context = context
this.activeFamilyId = context.family.familyId
localStorage.setItem('activeFamilyId', this.activeFamilyId)
this.babies = context.babies
this.members = context.members
this.quickRules = []
this.selectedBabyId = ''
localStorage.removeItem('selectedBabyId')
const selected = this.babies[0]
this.baby = selected || null
if (selected) {
this.selectedBabyId = selected.babyId
localStorage.setItem('selectedBabyId', selected.babyId)
}
const defaultMember = this.members.find(member => member.defaultOperator) || this.members[0]
if (defaultMember) {
this.setOperatorName(defaultMember.roleName)
}
},
async createFamily(payload: CreateFamilyPayload) {
const context = await apiCreateFamily(payload)
this.applyFamilyContext(context)
await this.reloadQuickRules()
if (this.baby) {
await this.refreshSummary()
} else {
this.summary = null
}
return context
},
async joinFamily(payload: JoinFamilyPayload) {
const context = await apiJoinFamily(payload)
this.applyFamilyContext(context)
await this.reloadQuickRules()
if (this.baby) {
await this.refreshSummary()
} else {
this.summary = null
}
return context
},
async refreshSummary() { async refreshSummary() {
if (!this.baby) return if (!this.baby) return
await this.syncServerTime() await this.syncServerTime()
@@ -164,6 +243,23 @@ export const useCareStore = defineStore('care', {
this.preferences = { ...this.preferences, ...prefs } this.preferences = { ...this.preferences, ...prefs }
localStorage.setItem('actionPreferences', JSON.stringify(this.preferences)) localStorage.setItem('actionPreferences', JSON.stringify(this.preferences))
}, },
async reloadQuickRules() {
const familyId = this.context?.family.familyId
this.quickRules = await getQuickRules(familyId)
},
async addQuickRule(rule: Omit<CareQuickRule, 'ruleId'>) {
const saved = await apiSaveQuickRule(rule)
await this.reloadQuickRules()
return saved
},
async updateQuickRule(ruleId: string, rule: Omit<CareQuickRule, 'ruleId'>) {
await apiSaveQuickRule({ ...rule, ruleId })
await this.reloadQuickRules()
},
async deleteQuickRule(ruleId: string) {
await apiDeleteQuickRule(ruleId)
await this.reloadQuickRules()
},
async saveBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) { async saveBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
this.baby = this.baby ? await updateBaby(this.baby.babyId, payload) : await updateCurrentBaby(payload) this.baby = this.baby ? await updateBaby(this.baby.babyId, payload) : await updateCurrentBaby(payload)
this.babies = this.babies.map(baby => baby.babyId === this.baby?.babyId ? this.baby! : baby) this.babies = this.babies.map(baby => baby.babyId === this.baby?.babyId ? this.baby! : baby)
@@ -226,6 +322,8 @@ export const useCareStore = defineStore('care', {
endTime?: string endTime?: string
leftDurationMinutes?: number leftDurationMinutes?: number
rightDurationMinutes?: number rightDurationMinutes?: number
effectiveFeedingMinutes?: number
pauseSegmentsJson?: string
note?: string note?: string
} | FeedingMethod, } | FeedingMethod,
amountMl?: number, amountMl?: number,
@@ -251,6 +349,8 @@ export const useCareStore = defineStore('care', {
endTime: payloadOrMethod.endTime, endTime: payloadOrMethod.endTime,
leftDurationMinutes: payloadOrMethod.leftDurationMinutes, leftDurationMinutes: payloadOrMethod.leftDurationMinutes,
rightDurationMinutes: payloadOrMethod.rightDurationMinutes, rightDurationMinutes: payloadOrMethod.rightDurationMinutes,
effectiveFeedingMinutes: payloadOrMethod.effectiveFeedingMinutes,
pauseSegmentsJson: payloadOrMethod.pauseSegmentsJson,
note: payloadOrMethod.note, note: payloadOrMethod.note,
operatorName: this.operatorName operatorName: this.operatorName
}) })
@@ -264,6 +364,9 @@ export const useCareStore = defineStore('care', {
activeSide: this.bfActiveSide, activeSide: this.bfActiveSide,
leftSeconds: this.bfLeftSeconds, leftSeconds: this.bfLeftSeconds,
rightSeconds: this.bfRightSeconds, rightSeconds: this.bfRightSeconds,
paused: this.bfPaused,
pauseStartedAt: this.bfPauseStartedAt,
pauseSegments: this.bfPauseSegments,
lastTickTime: this.bfLastTickTime lastTickTime: this.bfLastTickTime
})) }))
} catch { } catch {
@@ -290,9 +393,12 @@ export const useCareStore = defineStore('care', {
this.bfActiveSide = data.activeSide === 'right' ? 'right' : 'left' this.bfActiveSide = data.activeSide === 'right' ? 'right' : 'left'
this.bfLeftSeconds = Number(data.leftSeconds) || 0 this.bfLeftSeconds = Number(data.leftSeconds) || 0
this.bfRightSeconds = Number(data.rightSeconds) || 0 this.bfRightSeconds = Number(data.rightSeconds) || 0
this.bfPaused = !!data.paused
this.bfPauseStartedAt = Number(data.pauseStartedAt) || 0
this.bfPauseSegments = Array.isArray(data.pauseSegments) ? data.pauseSegments : []
const lastTick = Number(data.lastTickTime) || Date.now() const lastTick = Number(data.lastTickTime) || Date.now()
const delta = Math.max(0, Math.floor((Date.now() - lastTick) / 1000)) const delta = Math.max(0, Math.floor((Date.now() - lastTick) / 1000))
if (delta > 0) { if (!this.bfPaused && delta > 0) {
if (this.bfActiveSide === 'left') { if (this.bfActiveSide === 'left') {
this.bfLeftSeconds += delta this.bfLeftSeconds += delta
} else { } else {
@@ -312,6 +418,9 @@ export const useCareStore = defineStore('care', {
this.bfActiveSide = this.preferences.defaultBreastSide || 'left' this.bfActiveSide = this.preferences.defaultBreastSide || 'left'
this.bfLeftSeconds = this.bfActiveSide === 'left' ? totalElapsed : 0 this.bfLeftSeconds = this.bfActiveSide === 'left' ? totalElapsed : 0
this.bfRightSeconds = this.bfActiveSide === 'right' ? totalElapsed : 0 this.bfRightSeconds = this.bfActiveSide === 'right' ? totalElapsed : 0
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfPauseSegments = []
this.bfLastTickTime = Date.now() this.bfLastTickTime = Date.now()
this.bfTimerActive = true this.bfTimerActive = true
} }
@@ -322,6 +431,9 @@ export const useCareStore = defineStore('care', {
this.bfTimerActive = false this.bfTimerActive = false
this.bfLeftSeconds = 0 this.bfLeftSeconds = 0
this.bfRightSeconds = 0 this.bfRightSeconds = 0
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfPauseSegments = []
this.clearBfTimerStorage() this.clearBfTimerStorage()
stopBfTicker() stopBfTicker()
} }
@@ -338,6 +450,9 @@ export const useCareStore = defineStore('care', {
this.bfActiveSide = breastSide this.bfActiveSide = breastSide
this.bfLeftSeconds = 0 this.bfLeftSeconds = 0
this.bfRightSeconds = 0 this.bfRightSeconds = 0
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfPauseSegments = []
this.bfLastTickTime = Date.now() this.bfLastTickTime = Date.now()
this.persistBfTimer() this.persistBfTimer()
startBfTicker(this) startBfTicker(this)
@@ -345,6 +460,11 @@ export const useCareStore = defineStore('care', {
}, },
switchBreastfeedSide(targetSide: 'left' | 'right') { switchBreastfeedSide(targetSide: 'left' | 'right') {
if (!this.bfTimerActive || this.bfActiveSide === targetSide) return if (!this.bfTimerActive || this.bfActiveSide === targetSide) return
if (this.bfPaused) {
this.bfActiveSide = targetSide
this.persistBfTimer()
return
}
const now = Date.now() const now = Date.now()
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000)) const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
if (delta > 0) { if (delta > 0) {
@@ -358,9 +478,54 @@ export const useCareStore = defineStore('care', {
this.bfLastTickTime = now this.bfLastTickTime = now
this.persistBfTimer() this.persistBfTimer()
}, },
pauseBreastfeedTimer() {
if (!this.bfTimerActive || this.bfPaused) return
const now = Date.now()
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
if (delta > 0) {
if (this.bfActiveSide === 'left') {
this.bfLeftSeconds += delta
} else {
this.bfRightSeconds += delta
}
}
this.bfPaused = true
this.bfPauseStartedAt = now
this.bfLastTickTime = now
this.persistBfTimer()
},
resumeBreastfeedTimer(targetSide?: 'left' | 'right') {
if (!this.bfTimerActive || !this.bfPaused) return
const now = Date.now()
const pauseStart = this.bfPauseStartedAt || now
const durationSeconds = Math.max(0, Math.floor((now - pauseStart) / 1000))
this.bfPauseSegments.push({
startTime: toLocalDateTimeString(new Date(pauseStart)),
endTime: toLocalDateTimeString(new Date(now)),
durationSeconds
})
if (targetSide) {
this.bfActiveSide = targetSide
}
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfLastTickTime = now
this.persistBfTimer()
},
async endBreastfeedTimer() { async endBreastfeedTimer() {
if (!this.baby) return if (!this.baby) return
if (this.bfTimerActive) { if (this.bfTimerActive && this.bfPaused) {
const now = Date.now()
const pauseStart = this.bfPauseStartedAt || now
this.bfPauseSegments.push({
startTime: toLocalDateTimeString(new Date(pauseStart)),
endTime: toLocalDateTimeString(new Date(now)),
durationSeconds: Math.max(0, Math.floor((now - pauseStart) / 1000))
})
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfLastTickTime = now
} else if (this.bfTimerActive) {
const now = Date.now() const now = Date.now()
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000)) const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
if (delta > 0) { if (delta > 0) {
@@ -373,18 +538,24 @@ export const useCareStore = defineStore('care', {
} }
const leftMinutes = this.bfLeftSeconds > 0 ? Math.max(1, Math.round(this.bfLeftSeconds / 60)) : 0 const leftMinutes = this.bfLeftSeconds > 0 ? Math.max(1, Math.round(this.bfLeftSeconds / 60)) : 0
const rightMinutes = this.bfRightSeconds > 0 ? Math.max(1, Math.round(this.bfRightSeconds / 60)) : 0 const rightMinutes = this.bfRightSeconds > 0 ? Math.max(1, Math.round(this.bfRightSeconds / 60)) : 0
const effectiveMinutes = leftMinutes + rightMinutes
await endFeeding({ await endFeeding({
babyId: this.baby.babyId, babyId: this.baby.babyId,
breastSide: this.bfActiveSide, breastSide: this.bfActiveSide,
leftDurationMinutes: leftMinutes, leftDurationMinutes: leftMinutes,
rightDurationMinutes: rightMinutes, rightDurationMinutes: rightMinutes,
effectiveFeedingMinutes: effectiveMinutes,
pauseSegmentsJson: this.bfPauseSegments.length ? JSON.stringify(this.bfPauseSegments) : undefined,
operatorName: this.operatorName operatorName: this.operatorName
}) })
this.bfTimerActive = false this.bfTimerActive = false
this.bfLeftSeconds = 0 this.bfLeftSeconds = 0
this.bfRightSeconds = 0 this.bfRightSeconds = 0
this.bfPaused = false
this.bfPauseStartedAt = 0
this.bfPauseSegments = []
this.clearBfTimerStorage() this.clearBfTimerStorage()
stopBfTicker() stopBfTicker()
await this.refreshSummary() await this.refreshSummary()
@@ -426,6 +597,19 @@ export const useCareStore = defineStore('care', {
await this.refreshSummary() await this.refreshSummary()
return res return res
}, },
async manualLogMany(payloads: Array<Omit<CreateManualRecordPayload, 'babyId'>>) {
if (!this.baby || payloads.length === 0) return []
const results = []
for (const payload of payloads) {
const res = await createManualRecord({
...payload,
babyId: this.baby.babyId
})
results.push(res)
}
await this.refreshSummary()
return results
},
async editRecord(recordId: string, payload: UpdateCareRecordPayload) { async editRecord(recordId: string, payload: UpdateCareRecordPayload) {
const res = await updateRecord(recordId, payload) const res = await updateRecord(recordId, payload)
await this.refreshSummary() await this.refreshSummary()
+658
View File
@@ -575,6 +575,313 @@ button {
text-align: right; text-align: right;
} }
.family-overview-panel,
.baby-overview-panel {
display: grid;
gap: 10px;
}
.family-profile {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
padding: 0 0 12px;
border-bottom: 1px solid #f0ece5;
}
.family-profile strong {
display: block;
margin-top: 4px;
color: #17202a;
font-size: 22px;
line-height: 1.2;
word-break: break-word;
}
.family-profile p {
margin: 5px 0 0;
color: #65707d;
font-size: 12px;
line-height: 1.35;
word-break: break-all;
}
.family-profile-label {
display: block;
color: #65707d;
font-size: 13px;
font-weight: 800;
}
.icon-text-button {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 30px;
min-width: 44px;
padding: 6px 10px;
border-radius: 999px;
background: transparent;
color: #6b4a1d;
border: 1px solid #eadfcc;
font-size: 12px;
font-weight: 900;
cursor: pointer;
}
.icon-text-button::before {
content: "";
width: 10px;
height: 10px;
margin-right: 4px;
background: currentColor;
clip-path: polygon(74% 0, 100% 26%, 31% 95%, 0 100%, 5% 69%);
}
.icon-text-button:hover {
background: #eee6d9;
}
.family-compact-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 2px 0;
}
.family-compact-row > span {
color: #65707d;
font-size: 13px;
font-weight: 800;
}
.family-compact-row button {
min-width: 0;
display: inline-flex;
align-items: baseline;
gap: 8px;
padding: 7px 10px;
border-radius: 8px;
background: #faf7f1;
color: #1f2933;
cursor: pointer;
}
.family-compact-row button:active {
background: #f4efe6;
}
.family-compact-row strong {
font-size: 16px;
line-height: 1.2;
}
.family-compact-row small {
color: #8a540d;
font-size: 12px;
font-weight: 800;
}
.family-onboarding-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.family-onboarding-actions button {
padding: 9px 10px;
border-radius: 8px;
background: #f8fafc;
color: #475569;
border: 1px dashed #cbd5e1;
font-size: 13px;
font-weight: 800;
cursor: pointer;
}
.family-onboarding-actions button:active {
background: #eef2f7;
}
.family-core-grid {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
}
.family-core-grid div,
.copy-info-tile {
min-width: 0;
padding: 13px;
border-radius: 8px;
background: #faf7f1;
}
.copy-info-tile {
display: grid;
gap: 5px;
width: 100%;
border: 1px solid transparent;
color: #1f2933;
text-align: left;
cursor: pointer;
}
.copy-info-tile:active {
border-color: #d4c2a1;
background: #f4efe6;
}
.family-core-grid span,
.copy-info-tile span,
.family-id-row span {
display: block;
color: #65707d;
font-size: 12px;
font-weight: 800;
}
.family-core-grid strong,
.copy-info-tile strong {
display: block;
margin-top: 5px;
color: #1f2933;
font-size: 22px;
line-height: 1.25;
word-break: break-word;
}
.copy-info-tile small {
color: #8a540d;
font-size: 12px;
font-weight: 800;
}
.family-id-row {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #f0ece5;
}
.family-id-row strong {
min-width: 0;
color: #1f2933;
font-size: 13px;
text-align: right;
word-break: break-all;
}
.baby-profile {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
padding: 0 0 12px;
border-bottom: 1px solid #f0ece5;
}
.baby-profile strong {
display: block;
margin-top: 4px;
color: #17202a;
font-size: 22px;
line-height: 1.2;
word-break: break-word;
}
.baby-profile p {
margin: 5px 0 0;
color: #65707d;
font-size: 12px;
}
.baby-compact-row {
display: grid;
gap: 4px;
padding: 2px 0 4px;
}
.baby-compact-row span {
color: #65707d;
font-size: 13px;
font-weight: 800;
}
.baby-compact-row strong {
color: #1f2933;
font-size: 14px;
line-height: 1.35;
}
.baby-list {
display: grid;
gap: 6px;
padding-top: 2px;
}
.baby-list-item {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 9px 11px;
border: 1px solid #ebe4d8;
border-radius: 8px;
background: #fffdfa;
color: #1f2933;
text-align: left;
cursor: pointer;
}
.baby-list-item.active {
border-color: #1f7a5c;
background: #effaf5;
}
.baby-list-item span {
display: grid;
gap: 2px;
min-width: 0;
}
.baby-list-item strong {
font-size: 14px;
}
.baby-list-item small {
color: #65707d;
font-size: 12px;
}
.baby-list-item em {
flex: 0 0 auto;
padding: 2px 7px;
border-radius: 6px;
background: #d1fadf;
color: #027a48;
font-size: 11px;
font-style: normal;
font-weight: 800;
}
.baby-default-action {
display: flex;
justify-content: flex-end;
padding-top: 2px;
}
.form-actions {
display: grid;
grid-template-columns: 0.8fr 1.2fr;
gap: 10px;
}
.feeding-status, .feeding-status,
.amount-row, .amount-row,
.two-actions { .two-actions {
@@ -961,6 +1268,25 @@ button {
background: #734509; background: #734509;
} }
.secondary-pill-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 10px 16px;
border-radius: 999px;
background: #f4efe6;
color: #5d6470;
border: 1px solid #e4d8c6;
font-weight: 800;
font-size: 14px;
cursor: pointer;
}
.secondary-pill-button:hover {
background: #eee6d9;
}
.chip-group { .chip-group {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -1106,6 +1432,338 @@ button {
gap: 16px; gap: 16px;
} }
.manual-mode-tabs {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
padding: 4px;
margin-bottom: 16px;
border-radius: 12px;
background: #f4efe6;
}
.manual-mode-tabs button {
padding: 9px 8px;
border-radius: 9px;
background: transparent;
color: #65707d;
font-weight: 800;
cursor: pointer;
}
.manual-mode-tabs button.active {
background: #ffffff;
color: #8a540d;
box-shadow: 0 2px 8px rgba(80, 64, 43, 0.08);
}
.quick-manual-panel {
display: grid;
gap: 14px;
}
.quick-section {
display: grid;
gap: 8px;
color: #4b5563;
font-size: 14px;
font-weight: 800;
}
.quick-label {
color: #4b5563;
font-size: 14px;
font-weight: 800;
}
.quick-rule-grid {
display: grid;
gap: 8px;
}
.quick-rule-card {
display: grid;
gap: 3px;
padding: 11px 12px;
border: 1px solid #ebe4d8;
border-radius: 10px;
background: #fffdfa;
color: #1f2933;
text-align: left;
cursor: pointer;
}
.quick-rule-card.active {
border-color: #b7791f;
background: #fff7e6;
box-shadow: 0 0 0 2px rgba(183, 121, 31, 0.1);
}
.quick-rule-card span {
color: #65707d;
font-size: 12px;
font-weight: 600;
}
.quick-config-hint {
padding: 10px 12px;
border-radius: 10px;
background: #f8fafc;
color: #65707d;
font-size: 12px;
font-weight: 700;
}
.quick-time-presets {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.quick-two-cols,
.draft-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.quick-section input,
.quick-section select,
.draft-fields input,
.draft-fields select {
width: 100%;
border: 1px solid #ded6c8;
border-radius: 10px;
padding: 11px 12px;
background: #fffdfa;
color: #1f2933;
font-size: 14px;
}
.draft-panel {
display: grid;
gap: 10px;
padding-top: 4px;
}
.draft-panel-title {
display: flex;
justify-content: space-between;
gap: 10px;
color: #1f2933;
}
.draft-panel-title span {
color: #65707d;
font-size: 12px;
font-weight: 700;
}
.draft-card {
display: grid;
gap: 10px;
padding: 12px;
border: 1px solid #ebe4d8;
border-radius: 10px;
background: #faf7f1;
}
.draft-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.quick-rule-list,
.quick-rule-editor {
display: grid;
gap: 10px;
}
.quick-rule-editor {
padding-top: 12px;
border-top: 1px solid #f0ece5;
}
.action-mobile-page {
display: grid;
gap: 14px;
}
.action-mobile-card {
display: grid;
gap: 16px;
}
.action-card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.action-card-head h3 {
margin: 3px 0 0;
font-size: 20px;
}
.mini-save-btn {
padding: 8px 14px;
border-radius: 999px;
background: #238565;
color: #ffffff;
font-size: 13px;
font-weight: 800;
}
.mobile-setting-block {
display: grid;
gap: 10px;
}
.mobile-setting-title {
display: flex;
justify-content: space-between;
gap: 10px;
align-items: flex-end;
}
.mobile-setting-title strong {
color: #1f2933;
font-size: 15px;
}
.mobile-setting-title span {
color: #65707d;
font-size: 12px;
font-weight: 700;
}
.mobile-option-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.mobile-option-grid.two {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.mobile-option-grid.three {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.mobile-option {
min-height: 46px;
padding: 10px 8px;
border: 1px solid #eadfce;
border-radius: 12px;
background: #fffdfa;
color: #4b5563;
font-weight: 800;
}
.mobile-option.active {
border-color: #9a5f11;
background: #fff3d7;
color: #74470a;
box-shadow: 0 0 0 2px rgba(154, 95, 17, 0.08);
}
.amount-mobile-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.amount-mobile-row input,
.mobile-rule-editor input,
.mobile-offset-list input {
width: 100%;
border: 1px solid #ded6c8;
border-radius: 12px;
padding: 12px;
background: #fffdfa;
color: #1f2933;
font-size: 16px;
font-weight: 800;
}
.amount-chip-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 6px;
}
.mobile-switch-list {
display: grid;
gap: 8px;
padding-top: 4px;
border-top: 1px solid #f0ece5;
}
.mobile-switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 10px 0;
}
.mobile-switch-row span {
display: grid;
gap: 3px;
}
.mobile-switch-row strong {
color: #1f2933;
font-size: 14px;
}
.mobile-switch-row small {
color: #65707d;
font-size: 12px;
}
.mobile-switch-row input {
width: 24px;
height: 24px;
flex-shrink: 0;
}
.mobile-rule-card {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
}
.mobile-rule-editor label {
display: grid;
gap: 8px;
color: #4b5563;
font-size: 14px;
font-weight: 800;
}
.mobile-offset-list {
display: grid;
gap: 8px;
}
.mobile-offset-list label {
grid-template-columns: 1fr 82px auto;
align-items: center;
}
.mobile-offset-list span {
color: #65707d;
font-size: 12px;
font-weight: 700;
}
.modal-form label { .modal-form label {
display: grid; display: grid;
gap: 6px; gap: 6px;
+30
View File
@@ -1,6 +1,7 @@
export type FeedingMethod = 'breastfeed' | 'bottle' | 'formula' | 'mixed' | 'other' export type FeedingMethod = 'breastfeed' | 'bottle' | 'formula' | 'mixed' | 'other'
export type RecordType = 'feeding' | 'sleep' | 'excretion' export type RecordType = 'feeding' | 'sleep' | 'excretion'
export type ExcretionType = 'pee' | 'poop' export type ExcretionType = 'pee' | 'poop'
export type CareQuickAction = 'diaper' | 'feeding' | 'sleep'
export interface BabyProfile { export interface BabyProfile {
babyId: string babyId: string
@@ -45,6 +46,8 @@ export interface CareRecord {
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null leftDurationMinutes?: number | null
rightDurationMinutes?: number | null rightDurationMinutes?: number | null
effectiveFeedingMinutes?: number | null
pauseSegmentsJson?: string | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -80,6 +83,18 @@ export interface ActionPreferences {
autoBurpReminder: boolean autoBurpReminder: boolean
} }
export interface CareQuickRule {
ruleId: string
familyId: string
name: string
actions: CareQuickAction[]
diaperOffsetMinutes: number
feedingOffsetMinutes: number
sleepAfterFeedingMinutes: number
enabled: boolean
sortOrder: number
}
export interface CreateManualRecordPayload { export interface CreateManualRecordPayload {
babyId: string babyId: string
recordType: RecordType recordType: RecordType
@@ -88,6 +103,8 @@ export interface CreateManualRecordPayload {
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null leftDurationMinutes?: number | null
rightDurationMinutes?: number | null rightDurationMinutes?: number | null
effectiveFeedingMinutes?: number | null
pauseSegmentsJson?: string | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -102,6 +119,8 @@ export interface UpdateCareRecordPayload {
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null leftDurationMinutes?: number | null
rightDurationMinutes?: number | null rightDurationMinutes?: number | null
effectiveFeedingMinutes?: number | null
pauseSegmentsJson?: string | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -123,6 +142,17 @@ export interface UpdateFamilyPayload {
inviteCode?: string | null inviteCode?: string | null
} }
export interface CreateFamilyPayload {
name: string
roleName: string
inviteCode?: string | null
}
export interface JoinFamilyPayload {
inviteCode: string
roleName: string
}
export interface CreateMemberPayload { export interface CreateMemberPayload {
roleName: string roleName: string
roleType?: string roleType?: string
+1 -1
View File
@@ -73,7 +73,7 @@ export function formatMinutes(minutes: number) {
export const FEEDING_METHOD_MAP: Record<string, string> = { export const FEEDING_METHOD_MAP: Record<string, string> = {
breastfeed: '亲喂', breastfeed: '亲喂',
bottle: '瓶喂', bottle: '挤出母乳',
formula: '配方奶', formula: '配方奶',
mixed: '混合喂养', mixed: '混合喂养',
other: '其他' other: '其他'
@@ -0,0 +1,28 @@
# 常用规则补记照护设计与实现记录
## 背景
历史补录场景中,照护者往往记得的是一段连续照护行为,例如“换了尿布、喂了奶、哄睡了”,而不是单条数据库记录。原有补录入口一次只能创建一条照护记录,导致用户需要反复打开弹窗、重复选择时间和记录人。
## 目标
在不推翻单条补录能力的前提下,新增“常用补记”能力:
1. 页面内置固定照护规则,覆盖高频组合。
2. 用户选择日期、时间和少量参数后,前端自动生成多条明细草稿。
3. 用户可确认、删除或轻量修改草稿后再保存。
4. 保存时底层仍写入多条 `care_record`,保持统计、时间线和编辑逻辑不变。
## 本次范围
- 保留原有“补一条详细记录”入口。
- 新增系统内置规则:
- 完整照护:换尿布 + 喂奶 + 睡觉。
- 其他家庭常用补记不再由系统预置,后续在“家庭 · 行为”中独立配置。
- 前端先复用现有 `POST /api/v1/records` 单条接口循环保存。
## 暂不处理
- 暂不新增后端批量事务接口。
- 暂不开放用户自定义规则管理,仅在“家庭 · 行为”中预留独立分区。
- 暂不按宝宝保存独立规则配置,只复用当前宝宝的喂养偏好作为默认参数来源。
@@ -0,0 +1,90 @@
# 2026-09-26 家庭页入口合并与新用户闭环设计
## 背景
当前底部导航已经统一为【今日】、【记录】、【统计】、【家庭】。但家庭页内部仍拆为【宝宝】、【家庭】、【成员】、【行为】四个并列 Tab。对新用户而言,“宝宝”和“家庭”不是两个独立入口,而是同一个照护小家的上下文:一个家庭下可以有多个宝宝,也可以有多个照护成员。
现有实现更偏演示态:后端会返回默认家庭,前端直接展示已有家庭信息。真实新用户需要补齐“无家庭 -> 创建/加入家庭 -> 添加宝宝/成员 -> 开始记录”的闭环。
## 调整目标
1. 合并“宝宝”和“家庭”的导航入口,形成一个默认的“家庭”分区。
2. 保留数据层级:一个家庭下支持多个宝宝、多个成员。
3. 将“宝宝列表管理”和“当前家庭资料”放在同一个上下文中,降低首次理解成本。
4. 为后续创建家庭、通过邀请码加入家庭预留清晰的产品与接口方向。
## 页面结构
家庭页二级分段调整为:
```text
家庭
- 家庭资料:家庭名称、成员加入码、家庭编号
- 宝宝管理:当前照护宝宝、宝宝列表、新增宝宝、编辑宝宝、设为默认宝宝
成员
- 当前记录人
- 成员列表
- 新增/编辑/移除成员
行为
- 喂养、睡眠、补记等照护习惯
```
其中,“当前正在记录哪个宝宝”仍在今日页顶部快速切换;“这个家庭下有哪些宝宝”在家庭页维护。
家庭资料和宝宝档案均默认采用查看态:家庭区域只展示家庭名称、加入码和家庭编号;宝宝数量交由宝宝区域呈现,成员数量交由成员区域呈现。宝宝区域优先展示当前照护宝宝、出生日期、性别和分娩方式。两类信息各自通过“修改”按钮打开独立底部弹窗编辑,避免家庭页首屏一上来就是表单。
## 新用户闭环设计
后续应将家庭上下文分为三种状态:
```text
NO_FAMILY: 当前用户尚未加入任何家庭
NO_BABY: 已有家庭,但家庭下暂无宝宝档案
READY: 已有家庭且至少有一个宝宝
```
### 无家庭态
展示两个主要入口:
- 创建我的家庭
- 加入已有家庭
创建家庭时最少需要:
- 家庭名称
- 我在家里的称谓
- 可选的第一个宝宝档案
加入家庭时最少需要:
- 家庭邀请码
- 我在家里的称谓
### 已有家庭但无宝宝态
展示当前家庭信息和成员信息,主行动改为“添加宝宝信息”。添加宝宝后进入正常记录流程。
## 后端后续方向
建议新增或调整:
- `POST /api/v1/families`:创建家庭,同时创建当前用户的 owner 成员。
- `POST /api/v1/families/join`:通过邀请码加入家庭。
- `POST /api/v1/families/preview-join`:根据邀请码预览家庭名称、宝宝数、成员数。
- `GET /api/v1/families/current-context`:按当前用户归属返回家庭上下文,不再使用全局第一个家庭作为真实业务兜底。
当前无登录阶段可先引入本机访客身份,例如前端持久化 `visitorUserId` 并随请求头传递,后端用它映射 `family_member.user_id`。这样即使尚未接入微信登录,也能区分不同新用户的家庭归属。
## 本次实现范围
本次完成前端信息架构优化:合并“宝宝”和“家庭”两个二级 Tab,让家庭页先展示家庭核心信息,再管理多个宝宝和多个成员。
同时补充无家庭或切换家庭时的基础操作入口:
- 家庭核心信息区域提供“新建家庭”和“加入家庭”。
- 新建家庭创建家庭资料和当前用户的主理人成员。
- 加入家庭通过成员加入码进入已有家庭,并创建当前用户的照护成员。
- 前端记录当前家庭 ID,创建或加入成功后切换到对应家庭上下文。
@@ -0,0 +1,42 @@
# 喂养有效时长与暂停片段记录优化
## 背景
亲喂过程并不总是连续发生。新生儿喂养中常见拍嗝、安抚、调整姿势、短暂哭闹或换尿布等插曲,如果只用 `start_time` 与 `end_time` 推导总时长,会把暂停时间误算为有效喂养时间。
## 设计原则
- `start_time` / `end_time` 保留真实喂养过程跨度,用于还原本次照护发生的时间范围。
- `duration_minutes` 继续保持原有语义:起止时间跨度分钟数,避免影响睡眠与既有逻辑。
- 新增 `effective_feeding_minutes` 记录有效喂养分钟数,仅用于喂养记录,优先取左右侧亲喂时长之和。
- 新增 `pause_segments_json` 暂存暂停片段,先以 JSON 存储,后续如需要精细统计再拆分独立表。
## JSON 结构
`pause_segments_json` 暂定保存数组字符串:
```json
[
{
"startTime": "2026-09-26T22:10:00",
"endTime": "2026-09-26T22:13:00",
"durationSeconds": 180
}
]
```
## 今日页交互
- 亲喂计时中支持暂停。
- 暂停中左右侧有效计时停止。
- 暂停中可继续当前侧,也可点击另一侧后继续。
- 结束亲喂时提交:
- 左右侧有效分钟数;
- `effectiveFeedingMinutes`;
- 暂停片段 JSON。
## 影响范围
- SQL:新增迁移脚本并同步全量建表脚本。
- 后端:`CareRecord`、RO、DTO、VO、转换器与喂养创建/结束逻辑。
- 前端:亲喂计时状态增加暂停中状态与暂停片段持久化。
@@ -6,7 +6,7 @@
本次调整的目标是: 本次调整的目标是:
1. **设置页面全面维护**:宝宝、家庭、成员、行为 4 个 Tab 全面增加在线维护与修改能力; 1. **设置页面全面维护**:宝宝、家庭、成员、行为 4 个 Tab 全面增加在线维护与修改能力;
2. **流水内容可编辑与补录**:支持对喂养(亲喂/瓶喂)、睡眠、排泄三大类记录进行补录,并支持对已产生的流水进行修改更新。 2. **流水内容可编辑与补录**:支持对喂养(亲喂/挤出母乳)、睡眠、排泄三大类记录进行补录,并支持对已产生的流水进行修改更新。
--- ---
@@ -25,7 +25,7 @@
### 2.3 照护记录模块 (`CareRecordController` / `CareRecordService`) ### 2.3 照护记录模块 (`CareRecordController` / `CareRecordService`)
- `POST /api/v1/records`: 照护记录手动补录通用接口 (`CreateManualRecordRequest`): - `POST /api/v1/records`: 照护记录手动补录通用接口 (`CreateManualRecordRequest`):
- 支持喂养(瓶喂/亲喂、奶量/时长/喂奶侧)、睡眠(起止时间、睡眠时长)、排泄(小便/大便、性状颜色); - 支持喂养(挤出母乳/亲喂、奶量/时长/喂奶侧)、睡眠(起止时间、睡眠时长)、排泄(小便/大便、性状颜色);
- 支持指定发生时间、记录人及备注标签。 - 支持指定发生时间、记录人及备注标签。
- `PUT /api/v1/records/{recordId}`: 照护记录编辑修改接口 (`UpdateCareRecordRequest`),支持全字段覆写更新与时间范围修正。 - `PUT /api/v1/records/{recordId}`: 照护记录编辑修改接口 (`UpdateCareRecordRequest`),支持全字段覆写更新与时间范围修正。
@@ -55,7 +55,7 @@
- 支持一键快捷切换当前记录人(如妈妈喂奶交班给爸爸); - 支持一键快捷切换当前记录人(如妈妈喂奶交班给爸爸);
- 支持点击成员编辑角色称谓、提供「+ 添加成员」抽屉及「移除」确认操作。 - 支持点击成员编辑角色称谓、提供「+ 添加成员」抽屉及「移除」确认操作。
4. **行为偏好设置**: 4. **行为偏好设置**:
- 喂养偏好:默认喂养方式(亲喂/瓶喂/配方奶)、单次推荐奶量、间隔提醒; - 喂养偏好:默认喂养方式(亲喂/挤出母乳/配方奶)、单次推荐奶量、间隔提醒;
- 睡眠偏好:默认入睡辅助提示、睡眠时长预估; - 睡眠偏好:默认入睡辅助提示、睡眠时长预估;
- 排泄偏好:排泄观察关注项(小便量、便便性状等); - 排泄偏好:排泄观察关注项(小便量、便便性状等);
- 记录辅助:快速备注预设词、防误触确认开关,保存后即刻生效。 - 记录辅助:快速备注预设词、防误触确认开关,保存后即刻生效。
@@ -3,29 +3,29 @@
## 1. 背景与业务目标 ## 1. 背景与业务目标
- **当前现状**: - **当前现状**:
在【今日】(`TodayPage.vue`)照护首页中,“亲喂”与“瓶喂”各自占用独立的卡片面板,垂直占用了较多屏幕空间;同时,系统定义的基础喂养方式中的另外两种——**“配方奶 (formula)”**与**“混合喂养 (mixed)”**无法直接在今日首页快速录入,导致操作能力不全。 在【今日】(`TodayPage.vue`)照护首页中,“亲喂”与“挤出母乳”各自占用独立的卡片面板,垂直占用了较多屏幕空间;同时,系统定义的基础喂养方式中的另外两种——**“配方奶 (formula)”**与**“混合喂养 (mixed)”**无法直接在今日首页快速录入,导致操作能力不全。
- **优化目标**: - **优化目标**:
将“亲喂”、“瓶喂”、“配方奶”、“混合喂养”四大高频喂养方式合并收敛为统一的**【喂养】**面板,通过亲切友好的二级 Tab / 分段选择器(Segmented Tabs)切换,实现四合一极简高效操作。 将“亲喂”、“挤出母乳”、“配方奶”、“混合喂养”四大高频喂养方式合并收敛为统一的**【喂养】**面板,通过亲切友好的二级 Tab / 分段选择器(Segmented Tabs)切换,实现四合一极简高效操作。
--- ---
## 2. 交互与功能设计 ## 2. 交互与功能设计
### 2.1 面板布局结构 ### 2.1 面板布局结构
在【今日】页面中,原“亲喂”与“瓶喂”两个 Panel 合并为一个标准的【喂养】Panel: 在【今日】页面中,原“亲喂”与“挤出母乳”两个 Panel 合并为一个标准的【喂养】Panel:
``` ```
┌────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────┐
│ 喂养 [亲喂进行中] │ │ 喂养 [亲喂进行中] │
│ [ 亲喂 ] [ 瓶喂 ] [ 配方奶 ] [ 混合喂养 ] │ │ [ 亲喂 ] [ 挤出母乳 ] [ 配方奶 ] [ 混合喂养 ] │
├────────────────────────────────────────────────────────┤ ├────────────────────────────────────────────────────────┤
│ Tab 1: 亲喂 │ │ Tab 1: 亲喂 │
│ - 左右侧分别耗时卡片与计时状态 (00:00) │ │ - 左右侧分别耗时卡片与计时状态 (00:00) │
│ - 亲喂模式 (双侧/仅左/仅右) & 快捷耗时胶囊 │ │ - 亲喂模式 (双侧/仅左/仅右) & 快捷耗时胶囊 │
│ - 开始亲喂 / 一键记录 / 切换侧别 / 结束亲喂 │ │ - 开始亲喂 / 一键记录 / 切换侧别 / 结束亲喂 │
├────────────────────────────────────────────────────────┤ ├────────────────────────────────────────────────────────┤
│ Tab 2: 瓶喂 │ │ Tab 2: 挤出母乳 │
│ - 奶量步进器 (ml) & 30/60/90/120ml 快捷选项 │ │ - 奶量步进器 (ml) & 30/60/90/120ml 快捷选项 │
│ - 记录瓶喂按钮 │ │ - 记录挤出母乳按钮 │
├────────────────────────────────────────────────────────┤ ├────────────────────────────────────────────────────────┤
│ Tab 3: 配方奶 │ │ Tab 3: 配方奶 │
│ - 奶量步进器 (ml) & 快捷奶量选项 │ │ - 奶量步进器 (ml) & 快捷奶量选项 │
@@ -52,5 +52,5 @@
## 3. 验收标准 ## 3. 验收标准
1. 页面无两个分散的喂养面板,整合成一个带有 4 种喂养子 Tab 的统一卡片; 1. 页面无两个分散的喂养面板,整合成一个带有 4 种喂养子 Tab 的统一卡片;
2. 亲喂计时进行中不影响切换 Tab 查阅,切回亲喂 Tab 计时状态完全保持; 2. 亲喂计时进行中不影响切换 Tab 查阅,切回亲喂 Tab 计时状态完全保持;
3. 瓶喂、配方奶、混合喂养均可调节奶量并一键记录,数据正确计入今日统计与流水; 3. 挤出母乳、配方奶、混合喂养均可调节奶量并一键记录,数据正确计入今日统计与流水;
4. `npm run build` 前端编译与类型校验 100% 通过。 4. `npm run build` 前端编译与类型校验 100% 通过。
+3
View File
@@ -22,10 +22,13 @@
- [2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md](./2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md): 流水编辑弹窗位置修复与亲喂总时长起止时间优化记录。 - [2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md](./2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md): 流水编辑弹窗位置修复与亲喂总时长起止时间优化记录。
- [2026-09-26-navigation-tabs-wording-optimization.md](./2026-09-26-navigation-tabs-wording-optimization.md): 底部导航与页面文案贴心化(今日·记录·统计·家庭)优化记录。 - [2026-09-26-navigation-tabs-wording-optimization.md](./2026-09-26-navigation-tabs-wording-optimization.md): 底部导航与页面文案贴心化(今日·记录·统计·家庭)优化记录。
- [2026-09-26-breastfeeding-split-duration-fields.md](./2026-09-26-breastfeeding-split-duration-fields.md): 亲喂左右侧时长独立字段架构设计与落地记录。 - [2026-09-26-breastfeeding-split-duration-fields.md](./2026-09-26-breastfeeding-split-duration-fields.md): 亲喂左右侧时长独立字段架构设计与落地记录。
- [2026-09-26-feeding-effective-duration-and-pauses.md](./2026-09-26-feeding-effective-duration-and-pauses.md): 喂养有效时长与暂停片段 JSON 存储设计。
- [2026-09-26-server-time-sync-and-date-consistency.md](./2026-09-26-server-time-sync-and-date-consistency.md): 服务器时间同步与全端时区日期一致性设计方案。 - [2026-09-26-server-time-sync-and-date-consistency.md](./2026-09-26-server-time-sync-and-date-consistency.md): 服务器时间同步与全端时区日期一致性设计方案。
- [2026-09-26-today-feeding-tabs-unification.md](./2026-09-26-today-feeding-tabs-unification.md): 今日主页四大喂养方式聚合 Tab 设计方案。 - [2026-09-26-today-feeding-tabs-unification.md](./2026-09-26-today-feeding-tabs-unification.md): 今日主页四大喂养方式聚合 Tab 设计方案。
- [2026-09-26-today-action-debounce-and-disable.md](./2026-09-26-today-action-debounce-and-disable.md): 今日照护操作防重与接口响应置灰机制方案。 - [2026-09-26-today-action-debounce-and-disable.md](./2026-09-26-today-action-debounce-and-disable.md): 今日照护操作防重与接口响应置灰机制方案。
- [2026-09-26-server-shanghai-timezone-and-timeline-grouping.md](./2026-09-26-server-shanghai-timezone-and-timeline-grouping.md): 照护记录页面按日分组优化与服务端上海时区校准设计方案。 - [2026-09-26-server-shanghai-timezone-and-timeline-grouping.md](./2026-09-26-server-shanghai-timezone-and-timeline-grouping.md): 照护记录页面按日分组优化与服务端上海时区校准设计方案。
- [2026-09-26-care-rule-quick-manual-log.md](./2026-09-26-care-rule-quick-manual-log.md): 常用规则补记照护与多条明细草稿确认方案。
- [2026-09-26-family-home-and-onboarding.md](./2026-09-26-family-home-and-onboarding.md): 家庭页入口合并、多宝宝/多成员层级与新用户创建/加入家庭闭环设计。
## 记录原则 ## 记录原则
@@ -55,6 +55,20 @@ public class BabyService {
return BabyConvert.toVOList(babies); return BabyConvert.toVOList(babies);
} }
public List<BabyVO> listBabies(String familyId) {
if (familyId == null || familyId.trim().isEmpty()) {
return listBabies();
}
List<BabyProfile> babies = babyMapper.selectList(
new LambdaQueryWrapper<BabyProfile>()
.eq(BabyProfile::getFamilyId, familyId)
.eq(BabyProfile::getStatus, "active")
.orderByDesc(BabyProfile::getIsDefault)
.orderByAsc(BabyProfile::getBabyId)
);
return BabyConvert.toVOList(babies);
}
public BabyVO updateCurrentBaby(UpdateBabyRO request) { public BabyVO updateCurrentBaby(UpdateBabyRO request) {
BabyProfile currentBaby = getCurrentBabyEntity(); BabyProfile currentBaby = getCurrentBabyEntity();
return updateBaby(currentBaby.getBabyId(), request); return updateBaby(currentBaby.getBabyId(), request);
@@ -0,0 +1,68 @@
package com.babytracker.module.family;
import com.babytracker.common.model.BaseEntity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("care_quick_rule")
public class CareQuickRule extends BaseEntity {
/**
* 常用补记规则ID,雪花ID字符串
*/
@TableId(value = "id", type = IdType.INPUT)
private String ruleId;
/**
* 家庭ID
*/
@TableField("family_id")
private String familyId;
/**
* 规则名称
*/
@TableField("name")
private String name;
/**
* 动作列表,英文逗号分隔: diaper,feeding,sleep
*/
@TableField("actions")
private String actions;
/**
* 尿布动作相对起点偏移分钟
*/
@TableField("diaper_offset_minutes")
private Integer diaperOffsetMinutes;
/**
* 喂奶动作相对起点偏移分钟
*/
@TableField("feeding_offset_minutes")
private Integer feedingOffsetMinutes;
/**
* 喂奶结束后多久开始睡眠
*/
@TableField("sleep_after_feeding_minutes")
private Integer sleepAfterFeedingMinutes;
/**
* 是否启用
*/
@TableField("enabled")
private Boolean enabled;
/**
* 排序
*/
@TableField("sort_order")
private Integer sortOrder;
}
@@ -1,10 +1,15 @@
package com.babytracker.module.family; package com.babytracker.module.family;
import com.babytracker.common.response.ApiResponse; import com.babytracker.common.response.ApiResponse;
import com.babytracker.module.family.ro.CreateFamilyRO;
import com.babytracker.module.family.ro.CreateMemberRO; import com.babytracker.module.family.ro.CreateMemberRO;
import com.babytracker.module.family.ro.DeleteCareQuickRuleRO;
import com.babytracker.module.family.ro.DeleteMemberRO; import com.babytracker.module.family.ro.DeleteMemberRO;
import com.babytracker.module.family.ro.JoinFamilyRO;
import com.babytracker.module.family.ro.SaveCareQuickRuleRO;
import com.babytracker.module.family.ro.UpdateFamilyRO; import com.babytracker.module.family.ro.UpdateFamilyRO;
import com.babytracker.module.family.ro.UpdateMemberRO; import com.babytracker.module.family.ro.UpdateMemberRO;
import com.babytracker.module.family.vo.CareQuickRuleVO;
import com.babytracker.module.family.vo.FamilyContextVO; import com.babytracker.module.family.vo.FamilyContextVO;
import com.babytracker.module.family.vo.FamilyMemberVO; import com.babytracker.module.family.vo.FamilyMemberVO;
import com.babytracker.module.family.vo.FamilyVO; import com.babytracker.module.family.vo.FamilyVO;
@@ -16,8 +21,11 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Validated @Validated
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -26,8 +34,18 @@ public class FamilyController {
private final FamilyService familyService; private final FamilyService familyService;
@GetMapping("/current-context") @GetMapping("/current-context")
public ApiResponse<FamilyContextVO> currentContext() { public ApiResponse<FamilyContextVO> currentContext(@RequestParam(required = false) String familyId) {
return ApiResponse.ok(familyService.getCurrentContext()); return ApiResponse.ok(familyService.getCurrentContext(familyId));
}
@PostMapping
public ApiResponse<FamilyContextVO> createFamily(@Valid @RequestBody CreateFamilyRO request) {
return ApiResponse.ok(familyService.createFamily(request));
}
@PostMapping("/join")
public ApiResponse<FamilyContextVO> joinFamily(@Valid @RequestBody JoinFamilyRO request) {
return ApiResponse.ok(familyService.joinFamily(request));
} }
@PutMapping @PutMapping
@@ -50,4 +68,20 @@ public class FamilyController {
familyService.deleteMember(request.getFamilyId(), request.getMemberId()); familyService.deleteMember(request.getFamilyId(), request.getMemberId());
return ApiResponse.ok(null); return ApiResponse.ok(null);
} }
@GetMapping("/quick-rules")
public ApiResponse<List<CareQuickRuleVO>> listQuickRules(@RequestParam(required = false) String familyId) {
return ApiResponse.ok(familyService.listQuickRules(familyId));
}
@PostMapping("/quick-rules")
public ApiResponse<CareQuickRuleVO> saveQuickRule(@Valid @RequestBody SaveCareQuickRuleRO request) {
return ApiResponse.ok(familyService.saveQuickRule(request));
}
@PostMapping("/quick-rules/delete")
public ApiResponse<Void> deleteQuickRule(@Valid @RequestBody DeleteCareQuickRuleRO request) {
familyService.deleteQuickRule(request);
return ApiResponse.ok(null);
}
} }
@@ -6,9 +6,15 @@ import com.babytracker.module.baby.BabyService;
import com.babytracker.module.family.dto.FamilyConvert; import com.babytracker.module.family.dto.FamilyConvert;
import com.babytracker.module.family.mapper.FamilyMapper; import com.babytracker.module.family.mapper.FamilyMapper;
import com.babytracker.module.family.mapper.FamilyMemberMapper; import com.babytracker.module.family.mapper.FamilyMemberMapper;
import com.babytracker.module.family.mapper.CareQuickRuleMapper;
import com.babytracker.module.family.ro.CreateFamilyRO;
import com.babytracker.module.family.ro.DeleteCareQuickRuleRO;
import com.babytracker.module.family.ro.SaveCareQuickRuleRO;
import com.babytracker.module.family.ro.CreateMemberRO; import com.babytracker.module.family.ro.CreateMemberRO;
import com.babytracker.module.family.ro.JoinFamilyRO;
import com.babytracker.module.family.ro.UpdateFamilyRO; import com.babytracker.module.family.ro.UpdateFamilyRO;
import com.babytracker.module.family.ro.UpdateMemberRO; import com.babytracker.module.family.ro.UpdateMemberRO;
import com.babytracker.module.family.vo.CareQuickRuleVO;
import com.babytracker.module.family.vo.FamilyContextVO; import com.babytracker.module.family.vo.FamilyContextVO;
import com.babytracker.module.family.vo.FamilyMemberVO; import com.babytracker.module.family.vo.FamilyMemberVO;
import com.babytracker.module.family.vo.FamilyVO; import com.babytracker.module.family.vo.FamilyVO;
@@ -17,21 +23,77 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class FamilyService { public class FamilyService {
private final FamilyMapper familyMapper; private final FamilyMapper familyMapper;
private final FamilyMemberMapper familyMemberMapper; private final FamilyMemberMapper familyMemberMapper;
private final CareQuickRuleMapper careQuickRuleMapper;
private final BabyService babyService; private final BabyService babyService;
private final SnowflakeIdGenerator idGenerator; private final SnowflakeIdGenerator idGenerator;
public FamilyContextVO getCurrentContext() { public FamilyContextVO getCurrentContext() {
FamilyInfo family = getDefaultFamily(); return getCurrentContext(null);
}
public FamilyContextVO getCurrentContext(String familyId) {
FamilyInfo family = resolveFamily(familyId);
return buildContext(family);
}
public FamilyContextVO createFamily(CreateFamilyRO request) {
FamilyInfo family = new FamilyInfo();
family.setFamilyId(idGenerator.nextId());
family.setName(request.getName().trim());
family.setInviteCode(resolveInviteCode(request.getInviteCode()));
family.setStatus("active");
familyMapper.insert(family);
FamilyMember member = new FamilyMember();
member.setMemberId(idGenerator.nextId());
member.setFamilyId(family.getFamilyId());
member.setRoleName(request.getRoleName().trim());
member.setRoleType("owner");
member.setDefaultOperator(true);
member.setStatus("active");
familyMemberMapper.insert(member);
return buildContext(family);
}
public FamilyContextVO joinFamily(JoinFamilyRO request) {
String inviteCode = normalizeInviteCode(request.getInviteCode());
FamilyInfo family = familyMapper.selectOne(
new LambdaQueryWrapper<FamilyInfo>()
.eq(FamilyInfo::getInviteCode, inviteCode)
.eq(FamilyInfo::getStatus, "active")
.last("LIMIT 1")
);
if (family == null) {
throw new BusinessException("FAMILY_INVITE_CODE_INVALID", "未找到对应家庭");
}
FamilyMember member = new FamilyMember();
member.setMemberId(idGenerator.nextId());
member.setFamilyId(family.getFamilyId());
member.setRoleName(request.getRoleName().trim());
member.setRoleType("caregiver");
member.setDefaultOperator(false);
member.setStatus("active");
familyMemberMapper.insert(member);
return buildContext(family);
}
private FamilyContextVO buildContext(FamilyInfo family) {
FamilyContextVO context = new FamilyContextVO(); FamilyContextVO context = new FamilyContextVO();
context.setFamily(FamilyConvert.toVO(family)); context.setFamily(FamilyConvert.toVO(family));
context.setBabies(babyService.listBabies()); context.setBabies(babyService.listBabies(family.getFamilyId()));
context.setMembers(FamilyConvert.toMemberVOList(listMembers(family.getFamilyId()))); context.setMembers(FamilyConvert.toMemberVOList(listMembers(family.getFamilyId())));
return context; return context;
} }
@@ -135,6 +197,62 @@ public class FamilyService {
familyMemberMapper.deleteById(memberId); familyMemberMapper.deleteById(memberId);
} }
public List<CareQuickRuleVO> listQuickRules(String familyId) {
if (familyId == null || familyId.trim().isEmpty()) {
familyId = getDefaultFamily().getFamilyId();
}
List<CareQuickRule> rules = careQuickRuleMapper.selectList(
new LambdaQueryWrapper<CareQuickRule>()
.eq(CareQuickRule::getFamilyId, familyId)
.orderByAsc(CareQuickRule::getSortOrder)
.orderByAsc(CareQuickRule::getRuleId)
);
List<CareQuickRuleVO> result = new ArrayList<>(rules.size());
for (CareQuickRule rule : rules) {
result.add(toQuickRuleVO(rule));
}
return result;
}
public CareQuickRuleVO saveQuickRule(SaveCareQuickRuleRO request) {
String familyId = request.getFamilyId();
if (familyId == null || familyId.trim().isEmpty()) {
familyId = getDefaultFamily().getFamilyId();
}
CareQuickRule rule;
if (request.getRuleId() == null || request.getRuleId().trim().isEmpty()) {
rule = new CareQuickRule();
rule.setRuleId(idGenerator.nextId());
rule.setFamilyId(familyId);
} else {
rule = careQuickRuleMapper.selectById(request.getRuleId());
if (rule == null) {
throw new BusinessException("QUICK_RULE_NOT_FOUND", "常用补记不存在");
}
}
rule.setName(request.getName().trim());
rule.setActions(String.join(",", request.getActions()));
rule.setDiaperOffsetMinutes(request.getDiaperOffsetMinutes() == null ? 0 : request.getDiaperOffsetMinutes());
rule.setFeedingOffsetMinutes(request.getFeedingOffsetMinutes() == null ? 5 : request.getFeedingOffsetMinutes());
rule.setSleepAfterFeedingMinutes(request.getSleepAfterFeedingMinutes() == null ? 5 : request.getSleepAfterFeedingMinutes());
rule.setEnabled(request.getEnabled() == null || request.getEnabled());
rule.setSortOrder(request.getSortOrder() == null ? 100 : request.getSortOrder());
if (request.getRuleId() == null || request.getRuleId().trim().isEmpty()) {
careQuickRuleMapper.insert(rule);
} else {
careQuickRuleMapper.updateById(rule);
}
return toQuickRuleVO(rule);
}
public void deleteQuickRule(DeleteCareQuickRuleRO request) {
CareQuickRule rule = careQuickRuleMapper.selectById(request.getRuleId());
if (rule == null) {
throw new BusinessException("QUICK_RULE_NOT_FOUND", "常用补记不存在");
}
careQuickRuleMapper.deleteById(request.getRuleId());
}
public FamilyInfo getDefaultFamily() { public FamilyInfo getDefaultFamily() {
FamilyInfo family = familyMapper.selectOne( FamilyInfo family = familyMapper.selectOne(
new LambdaQueryWrapper<FamilyInfo>() new LambdaQueryWrapper<FamilyInfo>()
@@ -152,6 +270,59 @@ public class FamilyService {
return defaultFamily; return defaultFamily;
} }
private FamilyInfo resolveFamily(String familyId) {
if (familyId != null && !familyId.trim().isEmpty()) {
FamilyInfo family = familyMapper.selectById(familyId.trim());
if (family == null) {
throw new BusinessException("FAMILY_NOT_FOUND", "家庭不存在");
}
return family;
}
return getDefaultFamily();
}
private String resolveInviteCode(String inviteCode) {
String normalized = normalizeInviteCode(inviteCode);
if (!normalized.isEmpty()) {
ensureInviteCodeUnused(normalized);
return normalized;
}
String generated;
do {
generated = randomInviteCode();
} while (inviteCodeExists(generated));
return generated;
}
private String normalizeInviteCode(String inviteCode) {
return inviteCode == null ? "" : inviteCode.trim().toUpperCase(Locale.ROOT);
}
private void ensureInviteCodeUnused(String inviteCode) {
if (inviteCodeExists(inviteCode)) {
throw new BusinessException("FAMILY_INVITE_CODE_EXISTS", "成员加入码已被使用");
}
}
private boolean inviteCodeExists(String inviteCode) {
Long count = familyMapper.selectCount(
new LambdaQueryWrapper<FamilyInfo>()
.eq(FamilyInfo::getInviteCode, inviteCode)
);
return count != null && count > 0;
}
private String randomInviteCode() {
String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
StringBuilder code = new StringBuilder("BT");
long seed = Math.abs(idGenerator.nextId().hashCode());
for (int i = 0; i < 4; i++) {
int index = (int) ((seed + i * 17) % chars.length());
code.append(chars.charAt(index));
}
return code.toString();
}
public List<FamilyMember> listMembers(String familyId) { public List<FamilyMember> listMembers(String familyId) {
List<FamilyMember> members = familyMemberMapper.selectList( List<FamilyMember> members = familyMemberMapper.selectList(
new LambdaQueryWrapper<FamilyMember>() new LambdaQueryWrapper<FamilyMember>()
@@ -175,4 +346,21 @@ public class FamilyService {
mom.setDefaultOperator(true); mom.setDefaultOperator(true);
return List.of(mom); return List.of(mom);
} }
private CareQuickRuleVO toQuickRuleVO(CareQuickRule rule) {
CareQuickRuleVO vo = new CareQuickRuleVO();
vo.setRuleId(rule.getRuleId());
vo.setFamilyId(rule.getFamilyId());
vo.setName(rule.getName());
vo.setActions(Arrays.stream(rule.getActions().split(","))
.map(String::trim)
.filter(item -> !item.isEmpty())
.toList());
vo.setDiaperOffsetMinutes(rule.getDiaperOffsetMinutes());
vo.setFeedingOffsetMinutes(rule.getFeedingOffsetMinutes());
vo.setSleepAfterFeedingMinutes(rule.getSleepAfterFeedingMinutes());
vo.setEnabled(rule.getEnabled());
vo.setSortOrder(rule.getSortOrder());
return vo;
}
} }
@@ -0,0 +1,9 @@
package com.babytracker.module.family.mapper;
import com.babytracker.module.family.CareQuickRule;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CareQuickRuleMapper extends BaseMapper<CareQuickRule> {
}
@@ -0,0 +1,24 @@
package com.babytracker.module.family.ro;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class CreateFamilyRO {
/**
* 家庭名称,必填
*/
@NotBlank(message = "家庭名称不能为空")
private String name;
/**
* 当前用户在家庭里的称谓,必填,如宝妈、宝爸、奶奶
*/
@NotBlank(message = "成员称谓不能为空")
private String roleName;
/**
* 家庭成员加入码,选填;为空时由后端生成
*/
private String inviteCode;
}
@@ -0,0 +1,13 @@
package com.babytracker.module.family.ro;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class DeleteCareQuickRuleRO {
/**
* 规则ID
*/
@NotBlank(message = "规则ID不能为空")
private String ruleId;
}
@@ -0,0 +1,19 @@
package com.babytracker.module.family.ro;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class JoinFamilyRO {
/**
* 家庭成员加入码,必填
*/
@NotBlank(message = "成员加入码不能为空")
private String inviteCode;
/**
* 当前用户在家庭里的称谓,必填,如宝妈、宝爸、奶奶
*/
@NotBlank(message = "成员称谓不能为空")
private String roleName;
}
@@ -0,0 +1,57 @@
package com.babytracker.module.family.ro;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
@Data
public class SaveCareQuickRuleRO {
/**
* 规则ID,新增时为空,更新时必填
*/
private String ruleId;
/**
* 家庭ID,可为空,默认使用当前家庭
*/
private String familyId;
/**
* 规则名称
*/
@NotBlank(message = "规则名称不能为空")
private String name;
/**
* 动作列表: diaper, feeding, sleep
*/
@NotEmpty(message = "至少选择一个照护动作")
private List<String> actions;
/**
* 尿布动作相对起点偏移分钟
*/
private Integer diaperOffsetMinutes;
/**
* 喂奶动作相对起点偏移分钟
*/
private Integer feedingOffsetMinutes;
/**
* 喂奶结束后多久开始睡眠
*/
private Integer sleepAfterFeedingMinutes;
/**
* 是否启用
*/
private Boolean enabled;
/**
* 排序
*/
private Integer sortOrder;
}
@@ -0,0 +1,53 @@
package com.babytracker.module.family.vo;
import lombok.Data;
import java.util.List;
@Data
public class CareQuickRuleVO {
/**
* 规则ID
*/
private String ruleId;
/**
* 家庭ID
*/
private String familyId;
/**
* 规则名称
*/
private String name;
/**
* 动作列表
*/
private List<String> actions;
/**
* 尿布动作相对起点偏移分钟
*/
private Integer diaperOffsetMinutes;
/**
* 喂奶动作相对起点偏移分钟
*/
private Integer feedingOffsetMinutes;
/**
* 喂奶结束后多久开始睡眠
*/
private Integer sleepAfterFeedingMinutes;
/**
* 是否启用
*/
private Boolean enabled;
/**
* 排序
*/
private Integer sortOrder;
}
@@ -70,6 +70,18 @@ public class CareRecord extends BaseEntity {
@TableField("right_duration_minutes") @TableField("right_duration_minutes")
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停,仅喂养记录使用)
*/
@TableField("effective_feeding_minutes")
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON(记录暂停开始、结束与持续秒数)
*/
@TableField("pause_segments_json")
private String pauseSegmentsJson;
/** /**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他) * 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/ */
@@ -69,6 +69,8 @@ public class CareRecordService {
record.setEndTime(endTime); record.setEndTime(endTime);
record.setLeftDurationMinutes(request.getLeftDurationMinutes()); record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes()); record.setRightDurationMinutes(request.getRightDurationMinutes());
record.setEffectiveFeedingMinutes(resolveEffectiveFeedingMinutes(request.getEffectiveFeedingMinutes(), request.getLeftDurationMinutes(), request.getRightDurationMinutes(), duration));
record.setPauseSegmentsJson(normalizeBlank(request.getPauseSegmentsJson()));
if (duration != null) { if (duration != null) {
record.setDurationMinutes(duration); record.setDurationMinutes(duration);
} else if (record.getStartTime() != null && record.getEndTime() != null) { } else if (record.getStartTime() != null && record.getEndTime() != null) {
@@ -87,6 +89,8 @@ public class CareRecordService {
record.setFeedingMethod("breastfeed"); record.setFeedingMethod("breastfeed");
record.setLeftDurationMinutes(request.getLeftDurationMinutes()); record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes()); record.setRightDurationMinutes(request.getRightDurationMinutes());
record.setEffectiveFeedingMinutes(request.getEffectiveFeedingMinutes());
record.setPauseSegmentsJson(normalizeBlank(request.getPauseSegmentsJson()));
careRecordMapper.insert(record); careRecordMapper.insert(record);
return CareRecordConvert.toVO(record); return CareRecordConvert.toVO(record);
} }
@@ -107,6 +111,12 @@ public class CareRecordService {
if (request.getRightDurationMinutes() != null) { if (request.getRightDurationMinutes() != null) {
activeFeeding.setRightDurationMinutes(request.getRightDurationMinutes()); activeFeeding.setRightDurationMinutes(request.getRightDurationMinutes());
} }
if (request.getEffectiveFeedingMinutes() != null) {
activeFeeding.setEffectiveFeedingMinutes(request.getEffectiveFeedingMinutes());
}
if (request.getPauseSegmentsJson() != null) {
activeFeeding.setPauseSegmentsJson(normalizeBlank(request.getPauseSegmentsJson()));
}
if (request.getRemark() != null) { if (request.getRemark() != null) {
activeFeeding.setRemark(request.getRemark().trim().isEmpty() ? null : request.getRemark().trim()); activeFeeding.setRemark(request.getRemark().trim().isEmpty() ? null : request.getRemark().trim());
} }
@@ -114,6 +124,9 @@ public class CareRecordService {
if (request.getLeftDurationMinutes() != null || request.getRightDurationMinutes() != null) { if (request.getLeftDurationMinutes() != null || request.getRightDurationMinutes() != null) {
int sumSplit = (activeFeeding.getLeftDurationMinutes() == null ? 0 : activeFeeding.getLeftDurationMinutes()) int sumSplit = (activeFeeding.getLeftDurationMinutes() == null ? 0 : activeFeeding.getLeftDurationMinutes())
+ (activeFeeding.getRightDurationMinutes() == null ? 0 : activeFeeding.getRightDurationMinutes()); + (activeFeeding.getRightDurationMinutes() == null ? 0 : activeFeeding.getRightDurationMinutes());
if (activeFeeding.getEffectiveFeedingMinutes() == null && sumSplit > 0) {
activeFeeding.setEffectiveFeedingMinutes(sumSplit);
}
if (sumSplit > 0 && (activeFeeding.getDurationMinutes() == null || activeFeeding.getDurationMinutes() < sumSplit)) { if (sumSplit > 0 && (activeFeeding.getDurationMinutes() == null || activeFeeding.getDurationMinutes() < sumSplit)) {
activeFeeding.setDurationMinutes(sumSplit); activeFeeding.setDurationMinutes(sumSplit);
} }
@@ -177,6 +190,8 @@ public class CareRecordService {
record.setFeedingMethod(request.getFeedingMethod()); record.setFeedingMethod(request.getFeedingMethod());
record.setLeftDurationMinutes(request.getLeftDurationMinutes()); record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes()); record.setRightDurationMinutes(request.getRightDurationMinutes());
record.setEffectiveFeedingMinutes(resolveEffectiveFeedingMinutes(request.getEffectiveFeedingMinutes(), request.getLeftDurationMinutes(), request.getRightDurationMinutes(), request.getDurationMinutes()));
record.setPauseSegmentsJson(normalizeBlank(request.getPauseSegmentsJson()));
record.setAmountMl(request.getAmountMl()); record.setAmountMl(request.getAmountMl());
record.setExcretionType(request.getExcretionType()); record.setExcretionType(request.getExcretionType());
record.setOperatorName(request.getOperatorName() == null || request.getOperatorName().trim().isEmpty() ? "宝妈" : request.getOperatorName().trim()); record.setOperatorName(request.getOperatorName() == null || request.getOperatorName().trim().isEmpty() ? "宝妈" : request.getOperatorName().trim());
@@ -219,6 +234,14 @@ public class CareRecordService {
if (request.getRightDurationMinutes() != null) { if (request.getRightDurationMinutes() != null) {
record.setRightDurationMinutes(request.getRightDurationMinutes()); record.setRightDurationMinutes(request.getRightDurationMinutes());
} }
if (request.getEffectiveFeedingMinutes() != null) {
record.setEffectiveFeedingMinutes(request.getEffectiveFeedingMinutes());
} else if (request.getLeftDurationMinutes() != null || request.getRightDurationMinutes() != null) {
record.setEffectiveFeedingMinutes(resolveEffectiveFeedingMinutes(null, record.getLeftDurationMinutes(), record.getRightDurationMinutes(), record.getDurationMinutes()));
}
if (request.getPauseSegmentsJson() != null) {
record.setPauseSegmentsJson(normalizeBlank(request.getPauseSegmentsJson()));
}
if (request.getAmountMl() != null) { if (request.getAmountMl() != null) {
record.setAmountMl(request.getAmountMl()); record.setAmountMl(request.getAmountMl());
} }
@@ -284,6 +307,27 @@ public class CareRecordService {
return null; return null;
} }
private Integer resolveEffectiveFeedingMinutes(Integer effectiveMinutes, Integer leftMinutes, Integer rightMinutes, Integer fallbackDuration) {
if (effectiveMinutes != null) {
return effectiveMinutes;
}
if (leftMinutes != null || rightMinutes != null) {
int sum = (leftMinutes == null ? 0 : leftMinutes) + (rightMinutes == null ? 0 : rightMinutes);
if (sum > 0) {
return sum;
}
}
return fallbackDuration;
}
private String normalizeBlank(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
private CareRecordVO createExcretion(ExcretionRO request, String excretionType) { private CareRecordVO createExcretion(ExcretionRO request, String excretionType) {
CareRecord record = baseRecord(request.getBabyId(), "excretion", request.getTime(), request.getOperatorName(), request.getRemark()); CareRecord record = baseRecord(request.getBabyId(), "excretion", request.getTime(), request.getOperatorName(), request.getRemark());
record.setExcretionType(excretionType); record.setExcretionType(excretionType);
@@ -25,6 +25,8 @@ public final class CareRecordConvert {
vo.setDurationMinutes(entity.getDurationMinutes()); vo.setDurationMinutes(entity.getDurationMinutes());
vo.setLeftDurationMinutes(entity.getLeftDurationMinutes()); vo.setLeftDurationMinutes(entity.getLeftDurationMinutes());
vo.setRightDurationMinutes(entity.getRightDurationMinutes()); vo.setRightDurationMinutes(entity.getRightDurationMinutes());
vo.setEffectiveFeedingMinutes(entity.getEffectiveFeedingMinutes());
vo.setPauseSegmentsJson(entity.getPauseSegmentsJson());
vo.setFeedingMethod(entity.getFeedingMethod()); vo.setFeedingMethod(entity.getFeedingMethod());
vo.setAmountMl(entity.getAmountMl()); vo.setAmountMl(entity.getAmountMl());
vo.setExcretionType(entity.getExcretionType()); vo.setExcretionType(entity.getExcretionType());
@@ -66,6 +68,8 @@ public final class CareRecordConvert {
dto.setDurationMinutes(entity.getDurationMinutes()); dto.setDurationMinutes(entity.getDurationMinutes());
dto.setLeftDurationMinutes(entity.getLeftDurationMinutes()); dto.setLeftDurationMinutes(entity.getLeftDurationMinutes());
dto.setRightDurationMinutes(entity.getRightDurationMinutes()); dto.setRightDurationMinutes(entity.getRightDurationMinutes());
dto.setEffectiveFeedingMinutes(entity.getEffectiveFeedingMinutes());
dto.setPauseSegmentsJson(entity.getPauseSegmentsJson());
dto.setFeedingMethod(entity.getFeedingMethod()); dto.setFeedingMethod(entity.getFeedingMethod());
dto.setAmountMl(entity.getAmountMl()); dto.setAmountMl(entity.getAmountMl());
dto.setExcretionType(entity.getExcretionType()); dto.setExcretionType(entity.getExcretionType());
@@ -51,6 +51,16 @@ public class CareRecordDTO {
*/ */
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停,仅喂养记录使用)
*/
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON(记录暂停开始、结束与持续秒数)
*/
private String pauseSegmentsJson;
/** /**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他) * 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/ */
@@ -54,6 +54,16 @@ public class CreateFeedingRO {
*/ */
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停)
*/
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON
*/
private String pauseSegmentsJson;
/** /**
* 记录人称谓(如: 宝妈、宝爸、月嫂) * 记录人称谓(如: 宝妈、宝爸、月嫂)
*/ */
@@ -46,6 +46,16 @@ public class CreateManualRecordRO {
*/ */
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停)
*/
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON
*/
private String pauseSegmentsJson;
/** /**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他) * 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/ */
@@ -43,6 +43,16 @@ public class UpdateCareRecordRO {
*/ */
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停)
*/
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON
*/
private String pauseSegmentsJson;
/** /**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他) * 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/ */
@@ -51,6 +51,16 @@ public class CareRecordVO {
*/ */
private Integer rightDurationMinutes; private Integer rightDurationMinutes;
/**
* 有效喂养时长(分钟,不含暂停,仅喂养记录使用)
*/
private Integer effectiveFeedingMinutes;
/**
* 暂停片段JSON(记录暂停开始、结束与持续秒数)
*/
private String pauseSegmentsJson;
/** /**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他) * 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/ */
@@ -5,7 +5,7 @@ spring:
application: application:
name: baby-tracker-server name: baby-tracker-server
datasource: datasource:
url: ${DB_URL:jdbc:mysql://39.107.119.209:3306/yyyy?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai} url: ${DB_URL:jdbc:mysql://39.107.119.209:3306/yyyy2?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai}
username: ${DB_USER:yy_u} username: ${DB_USER:yy_u}
password: ${DB_PASSWORD:BBp5pjWr9LFiqua} password: ${DB_PASSWORD:BBp5pjWr9LFiqua}
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS `care_quick_rule` (
`id` CHAR(32) NOT NULL COMMENT '常用补记规则ID,雪花ID字符串',
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
`name` VARCHAR(50) NOT NULL COMMENT '规则名称',
`actions` VARCHAR(100) NOT NULL COMMENT '动作列表: diaper,feeding,sleep',
`diaper_offset_minutes` INT NOT NULL DEFAULT 0 COMMENT '尿布动作相对起点偏移分钟',
`feeding_offset_minutes` INT NOT NULL DEFAULT 5 COMMENT '喂奶动作相对起点偏移分钟',
`sleep_after_feeding_minutes` INT NOT NULL DEFAULT 5 COMMENT '喂奶结束后多久开始睡眠',
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
`sort_order` INT NOT NULL DEFAULT 100 COMMENT '排序',
`remark` VARCHAR(500) NULL COMMENT '备注',
`deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除',
`created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人',
`created_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人',
`updated_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_care_quick_rule_family_sort` (`family_id`, `sort_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭常用补记规则表';
@@ -0,0 +1,5 @@
-- V5: 喂养记录增加有效喂养时长与暂停片段 JSON
ALTER TABLE `care_record`
ADD COLUMN `effective_feeding_minutes` INT NULL COMMENT '有效喂养时长(分钟,不含暂停)' AFTER `right_duration_minutes`,
ADD COLUMN `pause_segments_json` JSON NULL COMMENT '暂停片段JSON' AFTER `effective_feeding_minutes`;
+4
View File
@@ -77,6 +77,10 @@ CREATE TABLE IF NOT EXISTS `care_record` (
`start_time` DATETIME NOT NULL COMMENT '开始/发生时间', `start_time` DATETIME NOT NULL COMMENT '开始/发生时间',
`end_time` DATETIME NULL COMMENT '结束时间', `end_time` DATETIME NULL COMMENT '结束时间',
`duration_minutes` INT NULL COMMENT '持续分钟数', `duration_minutes` INT NULL COMMENT '持续分钟数',
`left_duration_minutes` INT NULL COMMENT '亲喂左侧时长(分钟)',
`right_duration_minutes` INT NULL COMMENT '亲喂右侧时长(分钟)',
`effective_feeding_minutes` INT NULL COMMENT '有效喂养时长(分钟,不含暂停)',
`pause_segments_json` JSON NULL COMMENT '暂停片段JSON',
`feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式', `feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式',
`amount_ml` INT NULL COMMENT '奶量 ml,可选', `amount_ml` INT NULL COMMENT '奶量 ml,可选',
`excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop', `excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop',
+24 -1
View File
@@ -11,6 +11,7 @@ SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `flyway_schema_history`; DROP TABLE IF EXISTS `flyway_schema_history`;
DROP TABLE IF EXISTS `family_memo`; DROP TABLE IF EXISTS `family_memo`;
DROP TABLE IF EXISTS `care_quick_rule`;
DROP TABLE IF EXISTS `care_record`; DROP TABLE IF EXISTS `care_record`;
DROP TABLE IF EXISTS `baby_profile`; DROP TABLE IF EXISTS `baby_profile`;
DROP TABLE IF EXISTS `family_member`; DROP TABLE IF EXISTS `family_member`;
@@ -103,6 +104,8 @@ CREATE TABLE `care_record` (
`duration_minutes` INT NULL COMMENT '持续分钟数', `duration_minutes` INT NULL COMMENT '持续分钟数',
`left_duration_minutes` INT NULL COMMENT '亲喂左侧时长(分钟)', `left_duration_minutes` INT NULL COMMENT '亲喂左侧时长(分钟)',
`right_duration_minutes` INT NULL COMMENT '亲喂右侧时长(分钟)', `right_duration_minutes` INT NULL COMMENT '亲喂右侧时长(分钟)',
`effective_feeding_minutes` INT NULL COMMENT '有效喂养时长(分钟,不含暂停)',
`pause_segments_json` JSON NULL COMMENT '暂停片段JSON',
`feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式', `feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式',
`amount_ml` INT NULL COMMENT '奶量 ml,可选', `amount_ml` INT NULL COMMENT '奶量 ml,可选',
`excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop', `excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop',
@@ -121,6 +124,26 @@ CREATE TABLE `care_record` (
KEY `idx_care_record_type_time` (`record_type`, `start_time`) KEY `idx_care_record_type_time` (`record_type`, `start_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='照护记录表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='照护记录表';
CREATE TABLE `care_quick_rule` (
`id` CHAR(32) NOT NULL COMMENT '常用补记规则ID,雪花ID字符串',
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
`name` VARCHAR(50) NOT NULL COMMENT '规则名称',
`actions` VARCHAR(100) NOT NULL COMMENT '动作列表: diaper,feeding,sleep',
`diaper_offset_minutes` INT NOT NULL DEFAULT 0 COMMENT '尿布动作相对起点偏移分钟',
`feeding_offset_minutes` INT NOT NULL DEFAULT 5 COMMENT '喂奶动作相对起点偏移分钟',
`sleep_after_feeding_minutes` INT NOT NULL DEFAULT 5 COMMENT '喂奶结束后多久开始睡眠',
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
`sort_order` INT NOT NULL DEFAULT 100 COMMENT '排序',
`remark` VARCHAR(500) NULL COMMENT '备注',
`deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除',
`created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人',
`created_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人',
`updated_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_care_quick_rule_family_sort` (`family_id`, `sort_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭常用补记规则表';
INSERT IGNORE INTO `app_user` (`id`, `nickname`, `status`, `created_by`, `updated_by`) INSERT IGNORE INTO `app_user` (`id`, `nickname`, `status`, `created_by`, `updated_by`)
VALUES ('00000000000000361915955435016192', '默认看护人', 'active', 'admin', 'admin'); VALUES ('00000000000000361915955435016192', '默认看护人', 'active', 'admin', 'admin');
@@ -154,6 +177,6 @@ CREATE TABLE IF NOT EXISTS `flyway_schema_history` (
INSERT IGNORE INTO `flyway_schema_history` INSERT IGNORE INTO `flyway_schema_history`
(`installed_rank`, `version`, `description`, `type`, `script`, `checksum`, `installed_by`, `installed_on`, `execution_time`, `success`) (`installed_rank`, `version`, `description`, `type`, `script`, `checksum`, `installed_by`, `installed_on`, `execution_time`, `success`)
VALUES VALUES
(1, '3', '<< Flyway Baseline >>', 'BASELINE', '<< Flyway Baseline >>', NULL, 'admin', CURRENT_TIMESTAMP, 0, 1); (1, '4', '<< Flyway Baseline >>', 'BASELINE', '<< Flyway Baseline >>', NULL, 'admin', CURRENT_TIMESTAMP, 0, 1);
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;