优化代码结构
This commit is contained in:
1 parent
8c7a9040d2
commit
cbcd6b4c7f
97 files changed
+4350
-1183
No files matched your search
@@ -5,7 +5,8 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"build": "vue-tsc -b && vite build && node scripts/copy-artifacts.mjs",
|
||||
"copy-artifacts": "node scripts/copy-artifacts.mjs",
|
||||
"preview": "vite preview --host 0.0.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const webDir = path.resolve(__dirname, '..');
|
||||
const distDir = path.resolve(webDir, 'dist');
|
||||
const rootDir = path.resolve(webDir, '../..');
|
||||
|
||||
const targets = [
|
||||
path.resolve(rootDir, 'deploy/artifacts/web')
|
||||
];
|
||||
|
||||
if (!fs.existsSync(distDir)) {
|
||||
console.error(`[copy-artifacts] 错误: 前端 dist 目录不存在: ${distDir}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const targetDir of targets) {
|
||||
try {
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
// 清理旧产物,避免遗留老旧的静态资源 hash 文件
|
||||
fs.rmSync(targetDir, { recursive: true, force: true });
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
fs.cpSync(distDir, targetDir, { recursive: true });
|
||||
console.log(`[copy-artifacts] 成功复制前端构建产物到: ${targetDir}`);
|
||||
} catch (err) {
|
||||
console.error(`[copy-artifacts] 复制到 ${targetDir} 失败:`, err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,19 @@
|
||||
import type { ApiResponse, BabyProfile, CareRecord, DailySummary, FamilyContext, FeedingMethod } from '../types/domain'
|
||||
import type {
|
||||
ApiResponse,
|
||||
BabyProfile,
|
||||
CareRecord,
|
||||
CreateBabyPayload,
|
||||
CreateManualRecordPayload,
|
||||
CreateMemberPayload,
|
||||
DailySummary,
|
||||
FamilyContext,
|
||||
FamilyInfo,
|
||||
FamilyMember,
|
||||
FeedingMethod,
|
||||
UpdateCareRecordPayload,
|
||||
UpdateFamilyPayload,
|
||||
UpdateMemberPayload
|
||||
} from '../types/domain'
|
||||
|
||||
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
@@ -24,19 +39,61 @@ export function getFamilyContext() {
|
||||
}
|
||||
|
||||
export function updateCurrentBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
|
||||
return request<BabyProfile>('/api/v1/babies/current', {
|
||||
return request<BabyProfile>('/api/v1/babies', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function updateBaby(babyId: string, payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
|
||||
return request<BabyProfile>(`/api/v1/babies/${encodeURIComponent(babyId)}`, {
|
||||
return request<BabyProfile>('/api/v1/babies', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...payload, babyId })
|
||||
})
|
||||
}
|
||||
|
||||
export function createBaby(payload: CreateBabyPayload) {
|
||||
return request<BabyProfile>('/api/v1/babies', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function setDefaultBaby(babyId: string) {
|
||||
return request<BabyProfile>('/api/v1/babies/set-default', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ babyId })
|
||||
})
|
||||
}
|
||||
|
||||
export function updateFamily(familyId: string, payload: UpdateFamilyPayload) {
|
||||
return request<FamilyInfo>('/api/v1/families', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...payload, familyId })
|
||||
})
|
||||
}
|
||||
|
||||
export function createMember(familyId: string, payload: CreateMemberPayload) {
|
||||
return request<FamilyMember>('/api/v1/families/members', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...payload, familyId })
|
||||
})
|
||||
}
|
||||
|
||||
export function updateMember(familyId: string, memberId: string, payload: UpdateMemberPayload) {
|
||||
return request<FamilyMember>('/api/v1/families/members', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...payload, familyId, memberId })
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteMember(familyId: string, memberId: string) {
|
||||
return request<void>('/api/v1/families/members/delete', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ familyId, memberId })
|
||||
})
|
||||
}
|
||||
|
||||
export function getDailySummary(babyId: string) {
|
||||
return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`)
|
||||
}
|
||||
@@ -51,6 +108,8 @@ export function createFeeding(payload: {
|
||||
amountMl?: number
|
||||
breastSide?: 'left' | 'right'
|
||||
operatorName: string
|
||||
remark?: string
|
||||
note?: string
|
||||
}) {
|
||||
return request<CareRecord>('/api/v1/records/feeding', {
|
||||
method: 'POST',
|
||||
@@ -62,6 +121,8 @@ export function startFeeding(payload: {
|
||||
babyId: string
|
||||
breastSide: 'left' | 'right'
|
||||
operatorName: string
|
||||
remark?: string
|
||||
note?: string
|
||||
}) {
|
||||
return request<CareRecord>('/api/v1/records/feeding/start', {
|
||||
method: 'POST',
|
||||
@@ -76,6 +137,8 @@ export function endFeeding(payload: {
|
||||
babyId: string
|
||||
breastSide: 'left' | 'right'
|
||||
operatorName: string
|
||||
remark?: string
|
||||
note?: string
|
||||
}) {
|
||||
return request<CareRecord>('/api/v1/records/feeding/end', {
|
||||
method: 'POST',
|
||||
@@ -86,28 +149,28 @@ export function endFeeding(payload: {
|
||||
})
|
||||
}
|
||||
|
||||
export function startSleep(payload: { babyId: string; operatorName: string }) {
|
||||
export function startSleep(payload: { babyId: string; operatorName: string; remark?: string; note?: string }) {
|
||||
return request<CareRecord>('/api/v1/records/sleep/start', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function endSleep(payload: { babyId: string; operatorName: string }) {
|
||||
export function endSleep(payload: { babyId: string; operatorName: string; remark?: string; note?: string }) {
|
||||
return request<CareRecord>('/api/v1/records/sleep/end', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function createPee(payload: { babyId: string; operatorName: string }) {
|
||||
export function createPee(payload: { babyId: string; operatorName: string; remark?: string; note?: string }) {
|
||||
return request<CareRecord>('/api/v1/records/pee', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function createPoop(payload: { babyId: string; operatorName: string }) {
|
||||
export function createPoop(payload: { babyId: string; operatorName: string; remark?: string; note?: string }) {
|
||||
return request<CareRecord>('/api/v1/records/poop', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
@@ -115,5 +178,22 @@ export function createPoop(payload: { babyId: string; operatorName: string }) {
|
||||
}
|
||||
|
||||
export function deleteRecord(recordId: string) {
|
||||
return request<void>(`/api/v1/records/${recordId}`, { method: 'DELETE' })
|
||||
return request<void>('/api/v1/records/delete', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ recordId })
|
||||
})
|
||||
}
|
||||
|
||||
export function createManualRecord(payload: CreateManualRecordPayload) {
|
||||
return request<CareRecord>('/api/v1/records', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
}
|
||||
|
||||
export function updateRecord(recordId: string, payload: UpdateCareRecordPayload) {
|
||||
return request<CareRecord>('/api/v1/records', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...payload, recordId })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
import type { ActionPreferences } from '../../types/domain'
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
const actionForm = reactive<ActionPreferences>({
|
||||
defaultFeedingMethod: 'breastfeed',
|
||||
defaultBottleAmount: 60,
|
||||
defaultBreastSide: 'left',
|
||||
defaultSleepMode: 'timer',
|
||||
quickFeedbackToast: true,
|
||||
autoBurpReminder: true
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
syncActionForm()
|
||||
})
|
||||
|
||||
function syncActionForm() {
|
||||
Object.assign(actionForm, store.preferences)
|
||||
}
|
||||
|
||||
function saveActions() {
|
||||
store.savePreferences(actionForm)
|
||||
showToast({ message: '照护行为偏好已更新', type: 'success' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel form-panel">
|
||||
<div>
|
||||
<span class="eyebrow">照护行为偏好</span>
|
||||
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">自定义默认喂养、睡眠及操作习惯</p>
|
||||
</div>
|
||||
|
||||
<label>
|
||||
默认喂养方式
|
||||
<select v-model="actionForm.defaultFeedingMethod">
|
||||
<option value="breastfeed">亲喂 (母乳)</option>
|
||||
<option value="bottle">瓶喂 (母乳)</option>
|
||||
<option value="formula">配方奶</option>
|
||||
<option value="mixed">混合喂养</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
默认单次瓶喂奶量 (ml)
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<input v-model.number="actionForm.defaultBottleAmount" type="number" min="10" max="300" step="5" />
|
||||
<div class="chip-group" style="margin: 0;">
|
||||
<button
|
||||
v-for="amt in [30, 60, 90, 120]"
|
||||
:key="amt"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: actionForm.defaultBottleAmount === amt }"
|
||||
@click="actionForm.defaultBottleAmount = amt"
|
||||
>
|
||||
{{ amt }}ml
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
默认亲喂优先侧
|
||||
<select v-model="actionForm.defaultBreastSide">
|
||||
<option value="left">左侧优先 (Left)</option>
|
||||
<option value="right">右侧优先 (Right)</option>
|
||||
</select>
|
||||
</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>
|
||||
<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>
|
||||
</template>
|
||||
@@ -0,0 +1,202 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
// 宝宝表单
|
||||
const babyForm = reactive({
|
||||
name: '',
|
||||
gender: 'boy',
|
||||
birthDate: '',
|
||||
deliveryType: 'natural'
|
||||
})
|
||||
|
||||
// 添加宝宝弹窗
|
||||
const showAddBabyModal = ref(false)
|
||||
const newBabyForm = reactive({
|
||||
name: '',
|
||||
gender: 'boy',
|
||||
birthDate: new Date().toISOString().slice(0, 10),
|
||||
deliveryType: 'natural',
|
||||
isDefault: false
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
syncBabyForm()
|
||||
})
|
||||
|
||||
watch(() => store.baby?.babyId, () => {
|
||||
syncBabyForm()
|
||||
})
|
||||
|
||||
function syncBabyForm() {
|
||||
if (!store.baby) return
|
||||
babyForm.name = store.baby.name
|
||||
babyForm.gender = store.baby.gender
|
||||
babyForm.birthDate = store.baby.birthDate
|
||||
babyForm.deliveryType = store.baby.deliveryType
|
||||
}
|
||||
|
||||
// 保存当前宝宝信息
|
||||
async function saveBaby() {
|
||||
if (!babyForm.name.trim()) {
|
||||
showToast('请输入宝宝昵称')
|
||||
return
|
||||
}
|
||||
await store.saveBaby({
|
||||
name: babyForm.name.trim(),
|
||||
gender: babyForm.gender,
|
||||
birthDate: babyForm.birthDate,
|
||||
deliveryType: babyForm.deliveryType
|
||||
})
|
||||
showToast({ message: '宝宝档案已更新', type: 'success' })
|
||||
}
|
||||
|
||||
// 打开添加宝宝弹窗
|
||||
function openAddBabyModal() {
|
||||
newBabyForm.name = ''
|
||||
newBabyForm.gender = 'boy'
|
||||
newBabyForm.birthDate = new Date().toISOString().slice(0, 10)
|
||||
newBabyForm.deliveryType = 'natural'
|
||||
newBabyForm.isDefault = false
|
||||
showAddBabyModal.value = true
|
||||
}
|
||||
|
||||
// 确认添加宝宝
|
||||
async function submitAddBaby() {
|
||||
if (!newBabyForm.name.trim()) {
|
||||
showToast('请输入宝宝昵称')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.addBaby({
|
||||
familyId: store.context?.family.familyId,
|
||||
name: newBabyForm.name.trim(),
|
||||
gender: newBabyForm.gender,
|
||||
birthDate: newBabyForm.birthDate,
|
||||
deliveryType: newBabyForm.deliveryType,
|
||||
isDefault: newBabyForm.isDefault
|
||||
})
|
||||
showAddBabyModal.value = false
|
||||
showToast({ message: '成功添加宝宝', type: 'success' })
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '添加失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 设为默认宝宝
|
||||
async function handleSetDefaultBaby(babyId: string) {
|
||||
try {
|
||||
await store.setDefaultBaby(babyId)
|
||||
showToast({ message: '已设为默认宝宝', type: 'success' })
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '操作失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="timeline-header-actions">
|
||||
<div>
|
||||
<span class="eyebrow">宝宝管理</span>
|
||||
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">选择或维护宝宝档案</p>
|
||||
</div>
|
||||
<button class="primary-pill-button" @click="openAddBabyModal">
|
||||
+ 添加宝宝
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 宝宝切换卡片 -->
|
||||
<div class="chip-group" style="margin-bottom: 16px;">
|
||||
<button
|
||||
v-for="b in store.babies"
|
||||
:key="b.babyId"
|
||||
class="chip"
|
||||
:class="{ active: store.baby?.babyId === b.babyId }"
|
||||
@click="store.selectBaby(b.babyId)"
|
||||
>
|
||||
{{ b.name }} ({{ b.ageText }})
|
||||
<span v-if="b.isDefault" class="tag-badge default">默认</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="store.baby && store.babies.length > 1 && !store.baby.isDefault" style="margin-bottom: 16px;">
|
||||
<button class="secondary-button" style="font-size: 13px;" @click="handleSetDefaultBaby(store.baby.babyId)">
|
||||
设为全局默认宝宝
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 当前宝宝修改表单 -->
|
||||
<div class="form-panel" style="border-top: 1px solid #f0ece5; padding-top: 16px;">
|
||||
<label>
|
||||
宝宝昵称
|
||||
<input v-model="babyForm.name" placeholder="请输入宝宝名字或乳名" />
|
||||
</label>
|
||||
<label>
|
||||
出生日期
|
||||
<input v-model="babyForm.birthDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
性别
|
||||
<select v-model="babyForm.gender">
|
||||
<option value="boy">男宝</option>
|
||||
<option value="girl">女宝</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
分娩方式
|
||||
<select v-model="babyForm.deliveryType">
|
||||
<option value="natural">顺产 (Natural)</option>
|
||||
<option value="c_section">剖宫产 (C-Section)</option>
|
||||
<option value="unknown">暂不设置</option>
|
||||
</select>
|
||||
</label>
|
||||
<button class="save-button" @click="saveBaby">保存宝宝信息</button>
|
||||
</div>
|
||||
|
||||
<!-- 弹窗:添加新宝宝 -->
|
||||
<div v-if="showAddBabyModal" class="modal-backdrop" @click.self="showAddBabyModal = false">
|
||||
<div class="modal-sheet">
|
||||
<div class="modal-header">
|
||||
<h3>添加宝宝档案</h3>
|
||||
<button class="close-btn" @click="showAddBabyModal = false">×</button>
|
||||
</div>
|
||||
<div class="modal-form">
|
||||
<label>
|
||||
宝宝昵称 *
|
||||
<input v-model="newBabyForm.name" placeholder="例如:乐乐、二宝" />
|
||||
</label>
|
||||
<label>
|
||||
性别
|
||||
<select v-model="newBabyForm.gender">
|
||||
<option value="boy">男宝</option>
|
||||
<option value="girl">女宝</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
出生日期 *
|
||||
<input v-model="newBabyForm.birthDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
分娩方式
|
||||
<select v-model="newBabyForm.deliveryType">
|
||||
<option value="natural">顺产</option>
|
||||
<option value="c_section">剖宫产</option>
|
||||
</select>
|
||||
</label>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<input id="setDefCheck" v-model="newBabyForm.isDefault" type="checkbox" style="width: 20px; height: 20px;" />
|
||||
<label for="setDefCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为当前默认关注的宝宝</label>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="secondary-button" @click="showAddBabyModal = false">取消</button>
|
||||
<button class="save-button" @click="submitAddBaby">确认添加</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,90 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, watch } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
const familyForm = reactive({
|
||||
name: '',
|
||||
inviteCode: ''
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
syncFamilyForm()
|
||||
})
|
||||
|
||||
watch(() => store.context?.family.familyId, () => {
|
||||
syncFamilyForm()
|
||||
})
|
||||
|
||||
function syncFamilyForm() {
|
||||
if (!store.context?.family) return
|
||||
familyForm.name = store.context.family.name || ''
|
||||
familyForm.inviteCode = store.context.family.inviteCode || ''
|
||||
}
|
||||
|
||||
async function saveFamily() {
|
||||
if (!familyForm.name.trim()) {
|
||||
showToast('请输入家庭名称')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.saveFamily({
|
||||
name: familyForm.name.trim(),
|
||||
inviteCode: familyForm.inviteCode.trim()
|
||||
})
|
||||
showToast({ message: '家庭信息已保存', type: 'success' })
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '保存失败')
|
||||
}
|
||||
}
|
||||
|
||||
function generateInviteCode() {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
||||
let res = 'BT'
|
||||
for (let i = 0; i < 4; i++) {
|
||||
res += chars.charAt(Math.floor(Math.random() * chars.length))
|
||||
}
|
||||
familyForm.inviteCode = res
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel form-panel">
|
||||
<div>
|
||||
<span class="eyebrow">家庭基础设置</span>
|
||||
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">维护家庭名称与成员共享邀请码</p>
|
||||
</div>
|
||||
|
||||
<label>
|
||||
家庭名称
|
||||
<input v-model="familyForm.name" placeholder="例如:新生儿照护家庭、幸福小家" />
|
||||
</label>
|
||||
|
||||
<label>
|
||||
家庭邀请码
|
||||
<div style="display: flex; gap: 8px;">
|
||||
<input v-model="familyForm.inviteCode" placeholder="共享邀请码" style="flex: 1;" />
|
||||
<button class="secondary-button" type="button" @click="generateInviteCode">随机生成</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<div class="settings-list" style="margin: 8px 0;">
|
||||
<div>
|
||||
<span>家庭编号</span>
|
||||
<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>
|
||||
|
||||
<button class="save-button" @click="saveFamily">保存家庭信息</button>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,186 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { showToast, showConfirmDialog } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
import type { FamilyMember } from '../../types/domain'
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
// 成员维护弹窗
|
||||
const showMemberModal = ref(false)
|
||||
const isEditingMember = ref(false)
|
||||
const currentMemberId = ref('')
|
||||
const memberForm = reactive({
|
||||
roleName: '',
|
||||
roleType: 'caregiver',
|
||||
defaultOperator: false
|
||||
})
|
||||
const memberRolePresets = ['宝妈', '宝爸', '月嫂', '育儿嫂', '奶奶', '爷爷', '外婆', '外公', '阿姨']
|
||||
|
||||
function openAddMemberModal() {
|
||||
isEditingMember.value = false
|
||||
currentMemberId.value = ''
|
||||
memberForm.roleName = ''
|
||||
memberForm.roleType = 'caregiver'
|
||||
memberForm.defaultOperator = false
|
||||
showMemberModal.value = true
|
||||
}
|
||||
|
||||
function openEditMemberModal(member: FamilyMember) {
|
||||
isEditingMember.value = true
|
||||
currentMemberId.value = member.memberId
|
||||
memberForm.roleName = member.roleName
|
||||
memberForm.roleType = member.roleType
|
||||
memberForm.defaultOperator = member.defaultOperator
|
||||
showMemberModal.value = true
|
||||
}
|
||||
|
||||
async function submitMember() {
|
||||
if (!memberForm.roleName.trim()) {
|
||||
showToast('请输入成员称谓')
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (isEditingMember.value) {
|
||||
await store.editMember(currentMemberId.value, {
|
||||
roleName: memberForm.roleName.trim(),
|
||||
roleType: memberForm.roleType,
|
||||
defaultOperator: memberForm.defaultOperator
|
||||
})
|
||||
showToast({ message: '成员信息已修改', type: 'success' })
|
||||
} else {
|
||||
await store.addMember({
|
||||
roleName: memberForm.roleName.trim(),
|
||||
roleType: memberForm.roleType,
|
||||
defaultOperator: memberForm.defaultOperator
|
||||
})
|
||||
showToast({ message: '成功添加照护成员', type: 'success' })
|
||||
}
|
||||
showMemberModal.value = false
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveMember(memberId: string, roleName: string) {
|
||||
try {
|
||||
await showConfirmDialog({
|
||||
title: '确认移除',
|
||||
message: `确定要将成员“${roleName}”从家庭照护组中移除吗?`
|
||||
})
|
||||
await store.removeMember(memberId)
|
||||
showToast({ message: '成员已移除', type: 'success' })
|
||||
} catch {
|
||||
// cancel
|
||||
}
|
||||
}
|
||||
|
||||
function selectOperator(name: string) {
|
||||
store.setOperatorName(name)
|
||||
showToast({ message: `已切换当前记录人为: ${name}`, type: 'success' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel form-panel">
|
||||
<div class="timeline-header-actions">
|
||||
<div>
|
||||
<span class="eyebrow">照护成员管理</span>
|
||||
<p style="margin: 2px 0 0; color: #65707d; font-size: 13px;">维护看护团队与默认记录人</p>
|
||||
</div>
|
||||
<button class="primary-pill-button" @click="openAddMemberModal">
|
||||
+ 添加成员
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 当前生效记录人切换 -->
|
||||
<div style="background: #faf7f1; padding: 12px; border-radius: 12px;">
|
||||
<span style="font-size: 13px; color: #65707d; font-weight: 700;">当前快速记录人:</span>
|
||||
<strong style="font-size: 15px; color: #8a540d;">{{ store.operatorName }}</strong>
|
||||
<p style="margin: 4px 0 8px; font-size: 12px; color: #8c97a4;">点击下方快捷切换当前记录人:</p>
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="m in store.members"
|
||||
:key="m.memberId"
|
||||
class="chip sm"
|
||||
:class="{ active: store.operatorName === m.roleName }"
|
||||
@click="selectOperator(m.roleName)"
|
||||
>
|
||||
{{ m.roleName }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 成员列表 -->
|
||||
<div class="settings-list" style="margin-top: 10px;">
|
||||
<div v-for="member in store.members" :key="member.memberId" style="align-items: center;">
|
||||
<div>
|
||||
<strong style="font-size: 16px;">{{ member.roleName }}</strong>
|
||||
<span class="tag-badge" :class="member.roleType">
|
||||
{{ member.roleType === 'owner' ? '家庭管理员' : '照护成员' }}
|
||||
</span>
|
||||
<span v-if="member.defaultOperator" class="tag-badge default">默认记录人</span>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
<button class="edit-button" @click="openEditMemberModal(member)">修改</button>
|
||||
<button
|
||||
v-if="store.members.length > 1"
|
||||
class="delete-button"
|
||||
@click="handleRemoveMember(member.memberId, member.roleName)"
|
||||
>
|
||||
移除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 弹窗:添加/编辑家庭成员 -->
|
||||
<div v-if="showMemberModal" class="modal-backdrop" @click.self="showMemberModal = false">
|
||||
<div class="modal-sheet">
|
||||
<div class="modal-header">
|
||||
<h3>{{ isEditingMember ? '修改照护成员' : '添加照护成员' }}</h3>
|
||||
<button class="close-btn" @click="showMemberModal = false">×</button>
|
||||
</div>
|
||||
<div class="modal-form">
|
||||
<label>
|
||||
成员称谓 *
|
||||
<input v-model="memberForm.roleName" placeholder="例如:月嫂、奶奶、外婆" />
|
||||
</label>
|
||||
<div>
|
||||
<span style="font-size: 12px; color: #65707d;">快捷填入:</span>
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="preset in memberRolePresets"
|
||||
:key="preset"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: memberForm.roleName === preset }"
|
||||
@click="memberForm.roleName = preset"
|
||||
>
|
||||
{{ preset }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label>
|
||||
家庭角色
|
||||
<select v-model="memberForm.roleType">
|
||||
<option value="caregiver">照护成员 (Caregiver)</option>
|
||||
<option value="owner">家庭管理员 (Owner)</option>
|
||||
<option value="viewer">仅查看者 (Viewer)</option>
|
||||
</select>
|
||||
</label>
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<input id="defOpCheck" v-model="memberForm.defaultOperator" type="checkbox" style="width: 20px; height: 20px;" />
|
||||
<label for="defOpCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为默认记录人</label>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="secondary-button" @click="showMemberModal = false">取消</button>
|
||||
<button class="save-button" @click="submitMember">
|
||||
{{ isEditingMember ? '保存修改' : '确认添加' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,316 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
import type { CareRecord, ExcretionType, FeedingMethod, RecordType } from '../../types/domain'
|
||||
|
||||
const props = defineProps<{
|
||||
show: boolean
|
||||
record: CareRecord | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:show', value: boolean): void
|
||||
(e: 'success'): void
|
||||
}>()
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香']
|
||||
|
||||
const editForm = reactive({
|
||||
recordType: 'feeding' as RecordType,
|
||||
startDate: '',
|
||||
startTimeStr: '',
|
||||
hasEndTime: false,
|
||||
endDate: '',
|
||||
endTimeStr: '',
|
||||
durationMinutes: null as number | null,
|
||||
feedingMethod: 'breastfeed' as FeedingMethod,
|
||||
amountMl: null as number | null,
|
||||
breastSide: 'left' as 'left' | 'right',
|
||||
excretionType: 'pee' as ExcretionType,
|
||||
operatorName: '',
|
||||
note: ''
|
||||
})
|
||||
|
||||
watch(() => props.record, (newRecord) => {
|
||||
if (newRecord) {
|
||||
initFromRecord(newRecord)
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
function initFromRecord(record: CareRecord) {
|
||||
editForm.recordType = record.recordType
|
||||
const [sDate, sTime] = record.startTime ? record.startTime.split('T') : ['', '']
|
||||
editForm.startDate = sDate || ''
|
||||
editForm.startTimeStr = sTime ? sTime.slice(0, 5) : ''
|
||||
|
||||
if (record.endTime) {
|
||||
const [eDate, eTime] = record.endTime.split('T')
|
||||
editForm.hasEndTime = true
|
||||
editForm.endDate = eDate || ''
|
||||
editForm.endTimeStr = eTime ? eTime.slice(0, 5) : ''
|
||||
} else {
|
||||
editForm.hasEndTime = false
|
||||
editForm.endDate = sDate || ''
|
||||
editForm.endTimeStr = ''
|
||||
}
|
||||
|
||||
editForm.durationMinutes = record.durationMinutes || null
|
||||
editForm.feedingMethod = (record.feedingMethod as FeedingMethod) || 'breastfeed'
|
||||
editForm.amountMl = record.amountMl || null
|
||||
const noteStr = record.note || record.remark || ''
|
||||
editForm.breastSide = noteStr.includes('右侧') ? 'right' : 'left'
|
||||
editForm.excretionType = (record.excretionType as ExcretionType) || 'pee'
|
||||
editForm.operatorName = record.operatorName || store.operatorName
|
||||
editForm.note = noteStr
|
||||
}
|
||||
|
||||
function appendNote(tag: string) {
|
||||
editForm.note = editForm.note ? `${editForm.note},${tag}` : tag
|
||||
}
|
||||
|
||||
async function submitEdit() {
|
||||
if (!props.record) return
|
||||
if (!editForm.startDate || !editForm.startTimeStr) {
|
||||
showToast('请选择开始时间')
|
||||
return
|
||||
}
|
||||
const startTime = `${editForm.startDate}T${editForm.startTimeStr}:00`
|
||||
let endTime: string | null = null
|
||||
if (editForm.hasEndTime && editForm.endDate && editForm.endTimeStr) {
|
||||
endTime = `${editForm.endDate}T${editForm.endTimeStr}:00`
|
||||
}
|
||||
|
||||
let finalNote = editForm.note
|
||||
if (editForm.recordType === 'feeding' && editForm.feedingMethod === 'breastfeed' && editForm.breastSide) {
|
||||
const sideText = editForm.breastSide === 'left' ? '左侧' : '右侧'
|
||||
if (!finalNote.includes('亲喂侧')) {
|
||||
finalNote = `亲喂侧: ${sideText}${finalNote ? ';' + finalNote : ''}`
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await store.editRecord(props.record.recordId, {
|
||||
recordType: editForm.recordType,
|
||||
startTime,
|
||||
endTime,
|
||||
durationMinutes: editForm.durationMinutes,
|
||||
feedingMethod: editForm.recordType === 'feeding' ? editForm.feedingMethod : null,
|
||||
amountMl: editForm.recordType === 'feeding' && editForm.feedingMethod !== 'breastfeed' ? editForm.amountMl : null,
|
||||
excretionType: editForm.recordType === 'excretion' ? editForm.excretionType : null,
|
||||
operatorName: editForm.operatorName,
|
||||
note: finalNote
|
||||
})
|
||||
emit('update:show', false)
|
||||
emit('success')
|
||||
showToast({ message: '修改成功', type: 'success' })
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '修改失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.show" class="modal-backdrop" @click.self="emit('update:show', false)">
|
||||
<div class="modal-sheet">
|
||||
<div class="modal-header">
|
||||
<h3>编辑照护记录</h3>
|
||||
<button class="close-btn" @click="emit('update:show', false)">×</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-form">
|
||||
<!-- 记录类型选择 -->
|
||||
<label>
|
||||
记录类型
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: editForm.recordType === 'feeding' }"
|
||||
@click="editForm.recordType = 'feeding'"
|
||||
>
|
||||
🍼 喂奶
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: editForm.recordType === 'sleep' }"
|
||||
@click="editForm.recordType = 'sleep'"
|
||||
>
|
||||
🌙 睡眠
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: editForm.recordType === 'excretion' }"
|
||||
@click="editForm.recordType = 'excretion'"
|
||||
>
|
||||
🧷 尿布排泄
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<!-- 发生时间 -->
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
||||
<label>
|
||||
开始日期
|
||||
<input v-model="editForm.startDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
开始时间
|
||||
<input v-model="editForm.startTimeStr" type="time" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- 喂奶特定字段 -->
|
||||
<template v-if="editForm.recordType === 'feeding'">
|
||||
<label>
|
||||
喂养方式
|
||||
<select v-model="editForm.feedingMethod">
|
||||
<option value="breastfeed">亲喂 (母乳)</option>
|
||||
<option value="bottle">瓶喂 (母乳)</option>
|
||||
<option value="formula">配方奶</option>
|
||||
<option value="mixed">混合喂养</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div v-if="editForm.feedingMethod === 'breastfeed'">
|
||||
<label>
|
||||
亲喂侧
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: editForm.breastSide === 'left' }"
|
||||
@click="editForm.breastSide = 'left'"
|
||||
>
|
||||
左侧
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: editForm.breastSide === 'right' }"
|
||||
@click="editForm.breastSide = 'right'"
|
||||
>
|
||||
右侧
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<label>
|
||||
奶量 (ml)
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<input v-model.number="editForm.amountMl" type="number" placeholder="输入奶量 ml" />
|
||||
<div class="chip-group" style="margin: 0;">
|
||||
<button
|
||||
v-for="amt in [30, 60, 90, 120]"
|
||||
:key="amt"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: editForm.amountMl === amt }"
|
||||
@click="editForm.amountMl = amt"
|
||||
>
|
||||
{{ amt }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 睡眠特定字段 -->
|
||||
<template v-if="editForm.recordType === 'sleep'">
|
||||
<div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
|
||||
<input id="editHasEnd" v-model="editForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
|
||||
<label for="editHasEnd" style="font-size: 14px; cursor: pointer; color: #1f2933;">包含醒来结束时间</label>
|
||||
</div>
|
||||
|
||||
<div v-if="editForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
||||
<label>
|
||||
醒来日期
|
||||
<input v-model="editForm.endDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
醒来时间
|
||||
<input v-model="editForm.endTimeStr" type="time" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label v-if="!editForm.hasEndTime">
|
||||
睡眠持续时间 (分钟,可选)
|
||||
<input v-model.number="editForm.durationMinutes" type="number" placeholder="例如:45" />
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<!-- 排泄特定字段 -->
|
||||
<template v-if="editForm.recordType === 'excretion'">
|
||||
<label>
|
||||
排泄类型
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: editForm.excretionType === 'pee' }"
|
||||
@click="editForm.excretionType = 'pee'"
|
||||
>
|
||||
💧 嘘嘘 (尿尿)
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: editForm.excretionType === 'poop' }"
|
||||
@click="editForm.excretionType = 'poop'"
|
||||
>
|
||||
💩 便便 (大便)
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<!-- 记录人选择 -->
|
||||
<label>
|
||||
记录人称谓
|
||||
<input v-model="editForm.operatorName" placeholder="例如:宝妈、宝爸" />
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="m in store.members"
|
||||
:key="m.memberId"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: editForm.operatorName === m.roleName }"
|
||||
@click="editForm.operatorName = m.roleName"
|
||||
>
|
||||
{{ m.roleName }}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<!-- 备注与快捷标签 -->
|
||||
<label>
|
||||
备注说明
|
||||
<input v-model="editForm.note" placeholder="例如:拍嗝顺利、状态好" />
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="tag in quickNotes"
|
||||
:key="tag"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
@click="appendNote(tag)"
|
||||
>
|
||||
+ {{ tag }}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="secondary-button" @click="emit('update:show', false)">取消</button>
|
||||
<button class="save-button" @click="submitEdit">保存修改</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,306 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { useCareStore } from '../../stores/careStore'
|
||||
import type { ExcretionType, FeedingMethod, RecordType } from '../../types/domain'
|
||||
|
||||
const props = defineProps<{
|
||||
show: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:show', value: boolean): void
|
||||
(e: 'success'): void
|
||||
}>()
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香']
|
||||
|
||||
const manualForm = reactive({
|
||||
recordType: 'feeding' as RecordType,
|
||||
startDate: new Date().toISOString().slice(0, 10),
|
||||
startTimeStr: new Date().toTimeString().slice(0, 5),
|
||||
hasEndTime: false,
|
||||
endDate: new Date().toISOString().slice(0, 10),
|
||||
endTimeStr: '',
|
||||
durationMinutes: null as number | null,
|
||||
feedingMethod: 'breastfeed' as FeedingMethod,
|
||||
amountMl: null as number | null,
|
||||
breastSide: 'left' as 'left' | 'right',
|
||||
excretionType: 'pee' as ExcretionType,
|
||||
operatorName: store.operatorName,
|
||||
note: ''
|
||||
})
|
||||
|
||||
watch(() => props.show, (newVal) => {
|
||||
if (newVal) {
|
||||
initForm()
|
||||
}
|
||||
})
|
||||
|
||||
function initForm() {
|
||||
const now = new Date()
|
||||
manualForm.recordType = 'feeding'
|
||||
manualForm.startDate = now.toISOString().slice(0, 10)
|
||||
manualForm.startTimeStr = now.toTimeString().slice(0, 5)
|
||||
manualForm.hasEndTime = false
|
||||
manualForm.endDate = now.toISOString().slice(0, 10)
|
||||
manualForm.endTimeStr = ''
|
||||
manualForm.durationMinutes = null
|
||||
manualForm.feedingMethod = store.preferences.defaultFeedingMethod || 'breastfeed'
|
||||
manualForm.amountMl = manualForm.feedingMethod === 'bottle' ? store.preferences.defaultBottleAmount : null
|
||||
manualForm.breastSide = store.preferences.defaultBreastSide || 'left'
|
||||
manualForm.excretionType = 'pee'
|
||||
manualForm.operatorName = store.operatorName
|
||||
manualForm.note = ''
|
||||
}
|
||||
|
||||
function appendNote(tag: string) {
|
||||
manualForm.note = manualForm.note ? `${manualForm.note},${tag}` : tag
|
||||
}
|
||||
|
||||
async function submitManual() {
|
||||
if (!manualForm.startDate || !manualForm.startTimeStr) {
|
||||
showToast('请选择开始时间')
|
||||
return
|
||||
}
|
||||
const startTime = `${manualForm.startDate}T${manualForm.startTimeStr}:00`
|
||||
let endTime: string | null = null
|
||||
if (manualForm.hasEndTime && manualForm.endDate && manualForm.endTimeStr) {
|
||||
endTime = `${manualForm.endDate}T${manualForm.endTimeStr}:00`
|
||||
}
|
||||
|
||||
let finalNote = manualForm.note
|
||||
if (manualForm.recordType === 'feeding' && manualForm.feedingMethod === 'breastfeed' && manualForm.breastSide) {
|
||||
const sideText = manualForm.breastSide === 'left' ? '左侧' : '右侧'
|
||||
if (!finalNote.includes('亲喂侧')) {
|
||||
finalNote = `亲喂侧: ${sideText}${finalNote ? ';' + finalNote : ''}`
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await store.manualLog({
|
||||
recordType: manualForm.recordType,
|
||||
startTime,
|
||||
endTime,
|
||||
durationMinutes: manualForm.durationMinutes,
|
||||
feedingMethod: manualForm.recordType === 'feeding' ? manualForm.feedingMethod : null,
|
||||
amountMl: manualForm.recordType === 'feeding' && manualForm.feedingMethod !== 'breastfeed' ? manualForm.amountMl : null,
|
||||
excretionType: manualForm.recordType === 'excretion' ? manualForm.excretionType : null,
|
||||
operatorName: manualForm.operatorName || store.operatorName,
|
||||
note: finalNote
|
||||
})
|
||||
emit('update:show', false)
|
||||
emit('success')
|
||||
showToast({ message: '补录成功', type: 'success' })
|
||||
} catch (err: any) {
|
||||
showToast(err.message || '补录失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.show" class="modal-backdrop" @click.self="emit('update:show', false)">
|
||||
<div class="modal-sheet">
|
||||
<div class="modal-header">
|
||||
<h3>补录照护记录</h3>
|
||||
<button class="close-btn" @click="emit('update:show', false)">×</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-form">
|
||||
<!-- 记录类型选择 -->
|
||||
<label>
|
||||
记录类型
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: manualForm.recordType === 'feeding' }"
|
||||
@click="manualForm.recordType = 'feeding'"
|
||||
>
|
||||
🍼 喂奶
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: manualForm.recordType === 'sleep' }"
|
||||
@click="manualForm.recordType = 'sleep'"
|
||||
>
|
||||
🌙 睡眠
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: manualForm.recordType === 'excretion' }"
|
||||
@click="manualForm.recordType = 'excretion'"
|
||||
>
|
||||
🧷 尿布排泄
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<!-- 发生时间 -->
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
||||
<label>
|
||||
开始日期
|
||||
<input v-model="manualForm.startDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
开始时间
|
||||
<input v-model="manualForm.startTimeStr" type="time" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- 喂奶特定字段 -->
|
||||
<template v-if="manualForm.recordType === 'feeding'">
|
||||
<label>
|
||||
喂养方式
|
||||
<select v-model="manualForm.feedingMethod">
|
||||
<option value="breastfeed">亲喂 (母乳)</option>
|
||||
<option value="bottle">瓶喂 (母乳)</option>
|
||||
<option value="formula">配方奶</option>
|
||||
<option value="mixed">混合喂养</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div v-if="manualForm.feedingMethod === 'breastfeed'">
|
||||
<label>
|
||||
亲喂侧
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: manualForm.breastSide === 'left' }"
|
||||
@click="manualForm.breastSide = 'left'"
|
||||
>
|
||||
左侧
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: manualForm.breastSide === 'right' }"
|
||||
@click="manualForm.breastSide = 'right'"
|
||||
>
|
||||
右侧
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<label>
|
||||
奶量 (ml)
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<input v-model.number="manualForm.amountMl" type="number" placeholder="输入奶量 ml" />
|
||||
<div class="chip-group" style="margin: 0;">
|
||||
<button
|
||||
v-for="amt in [30, 60, 90, 120]"
|
||||
:key="amt"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: manualForm.amountMl === amt }"
|
||||
@click="manualForm.amountMl = amt"
|
||||
>
|
||||
{{ amt }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 睡眠特定字段 -->
|
||||
<template v-if="manualForm.recordType === 'sleep'">
|
||||
<div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
|
||||
<input id="manualHasEnd" v-model="manualForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
|
||||
<label for="manualHasEnd" style="font-size: 14px; cursor: pointer; color: #1f2933;">包含醒来结束时间</label>
|
||||
</div>
|
||||
|
||||
<div v-if="manualForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
||||
<label>
|
||||
醒来日期
|
||||
<input v-model="manualForm.endDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
醒来时间
|
||||
<input v-model="manualForm.endTimeStr" type="time" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label v-if="!manualForm.hasEndTime">
|
||||
睡眠持续时间 (分钟,可选)
|
||||
<input v-model.number="manualForm.durationMinutes" type="number" placeholder="例如:45" />
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<!-- 排泄特定字段 -->
|
||||
<template v-if="manualForm.recordType === 'excretion'">
|
||||
<label>
|
||||
排泄类型
|
||||
<div class="chip-group">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: manualForm.excretionType === 'pee' }"
|
||||
@click="manualForm.excretionType = 'pee'"
|
||||
>
|
||||
💧 嘘嘘 (尿尿)
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: manualForm.excretionType === 'poop' }"
|
||||
@click="manualForm.excretionType = 'poop'"
|
||||
>
|
||||
💩 便便 (大便)
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<!-- 记录人选择 -->
|
||||
<label>
|
||||
记录人称谓
|
||||
<div style="display: flex; gap: 8px;">
|
||||
<input v-model="manualForm.operatorName" placeholder="例如:宝妈、宝爸" />
|
||||
</div>
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="m in store.members"
|
||||
:key="m.memberId"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
:class="{ active: manualForm.operatorName === m.roleName }"
|
||||
@click="manualForm.operatorName = m.roleName"
|
||||
>
|
||||
{{ m.roleName }}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<!-- 备注与快捷标签 -->
|
||||
<label>
|
||||
备注说明
|
||||
<input v-model="manualForm.note" placeholder="例如:拍嗝顺利、状态好" />
|
||||
<div class="chip-group">
|
||||
<button
|
||||
v-for="tag in quickNotes"
|
||||
:key="tag"
|
||||
type="button"
|
||||
class="chip sm"
|
||||
@click="appendNote(tag)"
|
||||
>
|
||||
+ {{ tag }}
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="secondary-button" @click="emit('update:show', false)">取消</button>
|
||||
<button class="save-button" @click="submitManual">确认补录</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,141 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { showToast } from 'vant'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useCareStore } from '../stores/careStore'
|
||||
import BabySettingsTab from '../components/settings/BabySettingsTab.vue'
|
||||
import FamilySettingsTab from '../components/settings/FamilySettingsTab.vue'
|
||||
import MemberSettingsTab from '../components/settings/MemberSettingsTab.vue'
|
||||
import ActionSettingsTab from '../components/settings/ActionSettingsTab.vue'
|
||||
|
||||
const store = useCareStore()
|
||||
const activeTab = ref('baby')
|
||||
const form = reactive({
|
||||
name: '',
|
||||
gender: 'boy',
|
||||
birthDate: '',
|
||||
deliveryType: 'natural',
|
||||
operatorName: store.operatorName
|
||||
})
|
||||
|
||||
const currentBabyLabel = computed(() => store.baby ? `${store.baby.name} · ${store.baby.ageText}` : '未选择宝宝')
|
||||
const currentBabyLabel = computed(() =>
|
||||
store.baby ? `${store.baby.name} · ${store.baby.ageText}` : '未选择宝宝'
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
await store.load()
|
||||
syncBabyForm()
|
||||
})
|
||||
|
||||
watch(() => store.baby?.babyId, () => {
|
||||
syncBabyForm()
|
||||
})
|
||||
|
||||
watch(() => form.operatorName, value => {
|
||||
store.setOperatorName(value)
|
||||
})
|
||||
|
||||
function syncBabyForm() {
|
||||
if (!store.baby) return
|
||||
form.name = store.baby.name
|
||||
form.gender = store.baby.gender
|
||||
form.birthDate = store.baby.birthDate
|
||||
form.deliveryType = store.baby.deliveryType
|
||||
}
|
||||
|
||||
async function save() {
|
||||
await store.saveBaby({
|
||||
name: form.name,
|
||||
gender: form.gender,
|
||||
birthDate: form.birthDate,
|
||||
deliveryType: form.deliveryType
|
||||
})
|
||||
showToast({ message: '宝宝信息已保存', type: 'success' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow">设置</p>
|
||||
<p class="eyebrow">设置与配置</p>
|
||||
<h1>家庭照护维护</h1>
|
||||
<p>{{ currentBabyLabel }}</p>
|
||||
</header>
|
||||
|
||||
<van-tabs v-model:active="activeTab" shrink>
|
||||
<van-tabs v-model:active="activeTab" shrink animated swipeable>
|
||||
<!-- Tab 1: 宝宝维护 -->
|
||||
<van-tab title="宝宝" name="baby">
|
||||
<section class="panel form-panel">
|
||||
<label>
|
||||
宝宝昵称
|
||||
<input v-model="form.name" />
|
||||
</label>
|
||||
<label>
|
||||
出生日期
|
||||
<input v-model="form.birthDate" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
性别
|
||||
<select v-model="form.gender">
|
||||
<option value="boy">男宝</option>
|
||||
<option value="girl">女宝</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
分娩方式
|
||||
<select v-model="form.deliveryType">
|
||||
<option value="natural">顺产</option>
|
||||
<option value="c_section">剖宫产</option>
|
||||
<option value="unknown">暂不设置</option>
|
||||
</select>
|
||||
</label>
|
||||
<button class="save-button" @click="save">保存宝宝信息</button>
|
||||
</section>
|
||||
<BabySettingsTab />
|
||||
</van-tab>
|
||||
|
||||
<!-- Tab 2: 家庭维护 -->
|
||||
<van-tab title="家庭" name="family">
|
||||
<section class="panel">
|
||||
<div class="settings-list">
|
||||
<div>
|
||||
<span>家庭名称</span>
|
||||
<strong>{{ store.context?.family.name || '新生儿照护家庭' }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>邀请码</span>
|
||||
<strong>{{ store.context?.family.inviteCode || '暂未设置' }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>宝宝数量</span>
|
||||
<strong>{{ store.babies.length }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<FamilySettingsTab />
|
||||
</van-tab>
|
||||
|
||||
<!-- Tab 3: 成员维护 -->
|
||||
<van-tab title="成员" name="members">
|
||||
<section class="panel form-panel">
|
||||
<label>
|
||||
当前记录人
|
||||
<input v-model="form.operatorName" />
|
||||
</label>
|
||||
<div class="settings-list">
|
||||
<div v-for="member in store.members" :key="member.memberId">
|
||||
<span>{{ member.roleName }}</span>
|
||||
<strong>{{ member.roleType === 'owner' ? '家庭管理员' : '照护成员' }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<MemberSettingsTab />
|
||||
</van-tab>
|
||||
|
||||
<!-- Tab 4: 行为偏好维护 -->
|
||||
<van-tab title="行为" name="actions">
|
||||
<section class="panel">
|
||||
<div class="settings-list">
|
||||
<div>
|
||||
<span>亲喂</span>
|
||||
<strong>支持计时、左右侧切换、一键记录</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>瓶喂</span>
|
||||
<strong>支持调整奶量</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>快速反馈</span>
|
||||
<strong>记录成功后显示温馨提示</strong>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<ActionSettingsTab />
|
||||
</van-tab>
|
||||
</van-tabs>
|
||||
</section>
|
||||
|
||||
@@ -1,43 +1,111 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { showToast, showConfirmDialog } from 'vant'
|
||||
import { deleteRecord } from '../api/client'
|
||||
import { useCareStore } from '../stores/careStore'
|
||||
import { formatMinutes, formatTime, recordLabel } from '../utils/format'
|
||||
import type { CareRecord } from '../types/domain'
|
||||
import TimelineManualModal from '../components/timeline/TimelineManualModal.vue'
|
||||
import TimelineEditModal from '../components/timeline/TimelineEditModal.vue'
|
||||
|
||||
const store = useCareStore()
|
||||
|
||||
onMounted(() => {
|
||||
store.load()
|
||||
// 补录弹窗控制
|
||||
const showManualModal = ref(false)
|
||||
|
||||
// 编辑弹窗控制
|
||||
const showEditModal = ref(false)
|
||||
const selectedRecord = ref<CareRecord | null>(null)
|
||||
|
||||
onMounted(async () => {
|
||||
await store.load()
|
||||
})
|
||||
|
||||
function openManualModal() {
|
||||
showManualModal.value = true
|
||||
}
|
||||
|
||||
function openEditModal(record: CareRecord) {
|
||||
selectedRecord.value = record
|
||||
showEditModal.value = true
|
||||
}
|
||||
|
||||
async function remove(recordId: string) {
|
||||
await deleteRecord(recordId)
|
||||
await store.refreshSummary()
|
||||
try {
|
||||
await showConfirmDialog({
|
||||
title: '删除记录',
|
||||
message: '确定要删除这条照护记录吗?'
|
||||
})
|
||||
await deleteRecord(recordId)
|
||||
await store.refreshSummary()
|
||||
showToast({ message: '记录已删除', type: 'success' })
|
||||
} catch {
|
||||
// cancel
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<header class="page-header">
|
||||
<p class="eyebrow">今日记录</p>
|
||||
<p class="eyebrow">实时照护记录</p>
|
||||
<h1>照护流水</h1>
|
||||
</header>
|
||||
|
||||
<!-- 顶部操作栏 -->
|
||||
<div class="timeline-header-actions">
|
||||
<div>
|
||||
<span style="font-size: 13px; color: #65707d;">
|
||||
今日已记录 <strong>{{ store.summary?.timeline?.length || 0 }}</strong> 项
|
||||
</span>
|
||||
</div>
|
||||
<button class="primary-pill-button" @click="openManualModal">
|
||||
+ 补录记录
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 流水列表 -->
|
||||
<div class="timeline">
|
||||
<article v-for="record in store.summary?.timeline || []" :key="record.recordId" class="timeline-item">
|
||||
<div>
|
||||
<strong>{{ recordLabel(record.recordType, record.feedingMethod || record.excretionType) }}</strong>
|
||||
<article
|
||||
v-for="record in store.summary?.timeline || []"
|
||||
:key="record.recordId"
|
||||
class="timeline-item"
|
||||
>
|
||||
<div style="flex: 1;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<strong style="font-size: 16px;">
|
||||
{{ recordLabel(record.recordType, record.feedingMethod || record.excretionType) }}
|
||||
</strong>
|
||||
<span v-if="record.amountMl" style="background: #fff1cf; color: #8a540d; font-size: 12px; font-weight: 800; padding: 2px 6px; border-radius: 4px;">
|
||||
{{ record.amountMl }}ml
|
||||
</span>
|
||||
<span v-if="record.durationMinutes" style="background: #eee9ff; color: #5925dc; font-size: 12px; font-weight: 800; padding: 2px 6px; border-radius: 4px;">
|
||||
{{ formatMinutes(record.durationMinutes) }}
|
||||
</span>
|
||||
</div>
|
||||
<p>
|
||||
{{ formatTime(record.startTime) }}
|
||||
<span v-if="record.durationMinutes"> · {{ formatMinutes(record.durationMinutes) }}</span>
|
||||
<span v-if="record.amountMl"> · {{ record.amountMl }}ml</span>
|
||||
<span v-if="record.endTime"> ~ {{ formatTime(record.endTime) }}</span>
|
||||
</p>
|
||||
<small>{{ record.operatorName }}</small>
|
||||
<p v-if="record.note || record.remark" style="color: #4b5563; font-size: 13px; margin-top: 2px;">
|
||||
📝 {{ record.note || record.remark }}
|
||||
</p>
|
||||
<small>记录人: {{ record.operatorName }}</small>
|
||||
</div>
|
||||
|
||||
<div class="item-actions">
|
||||
<button class="edit-button" @click="openEditModal(record)">编辑</button>
|
||||
<button class="delete-button" @click="remove(record.recordId)">删除</button>
|
||||
</div>
|
||||
<button class="text-button" @click="remove(record.recordId)">删除</button>
|
||||
</article>
|
||||
<p v-if="!store.summary?.timeline?.length" class="empty">今天还没有记录。</p>
|
||||
|
||||
<p v-if="!store.summary?.timeline?.length" class="empty">今天还没有记录,点击上方“+ 补录记录”开始吧。</p>
|
||||
</div>
|
||||
|
||||
<!-- 弹窗:补录记录维护组件 -->
|
||||
<TimelineManualModal v-model:show="showManualModal" />
|
||||
|
||||
<!-- 弹窗:编辑记录维护组件 -->
|
||||
<TimelineEditModal v-model:show="showEditModal" :record="selectedRecord" />
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -1,18 +1,60 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
createBaby,
|
||||
createFeeding,
|
||||
createManualRecord,
|
||||
createMember,
|
||||
createPee,
|
||||
createPoop,
|
||||
deleteMember,
|
||||
endFeeding,
|
||||
endSleep,
|
||||
getFamilyContext,
|
||||
getDailySummary,
|
||||
getFamilyContext,
|
||||
setDefaultBaby as apiSetDefaultBaby,
|
||||
startFeeding,
|
||||
updateBaby,
|
||||
startSleep,
|
||||
updateCurrentBaby
|
||||
updateBaby,
|
||||
updateCurrentBaby,
|
||||
updateFamily,
|
||||
updateMember,
|
||||
updateRecord
|
||||
} from '../api/client'
|
||||
import type { BabyProfile, DailySummary, FamilyContext, FamilyMember, FeedingMethod } from '../types/domain'
|
||||
import type {
|
||||
ActionPreferences,
|
||||
BabyProfile,
|
||||
CreateBabyPayload,
|
||||
CreateManualRecordPayload,
|
||||
CreateMemberPayload,
|
||||
DailySummary,
|
||||
FamilyContext,
|
||||
FamilyMember,
|
||||
FeedingMethod,
|
||||
UpdateCareRecordPayload,
|
||||
UpdateFamilyPayload,
|
||||
UpdateMemberPayload
|
||||
} from '../types/domain'
|
||||
|
||||
const defaultPreferences: ActionPreferences = {
|
||||
defaultFeedingMethod: 'breastfeed',
|
||||
defaultBottleAmount: 60,
|
||||
defaultBreastSide: 'left',
|
||||
defaultSleepMode: 'timer',
|
||||
quickFeedbackToast: true,
|
||||
autoBurpReminder: true
|
||||
}
|
||||
|
||||
function loadInitialPreferences(): ActionPreferences {
|
||||
try {
|
||||
const raw = localStorage.getItem('actionPreferences')
|
||||
if (raw) {
|
||||
return { ...defaultPreferences, ...JSON.parse(raw) }
|
||||
}
|
||||
} catch {
|
||||
// fallback
|
||||
}
|
||||
return defaultPreferences
|
||||
}
|
||||
|
||||
export const useCareStore = defineStore('care', {
|
||||
state: () => ({
|
||||
@@ -23,6 +65,7 @@ export const useCareStore = defineStore('care', {
|
||||
baby: null as BabyProfile | null,
|
||||
summary: null as DailySummary | null,
|
||||
operatorName: localStorage.getItem('operatorName') || '宝妈',
|
||||
preferences: loadInitialPreferences() as ActionPreferences,
|
||||
loading: false,
|
||||
error: ''
|
||||
}),
|
||||
@@ -63,11 +106,62 @@ export const useCareStore = defineStore('care', {
|
||||
this.operatorName = name || '宝妈'
|
||||
localStorage.setItem('operatorName', this.operatorName)
|
||||
},
|
||||
savePreferences(prefs: Partial<ActionPreferences>) {
|
||||
this.preferences = { ...this.preferences, ...prefs }
|
||||
localStorage.setItem('actionPreferences', JSON.stringify(this.preferences))
|
||||
},
|
||||
async saveBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
|
||||
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)
|
||||
await this.refreshSummary()
|
||||
},
|
||||
async addBaby(payload: CreateBabyPayload) {
|
||||
const newBaby = await createBaby(payload)
|
||||
this.babies.push(newBaby)
|
||||
if (payload.isDefault || this.babies.length === 1) {
|
||||
await this.selectBaby(newBaby.babyId)
|
||||
}
|
||||
return newBaby
|
||||
},
|
||||
async setDefaultBaby(babyId: string) {
|
||||
const updated = await apiSetDefaultBaby(babyId)
|
||||
this.babies = this.babies.map(b => ({
|
||||
...b,
|
||||
isDefault: b.babyId === babyId ? 1 : 0
|
||||
}))
|
||||
await this.selectBaby(babyId)
|
||||
return updated
|
||||
},
|
||||
async saveFamily(payload: UpdateFamilyPayload) {
|
||||
if (!this.context?.family.familyId) return
|
||||
const updated = await updateFamily(this.context.family.familyId, payload)
|
||||
this.context.family = updated
|
||||
},
|
||||
async addMember(payload: CreateMemberPayload) {
|
||||
if (!this.context?.family.familyId) return
|
||||
const newMember = await createMember(this.context.family.familyId, payload)
|
||||
if (payload.defaultOperator) {
|
||||
this.members.forEach(m => { m.defaultOperator = false })
|
||||
this.setOperatorName(newMember.roleName)
|
||||
}
|
||||
this.members.push(newMember)
|
||||
return newMember
|
||||
},
|
||||
async editMember(memberId: string, payload: UpdateMemberPayload) {
|
||||
if (!this.context?.family.familyId) return
|
||||
const updated = await updateMember(this.context.family.familyId, memberId, payload)
|
||||
if (payload.defaultOperator) {
|
||||
this.members.forEach(m => { m.defaultOperator = false })
|
||||
this.setOperatorName(updated.roleName)
|
||||
}
|
||||
this.members = this.members.map(m => m.memberId === memberId ? updated : m)
|
||||
return updated
|
||||
},
|
||||
async removeMember(memberId: string) {
|
||||
if (!this.context?.family.familyId) return
|
||||
await deleteMember(this.context.family.familyId, memberId)
|
||||
this.members = this.members.filter(m => m.memberId !== memberId)
|
||||
},
|
||||
async logFeeding(method: FeedingMethod, amountMl?: number, breastSide?: 'left' | 'right') {
|
||||
if (!this.baby) return
|
||||
await createFeeding({
|
||||
@@ -106,6 +200,20 @@ export const useCareStore = defineStore('care', {
|
||||
if (!this.baby) return
|
||||
await createPoop({ babyId: this.baby.babyId, operatorName: this.operatorName })
|
||||
await this.refreshSummary()
|
||||
},
|
||||
async manualLog(payload: Omit<CreateManualRecordPayload, 'babyId'>) {
|
||||
if (!this.baby) return
|
||||
const res = await createManualRecord({
|
||||
...payload,
|
||||
babyId: this.baby.babyId
|
||||
})
|
||||
await this.refreshSummary()
|
||||
return res
|
||||
},
|
||||
async editRecord(recordId: string, payload: UpdateCareRecordPayload) {
|
||||
const res = await updateRecord(recordId, payload)
|
||||
await this.refreshSummary()
|
||||
return res
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -344,6 +344,219 @@ button {
|
||||
background: #1f7a5c;
|
||||
color: white;
|
||||
font-weight: 900;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.save-button:hover {
|
||||
background: #18634a;
|
||||
}
|
||||
|
||||
.secondary-button {
|
||||
padding: 10px 16px;
|
||||
border-radius: 12px;
|
||||
background: #f0ece5;
|
||||
color: #4b5563;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.secondary-button:hover {
|
||||
background: #e3ded6;
|
||||
}
|
||||
|
||||
.primary-pill-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 18px;
|
||||
border-radius: 999px;
|
||||
background: #8a540d;
|
||||
color: white;
|
||||
font-weight: 800;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.primary-pill-button:hover {
|
||||
background: #734509;
|
||||
}
|
||||
|
||||
.chip-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.chip {
|
||||
padding: 6px 14px;
|
||||
border-radius: 999px;
|
||||
background: #f4efe6;
|
||||
color: #555e69;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
border: 1px solid transparent;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.chip.active {
|
||||
background: #8a540d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.chip.sm {
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.edit-button {
|
||||
background: #eef6ff;
|
||||
color: #175cd3;
|
||||
border-radius: 999px;
|
||||
padding: 6px 12px;
|
||||
font-weight: 800;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.delete-button {
|
||||
background: #fff0f0;
|
||||
color: #b42318;
|
||||
border-radius: 999px;
|
||||
padding: 6px 12px;
|
||||
font-weight: 800;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.45);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.modal-sheet {
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
background: #ffffff;
|
||||
border-radius: 24px 24px 0 0;
|
||||
padding: 24px 20px 36px;
|
||||
box-shadow: 0 -10px 40px rgba(0, 0, 0, 0.15);
|
||||
animation: slideUp 0.25s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from { transform: translateY(100%); }
|
||||
to { transform: translateY(0); }
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.modal-header h3 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
color: #1f2933;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: #f0ece5;
|
||||
color: #65707d;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-form {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.modal-form label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
color: #4b5563;
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.modal-form input,
|
||||
.modal-form select,
|
||||
.modal-form textarea {
|
||||
width: 100%;
|
||||
border: 1px solid #ded6c8;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
background: #fffdfa;
|
||||
color: #1f2933;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.timeline-header-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.tag-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
.tag-badge.owner {
|
||||
background: #fef0c7;
|
||||
color: #b54708;
|
||||
}
|
||||
|
||||
.tag-badge.caregiver {
|
||||
background: #e0f2fe;
|
||||
color: #026aa2;
|
||||
}
|
||||
|
||||
.tag-badge.default {
|
||||
background: #d1fadf;
|
||||
color: #027a48;
|
||||
}
|
||||
|
||||
@media (min-width: 720px) {
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface BabyProfile {
|
||||
deliveryType: string
|
||||
ageDays: number
|
||||
ageText: string
|
||||
isDefault?: boolean | number
|
||||
}
|
||||
|
||||
export interface FamilyInfo {
|
||||
@@ -47,7 +48,11 @@ export interface CareRecord {
|
||||
excretionType?: ExcretionType | null
|
||||
operatorName: string
|
||||
note?: string | null
|
||||
createdAt: string
|
||||
remark?: string | null
|
||||
createdAt?: string
|
||||
createdTime?: string
|
||||
updatedAt?: string
|
||||
updatedTime?: string
|
||||
}
|
||||
|
||||
export interface DailySummary {
|
||||
@@ -64,6 +69,66 @@ export interface DailySummary {
|
||||
timeline: CareRecord[]
|
||||
}
|
||||
|
||||
export interface ActionPreferences {
|
||||
defaultFeedingMethod: FeedingMethod
|
||||
defaultBottleAmount: number
|
||||
defaultBreastSide: 'left' | 'right'
|
||||
defaultSleepMode: 'timer' | 'manual'
|
||||
quickFeedbackToast: boolean
|
||||
autoBurpReminder: boolean
|
||||
}
|
||||
|
||||
export interface CreateManualRecordPayload {
|
||||
babyId: string
|
||||
recordType: RecordType
|
||||
startTime: string
|
||||
endTime?: string | null
|
||||
durationMinutes?: number | null
|
||||
feedingMethod?: FeedingMethod | null
|
||||
amountMl?: number | null
|
||||
excretionType?: ExcretionType | null
|
||||
operatorName?: string
|
||||
note?: string | null
|
||||
}
|
||||
|
||||
export interface UpdateCareRecordPayload {
|
||||
recordType?: RecordType
|
||||
startTime?: string
|
||||
endTime?: string | null
|
||||
durationMinutes?: number | null
|
||||
feedingMethod?: FeedingMethod | null
|
||||
amountMl?: number | null
|
||||
excretionType?: ExcretionType | null
|
||||
operatorName?: string
|
||||
note?: string | null
|
||||
}
|
||||
|
||||
export interface CreateBabyPayload {
|
||||
familyId?: string
|
||||
name: string
|
||||
gender?: string
|
||||
birthDate: string
|
||||
deliveryType?: string
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
export interface UpdateFamilyPayload {
|
||||
name: string
|
||||
inviteCode?: string | null
|
||||
}
|
||||
|
||||
export interface CreateMemberPayload {
|
||||
roleName: string
|
||||
roleType?: string
|
||||
defaultOperator?: boolean
|
||||
}
|
||||
|
||||
export interface UpdateMemberPayload {
|
||||
roleName: string
|
||||
roleType?: string
|
||||
defaultOperator?: boolean
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean
|
||||
data: T
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.git
|
||||
*.log
|
||||
.env
|
||||
@@ -1,7 +1,7 @@
|
||||
FROM eclipse-temurin:21-jre
|
||||
|
||||
WORKDIR /app
|
||||
COPY deploy/artifacts/server/app.jar /app/app.jar
|
||||
COPY artifacts/server/baby-tracker-server-0.1.0.jar /app/app.jar
|
||||
|
||||
EXPOSE 9899
|
||||
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
.git
|
||||
.agents
|
||||
openspec
|
||||
doc
|
||||
apps/web/node_modules
|
||||
apps/web/dist
|
||||
server-java/target
|
||||
**/*.log
|
||||
**/.env
|
||||
deploy/.env
|
||||
*.log
|
||||
.env
|
||||
@@ -1,6 +1,6 @@
|
||||
FROM nginx:1.27-alpine
|
||||
|
||||
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY deploy/artifacts/web/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY artifacts/web /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
@@ -1,10 +1,3 @@
|
||||
.git
|
||||
.agents
|
||||
openspec
|
||||
doc
|
||||
apps/web/node_modules
|
||||
apps/web/dist
|
||||
server-java/target
|
||||
**/*.log
|
||||
**/.env
|
||||
deploy/.env
|
||||
*.log
|
||||
.env
|
||||
+16
-11
@@ -44,35 +44,40 @@ yyMMdd_HHmm
|
||||
- `baby-tracker-server:latest`
|
||||
- `baby-tracker-web:latest`
|
||||
|
||||
## 首次部署
|
||||
## 首次与更新部署
|
||||
|
||||
先在本地或 CI 完成编译,并把产物上传到服务器:
|
||||
编译时前后端产物会自动输出并复制到 `deploy/artifacts/server` 与 `deploy/artifacts/web` 目录下:
|
||||
|
||||
```text
|
||||
deploy/artifacts/server/app.jar
|
||||
deploy/artifacts/web/dist/index.html
|
||||
deploy/artifacts/server/baby-tracker-server-0.1.0.jar
|
||||
deploy/artifacts/web/index.html
|
||||
```
|
||||
|
||||
本地编译命令:
|
||||
### 1. 本地一键编译与产物收集
|
||||
|
||||
根目录提供了一键脚本:
|
||||
- Windows: `.\build-artifacts.ps1`
|
||||
- Linux / macOS: `./build-artifacts.sh`
|
||||
|
||||
也可以分别进入目录独立编译(均会自动拷贝到 `deploy/artifacts` 目录):
|
||||
```bash
|
||||
# 后端编译(自动将生成的 baby-tracker-server-0.1.0.jar 拷贝到 deploy/artifacts/server/)
|
||||
cd server-java
|
||||
mvn -DskipTests package
|
||||
|
||||
# 前端编译(自动将生成的 dist 文件夹内容拷贝到 deploy/artifacts/web/)
|
||||
cd ../apps/web
|
||||
npm run build
|
||||
```
|
||||
|
||||
上传时:
|
||||
### 2. 上传与部署
|
||||
|
||||
- 将 `server-java/target/baby-tracker-server-0.1.0.jar` 上传为 `deploy/artifacts/server/app.jar`
|
||||
- 将 `apps/web/dist` 整个目录上传到 `deploy/artifacts/web/dist`
|
||||
|
||||
服务器执行:
|
||||
编译完成后,**直接将 `deploy/artifacts` 文件夹复制到服务器的 `deploy/artifacts`**。
|
||||
|
||||
服务器执行部署:
|
||||
```bash
|
||||
cd deploy
|
||||
cp env.example .env
|
||||
cp env.example .env # 首次部署请配置 .env
|
||||
vim .env
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
+12
-6
@@ -29,15 +29,21 @@ if [ ! -f ".env" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "artifacts/server/app.jar" ]; then
|
||||
echo "未找到后端产物: deploy/artifacts/server/app.jar" >&2
|
||||
echo "请先上传已编译好的 Spring Boot 可执行 jar,并命名为 app.jar。" >&2
|
||||
# 如果 artifacts 文件夹被直接复制到了项目根目录(上级目录),而 deploy 目录下尚未存在,则自动复制或链接过来
|
||||
if [ ! -d "artifacts" ] && [ -d "../artifacts" ]; then
|
||||
echo "检测到项目根目录下存在 artifacts 目录,正在同步至 deploy/artifacts..."
|
||||
cp -r ../artifacts ./artifacts
|
||||
fi
|
||||
|
||||
if [ ! -f "artifacts/server/baby-tracker-server-0.1.0.jar" ]; then
|
||||
echo "未找到后端产物: artifacts/server/baby-tracker-server-0.1.0.jar" >&2
|
||||
echo "请先完成后端编译并复制 artifacts 文件夹到当前部署目录。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "artifacts/web/dist/index.html" ]; then
|
||||
echo "未找到前端产物: deploy/artifacts/web/dist/index.html" >&2
|
||||
echo "请先上传前端 dist 目录到 deploy/artifacts/web/dist。" >&2
|
||||
if [ ! -f "artifacts/web/index.html" ]; then
|
||||
echo "未找到前端产物: artifacts/web/index.html" >&2
|
||||
echo "请先完成前端编译并复制 artifacts 文件夹到当前部署目录。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
services:
|
||||
baby-tracker-server:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/Dockerfile.server
|
||||
context: .
|
||||
dockerfile: Dockerfile.server
|
||||
image: baby-tracker-server:${IMAGE_VERSION:-latest}
|
||||
container_name: baby-tracker-server
|
||||
restart: always
|
||||
@@ -13,8 +13,8 @@ services:
|
||||
|
||||
baby-tracker-web:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/Dockerfile.web
|
||||
context: .
|
||||
dockerfile: Dockerfile.web
|
||||
image: baby-tracker-web:${IMAGE_VERSION:-latest}
|
||||
container_name: baby-tracker-web
|
||||
restart: always
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# 2026-09-26 统一通用审计字段、请求/响应/转化体分层与接口规范化调整
|
||||
|
||||
## 1. 调整背景与目标
|
||||
|
||||
为规范 baby-tracker 后端工程架构、数据库模型与 API 交互协议,本次调整实现了以下四项核心改造:
|
||||
1. **统一表结构标准字段**:
|
||||
所有表结构统一具备 6 个标准审计与状态字段:
|
||||
- 备注 (`remark`, `VARCHAR(500)`)
|
||||
- 删除状态 (`deleted`, `TINYINT(1)`, 逻辑删除: 0未删除, 1已删除)
|
||||
- 创建人 (`created_by`, `VARCHAR(50)`, 默认 `admin`)
|
||||
- 创建时间 (`created_time`, `DATETIME`, 默认 `CURRENT_TIMESTAMP`)
|
||||
- 修改人 (`updated_by`, `VARCHAR(50)`, 默认 `admin`)
|
||||
- 修改时间 (`updated_time`, `DATETIME`, 默认 `CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`)
|
||||
2. **MyBatis-Plus 统一拦截与元数据填充**:
|
||||
- 通过 `AuditFieldFillInterceptor`(实现 `InnerInterceptor` 并注册至 `MybatisPlusInterceptor`)与 `AuditMetaObjectHandler`(实现 `MetaObjectHandler`)双重保障,在实体插入与更新时自动捕获并填充审计字段;
|
||||
- 引入 `UserContext` 上下文机制,若无登录会话信息,创建人与修改人统一自动降级默认取 `"admin"`。
|
||||
3. **数据库精简与索引优化**:
|
||||
- 全面去除所有表针对 `deleted` 字段的单独索引,精简写开销;
|
||||
- `care_record` 彻底剔除历史多余的 `note`(存量自动同步迁移至 `remark`)与 `deleted_at`(存量删除状态已映射为 `deleted = 1`),仅保留标准 `remark` 与 `deleted`。
|
||||
4. **接口协议规范与分层治理**:
|
||||
- 后端 Controller 接口**全面废止 `@PathVariable`**,需传参接口一律改为使用 `@RequestBody`;
|
||||
- 各业务模块结构规范化:各模块下分别创建 `ro/`(请求体)、`vo/`(响应体)、`dto/`(转化体与转换器)文件夹,文件命名分别调整为 `xxRO`、`xxVO`、`xxDTO`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 数据库与实体架构设计
|
||||
|
||||
### 2.1 数据库结构升级 (`V2__audit_fields_and_logic_delete.sql`)
|
||||
- 涉及表:`app_user`、`family`、`family_member`、`baby_profile`、`care_record`;
|
||||
- 执行字段重命名与新增:
|
||||
- `created_at` 重命名为 `created_time`;
|
||||
- `updated_at` 重命名为 `updated_time`;
|
||||
- 增加 `remark`、`deleted`、`created_by`、`updated_by`;
|
||||
- `care_record` 表清理:
|
||||
- 迁移历史数据:`UPDATE care_record SET remark = note WHERE remark IS NULL AND note IS NOT NULL;`
|
||||
- 迁移删除标记:`UPDATE care_record SET deleted = 1 WHERE deleted_at IS NOT NULL;`
|
||||
- 删除 `idx_care_record_deleted` 索引,并彻底 `DROP COLUMN note` 与 `DROP COLUMN deleted_at`;
|
||||
- 索引约束:全表均无 `deleted` 单独索引。
|
||||
|
||||
### 2.2 基础实体 (`BaseEntity`)
|
||||
```java
|
||||
@Data
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableLogic
|
||||
@TableField(value = "deleted", fill = FieldFill.INSERT)
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "created_by", fill = FieldFill.INSERT)
|
||||
private String createdBy;
|
||||
|
||||
@TableField(value = "created_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createdTime;
|
||||
|
||||
@TableField(value = "updated_by", fill = FieldFill.INSERT_UPDATE)
|
||||
private String updatedBy;
|
||||
|
||||
@TableField(value = "updated_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 拦截器与自动填充
|
||||
- **`UserContext`**:
|
||||
封装 `ThreadLocal<String>`,提供 `getCurrentUser()`,无当前用户时默认返回 `"admin"`。
|
||||
- **`AuditFieldFillInterceptor`**:
|
||||
实现 `InnerInterceptor.beforeUpdate`,拦截 MyBatis-Plus 执行的所有 INSERT/UPDATE 操作,提取 `BaseEntity` 实例进行时间戳与操作人补填。
|
||||
- **`AuditMetaObjectHandler`**:
|
||||
实现 `MetaObjectHandler.insertFill` 与 `updateFill`,通过 MyBatis-Plus 标准元对象反射统一注入 `created_by`、`created_time`、`updated_by`、`updated_time` 与 `deleted`。
|
||||
- **`application.yml`**:
|
||||
配置 `logic-delete-field: deleted`、`logic-delete-value: 1`、`logic-not-delete-value: 0`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 模块对象分层架构 (RO / VO / DTO)
|
||||
|
||||
各模块目录结构统一演进为:
|
||||
```text
|
||||
module/
|
||||
├── baby/
|
||||
│ ├── ro/ # 请求体: CreateBabyRO, UpdateBabyRO, SetDefaultBabyRO
|
||||
│ ├── vo/ # 响应体: BabyVO
|
||||
│ ├── dto/ # 转化体: BabyDTO, BabyConvert
|
||||
│ ├── mapper/ # MyBatis-Plus BaseMapper
|
||||
│ ├── BabyProfile.java # Entity 实体 (继承 BaseEntity)
|
||||
│ ├── BabyService.java
|
||||
│ └── BabyController.java
|
||||
├── family/
|
||||
│ ├── ro/ # 请求体: CreateMemberRO, UpdateFamilyRO, UpdateMemberRO, DeleteMemberRO
|
||||
│ ├── vo/ # 响应体: FamilyVO, FamilyMemberVO, FamilyContextVO
|
||||
│ ├── dto/ # 转化体: FamilyDTO, FamilyMemberDTO, FamilyConvert
|
||||
│ ├── mapper/
|
||||
│ ├── FamilyInfo.java
|
||||
│ ├── FamilyMember.java
|
||||
│ ├── FamilyService.java
|
||||
│ └── FamilyController.java
|
||||
├── record/
|
||||
│ ├── ro/ # 请求体: CreateFeedingRO, CreateManualRecordRO, SleepRO, ExcretionRO, UpdateCareRecordRO, DeleteCareRecordRO
|
||||
│ ├── vo/ # 响应体: CareRecordVO
|
||||
│ ├── dto/ # 转化体: CareRecordDTO, CareRecordConvert
|
||||
│ ├── mapper/
|
||||
│ ├── CareRecord.java
|
||||
│ ├── CareRecordService.java
|
||||
│ └── CareRecordController.java
|
||||
└── summary/
|
||||
├── ro/ # 请求体: SummaryQueryRO
|
||||
├── vo/ # 响应体: DailySummaryVO
|
||||
├── dto/ # 转化体: DailySummaryDTO, SummaryConvert
|
||||
├── SummaryService.java
|
||||
└── SummaryController.java
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 接口协议重构(去除 `@PathVariable`)
|
||||
|
||||
所有接口全面统一为基于 RequestBody 传参:
|
||||
|
||||
| 模块 | 原接口形式 (PathVariable) | 调整后接口形式 (RequestBody) | 请求体 RO |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Baby** | `PUT /api/v1/babies/{babyId}` | `PUT /api/v1/babies` | `UpdateBabyRO` (含 `babyId`) |
|
||||
| **Baby** | `POST /api/v1/babies/{babyId}/set-default` | `POST /api/v1/babies/set-default` | `SetDefaultBabyRO` (含 `babyId`) |
|
||||
| **Family** | `PUT /api/v1/families/{familyId}` | `PUT /api/v1/families` | `UpdateFamilyRO` (含 `familyId`) |
|
||||
| **Family** | `POST /api/v1/families/{familyId}/members` | `POST /api/v1/families/members` | `CreateMemberRO` (含 `familyId`) |
|
||||
| **Family** | `PUT /api/v1/families/{familyId}/members/{memberId}` | `PUT /api/v1/families/members` | `UpdateMemberRO` (含 `familyId`, `memberId`) |
|
||||
| **Family** | `DELETE /api/v1/families/{familyId}/members/{memberId}` | `POST /api/v1/families/members/delete` | `DeleteMemberRO` (含 `familyId`, `memberId`) |
|
||||
| **Record** | `PUT /api/v1/records/{recordId}` | `PUT /api/v1/records` | `UpdateCareRecordRO` (含 `recordId`) |
|
||||
| **Record** | `DELETE /api/v1/records/{recordId}` | `POST /api/v1/records/delete` | `DeleteCareRecordRO` (含 `recordId`) |
|
||||
|
||||
前端 `apps/web/src/api/client.ts` 同步完成重构适配,保持全流程闭环通畅。
|
||||
|
||||
---
|
||||
|
||||
## 5. 验证与产物构建结果
|
||||
|
||||
1. **Flyway 与数据库迁移验证**:
|
||||
- 数据库 schema 成功从版本 1 平滑迁移至版本 2 (`v2 - audit fields and logic delete`);
|
||||
- 存量数据已安全对齐 `remark` 与 `deleted`。
|
||||
2. **后端测试用例**:
|
||||
- `BabyTrackerApplicationTests` 验证通过:
|
||||
- 验证 `created_by` 与 `updated_by` 自动填充为 `"admin"`;
|
||||
- 验证 `created_time` 与 `updated_time` 正常填充当前时间;
|
||||
- 验证 `deleted = 0` 初始填充与逻辑删除执行。
|
||||
3. **前端构建与一键部署打包**:
|
||||
- `apps/web` 成功通过 `vue-tsc` 严格校验与 `vite build`;
|
||||
- `build-artifacts.ps1` 一键编译归档成功,产物已输出至 `deploy/artifacts/server` 与 `deploy/artifacts/web`。
|
||||
@@ -0,0 +1,83 @@
|
||||
# 2026-09-26 记录:构建与部署流程优化
|
||||
|
||||
## 背景
|
||||
|
||||
在原本的构建与部署流程中存在以下痛点:
|
||||
1. **手动操作繁琐**:前后端编译后,需要人工将后端 jar 包重命名为 `app.jar` 并拷贝,同时需手动将前端 `dist` 目录上传至特定深层路径。
|
||||
2. **包名不直观**:`Dockerfile.server` 中固定硬编码了 `app.jar`,脱离了 Maven 实际生成的版本包名 `baby-tracker-server-0.1.0.jar`。
|
||||
3. **前端目录结构冗余**:前端静态资源之前存放在 `deploy/artifacts/web/dist`,导致多了一层目录。
|
||||
4. **服务器路径强耦合导致构建报错**:之前 `deploy/docker-compose.yml` 使用 `context: ..`,当服务器将部署目录直接放置在 `/opt/docker/baby-tracker` 下执行 `./deploy.sh` 时,Docker 尝试向上一级寻找 `deploy` 目录,抛出 `resolve : lstat /opt/docker/deploy: no such file or directory` 错误。
|
||||
|
||||
---
|
||||
|
||||
## 本次优化内容
|
||||
|
||||
### 1. 前后端编译自动归档至 `deploy/artifacts`
|
||||
- **后端自动归档**:在 `server-java/pom.xml` 中引入 `maven-antrun-plugin`,绑定在 `package` 生命周期后,将实际构建生成的 `baby-tracker-server-0.1.0.jar` 自动复制到 `deploy/artifacts/server/`。
|
||||
- **前端自动归档**:编写跨平台脚本 `apps/web/scripts/copy-artifacts.mjs`,集成至 `apps/web/package.json` 的 `npm run build`。编译完成后自动将 `dist` **文件夹下的全部内容**(平铺形式)复制到 `deploy/artifacts/web/`,并自动清理旧版本构建哈希文件。
|
||||
- **版本库排除**:在根目录 `.gitignore` 中配置 `deploy/artifacts/`,防止构建产物误入 Git 版本库,且移除了根目录下多余的临时副本,统一输出至 `deploy/artifacts`。
|
||||
|
||||
### 2. 后端 Dockerfile 使用实际包名
|
||||
修改 `deploy/Dockerfile.server`:
|
||||
- 将复制前的包名从 `app.jar` 改为实际生成的包名 `baby-tracker-server-0.1.0.jar`:
|
||||
```dockerfile
|
||||
COPY artifacts/server/baby-tracker-server-0.1.0.jar /app/app.jar
|
||||
```
|
||||
- 容器内部仍命名为 `/app/app.jar`,保持入口指令简洁稳定。
|
||||
|
||||
### 3. 前端 Dockerfile 适配平铺目录
|
||||
修改 `deploy/Dockerfile.web`:
|
||||
- 直接复制 `artifacts/web` 下的内容至 Nginx 静态文件根目录:
|
||||
```dockerfile
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY artifacts/web /usr/share/nginx/html
|
||||
```
|
||||
|
||||
### 4. 部署目录自闭环与独立 Context(解决服务器报错)
|
||||
- 修改 `deploy/docker-compose.yml`,将构建上下文由 `context: ..` 改为当前目录 `context: .`,`dockerfile` 指定为 `Dockerfile.server` 与 `Dockerfile.web`。
|
||||
- `Dockerfile` 内部去除了 `deploy/` 前缀引用。
|
||||
- 服务器部署时,无论部署目录命名为何(例如 `/opt/docker/baby-tracker`),均可自包含独立构建运行,彻底解决 `lstat ... no such file or directory` 路径找不到的问题。
|
||||
|
||||
### 5. 一键编译与部署脚本
|
||||
- 提供根目录一键编译脚本:
|
||||
- Windows: `build-artifacts.ps1`
|
||||
- Linux / macOS: `build-artifacts.sh`
|
||||
- `deploy/deploy.sh` 优化产物检查逻辑,直接检查 `artifacts/server/baby-tracker-server-0.1.0.jar` 与 `artifacts/web/index.html`。
|
||||
|
||||
---
|
||||
|
||||
## 产物与部署结构
|
||||
|
||||
编译后 `deploy/artifacts` 目录结构如下:
|
||||
|
||||
```text
|
||||
deploy/artifacts/
|
||||
├── server/
|
||||
│ └── baby-tracker-server-0.1.0.jar
|
||||
└── web/
|
||||
├── index.html
|
||||
└── assets/
|
||||
├── index-*.js
|
||||
└── index-*.css
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 快速使用指南
|
||||
|
||||
### 本地编译
|
||||
- **方式一(一键编译)**:
|
||||
- Windows 运行:`.\build-artifacts.ps1`
|
||||
- Linux/macOS 运行:`./build-artifacts.sh`
|
||||
- **方式二(分别编译)**:
|
||||
```bash
|
||||
cd server-java && mvn clean package -DskipTests
|
||||
cd ../apps/web && npm run build
|
||||
```
|
||||
|
||||
### 服务器部署
|
||||
直接将包含产物的 `deploy`(或直接将 `artifacts` 复制到服务器部署目录的 `artifacts` 对应位置),在服务器执行:
|
||||
```bash
|
||||
cd /opt/docker/baby-tracker
|
||||
./deploy.sh
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
# 2026-09-26 前端设置页与流水维护操作子组件化重构
|
||||
|
||||
## 1. 重构背景与目标
|
||||
|
||||
随着业务维护功能的丰富,`SettingsPage.vue` 包含了宝宝管理、家庭信息、成员团队和行为习惯四大模块的所有表单与弹窗,单文件代码量超过 580 行;同时 `TimelinePage.vue` 承载了流水列表展现、补录表单、编辑表单及其弹窗,单文件代码量达到近 700 行。
|
||||
|
||||
为了提升代码可维护性、关注点分离和组件复用性,本次进行了以下组件化拆分:
|
||||
1. **设置页(SettingsPage)四大 Tab 独立组件化**:
|
||||
- 宝宝设置:`src/components/settings/BabySettingsTab.vue`
|
||||
- 家庭设置:`src/components/settings/FamilySettingsTab.vue`
|
||||
- 成员维护:`src/components/settings/MemberSettingsTab.vue`
|
||||
- 行为偏好:`src/components/settings/ActionSettingsTab.vue`
|
||||
- `SettingsPage.vue` 仅作为容器路由页面,代码缩减至 40 行左右。
|
||||
2. **流水页(TimelinePage)维护弹窗独立组件化**:
|
||||
- 补录记录弹窗:`src/components/timeline/TimelineManualModal.vue`
|
||||
- 编辑记录弹窗:`src/components/timeline/TimelineEditModal.vue`
|
||||
- `TimelinePage.vue` 专注于流水展示与触发事件,代码缩减至 100 行左右。
|
||||
|
||||
---
|
||||
|
||||
## 2. 组件架构拆分明细
|
||||
|
||||
### 2.1 设置模块子组件 (`apps/web/src/components/settings/`)
|
||||
- **`BabySettingsTab.vue`**:
|
||||
- 承载当前宝宝档案展示与修改表单(昵称、出生日期、性别、分娩方式);
|
||||
- 承载多宝宝平铺卡片切换与“设为默认宝宝”交互;
|
||||
- 承载「+ 添加宝宝」弹窗表单与异步提交。
|
||||
- **`FamilySettingsTab.vue`**:
|
||||
- 承载家庭名称编辑与保存;
|
||||
- 承载 8 位家庭共享邀请码的查看、编辑与前端随机生成;
|
||||
- 承载家庭编号、宝宝总数、成员总数的概要统计展示。
|
||||
- **`MemberSettingsTab.vue`**:
|
||||
- 承载当前快速记录人的一键切换交互;
|
||||
- 承载照护团队成员列表与角色权限展示;
|
||||
- 承载添加成员与修改成员的共用抽屉弹窗(含常见预设身份称谓);
|
||||
- 承载移除成员操作及二次确认弹窗。
|
||||
- **`ActionSettingsTab.vue`**:
|
||||
- 承载喂养偏好配置(默认喂养方式、瓶喂默认单次奶量、亲喂优先侧);
|
||||
- 承载睡眠偏好模式选择(计时器模式 / 快捷录入模式);
|
||||
- 承载全局记录成功提示开关与拍嗝提醒开关;
|
||||
- 统一持久化至 `localStorage`。
|
||||
|
||||
### 2.2 流水维护子组件 (`apps/web/src/components/timeline/`)
|
||||
- **`TimelineManualModal.vue`**:
|
||||
- 双向绑定 `v-model:show` 控制弹出抽屉;
|
||||
- 支持喂奶(亲喂左右侧、瓶喂奶量)、睡眠(起止时间、持续分钟数)、排泄(嘘嘘/便便)分类动态切换;
|
||||
- 支持快捷备注标签(拍嗝顺利、溢奶微量、金黄色便便、安睡无闹等)点击追加;
|
||||
- 封装参数校验与 `store.manualLog` 接口调用,成功后触发 `success` 事件自动刷新视图。
|
||||
- **`TimelineEditModal.vue`**:
|
||||
- 传入 `record` 属性与 `v-model:show`;
|
||||
- 监听传入记录自动回填表单数据(类型、起止时间拆分、奶量、左右侧识别、备注等);
|
||||
- 封装参数更新与 `store.editRecord` 接口调用,提交后通知父页面刷新。
|
||||
|
||||
---
|
||||
|
||||
## 3. 构建与验证结果
|
||||
|
||||
1. **类型检查与打包验证**:
|
||||
- 执行 `npm run build`,Vue 3 + TypeScript 编译零错误,组件间 `props` 与 `emit` 类型定义严格对齐;
|
||||
2. **打包归档验证**:
|
||||
- 运行 `./build-artifacts.ps1`,前后端编译全绿,最新产物已完整归档至 `deploy/artifacts/server` 与 `deploy/artifacts/web`。
|
||||
@@ -0,0 +1,44 @@
|
||||
# 2026-09-26 记录:后端引入 Lombok 优化代码结构
|
||||
|
||||
## 背景
|
||||
|
||||
在后端模型与服务层中,存在大量冗余的 Getter、Setter、ToString、构造函数样板代码以及异常日志记录的样板实现,使得实体类和控制层代码冗长,降低了核心业务逻辑的可读性。
|
||||
|
||||
---
|
||||
|
||||
## 本次优化内容
|
||||
|
||||
### 1. 依赖与编译器插件配置
|
||||
- 在 `server-java/pom.xml` 中引入 `org.projectlombok:lombok`:
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
```
|
||||
- 配置 `maven-compiler-plugin` 注解处理器路径 `annotationProcessorPaths`,确保 Java 21 环境下 Lombok 注解能够无缝编译。
|
||||
|
||||
### 2. 实体与 DTO 模型精简
|
||||
- **领域实体类**:
|
||||
- `BabyProfile`: 使用 `@Data` 消除样板 getter/setter,保留自定义年龄推算逻辑 `getAgeDays()` 与 `getAgeText()`。
|
||||
- `CareRecord`: 使用 `@Data` 简化数据模型。
|
||||
- `FamilyInfo`: 使用 `@Data` 简化模型。
|
||||
- `FamilyMember`: 使用 `@Data` 简化模型。
|
||||
- `FamilyContext`: 使用 `@Data`。
|
||||
- **请求/响应 DTO**:
|
||||
- `ApiResponse`、`ApiError`: 使用 `@Data`、`@NoArgsConstructor`、`@AllArgsConstructor`。
|
||||
- `UpdateBabyRequest`、`CreateFeedingRequest`、`ExcretionRequest`、`SleepRequest`、`DailySummary`: 全面应用 `@Data`。
|
||||
- **异常类**:
|
||||
- `BusinessException`: 使用 `@Getter`。
|
||||
|
||||
### 3. Service 与 Controller 依赖注入优化
|
||||
- 全部服务与控制层类(`BabyService`、`FamilyService`、`CareRecordService`、`SummaryService`、`BabyController`、`FamilyController`、`CareRecordController`、`SummaryController`)均采用 Lombok 的 `@RequiredArgsConstructor` 注解替代冗长的手写构造函数,使得组件依赖更加清爽、不可变(final)语义更加清晰。
|
||||
- 全局异常处理器 `GlobalExceptionHandler` 引入 `@Slf4j` 注解,规范各级异常日志输出。
|
||||
|
||||
---
|
||||
|
||||
## 验证结果
|
||||
|
||||
- **编译与单元测试**:运行 `mvn clean package`,所有 29 个源文件顺利编译,`BabyTrackerApplicationTests` 集成测试通过率 100%。
|
||||
- **自动归档正常**:生成的 `baby-tracker-server-0.1.0.jar` 自动发布至 `deploy/artifacts/server/`。
|
||||
@@ -0,0 +1,60 @@
|
||||
# 2026-09-26 记录:引入 MyBatis-Plus 并重构优化 SQL 操作
|
||||
|
||||
## 背景
|
||||
|
||||
在此前的 MVP 落地版本中,后端通过 Spring `JdbcTemplate` 直接执行手写 SQL 字符串,并手工解析 `ResultSet`。这种方式存在以下局限:
|
||||
1. **样板代码冗余**:大量的 SQL 字符串拼接、参数下标占位符(`?`)以及字段级手写映射(`rs.getString(...)` 等)充斥在各个 Service 中;
|
||||
2. **缺乏编译期类型安全**:字段名硬编码在字符串中,表结构变更时无法在编译期暴露潜在缺陷;
|
||||
3. **维护成本高**:查询条件的组合、分页与排序等手写 SQL 复杂度高,不利于后续快速迭代。
|
||||
|
||||
---
|
||||
|
||||
## 本次改造内容
|
||||
|
||||
### 1. 引入 MyBatis-Plus 依赖与配置
|
||||
- 针对 Spring Boot 3.3.5 与 Java 21 环境,在 `server-java/pom.xml` 中引入官方 Spring Boot 3 专版 starter:
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>3.5.9</version>
|
||||
</dependency>
|
||||
```
|
||||
- 在 `application.yml` 中补充 MyBatis-Plus 配置:
|
||||
- 开启下划线到驼峰命名的自动映射:`map-underscore-to-camel-case: true`
|
||||
- 日志打印配置:`log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl`
|
||||
- 全局主键策略配置:`id-type: input`(与项目当前的 SnowflakeIdGenerator 32位雪花算法保持一致)
|
||||
- 在 `BabyTrackerApplication` 启动类上增加 Mapper 扫描注解:
|
||||
```java
|
||||
@MapperScan("com.babytracker.module.**.mapper")
|
||||
```
|
||||
|
||||
### 2. 实体类完善与 Mapper 接口创建
|
||||
为系统核心领域模型配置 MyBatis-Plus 注解并创建继承 `BaseMapper<T>` 的强类型 Mapper 接口:
|
||||
- **宝宝模块**:
|
||||
- `BabyProfile`: 配置 `@TableName("baby_profile")` 与 `@TableId(value = "id", type = IdType.INPUT)`
|
||||
- `BabyMapper`: 继承 `BaseMapper<BabyProfile>`
|
||||
- **家庭与成员模块**:
|
||||
- `FamilyInfo`: 配置 `@TableName("family")` 与 `@TableId(value = "id", type = IdType.INPUT)`
|
||||
- `FamilyMember`: 配置 `@TableName("family_member")`、`@TableId` 与字段映射 `@TableField("is_default_operator")`
|
||||
- `FamilyMapper`: 继承 `BaseMapper<FamilyInfo>`
|
||||
- `FamilyMemberMapper`: 继承 `BaseMapper<FamilyMember>`
|
||||
- **照护记录模块**:
|
||||
- `CareRecord`: 配置 `@TableName("care_record")` 与各字段映射
|
||||
- `CareRecordMapper`: 继承 `BaseMapper<CareRecord>`
|
||||
|
||||
### 3. Service 层全面重构与 SQL 优化
|
||||
用类型安全的 Lambda 包装器(`LambdaQueryWrapper` / `LambdaUpdateWrapper`)与 `BaseMapper` CRUD 方法替代全部 `JdbcTemplate`:
|
||||
- **查询优化**:使用方法引用表达查询条件(如 `CareRecord::getBabyId`, `CareRecord::getStartTime`),避免字符串拼写错误,自带预编译防注入;
|
||||
- **更新优化**:使用 `LambdaUpdateWrapper` 仅更新指定字段或使用 `updateById`,大幅简化更新语句;
|
||||
- **消除手动映射**:自动完成驼峰字段到实体对象的映射,淘汰所有手写的 `mapRecord`、`mapBaby` 方法;
|
||||
- **软删除规范化**:通过 Wrapper 条件精准控制 `deleted_at` 字段。
|
||||
|
||||
---
|
||||
|
||||
## 验证结果
|
||||
|
||||
1. **单元测试与集成测试**:
|
||||
编写集成测试 `BabyTrackerApplicationTests`,验证 MyBatis-Plus 自动配置、数据源连接池、Flyway 脚本执行、以及各 Service 的核心 CRUD 逻辑全部通过(测试用例通过率 100%)。
|
||||
2. **打包构建与自动归档**:
|
||||
执行 `mvn clean package`,代码编译、测试运行及产物自动复制到 `deploy/artifacts/server/baby-tracker-server-0.1.0.jar` 全流程成功。
|
||||
@@ -0,0 +1,85 @@
|
||||
# 2026-09-26 设置模块全面维护与流水编辑/补录功能实现
|
||||
|
||||
## 1. 调整背景
|
||||
|
||||
在第一版 MVP 中,设置页面以信息展示与基础切换为主,缺少对宝宝档案、家庭信息、成员角色以及行为习惯的完整维护编辑交互;同时照护流水(Timeline)仅支持实时操作生成的记录查看与删除,缺乏“补录历史记录”(如夜间纸笔记录后补录、家人外出归来后补录)与“编辑修改错误记录”的能力。
|
||||
|
||||
本次调整的目标是:
|
||||
1. **设置页面全面维护**:宝宝、家庭、成员、行为 4 个 Tab 全面增加在线维护与修改能力;
|
||||
2. **流水内容可编辑与补录**:支持对喂养(亲喂/瓶喂)、睡眠、排泄三大类记录进行补录,并支持对已产生的流水进行修改更新。
|
||||
|
||||
---
|
||||
|
||||
## 2. 后端接口扩展
|
||||
|
||||
### 2.1 宝宝档案模块 (`BabyController` / `BabyService`)
|
||||
- `POST /api/v1/babies`: 新建宝宝档案 (`CreateBabyRequest`),支持自动关联当前家庭,并指定是否设为默认宝宝。
|
||||
- `PUT /api/v1/babies/{babyId}`: 根据宝宝 ID 修改宝宝昵称、性别、出生日期、分娩方式等字段。
|
||||
- `POST /api/v1/babies/{babyId}/set-default`: 将指定宝宝设为默认展示宝宝,系统保证同一家庭下只有一个默认宝宝。
|
||||
|
||||
### 2.2 家庭与成员模块 (`FamilyController` / `FamilyService`)
|
||||
- `PUT /api/v1/families/{familyId}`: 修改家庭名称及邀请码 (`UpdateFamilyRequest`)。
|
||||
- `POST /api/v1/families/{familyId}/members`: 新增家庭成员 (`CreateMemberRequest`),支持角色称谓(爸爸/妈妈/月嫂等)及默认记录人设置。
|
||||
- `PUT /api/v1/families/{familyId}/members/{memberId}`: 修改成员角色称谓及权限。
|
||||
- `DELETE /api/v1/families/{familyId}/members/{memberId}`: 移除家庭成员(内置兜底逻辑:同一家庭至少保留 1 名成员)。
|
||||
|
||||
### 2.3 照护记录模块 (`CareRecordController` / `CareRecordService`)
|
||||
- `POST /api/v1/records`: 照护记录手动补录通用接口 (`CreateManualRecordRequest`):
|
||||
- 支持喂养(瓶喂/亲喂、奶量/时长/喂奶侧)、睡眠(起止时间、睡眠时长)、排泄(小便/大便、性状颜色);
|
||||
- 支持指定发生时间、记录人及备注标签。
|
||||
- `PUT /api/v1/records/{recordId}`: 照护记录编辑修改接口 (`UpdateCareRecordRequest`),支持全字段覆写更新与时间范围修正。
|
||||
|
||||
---
|
||||
|
||||
## 3. 前端交互与架构设计
|
||||
|
||||
### 3.1 状态管理与 API 封装
|
||||
- **API 客户端 (`apps/web/src/api/client.ts`)**:
|
||||
- 增补 `createBaby`, `setDefaultBaby`, `updateFamily`, `createMember`, `updateMember`, `deleteMember`, `createManualRecord`, `updateRecord` 接口。
|
||||
- **Store 响应式驱动 (`apps/web/src/stores/careStore.ts`)**:
|
||||
- 新增 `addBaby`, `setDefaultBaby`, `saveFamily`, `addMember`, `editMember`, `removeMember` 等业务动作;
|
||||
- 新增 `manualLog(payload)`(流水补录并刷新首页与今日摘要);
|
||||
- 新增 `editRecord(recordId, payload)`(流水编辑并局部/全量刷新);
|
||||
- 新增 `actionPreferences` 行为偏好配置,持久化于本地存储并在记录时作为默认表单项生效。
|
||||
|
||||
### 3.2 设置页面 (`SettingsPage.vue`) 4 大 Tab 维护
|
||||
1. **宝宝设置**:
|
||||
- 顶部提供宝宝平铺切换 Chip,支持高亮选中与“设为全局默认”;
|
||||
- 支持实时修改当前宝宝的昵称、出生日期、性别、分娩方式并保存;
|
||||
- 提供「+ 添加宝宝」交互抽屉/弹窗,支持二胎/多宝家庭扩展。
|
||||
2. **家庭设置**:
|
||||
- 支持编辑家庭空间名称;
|
||||
- 支持修改或一键重置 8 位家庭邀请码,便于其他家属扫码/输码加入。
|
||||
3. **成员维护**:
|
||||
- 成员列表卡片化展示,标明当前登录人与记录人;
|
||||
- 支持一键快捷切换当前记录人(如妈妈喂奶交班给爸爸);
|
||||
- 支持点击成员编辑角色称谓、提供「+ 添加成员」抽屉及「移除」确认操作。
|
||||
4. **行为偏好设置**:
|
||||
- 喂养偏好:默认喂养方式(亲喂/瓶喂/配方奶)、单次推荐奶量、间隔提醒;
|
||||
- 睡眠偏好:默认入睡辅助提示、睡眠时长预估;
|
||||
- 排泄偏好:排泄观察关注项(小便量、便便性状等);
|
||||
- 记录辅助:快速备注预设词、防误触确认开关,保存后即刻生效。
|
||||
|
||||
### 3.3 流水页面 (`TimelinePage.vue`) 补录与编辑
|
||||
1. **补录功能(+ 补录记录)**:
|
||||
- 列表顶部显著放置「+ 补录记录」操作;
|
||||
- 弹出底部交互抽屉,支持选择记录类型(喂养/睡眠/排泄),表单动态切换对应项(时间、奶量、左右侧、睡眠起止时间、便便性状、记录人等);
|
||||
- 提供常用快捷备注标签(如“喝得急”、“吐奶少量”、“自主入睡”、“黄金便”),点击即填;
|
||||
- 提交成功后自动同步刷新最新流水与今日统计看板。
|
||||
2. **编辑与维护已存流水**:
|
||||
- 每条流水记录卡片增加「编辑」入口;
|
||||
- 点击唤起「编辑记录」抽屉,表单自动回填已有参数;
|
||||
- 支持修改发生时间、喂养量/时长、排泄性状、记录人与备注信息;
|
||||
- 支持保存修改并即时响应在时间线上。
|
||||
|
||||
---
|
||||
|
||||
## 4. 验证与打包
|
||||
|
||||
1. **后端验证**:
|
||||
- 执行 `mvn clean test`,测试用例全部通过,验证了 MyBatis-Plus 条件构造器与多表 CRUD 操作的正确性。
|
||||
2. **前端验证**:
|
||||
- 执行 `npm run build` (`vue-tsc -b && vite build`),TS 严格模式编译无警告,生产包体积受控。
|
||||
3. **一键构建归档**:
|
||||
- 执行 `build-artifacts.ps1`,成功完成前后端并行打包;
|
||||
- 产物自动无污染归档至 `deploy/artifacts/server` 与 `deploy/artifacts/web`,准备好随时一键推送到服务器。
|
||||
@@ -11,6 +11,12 @@
|
||||
- [2026-09-25-cleanup-and-deploy.md](./2026-09-25-cleanup-and-deploy.md): 旧原型清理记录,以及新部署目录结构说明。
|
||||
- [2026-09-26-family-feeding-settings.md](./2026-09-26-family-feeding-settings.md): 家庭/成员/宝宝关系、亲喂计时、设置结构和 UI 框架调整记录。
|
||||
- [2026-09-26-id-strategy.md](./2026-09-26-id-strategy.md): 新表统一 32 位字符串 ID 和雪花 ID 生成策略。
|
||||
- [2026-09-26-deploy-script-optimization.md](./2026-09-26-deploy-script-optimization.md): 前后端编译产物自动归档、Dockerfile 包名修正及部署自闭环优化记录。
|
||||
- [2026-09-26-mybatis-plus-integration.md](./2026-09-26-mybatis-plus-integration.md): 后端补充 MyBatis-Plus 依赖与全面重构优化 SQL 操作记录。
|
||||
- [2026-09-26-lombok-optimization.md](./2026-09-26-lombok-optimization.md): 后端引入 Lombok 简化实体与构造注入代码结构记录。
|
||||
- [2026-09-26-settings-maintenance-and-timeline-edit.md](./2026-09-26-settings-maintenance-and-timeline-edit.md): 前端设置模块(宝宝/家庭/成员/行为)全面维护与流水编辑/补录功能实现记录。
|
||||
- [2026-09-26-audit-fields-ro-vo-dto-restructure.md](./2026-09-26-audit-fields-ro-vo-dto-restructure.md): 统一通用审计字段、请求/响应/转化体分层(RO/VO/DTO)与接口规范化调整记录。
|
||||
- [2026-09-26-frontend-settings-timeline-component-split.md](./2026-09-26-frontend-settings-timeline-component-split.md): 前端设置页(4 个 Tab)与流水维护操作(补录/编辑)子组件化重构记录。
|
||||
|
||||
## 记录原则
|
||||
|
||||
|
||||
+49
-1
@@ -40,6 +40,11 @@
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>3.5.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
@@ -48,6 +53,11 @@
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-mysql</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
@@ -56,13 +66,29 @@
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${project.basedir}/../sql/migration</directory>
|
||||
<targetPath>db/migration</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.10.1</version>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<release>${java.version}</release>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.34</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@@ -74,6 +100,28 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-artifacts</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<mkdir dir="${project.basedir}/../deploy/artifacts/server"/>
|
||||
<copy file="${project.build.directory}/${project.build.finalName}.jar"
|
||||
todir="${project.basedir}/../deploy/artifacts/server"
|
||||
overwrite="true"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.babytracker;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@MapperScan("com.babytracker.module.**.mapper")
|
||||
public class BabyTrackerApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BabyTrackerApplication.class, args);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.babytracker.common.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class BusinessException extends RuntimeException {
|
||||
private final String code;
|
||||
|
||||
@@ -7,9 +10,4 @@ public class BusinessException extends RuntimeException {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -1,6 +1,7 @@
|
||||
package com.babytracker.common.exception;
|
||||
|
||||
import com.babytracker.common.response.ApiResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
@@ -8,24 +9,28 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<Void> handleBusiness(BusinessException ex) {
|
||||
log.warn("业务异常: code={}, message={}", ex.getCode(), ex.getMessage());
|
||||
return ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<Void> handleValidation(Exception ex) {
|
||||
log.warn("参数校验异常: {}", ex.getMessage());
|
||||
return ApiResponse.fail("VALIDATION_ERROR", "参数不合法");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<Void> handleException(Exception ex) {
|
||||
log.error("系统内部异常: ", ex);
|
||||
return ApiResponse.fail("INTERNAL_ERROR", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.babytracker.common.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableLogic
|
||||
@TableField(value = "deleted", fill = FieldFill.INSERT)
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "created_by", fill = FieldFill.INSERT)
|
||||
private String createdBy;
|
||||
|
||||
@TableField(value = "created_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createdTime;
|
||||
|
||||
@TableField(value = "updated_by", fill = FieldFill.INSERT_UPDATE)
|
||||
private String updatedBy;
|
||||
|
||||
@TableField(value = "updated_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.babytracker.common.mybatis;
|
||||
|
||||
import com.babytracker.common.model.BaseEntity;
|
||||
import com.babytracker.common.security.UserContext;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Constants;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.executor.Executor;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.mapping.SqlCommandType;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuditFieldFillInterceptor implements InnerInterceptor {
|
||||
|
||||
@Override
|
||||
public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
|
||||
if (parameter == null) {
|
||||
return;
|
||||
}
|
||||
SqlCommandType commandType = ms.getSqlCommandType();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
String user = UserContext.getCurrentUser();
|
||||
|
||||
if (parameter instanceof BaseEntity entity) {
|
||||
fillAuditFields(entity, commandType, now, user);
|
||||
} else if (parameter instanceof Map<?, ?> map) {
|
||||
if (map.containsKey(Constants.ENTITY) && map.get(Constants.ENTITY) instanceof BaseEntity entity) {
|
||||
fillAuditFields(entity, commandType, now, user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void fillAuditFields(BaseEntity entity, SqlCommandType commandType, LocalDateTime now, String user) {
|
||||
if (commandType == SqlCommandType.INSERT) {
|
||||
if (entity.getCreatedTime() == null) {
|
||||
entity.setCreatedTime(now);
|
||||
}
|
||||
if (entity.getUpdatedTime() == null) {
|
||||
entity.setUpdatedTime(now);
|
||||
}
|
||||
if (entity.getCreatedBy() == null || entity.getCreatedBy().trim().isEmpty()) {
|
||||
entity.setCreatedBy(user);
|
||||
}
|
||||
if (entity.getUpdatedBy() == null || entity.getUpdatedBy().trim().isEmpty()) {
|
||||
entity.setUpdatedBy(user);
|
||||
}
|
||||
if (entity.getDeleted() == null) {
|
||||
entity.setDeleted(0);
|
||||
}
|
||||
} else if (commandType == SqlCommandType.UPDATE) {
|
||||
entity.setUpdatedTime(now);
|
||||
entity.setUpdatedBy(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.babytracker.common.mybatis;
|
||||
|
||||
import com.babytracker.common.security.UserContext;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuditMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
String user = UserContext.getCurrentUser();
|
||||
|
||||
this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, now);
|
||||
this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class, now);
|
||||
this.strictInsertFill(metaObject, "createdBy", String.class, user);
|
||||
this.strictInsertFill(metaObject, "updatedBy", String.class, user);
|
||||
this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
|
||||
|
||||
// 兜底补填(防止由于直接赋值 null 导致 strictInsertFill 忽略)
|
||||
if (this.getFieldValByName("createdBy", metaObject) == null) {
|
||||
this.setFieldValByName("createdBy", user, metaObject);
|
||||
}
|
||||
if (this.getFieldValByName("updatedBy", metaObject) == null) {
|
||||
this.setFieldValByName("updatedBy", user, metaObject);
|
||||
}
|
||||
if (this.getFieldValByName("createdTime", metaObject) == null) {
|
||||
this.setFieldValByName("createdTime", now, metaObject);
|
||||
}
|
||||
if (this.getFieldValByName("updatedTime", metaObject) == null) {
|
||||
this.setFieldValByName("updatedTime", now, metaObject);
|
||||
}
|
||||
if (this.getFieldValByName("deleted", metaObject) == null) {
|
||||
this.setFieldValByName("deleted", 0, metaObject);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
String user = UserContext.getCurrentUser();
|
||||
|
||||
this.setFieldValByName("updatedTime", now, metaObject);
|
||||
this.setFieldValByName("updatedBy", user, metaObject);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.babytracker.common.mybatis;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor(AuditFieldFillInterceptor auditFieldFillInterceptor) {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// 注入统一审计字段拦截器
|
||||
interceptor.addInnerInterceptor(auditFieldFillInterceptor);
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,13 @@
|
||||
package com.babytracker.common.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ApiError {
|
||||
private String code;
|
||||
private String message;
|
||||
|
||||
public ApiError() {
|
||||
}
|
||||
|
||||
public ApiError(String code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
package com.babytracker.common.response;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class ApiResponse<T> {
|
||||
private boolean success;
|
||||
private T data;
|
||||
@@ -18,29 +23,4 @@ public class ApiResponse<T> {
|
||||
response.error = new ApiError(code, message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public ApiError getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public void setError(ApiError error) {
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.babytracker.common.security;
|
||||
|
||||
public final class UserContext {
|
||||
private static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
|
||||
|
||||
private UserContext() {}
|
||||
|
||||
public static String getCurrentUser() {
|
||||
String user = CURRENT_USER.get();
|
||||
return (user != null && !user.trim().isEmpty()) ? user.trim() : "admin";
|
||||
}
|
||||
|
||||
public static void setCurrentUser(String username) {
|
||||
CURRENT_USER.set(username);
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT_USER.remove();
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,59 @@
|
||||
package com.babytracker.module.baby;
|
||||
|
||||
import com.babytracker.common.response.ApiResponse;
|
||||
import com.babytracker.module.baby.ro.CreateBabyRO;
|
||||
import com.babytracker.module.baby.ro.SetDefaultBabyRO;
|
||||
import com.babytracker.module.baby.ro.UpdateBabyRO;
|
||||
import com.babytracker.module.baby.vo.BabyVO;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/babies")
|
||||
public class BabyController {
|
||||
private final BabyService babyService;
|
||||
|
||||
public BabyController(BabyService babyService) {
|
||||
this.babyService = babyService;
|
||||
}
|
||||
|
||||
@GetMapping("/current")
|
||||
public ApiResponse<BabyProfile> current() {
|
||||
public ApiResponse<BabyVO> current() {
|
||||
return ApiResponse.ok(babyService.getCurrentBaby());
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<BabyProfile>> list() {
|
||||
public ApiResponse<List<BabyVO>> list() {
|
||||
return ApiResponse.ok(babyService.listBabies());
|
||||
}
|
||||
|
||||
@PutMapping("/current")
|
||||
public ApiResponse<BabyProfile> update(@Valid @RequestBody UpdateBabyRequest request) {
|
||||
@PutMapping
|
||||
public ApiResponse<BabyVO> update(@Valid @RequestBody UpdateBabyRO request) {
|
||||
if (request.getBabyId() != null && !request.getBabyId().trim().isEmpty()) {
|
||||
return ApiResponse.ok(babyService.updateBaby(request.getBabyId().trim(), request));
|
||||
}
|
||||
return ApiResponse.ok(babyService.updateCurrentBaby(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{babyId}")
|
||||
public ApiResponse<BabyProfile> updateById(@PathVariable String babyId, @Valid @RequestBody UpdateBabyRequest request) {
|
||||
return ApiResponse.ok(babyService.updateBaby(babyId, request));
|
||||
@PutMapping("/current")
|
||||
public ApiResponse<BabyVO> updateCurrent(@Valid @RequestBody UpdateBabyRO request) {
|
||||
return ApiResponse.ok(babyService.updateCurrentBaby(request));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<BabyVO> create(@Valid @RequestBody CreateBabyRO request) {
|
||||
return ApiResponse.ok(babyService.createBaby(request));
|
||||
}
|
||||
|
||||
@PostMapping("/set-default")
|
||||
public ApiResponse<BabyVO> setDefault(@Valid @RequestBody SetDefaultBabyRO request) {
|
||||
return ApiResponse.ok(babyService.setDefaultBaby(request.getBabyId().trim()));
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,45 @@
|
||||
package com.babytracker.module.baby;
|
||||
|
||||
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;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class BabyProfile {
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("baby_profile")
|
||||
public class BabyProfile extends BaseEntity {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String babyId;
|
||||
|
||||
@TableField("family_id")
|
||||
private String familyId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("gender")
|
||||
private String gender;
|
||||
|
||||
@TableField("birth_date")
|
||||
private LocalDate birthDate;
|
||||
|
||||
@TableField("delivery_type")
|
||||
private String deliveryType;
|
||||
|
||||
@TableField("is_default")
|
||||
private Integer isDefault;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
public static BabyProfile defaultBaby() {
|
||||
BabyProfile baby = new BabyProfile();
|
||||
baby.babyId = "00000000000000361915955447599104";
|
||||
@@ -19,62 +48,19 @@ public class BabyProfile {
|
||||
baby.gender = "boy";
|
||||
baby.birthDate = LocalDate.now().minusDays(3);
|
||||
baby.deliveryType = "natural";
|
||||
baby.isDefault = 1;
|
||||
baby.status = "active";
|
||||
return baby;
|
||||
}
|
||||
|
||||
public long getAgeDays() {
|
||||
if (birthDate == null) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, ChronoUnit.DAYS.between(birthDate, LocalDate.now()));
|
||||
}
|
||||
|
||||
public String getAgeText() {
|
||||
return "出生第 " + getAgeDays() + " 天";
|
||||
}
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public String getFamilyId() {
|
||||
return familyId;
|
||||
}
|
||||
|
||||
public void setFamilyId(String familyId) {
|
||||
this.familyId = familyId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(LocalDate birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String getDeliveryType() {
|
||||
return deliveryType;
|
||||
}
|
||||
|
||||
public void setDeliveryType(String deliveryType) {
|
||||
this.deliveryType = deliveryType;
|
||||
}
|
||||
}
|
||||
@@ -1,90 +1,143 @@
|
||||
package com.babytracker.module.baby;
|
||||
|
||||
import com.babytracker.common.id.SnowflakeIdGenerator;
|
||||
import com.babytracker.module.baby.dto.BabyConvert;
|
||||
import com.babytracker.module.baby.mapper.BabyMapper;
|
||||
import com.babytracker.module.baby.ro.CreateBabyRO;
|
||||
import com.babytracker.module.baby.ro.UpdateBabyRO;
|
||||
import com.babytracker.module.baby.vo.BabyVO;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BabyService {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final BabyMapper babyMapper;
|
||||
private final SnowflakeIdGenerator idGenerator;
|
||||
|
||||
public BabyService(JdbcTemplate jdbcTemplate, SnowflakeIdGenerator idGenerator) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.idGenerator = idGenerator;
|
||||
}
|
||||
|
||||
public BabyProfile getCurrentBaby() {
|
||||
List<BabyProfile> babies = jdbcTemplate.query(
|
||||
"SELECT id, family_id, name, gender, birth_date, delivery_type FROM baby_profile WHERE status = 'active' ORDER BY is_default DESC, id ASC LIMIT 1",
|
||||
(rs, rowNum) -> mapBaby(rs)
|
||||
public BabyProfile getCurrentBabyEntity() {
|
||||
BabyProfile baby = babyMapper.selectOne(
|
||||
new LambdaQueryWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getStatus, "active")
|
||||
.orderByDesc(BabyProfile::getIsDefault)
|
||||
.orderByAsc(BabyProfile::getBabyId)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
if (!babies.isEmpty()) {
|
||||
return babies.get(0);
|
||||
if (baby != null) {
|
||||
return baby;
|
||||
}
|
||||
|
||||
BabyProfile baby = BabyProfile.defaultBaby();
|
||||
baby.setBabyId(idGenerator.nextId());
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO baby_profile (id, family_id, name, gender, birth_date, delivery_type, is_default, status) VALUES (?, ?, ?, ?, ?, ?, 1, 'active')",
|
||||
baby.getBabyId(), baby.getFamilyId(), baby.getName(), baby.getGender(), Date.valueOf(baby.getBirthDate()), baby.getDeliveryType()
|
||||
);
|
||||
return baby;
|
||||
BabyProfile defaultBaby = BabyProfile.defaultBaby();
|
||||
defaultBaby.setBabyId(idGenerator.nextId());
|
||||
babyMapper.insert(defaultBaby);
|
||||
return defaultBaby;
|
||||
}
|
||||
|
||||
public List<BabyProfile> listBabies() {
|
||||
List<BabyProfile> babies = jdbcTemplate.query(
|
||||
"SELECT id, family_id, name, gender, birth_date, delivery_type FROM baby_profile WHERE status = 'active' ORDER BY is_default DESC, id ASC",
|
||||
(rs, rowNum) -> mapBaby(rs)
|
||||
public BabyVO getCurrentBaby() {
|
||||
return BabyConvert.toVO(getCurrentBabyEntity());
|
||||
}
|
||||
|
||||
public List<BabyVO> listBabies() {
|
||||
List<BabyProfile> babies = babyMapper.selectList(
|
||||
new LambdaQueryWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getStatus, "active")
|
||||
.orderByDesc(BabyProfile::getIsDefault)
|
||||
.orderByAsc(BabyProfile::getBabyId)
|
||||
);
|
||||
if (babies.isEmpty()) {
|
||||
return List.of(getCurrentBaby());
|
||||
}
|
||||
return babies;
|
||||
return BabyConvert.toVOList(babies);
|
||||
}
|
||||
|
||||
public BabyProfile updateCurrentBaby(UpdateBabyRequest request) {
|
||||
BabyProfile currentBaby = getCurrentBaby();
|
||||
public BabyVO updateCurrentBaby(UpdateBabyRO request) {
|
||||
BabyProfile currentBaby = getCurrentBabyEntity();
|
||||
return updateBaby(currentBaby.getBabyId(), request);
|
||||
}
|
||||
|
||||
public BabyProfile updateBaby(String babyId, UpdateBabyRequest request) {
|
||||
jdbcTemplate.update(
|
||||
"UPDATE baby_profile SET name = ?, gender = ?, birth_date = ?, delivery_type = ? WHERE id = ?",
|
||||
request.getName().trim(),
|
||||
request.getGender() == null || "unknown".equals(request.getGender()) ? "boy" : request.getGender(),
|
||||
Date.valueOf(request.getBirthDate()),
|
||||
request.getDeliveryType() == null ? "natural" : request.getDeliveryType(),
|
||||
babyId
|
||||
public BabyVO updateBaby(String babyId, UpdateBabyRO request) {
|
||||
String gender = request.getGender() == null || "unknown".equals(request.getGender()) ? "boy" : request.getGender();
|
||||
String deliveryType = request.getDeliveryType() == null ? "natural" : request.getDeliveryType();
|
||||
LocalDate birthDate = request.getBirthDate() != null ? LocalDate.parse(request.getBirthDate()) : null;
|
||||
|
||||
LambdaUpdateWrapper<BabyProfile> wrapper = new LambdaUpdateWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getBabyId, babyId)
|
||||
.set(BabyProfile::getName, request.getName().trim())
|
||||
.set(BabyProfile::getGender, gender)
|
||||
.set(BabyProfile::getDeliveryType, deliveryType);
|
||||
if (birthDate != null) {
|
||||
wrapper.set(BabyProfile::getBirthDate, birthDate);
|
||||
}
|
||||
if (request.getRemark() != null) {
|
||||
wrapper.set(BabyProfile::getRemark, request.getRemark().trim());
|
||||
}
|
||||
babyMapper.update(null, wrapper);
|
||||
return BabyConvert.toVO(findByBabyId(babyId));
|
||||
}
|
||||
|
||||
public BabyVO createBaby(CreateBabyRO request) {
|
||||
String familyId = request.getFamilyId();
|
||||
if (familyId == null || familyId.trim().isEmpty()) {
|
||||
BabyProfile current = getCurrentBabyEntity();
|
||||
familyId = current.getFamilyId();
|
||||
}
|
||||
|
||||
boolean isDef = Boolean.TRUE.equals(request.getIsDefault());
|
||||
if (isDef) {
|
||||
babyMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getFamilyId, familyId)
|
||||
.set(BabyProfile::getIsDefault, 0)
|
||||
);
|
||||
}
|
||||
|
||||
BabyProfile baby = new BabyProfile();
|
||||
baby.setBabyId(idGenerator.nextId());
|
||||
baby.setFamilyId(familyId);
|
||||
baby.setName(request.getName().trim());
|
||||
baby.setGender(request.getGender() == null || "unknown".equals(request.getGender()) ? "boy" : request.getGender());
|
||||
if (request.getBirthDate() != null && !request.getBirthDate().trim().isEmpty()) {
|
||||
baby.setBirthDate(LocalDate.parse(request.getBirthDate().trim()));
|
||||
} else {
|
||||
baby.setBirthDate(LocalDate.now());
|
||||
}
|
||||
baby.setDeliveryType(request.getDeliveryType() == null ? "natural" : request.getDeliveryType());
|
||||
baby.setIsDefault(isDef ? 1 : 0);
|
||||
baby.setStatus("active");
|
||||
baby.setRemark(request.getRemark());
|
||||
babyMapper.insert(baby);
|
||||
return BabyConvert.toVO(baby);
|
||||
}
|
||||
|
||||
public BabyVO setDefaultBaby(String babyId) {
|
||||
BabyProfile baby = findByBabyId(babyId);
|
||||
babyMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getFamilyId, baby.getFamilyId())
|
||||
.set(BabyProfile::getIsDefault, 0)
|
||||
);
|
||||
return findByBabyId(babyId);
|
||||
babyMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<BabyProfile>()
|
||||
.eq(BabyProfile::getBabyId, babyId)
|
||||
.set(BabyProfile::getIsDefault, 1)
|
||||
);
|
||||
baby.setIsDefault(1);
|
||||
return BabyConvert.toVO(baby);
|
||||
}
|
||||
|
||||
public BabyProfile findByBabyId(String babyId) {
|
||||
List<BabyProfile> babies = jdbcTemplate.query(
|
||||
"SELECT id, family_id, name, gender, birth_date, delivery_type FROM baby_profile WHERE id = ? LIMIT 1",
|
||||
(rs, rowNum) -> mapBaby(rs),
|
||||
babyId
|
||||
);
|
||||
if (babies.isEmpty()) {
|
||||
return getCurrentBaby();
|
||||
BabyProfile baby = babyMapper.selectById(babyId);
|
||||
if (baby == null) {
|
||||
return getCurrentBabyEntity();
|
||||
}
|
||||
return babies.get(0);
|
||||
}
|
||||
|
||||
private BabyProfile mapBaby(ResultSet rs) throws SQLException {
|
||||
BabyProfile baby = new BabyProfile();
|
||||
baby.setBabyId(rs.getString("id"));
|
||||
baby.setFamilyId(rs.getString("family_id"));
|
||||
baby.setName(rs.getString("name"));
|
||||
baby.setGender(rs.getString("gender"));
|
||||
baby.setBirthDate(rs.getDate("birth_date").toLocalDate());
|
||||
baby.setDeliveryType(rs.getString("delivery_type"));
|
||||
return baby;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.babytracker.module.baby;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class UpdateBabyRequest {
|
||||
@NotBlank
|
||||
private String name;
|
||||
private String gender;
|
||||
@NotNull
|
||||
private LocalDate birthDate;
|
||||
private String deliveryType;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public LocalDate getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(LocalDate birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public String getDeliveryType() {
|
||||
return deliveryType;
|
||||
}
|
||||
|
||||
public void setDeliveryType(String deliveryType) {
|
||||
this.deliveryType = deliveryType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.babytracker.module.baby.dto;
|
||||
|
||||
import com.babytracker.module.baby.BabyProfile;
|
||||
import com.babytracker.module.baby.vo.BabyVO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class BabyConvert {
|
||||
|
||||
private BabyConvert() {}
|
||||
|
||||
public static BabyVO toVO(BabyProfile entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
BabyVO vo = new BabyVO();
|
||||
vo.setBabyId(entity.getBabyId());
|
||||
vo.setFamilyId(entity.getFamilyId());
|
||||
vo.setName(entity.getName());
|
||||
vo.setGender(entity.getGender());
|
||||
vo.setBirthDate(entity.getBirthDate());
|
||||
vo.setDeliveryType(entity.getDeliveryType());
|
||||
vo.setIsDefault(entity.getIsDefault());
|
||||
vo.setStatus(entity.getStatus());
|
||||
vo.setAgeDays(entity.getAgeDays());
|
||||
vo.setAgeText(entity.getAgeText());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setCreatedBy(entity.getCreatedBy());
|
||||
vo.setCreatedTime(entity.getCreatedTime());
|
||||
vo.setUpdatedBy(entity.getUpdatedBy());
|
||||
vo.setUpdatedTime(entity.getUpdatedTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public static List<BabyVO> toVOList(List<BabyProfile> list) {
|
||||
if (list == null || list.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<BabyVO> voList = new ArrayList<>(list.size());
|
||||
for (BabyProfile entity : list) {
|
||||
voList.add(toVO(entity));
|
||||
}
|
||||
return voList;
|
||||
}
|
||||
|
||||
public static BabyDTO toDTO(BabyProfile entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
BabyDTO dto = new BabyDTO();
|
||||
dto.setBabyId(entity.getBabyId());
|
||||
dto.setFamilyId(entity.getFamilyId());
|
||||
dto.setName(entity.getName());
|
||||
dto.setGender(entity.getGender());
|
||||
dto.setBirthDate(entity.getBirthDate());
|
||||
dto.setDeliveryType(entity.getDeliveryType());
|
||||
dto.setIsDefault(entity.getIsDefault());
|
||||
dto.setStatus(entity.getStatus());
|
||||
dto.setAgeDays(entity.getAgeDays());
|
||||
dto.setAgeText(entity.getAgeText());
|
||||
dto.setRemark(entity.getRemark());
|
||||
dto.setCreatedBy(entity.getCreatedBy());
|
||||
dto.setCreatedTime(entity.getCreatedTime());
|
||||
dto.setUpdatedBy(entity.getUpdatedBy());
|
||||
dto.setUpdatedTime(entity.getUpdatedTime());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.babytracker.module.baby.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class BabyDTO {
|
||||
private String babyId;
|
||||
private String familyId;
|
||||
private String name;
|
||||
private String gender;
|
||||
private LocalDate birthDate;
|
||||
private String deliveryType;
|
||||
private Integer isDefault;
|
||||
private String status;
|
||||
private long ageDays;
|
||||
private String ageText;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.babytracker.module.baby.mapper;
|
||||
|
||||
import com.babytracker.module.baby.BabyProfile;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface BabyMapper extends BaseMapper<BabyProfile> {
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.babytracker.module.baby.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CreateBabyRO {
|
||||
private String familyId;
|
||||
|
||||
@NotBlank(message = "宝宝姓名不能为空")
|
||||
private String name;
|
||||
|
||||
private String gender;
|
||||
|
||||
private String birthDate;
|
||||
|
||||
private String deliveryType;
|
||||
|
||||
private Boolean isDefault;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.babytracker.module.baby.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SetDefaultBabyRO {
|
||||
@NotBlank(message = "宝宝ID不能为空")
|
||||
private String babyId;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.babytracker.module.baby.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateBabyRO {
|
||||
private String babyId;
|
||||
|
||||
@NotBlank(message = "宝宝姓名不能为空")
|
||||
private String name;
|
||||
|
||||
private String gender;
|
||||
|
||||
private String birthDate;
|
||||
|
||||
private String deliveryType;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.babytracker.module.baby.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class BabyVO {
|
||||
private String babyId;
|
||||
private String familyId;
|
||||
private String name;
|
||||
private String gender;
|
||||
private LocalDate birthDate;
|
||||
private String deliveryType;
|
||||
private Integer isDefault;
|
||||
private String status;
|
||||
private long ageDays;
|
||||
private String ageText;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getUpdatedAt() {
|
||||
return updatedTime;
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.babytracker.module.family;
|
||||
|
||||
import com.babytracker.module.baby.BabyProfile;
|
||||
import java.util.List;
|
||||
|
||||
public class FamilyContext {
|
||||
private FamilyInfo family;
|
||||
private List<BabyProfile> babies;
|
||||
private List<FamilyMember> members;
|
||||
|
||||
public FamilyInfo getFamily() {
|
||||
return family;
|
||||
}
|
||||
|
||||
public void setFamily(FamilyInfo family) {
|
||||
this.family = family;
|
||||
}
|
||||
|
||||
public List<BabyProfile> getBabies() {
|
||||
return babies;
|
||||
}
|
||||
|
||||
public void setBabies(List<BabyProfile> babies) {
|
||||
this.babies = babies;
|
||||
}
|
||||
|
||||
public List<FamilyMember> getMembers() {
|
||||
return members;
|
||||
}
|
||||
|
||||
public void setMembers(List<FamilyMember> members) {
|
||||
this.members = members;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,53 @@
|
||||
package com.babytracker.module.family;
|
||||
|
||||
import com.babytracker.common.response.ApiResponse;
|
||||
import com.babytracker.module.family.ro.CreateMemberRO;
|
||||
import com.babytracker.module.family.ro.DeleteMemberRO;
|
||||
import com.babytracker.module.family.ro.UpdateFamilyRO;
|
||||
import com.babytracker.module.family.ro.UpdateMemberRO;
|
||||
import com.babytracker.module.family.vo.FamilyContextVO;
|
||||
import com.babytracker.module.family.vo.FamilyMemberVO;
|
||||
import com.babytracker.module.family.vo.FamilyVO;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/families")
|
||||
public class FamilyController {
|
||||
private final FamilyService familyService;
|
||||
|
||||
public FamilyController(FamilyService familyService) {
|
||||
this.familyService = familyService;
|
||||
}
|
||||
|
||||
@GetMapping("/current-context")
|
||||
public ApiResponse<FamilyContext> currentContext() {
|
||||
public ApiResponse<FamilyContextVO> currentContext() {
|
||||
return ApiResponse.ok(familyService.getCurrentContext());
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public ApiResponse<FamilyVO> updateFamily(@Valid @RequestBody UpdateFamilyRO request) {
|
||||
return ApiResponse.ok(familyService.updateFamily(request));
|
||||
}
|
||||
|
||||
@PostMapping("/members")
|
||||
public ApiResponse<FamilyMemberVO> createMember(@Valid @RequestBody CreateMemberRO request) {
|
||||
return ApiResponse.ok(familyService.createMember(request));
|
||||
}
|
||||
|
||||
@PutMapping("/members")
|
||||
public ApiResponse<FamilyMemberVO> updateMember(@Valid @RequestBody UpdateMemberRO request) {
|
||||
return ApiResponse.ok(familyService.updateMember(request));
|
||||
}
|
||||
|
||||
@PostMapping("/members/delete")
|
||||
public ApiResponse<Void> deleteMember(@Valid @RequestBody DeleteMemberRO request) {
|
||||
familyService.deleteMember(request.getFamilyId(), request.getMemberId());
|
||||
return ApiResponse.ok(null);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,27 @@
|
||||
package com.babytracker.module.family;
|
||||
|
||||
public class FamilyInfo {
|
||||
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("family")
|
||||
public class FamilyInfo extends BaseEntity {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String familyId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("invite_code")
|
||||
private String inviteCode;
|
||||
|
||||
public String getFamilyId() {
|
||||
return familyId;
|
||||
}
|
||||
|
||||
public void setFamilyId(String familyId) {
|
||||
this.familyId = familyId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getInviteCode() {
|
||||
return inviteCode;
|
||||
}
|
||||
|
||||
public void setInviteCode(String inviteCode) {
|
||||
this.inviteCode = inviteCode;
|
||||
}
|
||||
@TableField("status")
|
||||
private String status;
|
||||
}
|
||||
@@ -1,58 +1,36 @@
|
||||
package com.babytracker.module.family;
|
||||
|
||||
public class FamilyMember {
|
||||
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("family_member")
|
||||
public class FamilyMember extends BaseEntity {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String memberId;
|
||||
|
||||
@TableField("family_id")
|
||||
private String familyId;
|
||||
|
||||
@TableField("user_id")
|
||||
private String userId;
|
||||
|
||||
@TableField("role_name")
|
||||
private String roleName;
|
||||
|
||||
@TableField("role_type")
|
||||
private String roleType;
|
||||
|
||||
@TableField("is_default_operator")
|
||||
private boolean defaultOperator;
|
||||
|
||||
public String getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(String memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public String getFamilyId() {
|
||||
return familyId;
|
||||
}
|
||||
|
||||
public void setFamilyId(String familyId) {
|
||||
this.familyId = familyId;
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return roleName;
|
||||
}
|
||||
|
||||
public void setRoleName(String roleName) {
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
public String getRoleType() {
|
||||
return roleType;
|
||||
}
|
||||
|
||||
public void setRoleType(String roleType) {
|
||||
this.roleType = roleType;
|
||||
}
|
||||
|
||||
public boolean isDefaultOperator() {
|
||||
return defaultOperator;
|
||||
}
|
||||
|
||||
public void setDefaultOperator(boolean defaultOperator) {
|
||||
this.defaultOperator = defaultOperator;
|
||||
}
|
||||
@TableField("status")
|
||||
private String status;
|
||||
}
|
||||
@@ -1,65 +1,164 @@
|
||||
package com.babytracker.module.family;
|
||||
|
||||
import com.babytracker.module.baby.BabyProfile;
|
||||
import com.babytracker.common.exception.BusinessException;
|
||||
import com.babytracker.common.id.SnowflakeIdGenerator;
|
||||
import com.babytracker.module.baby.BabyService;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import com.babytracker.module.family.dto.FamilyConvert;
|
||||
import com.babytracker.module.family.mapper.FamilyMapper;
|
||||
import com.babytracker.module.family.mapper.FamilyMemberMapper;
|
||||
import com.babytracker.module.family.ro.CreateMemberRO;
|
||||
import com.babytracker.module.family.ro.UpdateFamilyRO;
|
||||
import com.babytracker.module.family.ro.UpdateMemberRO;
|
||||
import com.babytracker.module.family.vo.FamilyContextVO;
|
||||
import com.babytracker.module.family.vo.FamilyMemberVO;
|
||||
import com.babytracker.module.family.vo.FamilyVO;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FamilyService {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final FamilyMapper familyMapper;
|
||||
private final FamilyMemberMapper familyMemberMapper;
|
||||
private final BabyService babyService;
|
||||
private final SnowflakeIdGenerator idGenerator;
|
||||
|
||||
public FamilyService(JdbcTemplate jdbcTemplate, BabyService babyService) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.babyService = babyService;
|
||||
}
|
||||
|
||||
public FamilyContext getCurrentContext() {
|
||||
FamilyContext context = new FamilyContext();
|
||||
context.setFamily(getDefaultFamily());
|
||||
public FamilyContextVO getCurrentContext() {
|
||||
FamilyInfo family = getDefaultFamily();
|
||||
FamilyContextVO context = new FamilyContextVO();
|
||||
context.setFamily(FamilyConvert.toVO(family));
|
||||
context.setBabies(babyService.listBabies());
|
||||
context.setMembers(listMembers(context.getFamily().getFamilyId()));
|
||||
context.setMembers(FamilyConvert.toMemberVOList(listMembers(family.getFamilyId())));
|
||||
return context;
|
||||
}
|
||||
|
||||
private FamilyInfo getDefaultFamily() {
|
||||
List<FamilyInfo> families = jdbcTemplate.query(
|
||||
"SELECT id, name, invite_code FROM family ORDER BY id ASC LIMIT 1",
|
||||
(rs, rowNum) -> {
|
||||
FamilyInfo family = new FamilyInfo();
|
||||
family.setFamilyId(rs.getString("id"));
|
||||
family.setName(rs.getString("name"));
|
||||
family.setInviteCode(rs.getString("invite_code"));
|
||||
return family;
|
||||
}
|
||||
);
|
||||
if (!families.isEmpty()) {
|
||||
return families.get(0);
|
||||
public FamilyVO updateFamily(UpdateFamilyRO request) {
|
||||
String familyId = request.getFamilyId();
|
||||
if (familyId == null || familyId.trim().isEmpty()) {
|
||||
familyId = getDefaultFamily().getFamilyId();
|
||||
}
|
||||
FamilyInfo family = new FamilyInfo();
|
||||
family.setFamilyId("00000000000000361915955439210496");
|
||||
family.setName("新生儿照护家庭");
|
||||
family.setInviteCode("BT2026");
|
||||
return family;
|
||||
FamilyInfo family = familyMapper.selectById(familyId);
|
||||
if (family == null) {
|
||||
throw new BusinessException("FAMILY_NOT_FOUND", "家庭不存在");
|
||||
}
|
||||
family.setName(request.getName().trim());
|
||||
if (request.getInviteCode() != null) {
|
||||
family.setInviteCode(request.getInviteCode().trim());
|
||||
}
|
||||
if (request.getRemark() != null) {
|
||||
family.setRemark(request.getRemark().trim());
|
||||
}
|
||||
familyMapper.updateById(family);
|
||||
return FamilyConvert.toVO(family);
|
||||
}
|
||||
|
||||
private List<FamilyMember> listMembers(String familyId) {
|
||||
List<FamilyMember> members = jdbcTemplate.query(
|
||||
"SELECT id, family_id, user_id, role_name, role_type, is_default_operator FROM family_member WHERE family_id = ? AND status = 'active' ORDER BY is_default_operator DESC, id ASC",
|
||||
(rs, rowNum) -> {
|
||||
FamilyMember member = new FamilyMember();
|
||||
member.setMemberId(rs.getString("id"));
|
||||
member.setFamilyId(rs.getString("family_id"));
|
||||
member.setUserId(rs.getString("user_id"));
|
||||
member.setRoleName(rs.getString("role_name"));
|
||||
member.setRoleType(rs.getString("role_type"));
|
||||
member.setDefaultOperator(rs.getBoolean("is_default_operator"));
|
||||
return member;
|
||||
},
|
||||
familyId
|
||||
public FamilyMemberVO createMember(CreateMemberRO request) {
|
||||
String familyId = request.getFamilyId();
|
||||
if (familyId == null || familyId.trim().isEmpty()) {
|
||||
familyId = getDefaultFamily().getFamilyId();
|
||||
}
|
||||
|
||||
boolean isDef = Boolean.TRUE.equals(request.getDefaultOperator());
|
||||
if (isDef) {
|
||||
familyMemberMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<FamilyMember>()
|
||||
.eq(FamilyMember::getFamilyId, familyId)
|
||||
.set(FamilyMember::isDefaultOperator, false)
|
||||
);
|
||||
}
|
||||
|
||||
FamilyMember member = new FamilyMember();
|
||||
member.setMemberId(idGenerator.nextId());
|
||||
member.setFamilyId(familyId);
|
||||
member.setRoleName(request.getRoleName().trim());
|
||||
member.setRoleType(request.getRoleType() == null || request.getRoleType().trim().isEmpty() ? "caregiver" : request.getRoleType().trim());
|
||||
member.setDefaultOperator(isDef);
|
||||
member.setStatus("active");
|
||||
member.setRemark(request.getRemark());
|
||||
familyMemberMapper.insert(member);
|
||||
return FamilyConvert.toVO(member);
|
||||
}
|
||||
|
||||
public FamilyMemberVO updateMember(UpdateMemberRO request) {
|
||||
String memberId = request.getMemberId();
|
||||
FamilyMember member = familyMemberMapper.selectById(memberId);
|
||||
if (member == null) {
|
||||
throw new BusinessException("MEMBER_NOT_FOUND", "家庭成员不存在");
|
||||
}
|
||||
String familyId = request.getFamilyId() != null && !request.getFamilyId().trim().isEmpty()
|
||||
? request.getFamilyId() : member.getFamilyId();
|
||||
|
||||
boolean isDef = Boolean.TRUE.equals(request.getDefaultOperator());
|
||||
if (isDef) {
|
||||
familyMemberMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<FamilyMember>()
|
||||
.eq(FamilyMember::getFamilyId, familyId)
|
||||
.set(FamilyMember::isDefaultOperator, false)
|
||||
);
|
||||
}
|
||||
|
||||
member.setRoleName(request.getRoleName().trim());
|
||||
if (request.getRoleType() != null && !request.getRoleType().trim().isEmpty()) {
|
||||
member.setRoleType(request.getRoleType().trim());
|
||||
}
|
||||
member.setDefaultOperator(isDef);
|
||||
if (request.getRemark() != null) {
|
||||
member.setRemark(request.getRemark().trim());
|
||||
}
|
||||
familyMemberMapper.updateById(member);
|
||||
return FamilyConvert.toVO(member);
|
||||
}
|
||||
|
||||
public void deleteMember(String familyId, String memberId) {
|
||||
if (familyId == null || familyId.trim().isEmpty()) {
|
||||
FamilyMember member = familyMemberMapper.selectById(memberId);
|
||||
if (member == null) {
|
||||
throw new BusinessException("MEMBER_NOT_FOUND", "家庭成员不存在");
|
||||
}
|
||||
familyId = member.getFamilyId();
|
||||
}
|
||||
List<FamilyMember> members = listMembers(familyId);
|
||||
if (members.size() <= 1) {
|
||||
throw new BusinessException("CANNOT_DELETE_LAST_MEMBER", "家庭中至少需保留一名成员");
|
||||
}
|
||||
FamilyMember member = familyMemberMapper.selectById(memberId);
|
||||
if (member == null || !familyId.equals(member.getFamilyId())) {
|
||||
throw new BusinessException("MEMBER_NOT_FOUND", "家庭成员不存在");
|
||||
}
|
||||
member.setStatus("left");
|
||||
familyMemberMapper.deleteById(memberId);
|
||||
}
|
||||
|
||||
public FamilyInfo getDefaultFamily() {
|
||||
FamilyInfo family = familyMapper.selectOne(
|
||||
new LambdaQueryWrapper<FamilyInfo>()
|
||||
.orderByAsc(FamilyInfo::getFamilyId)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
if (family != null) {
|
||||
return family;
|
||||
}
|
||||
FamilyInfo defaultFamily = new FamilyInfo();
|
||||
defaultFamily.setFamilyId("00000000000000361915955439210496");
|
||||
defaultFamily.setName("新生儿照护家庭");
|
||||
defaultFamily.setInviteCode("BT2026");
|
||||
familyMapper.insert(defaultFamily);
|
||||
return defaultFamily;
|
||||
}
|
||||
|
||||
public List<FamilyMember> listMembers(String familyId) {
|
||||
List<FamilyMember> members = familyMemberMapper.selectList(
|
||||
new LambdaQueryWrapper<FamilyMember>()
|
||||
.eq(FamilyMember::getFamilyId, familyId)
|
||||
.eq(FamilyMember::getStatus, "active")
|
||||
.orderByDesc(FamilyMember::isDefaultOperator)
|
||||
.orderByAsc(FamilyMember::getMemberId)
|
||||
);
|
||||
if (!members.isEmpty()) {
|
||||
return members;
|
||||
@@ -76,5 +175,4 @@ public class FamilyService {
|
||||
mom.setDefaultOperator(true);
|
||||
return List.of(mom);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.babytracker.module.family.dto;
|
||||
|
||||
import com.babytracker.module.family.FamilyInfo;
|
||||
import com.babytracker.module.family.FamilyMember;
|
||||
import com.babytracker.module.family.vo.FamilyMemberVO;
|
||||
import com.babytracker.module.family.vo.FamilyVO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class FamilyConvert {
|
||||
|
||||
private FamilyConvert() {}
|
||||
|
||||
public static FamilyVO toVO(FamilyInfo entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FamilyVO vo = new FamilyVO();
|
||||
vo.setFamilyId(entity.getFamilyId());
|
||||
vo.setName(entity.getName());
|
||||
vo.setInviteCode(entity.getInviteCode());
|
||||
vo.setStatus(entity.getStatus());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setCreatedBy(entity.getCreatedBy());
|
||||
vo.setCreatedTime(entity.getCreatedTime());
|
||||
vo.setUpdatedBy(entity.getUpdatedBy());
|
||||
vo.setUpdatedTime(entity.getUpdatedTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public static FamilyDTO toDTO(FamilyInfo entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FamilyDTO dto = new FamilyDTO();
|
||||
dto.setFamilyId(entity.getFamilyId());
|
||||
dto.setName(entity.getName());
|
||||
dto.setInviteCode(entity.getInviteCode());
|
||||
dto.setStatus(entity.getStatus());
|
||||
dto.setRemark(entity.getRemark());
|
||||
dto.setCreatedBy(entity.getCreatedBy());
|
||||
dto.setCreatedTime(entity.getCreatedTime());
|
||||
dto.setUpdatedBy(entity.getUpdatedBy());
|
||||
dto.setUpdatedTime(entity.getUpdatedTime());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public static FamilyMemberVO toVO(FamilyMember entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FamilyMemberVO vo = new FamilyMemberVO();
|
||||
vo.setMemberId(entity.getMemberId());
|
||||
vo.setFamilyId(entity.getFamilyId());
|
||||
vo.setUserId(entity.getUserId());
|
||||
vo.setRoleName(entity.getRoleName());
|
||||
vo.setRoleType(entity.getRoleType());
|
||||
vo.setDefaultOperator(entity.isDefaultOperator());
|
||||
vo.setStatus(entity.getStatus());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setCreatedBy(entity.getCreatedBy());
|
||||
vo.setCreatedTime(entity.getCreatedTime());
|
||||
vo.setUpdatedBy(entity.getUpdatedBy());
|
||||
vo.setUpdatedTime(entity.getUpdatedTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public static List<FamilyMemberVO> toMemberVOList(List<FamilyMember> list) {
|
||||
if (list == null || list.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<FamilyMemberVO> voList = new ArrayList<>(list.size());
|
||||
for (FamilyMember entity : list) {
|
||||
voList.add(toVO(entity));
|
||||
}
|
||||
return voList;
|
||||
}
|
||||
|
||||
public static FamilyMemberDTO toDTO(FamilyMember entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FamilyMemberDTO dto = new FamilyMemberDTO();
|
||||
dto.setMemberId(entity.getMemberId());
|
||||
dto.setFamilyId(entity.getFamilyId());
|
||||
dto.setUserId(entity.getUserId());
|
||||
dto.setRoleName(entity.getRoleName());
|
||||
dto.setRoleType(entity.getRoleType());
|
||||
dto.setDefaultOperator(entity.isDefaultOperator());
|
||||
dto.setStatus(entity.getStatus());
|
||||
dto.setRemark(entity.getRemark());
|
||||
dto.setCreatedBy(entity.getCreatedBy());
|
||||
dto.setCreatedTime(entity.getCreatedTime());
|
||||
dto.setUpdatedBy(entity.getUpdatedBy());
|
||||
dto.setUpdatedTime(entity.getUpdatedTime());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.babytracker.module.family.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class FamilyDTO {
|
||||
private String familyId;
|
||||
private String name;
|
||||
private String inviteCode;
|
||||
private String status;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.babytracker.module.family.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class FamilyMemberDTO {
|
||||
private String memberId;
|
||||
private String familyId;
|
||||
private String userId;
|
||||
private String roleName;
|
||||
private String roleType;
|
||||
private boolean defaultOperator;
|
||||
private String status;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.babytracker.module.family.mapper;
|
||||
|
||||
import com.babytracker.module.family.FamilyInfo;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface FamilyMapper extends BaseMapper<FamilyInfo> {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.babytracker.module.family.mapper;
|
||||
|
||||
import com.babytracker.module.family.FamilyMember;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface FamilyMemberMapper extends BaseMapper<FamilyMember> {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.babytracker.module.family.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CreateMemberRO {
|
||||
private String familyId;
|
||||
|
||||
@NotBlank(message = "角色称谓不能为空")
|
||||
private String roleName;
|
||||
|
||||
private String roleType; // owner, caregiver, viewer
|
||||
|
||||
private Boolean defaultOperator;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.babytracker.module.family.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class DeleteMemberRO {
|
||||
private String familyId;
|
||||
|
||||
@NotBlank(message = "成员ID不能为空")
|
||||
private String memberId;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.babytracker.module.family.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateFamilyRO {
|
||||
private String familyId;
|
||||
|
||||
@NotBlank(message = "家庭名称不能为空")
|
||||
private String name;
|
||||
|
||||
private String inviteCode;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.babytracker.module.family.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateMemberRO {
|
||||
private String familyId;
|
||||
|
||||
@NotBlank(message = "成员ID不能为空")
|
||||
private String memberId;
|
||||
|
||||
@NotBlank(message = "角色称谓不能为空")
|
||||
private String roleName;
|
||||
|
||||
private String roleType; // owner, caregiver, viewer
|
||||
|
||||
private Boolean defaultOperator;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.babytracker.module.family.vo;
|
||||
|
||||
import com.babytracker.module.baby.vo.BabyVO;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class FamilyContextVO {
|
||||
private FamilyVO family;
|
||||
private List<BabyVO> babies;
|
||||
private List<FamilyMemberVO> members;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.babytracker.module.family.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class FamilyMemberVO {
|
||||
private String memberId;
|
||||
private String familyId;
|
||||
private String userId;
|
||||
private String roleName;
|
||||
private String roleType;
|
||||
private boolean defaultOperator;
|
||||
private String status;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getUpdatedAt() {
|
||||
return updatedTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.babytracker.module.family.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class FamilyVO {
|
||||
private String familyId;
|
||||
private String name;
|
||||
private String inviteCode;
|
||||
private String status;
|
||||
private String remark;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getUpdatedAt() {
|
||||
return updatedTime;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,59 @@
|
||||
package com.babytracker.module.record;
|
||||
|
||||
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;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class CareRecord {
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("care_record")
|
||||
public class CareRecord extends BaseEntity {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String recordId;
|
||||
|
||||
@TableField("family_id")
|
||||
private String familyId;
|
||||
|
||||
@TableField("baby_id")
|
||||
private String babyId;
|
||||
|
||||
@TableField("record_type")
|
||||
private String recordType;
|
||||
|
||||
@TableField("start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@TableField("end_time")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@TableField("duration_minutes")
|
||||
private Integer durationMinutes;
|
||||
|
||||
@TableField("feeding_method")
|
||||
private String feedingMethod;
|
||||
|
||||
@TableField("amount_ml")
|
||||
private Integer amountMl;
|
||||
|
||||
@TableField("excretion_type")
|
||||
private String excretionType;
|
||||
|
||||
@TableField("operator_name")
|
||||
private String operatorName;
|
||||
private String note;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@TableField("operator_user_id")
|
||||
private String operatorUserId;
|
||||
|
||||
@TableField("source")
|
||||
private String source = "h5";
|
||||
|
||||
public void recalculateDuration() {
|
||||
if (startTime != null && endTime != null) {
|
||||
@@ -24,108 +61,11 @@ public class CareRecord {
|
||||
}
|
||||
}
|
||||
|
||||
public String getRecordId() {
|
||||
return recordId;
|
||||
}
|
||||
|
||||
public void setRecordId(String recordId) {
|
||||
this.recordId = recordId;
|
||||
}
|
||||
|
||||
public String getFamilyId() {
|
||||
return familyId;
|
||||
}
|
||||
|
||||
public void setFamilyId(String familyId) {
|
||||
this.familyId = familyId;
|
||||
}
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public String getRecordType() {
|
||||
return recordType;
|
||||
}
|
||||
|
||||
public void setRecordType(String recordType) {
|
||||
this.recordType = recordType;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getDurationMinutes() {
|
||||
return durationMinutes;
|
||||
}
|
||||
|
||||
public void setDurationMinutes(Integer durationMinutes) {
|
||||
this.durationMinutes = durationMinutes;
|
||||
}
|
||||
|
||||
public String getFeedingMethod() {
|
||||
return feedingMethod;
|
||||
}
|
||||
|
||||
public void setFeedingMethod(String feedingMethod) {
|
||||
this.feedingMethod = feedingMethod;
|
||||
}
|
||||
|
||||
public Integer getAmountMl() {
|
||||
return amountMl;
|
||||
}
|
||||
|
||||
public void setAmountMl(Integer amountMl) {
|
||||
this.amountMl = amountMl;
|
||||
}
|
||||
|
||||
public String getExcretionType() {
|
||||
return excretionType;
|
||||
}
|
||||
|
||||
public void setExcretionType(String excretionType) {
|
||||
this.excretionType = excretionType;
|
||||
}
|
||||
|
||||
public String getOperatorName() {
|
||||
return operatorName;
|
||||
}
|
||||
|
||||
public void setOperatorName(String operatorName) {
|
||||
this.operatorName = operatorName;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
return getRemark();
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.note = note;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
setRemark(note);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,37 @@
|
||||
package com.babytracker.module.record;
|
||||
|
||||
import com.babytracker.common.response.ApiResponse;
|
||||
import com.babytracker.module.record.ro.CreateFeedingRO;
|
||||
import com.babytracker.module.record.ro.CreateManualRecordRO;
|
||||
import com.babytracker.module.record.ro.DeleteCareRecordRO;
|
||||
import com.babytracker.module.record.ro.ExcretionRO;
|
||||
import com.babytracker.module.record.ro.SleepRO;
|
||||
import com.babytracker.module.record.ro.UpdateCareRecordRO;
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/records")
|
||||
public class CareRecordController {
|
||||
private final CareRecordService careRecordService;
|
||||
|
||||
public CareRecordController(CareRecordService careRecordService) {
|
||||
this.careRecordService = careRecordService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<CareRecord>> list(
|
||||
public ApiResponse<List<CareRecordVO>> list(
|
||||
@RequestParam String babyId,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
|
||||
) {
|
||||
@@ -35,43 +39,53 @@ public class CareRecordController {
|
||||
}
|
||||
|
||||
@PostMapping("/feeding")
|
||||
public ApiResponse<CareRecord> feeding(@Valid @RequestBody CreateFeedingRequest request) {
|
||||
public ApiResponse<CareRecordVO> feeding(@Valid @RequestBody CreateFeedingRO request) {
|
||||
return ApiResponse.ok(careRecordService.createFeeding(request));
|
||||
}
|
||||
|
||||
@PostMapping("/feeding/start")
|
||||
public ApiResponse<CareRecord> startFeeding(@Valid @RequestBody CreateFeedingRequest request) {
|
||||
public ApiResponse<CareRecordVO> startFeeding(@Valid @RequestBody CreateFeedingRO request) {
|
||||
return ApiResponse.ok(careRecordService.startFeeding(request));
|
||||
}
|
||||
|
||||
@PostMapping("/feeding/end")
|
||||
public ApiResponse<CareRecord> endFeeding(@Valid @RequestBody CreateFeedingRequest request) {
|
||||
public ApiResponse<CareRecordVO> endFeeding(@Valid @RequestBody CreateFeedingRO request) {
|
||||
return ApiResponse.ok(careRecordService.endFeeding(request));
|
||||
}
|
||||
|
||||
@PostMapping("/sleep/start")
|
||||
public ApiResponse<CareRecord> startSleep(@Valid @RequestBody SleepRequest request) {
|
||||
public ApiResponse<CareRecordVO> startSleep(@Valid @RequestBody SleepRO request) {
|
||||
return ApiResponse.ok(careRecordService.startSleep(request));
|
||||
}
|
||||
|
||||
@PostMapping("/sleep/end")
|
||||
public ApiResponse<CareRecord> endSleep(@Valid @RequestBody SleepRequest request) {
|
||||
public ApiResponse<CareRecordVO> endSleep(@Valid @RequestBody SleepRO request) {
|
||||
return ApiResponse.ok(careRecordService.endSleep(request));
|
||||
}
|
||||
|
||||
@PostMapping("/pee")
|
||||
public ApiResponse<CareRecord> pee(@Valid @RequestBody ExcretionRequest request) {
|
||||
public ApiResponse<CareRecordVO> pee(@Valid @RequestBody ExcretionRO request) {
|
||||
return ApiResponse.ok(careRecordService.createPee(request));
|
||||
}
|
||||
|
||||
@PostMapping("/poop")
|
||||
public ApiResponse<CareRecord> poop(@Valid @RequestBody ExcretionRequest request) {
|
||||
public ApiResponse<CareRecordVO> poop(@Valid @RequestBody ExcretionRO request) {
|
||||
return ApiResponse.ok(careRecordService.createPoop(request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{recordId}")
|
||||
public ApiResponse<Void> delete(@PathVariable String recordId) {
|
||||
careRecordService.delete(recordId);
|
||||
@PostMapping
|
||||
public ApiResponse<CareRecordVO> createManual(@Valid @RequestBody CreateManualRecordRO request) {
|
||||
return ApiResponse.ok(careRecordService.createManual(request));
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public ApiResponse<CareRecordVO> update(@Valid @RequestBody UpdateCareRecordRO request) {
|
||||
return ApiResponse.ok(careRecordService.update(request));
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
public ApiResponse<Void> delete(@Valid @RequestBody DeleteCareRecordRO request) {
|
||||
careRecordService.delete(request.getRecordId());
|
||||
return ApiResponse.ok(null);
|
||||
}
|
||||
}
|
||||
@@ -2,75 +2,72 @@ package com.babytracker.module.record;
|
||||
|
||||
import com.babytracker.common.exception.BusinessException;
|
||||
import com.babytracker.common.id.SnowflakeIdGenerator;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import com.babytracker.module.baby.BabyProfile;
|
||||
import com.babytracker.module.baby.mapper.BabyMapper;
|
||||
import com.babytracker.module.record.dto.CareRecordConvert;
|
||||
import com.babytracker.module.record.mapper.CareRecordMapper;
|
||||
import com.babytracker.module.record.ro.CreateFeedingRO;
|
||||
import com.babytracker.module.record.ro.CreateManualRecordRO;
|
||||
import com.babytracker.module.record.ro.ExcretionRO;
|
||||
import com.babytracker.module.record.ro.SleepRO;
|
||||
import com.babytracker.module.record.ro.UpdateCareRecordRO;
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CareRecordService {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final CareRecordMapper careRecordMapper;
|
||||
private final BabyMapper babyMapper;
|
||||
private final SnowflakeIdGenerator idGenerator;
|
||||
|
||||
public CareRecordService(JdbcTemplate jdbcTemplate, SnowflakeIdGenerator idGenerator) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.idGenerator = idGenerator;
|
||||
}
|
||||
|
||||
public List<CareRecord> list(String babyId, LocalDate date) {
|
||||
public List<CareRecordVO> list(String babyId, LocalDate date) {
|
||||
LocalDate targetDate = date == null ? LocalDate.now() : date;
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM care_record WHERE baby_id = ? AND deleted_at IS NULL AND start_time >= ? AND start_time < ? ORDER BY start_time DESC, id DESC",
|
||||
(rs, rowNum) -> mapRecord(rs),
|
||||
babyId,
|
||||
Timestamp.valueOf(targetDate.atStartOfDay()),
|
||||
Timestamp.valueOf(targetDate.plusDays(1).atStartOfDay())
|
||||
LocalDateTime dayStart = targetDate.atStartOfDay();
|
||||
LocalDateTime dayEnd = targetDate.plusDays(1).atStartOfDay();
|
||||
|
||||
List<CareRecord> records = careRecordMapper.selectList(
|
||||
new LambdaQueryWrapper<CareRecord>()
|
||||
.eq(CareRecord::getBabyId, babyId)
|
||||
.ge(CareRecord::getStartTime, dayStart)
|
||||
.lt(CareRecord::getStartTime, dayEnd)
|
||||
.orderByDesc(CareRecord::getStartTime)
|
||||
.orderByDesc(CareRecord::getRecordId)
|
||||
);
|
||||
return CareRecordConvert.toVOList(records);
|
||||
}
|
||||
|
||||
public List<CareRecord> allByBaby(String babyId) {
|
||||
return jdbcTemplate.query(
|
||||
"SELECT * FROM care_record WHERE baby_id = ? AND deleted_at IS NULL ORDER BY start_time ASC, id ASC",
|
||||
(rs, rowNum) -> mapRecord(rs),
|
||||
babyId
|
||||
);
|
||||
}
|
||||
|
||||
public CareRecord createFeeding(CreateFeedingRequest request) {
|
||||
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingNote(request));
|
||||
public CareRecordVO createFeeding(CreateFeedingRO request) {
|
||||
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), request.getRemark());
|
||||
record.setFeedingMethod(request.getFeedingMethod());
|
||||
record.setAmountMl(request.getAmountMl());
|
||||
LocalDateTime endTime = request.getEndTime() == null ? record.getStartTime() : request.getEndTime();
|
||||
if (endTime != null) {
|
||||
if (endTime.isBefore(record.getStartTime())) {
|
||||
throw new BusinessException("INVALID_FEEDING_TIME", "喂奶结束时间不能早于开始时间");
|
||||
}
|
||||
record.setEndTime(endTime);
|
||||
record.setEndTime(request.getEndTime());
|
||||
if (record.getStartTime() != null && record.getEndTime() != null) {
|
||||
record.recalculateDuration();
|
||||
}
|
||||
insert(record);
|
||||
return record;
|
||||
careRecordMapper.insert(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
public CareRecord startFeeding(CreateFeedingRequest request) {
|
||||
CareRecord activeFeeding = findActiveFeeding(request.getBabyId());
|
||||
public CareRecordVO startFeeding(CreateFeedingRO request) {
|
||||
CareRecord activeFeeding = findActiveFeedingEntity(request.getBabyId());
|
||||
if (activeFeeding != null) {
|
||||
throw new BusinessException("FEEDING_ALREADY_STARTED", "当前已有进行中的亲喂记录");
|
||||
}
|
||||
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingNote(request));
|
||||
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingRemark(request));
|
||||
record.setFeedingMethod("breastfeed");
|
||||
insert(record);
|
||||
return record;
|
||||
careRecordMapper.insert(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
public CareRecord endFeeding(CreateFeedingRequest request) {
|
||||
CareRecord activeFeeding = findActiveFeeding(request.getBabyId());
|
||||
public CareRecordVO endFeeding(CreateFeedingRO request) {
|
||||
CareRecord activeFeeding = findActiveFeedingEntity(request.getBabyId());
|
||||
if (activeFeeding == null) {
|
||||
throw new BusinessException("NO_ACTIVE_FEEDING", "当前没有进行中的亲喂记录");
|
||||
}
|
||||
@@ -79,30 +76,26 @@ public class CareRecordService {
|
||||
throw new BusinessException("INVALID_FEEDING_TIME", "喂奶结束时间不能早于开始时间");
|
||||
}
|
||||
activeFeeding.setEndTime(end);
|
||||
activeFeeding.setNote(request.getNote() == null ? activeFeeding.getNote() : buildFeedingNote(request));
|
||||
if (request.getRemark() != null) {
|
||||
activeFeeding.setRemark(buildFeedingRemark(request));
|
||||
}
|
||||
activeFeeding.recalculateDuration();
|
||||
jdbcTemplate.update(
|
||||
"UPDATE care_record SET end_time = ?, duration_minutes = ?, note = ? WHERE id = ?",
|
||||
Timestamp.valueOf(activeFeeding.getEndTime()),
|
||||
activeFeeding.getDurationMinutes(),
|
||||
activeFeeding.getNote(),
|
||||
activeFeeding.getRecordId()
|
||||
);
|
||||
return activeFeeding;
|
||||
careRecordMapper.updateById(activeFeeding);
|
||||
return CareRecordConvert.toVO(activeFeeding);
|
||||
}
|
||||
|
||||
public CareRecord startSleep(SleepRequest request) {
|
||||
CareRecord activeSleep = findActiveSleep(request.getBabyId());
|
||||
public CareRecordVO startSleep(SleepRO request) {
|
||||
CareRecord activeSleep = findActiveSleepEntity(request.getBabyId());
|
||||
if (activeSleep != null) {
|
||||
throw new BusinessException("SLEEP_ALREADY_STARTED", "当前已有进行中的睡眠记录");
|
||||
}
|
||||
CareRecord record = baseRecord(request.getBabyId(), "sleep", request.getTime(), request.getOperatorName(), request.getNote());
|
||||
insert(record);
|
||||
return record;
|
||||
CareRecord record = baseRecord(request.getBabyId(), "sleep", request.getTime(), request.getOperatorName(), request.getRemark());
|
||||
careRecordMapper.insert(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
public CareRecord endSleep(SleepRequest request) {
|
||||
CareRecord activeSleep = findActiveSleep(request.getBabyId());
|
||||
public CareRecordVO endSleep(SleepRO request) {
|
||||
CareRecord activeSleep = findActiveSleepEntity(request.getBabyId());
|
||||
if (activeSleep == null) {
|
||||
throw new BusinessException("NO_ACTIVE_SLEEP", "当前没有进行中的睡眠记录");
|
||||
}
|
||||
@@ -111,72 +104,153 @@ public class CareRecordService {
|
||||
throw new BusinessException("INVALID_SLEEP_TIME", "睡眠结束时间不能早于开始时间");
|
||||
}
|
||||
activeSleep.setEndTime(end);
|
||||
activeSleep.setNote(request.getNote() == null ? activeSleep.getNote() : request.getNote());
|
||||
if (request.getRemark() != null) {
|
||||
activeSleep.setRemark(request.getRemark());
|
||||
}
|
||||
activeSleep.recalculateDuration();
|
||||
jdbcTemplate.update(
|
||||
"UPDATE care_record SET end_time = ?, duration_minutes = ?, note = ? WHERE id = ?",
|
||||
Timestamp.valueOf(activeSleep.getEndTime()),
|
||||
activeSleep.getDurationMinutes(),
|
||||
activeSleep.getNote(),
|
||||
activeSleep.getRecordId()
|
||||
);
|
||||
return activeSleep;
|
||||
careRecordMapper.updateById(activeSleep);
|
||||
return CareRecordConvert.toVO(activeSleep);
|
||||
}
|
||||
|
||||
public CareRecord createPee(ExcretionRequest request) {
|
||||
public CareRecordVO createPee(ExcretionRO request) {
|
||||
return createExcretion(request, "pee");
|
||||
}
|
||||
|
||||
public CareRecord createPoop(ExcretionRequest request) {
|
||||
public CareRecordVO createPoop(ExcretionRO request) {
|
||||
return createExcretion(request, "poop");
|
||||
}
|
||||
|
||||
public void delete(String recordId) {
|
||||
int affected = jdbcTemplate.update("UPDATE care_record SET deleted_at = NOW() WHERE id = ? AND deleted_at IS NULL", recordId);
|
||||
if (affected == 0) {
|
||||
public CareRecordVO createManual(CreateManualRecordRO request) {
|
||||
if (request.getEndTime() != null && request.getEndTime().isBefore(request.getStartTime())) {
|
||||
throw new BusinessException("INVALID_TIME", "结束时间不能早于开始时间");
|
||||
}
|
||||
CareRecord record = new CareRecord();
|
||||
record.setRecordId(idGenerator.nextId());
|
||||
record.setFamilyId(resolveFamilyId(request.getBabyId()));
|
||||
record.setBabyId(request.getBabyId());
|
||||
record.setRecordType(request.getRecordType());
|
||||
record.setStartTime(request.getStartTime());
|
||||
record.setEndTime(request.getEndTime());
|
||||
if (request.getDurationMinutes() != null) {
|
||||
record.setDurationMinutes(request.getDurationMinutes());
|
||||
} else if (record.getStartTime() != null && record.getEndTime() != null) {
|
||||
record.recalculateDuration();
|
||||
}
|
||||
record.setFeedingMethod(request.getFeedingMethod());
|
||||
record.setAmountMl(request.getAmountMl());
|
||||
record.setExcretionType(request.getExcretionType());
|
||||
record.setOperatorName(request.getOperatorName() == null || request.getOperatorName().trim().isEmpty() ? "宝妈" : request.getOperatorName().trim());
|
||||
record.setRemark(request.getRemark());
|
||||
record.setSource("h5");
|
||||
careRecordMapper.insert(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
public CareRecordVO update(UpdateCareRecordRO request) {
|
||||
String recordId = request.getRecordId();
|
||||
CareRecord record = careRecordMapper.selectById(recordId);
|
||||
if (record == null) {
|
||||
throw new BusinessException("RECORD_NOT_FOUND", "记录不存在");
|
||||
}
|
||||
|
||||
if (request.getStartTime() != null) {
|
||||
record.setStartTime(request.getStartTime());
|
||||
}
|
||||
if (request.getEndTime() != null) {
|
||||
if (record.getStartTime() != null && request.getEndTime().isBefore(record.getStartTime())) {
|
||||
throw new BusinessException("INVALID_TIME", "结束时间不能早于开始时间");
|
||||
}
|
||||
record.setEndTime(request.getEndTime());
|
||||
}
|
||||
if (request.getDurationMinutes() != null) {
|
||||
record.setDurationMinutes(request.getDurationMinutes());
|
||||
} else if (record.getStartTime() != null && record.getEndTime() != null) {
|
||||
record.recalculateDuration();
|
||||
}
|
||||
if (request.getRecordType() != null) {
|
||||
record.setRecordType(request.getRecordType());
|
||||
}
|
||||
if (request.getFeedingMethod() != null) {
|
||||
record.setFeedingMethod(request.getFeedingMethod());
|
||||
}
|
||||
if (request.getAmountMl() != null) {
|
||||
record.setAmountMl(request.getAmountMl());
|
||||
}
|
||||
if (request.getExcretionType() != null) {
|
||||
record.setExcretionType(request.getExcretionType());
|
||||
}
|
||||
if (request.getOperatorName() != null) {
|
||||
record.setOperatorName(request.getOperatorName().trim());
|
||||
}
|
||||
if (request.getRemark() != null) {
|
||||
record.setRemark(request.getRemark());
|
||||
}
|
||||
careRecordMapper.updateById(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
public CareRecord findActiveSleep(String babyId) {
|
||||
List<CareRecord> active = jdbcTemplate.query(
|
||||
"SELECT * FROM care_record WHERE baby_id = ? AND record_type = 'sleep' AND end_time IS NULL AND deleted_at IS NULL ORDER BY start_time DESC, id DESC LIMIT 1",
|
||||
(rs, rowNum) -> mapRecord(rs),
|
||||
babyId
|
||||
public void delete(String recordId) {
|
||||
CareRecord record = careRecordMapper.selectById(recordId);
|
||||
if (record == null) {
|
||||
throw new BusinessException("RECORD_NOT_FOUND", "记录不存在");
|
||||
}
|
||||
careRecordMapper.deleteById(recordId);
|
||||
}
|
||||
|
||||
public CareRecord findActiveSleepEntity(String babyId) {
|
||||
return careRecordMapper.selectOne(
|
||||
new LambdaQueryWrapper<CareRecord>()
|
||||
.eq(CareRecord::getBabyId, babyId)
|
||||
.eq(CareRecord::getRecordType, "sleep")
|
||||
.isNull(CareRecord::getEndTime)
|
||||
.orderByDesc(CareRecord::getStartTime)
|
||||
.orderByDesc(CareRecord::getRecordId)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return active.isEmpty() ? null : active.get(0);
|
||||
}
|
||||
|
||||
public CareRecord findActiveFeeding(String babyId) {
|
||||
List<CareRecord> active = jdbcTemplate.query(
|
||||
"SELECT * FROM care_record WHERE baby_id = ? AND record_type = 'feeding' AND feeding_method = 'breastfeed' AND end_time IS NULL AND deleted_at IS NULL ORDER BY start_time DESC, id DESC LIMIT 1",
|
||||
(rs, rowNum) -> mapRecord(rs),
|
||||
babyId
|
||||
public CareRecordVO findActiveSleep(String babyId) {
|
||||
return CareRecordConvert.toVO(findActiveSleepEntity(babyId));
|
||||
}
|
||||
|
||||
public CareRecord findActiveFeedingEntity(String babyId) {
|
||||
return careRecordMapper.selectOne(
|
||||
new LambdaQueryWrapper<CareRecord>()
|
||||
.eq(CareRecord::getBabyId, babyId)
|
||||
.eq(CareRecord::getRecordType, "feeding")
|
||||
.eq(CareRecord::getFeedingMethod, "breastfeed")
|
||||
.isNull(CareRecord::getEndTime)
|
||||
.orderByDesc(CareRecord::getStartTime)
|
||||
.orderByDesc(CareRecord::getRecordId)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
return active.isEmpty() ? null : active.get(0);
|
||||
}
|
||||
|
||||
private String buildFeedingNote(CreateFeedingRequest request) {
|
||||
public CareRecordVO findActiveFeeding(String babyId) {
|
||||
return CareRecordConvert.toVO(findActiveFeedingEntity(babyId));
|
||||
}
|
||||
|
||||
private String buildFeedingRemark(CreateFeedingRO request) {
|
||||
String side = request.getBreastSide();
|
||||
String note = request.getNote();
|
||||
String remark = request.getRemark();
|
||||
if (side == null || side.trim().isEmpty()) {
|
||||
return note;
|
||||
return remark;
|
||||
}
|
||||
String sideText = "left".equals(side) ? "左侧" : "right".equals(side) ? "右侧" : side.trim();
|
||||
if (note == null || note.trim().isEmpty()) {
|
||||
if (remark == null || remark.trim().isEmpty()) {
|
||||
return "亲喂侧: " + sideText;
|
||||
}
|
||||
return "亲喂侧: " + sideText + ";" + note.trim();
|
||||
return "亲喂侧: " + sideText + ";" + remark.trim();
|
||||
}
|
||||
|
||||
private CareRecord createExcretion(ExcretionRequest request, String excretionType) {
|
||||
CareRecord record = baseRecord(request.getBabyId(), "excretion", request.getTime(), request.getOperatorName(), request.getNote());
|
||||
private CareRecordVO createExcretion(ExcretionRO request, String excretionType) {
|
||||
CareRecord record = baseRecord(request.getBabyId(), "excretion", request.getTime(), request.getOperatorName(), request.getRemark());
|
||||
record.setExcretionType(excretionType);
|
||||
insert(record);
|
||||
return record;
|
||||
careRecordMapper.insert(record);
|
||||
return CareRecordConvert.toVO(record);
|
||||
}
|
||||
|
||||
private CareRecord baseRecord(String babyId, String type, LocalDateTime time, String operatorName, String note) {
|
||||
private CareRecord baseRecord(String babyId, String type, LocalDateTime time, String operatorName, String remark) {
|
||||
CareRecord record = new CareRecord();
|
||||
record.setRecordId(idGenerator.nextId());
|
||||
record.setFamilyId(resolveFamilyId(babyId));
|
||||
@@ -184,62 +258,22 @@ public class CareRecordService {
|
||||
record.setRecordType(type);
|
||||
record.setStartTime(time == null ? LocalDateTime.now() : time);
|
||||
record.setOperatorName(operatorName == null || operatorName.trim().isEmpty() ? "宝妈" : operatorName.trim());
|
||||
record.setNote(note);
|
||||
record.setCreatedAt(LocalDateTime.now());
|
||||
record.setRemark(remark);
|
||||
record.setSource("h5");
|
||||
return record;
|
||||
}
|
||||
|
||||
private String resolveFamilyId(String babyId) {
|
||||
List<String> familyIds = jdbcTemplate.query(
|
||||
"SELECT family_id FROM baby_profile WHERE id = ? AND status = 'active' LIMIT 1",
|
||||
(rs, rowNum) -> rs.getString("family_id"),
|
||||
babyId
|
||||
BabyProfile baby = babyMapper.selectOne(
|
||||
new LambdaQueryWrapper<BabyProfile>()
|
||||
.select(BabyProfile::getFamilyId)
|
||||
.eq(BabyProfile::getBabyId, babyId)
|
||||
.eq(BabyProfile::getStatus, "active")
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
if (familyIds.isEmpty()) {
|
||||
if (baby == null || baby.getFamilyId() == null) {
|
||||
throw new BusinessException("BABY_NOT_FOUND", "宝宝档案不存在");
|
||||
}
|
||||
return familyIds.get(0);
|
||||
}
|
||||
|
||||
private void insert(CareRecord record) {
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO care_record (id, family_id, baby_id, record_type, start_time, end_time, duration_minutes, feeding_method, amount_ml, excretion_type, operator_name, note, source, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'h5', ?)",
|
||||
record.getRecordId(),
|
||||
record.getFamilyId(),
|
||||
record.getBabyId(),
|
||||
record.getRecordType(),
|
||||
Timestamp.valueOf(record.getStartTime()),
|
||||
record.getEndTime() == null ? null : Timestamp.valueOf(record.getEndTime()),
|
||||
record.getDurationMinutes(),
|
||||
record.getFeedingMethod(),
|
||||
record.getAmountMl(),
|
||||
record.getExcretionType(),
|
||||
record.getOperatorName(),
|
||||
record.getNote(),
|
||||
Timestamp.valueOf(record.getCreatedAt())
|
||||
);
|
||||
}
|
||||
|
||||
private CareRecord mapRecord(ResultSet rs) throws SQLException {
|
||||
CareRecord record = new CareRecord();
|
||||
record.setRecordId(rs.getString("id"));
|
||||
record.setFamilyId(rs.getString("family_id"));
|
||||
record.setBabyId(rs.getString("baby_id"));
|
||||
record.setRecordType(rs.getString("record_type"));
|
||||
record.setStartTime(rs.getTimestamp("start_time").toLocalDateTime());
|
||||
Timestamp endTime = rs.getTimestamp("end_time");
|
||||
record.setEndTime(endTime == null ? null : endTime.toLocalDateTime());
|
||||
record.setDurationMinutes((Integer) rs.getObject("duration_minutes"));
|
||||
record.setFeedingMethod(rs.getString("feeding_method"));
|
||||
record.setAmountMl((Integer) rs.getObject("amount_ml"));
|
||||
record.setExcretionType(rs.getString("excretion_type"));
|
||||
record.setOperatorName(rs.getString("operator_name"));
|
||||
record.setNote(rs.getString("note"));
|
||||
Timestamp createdAt = rs.getTimestamp("created_at");
|
||||
record.setCreatedAt(createdAt == null ? record.getStartTime() : createdAt.toLocalDateTime());
|
||||
if ("sleep".equals(record.getRecordType()) && record.getEndTime() != null && record.getDurationMinutes() == null) {
|
||||
record.setDurationMinutes((int) Math.max(0, Duration.between(record.getStartTime(), record.getEndTime()).toMinutes()));
|
||||
}
|
||||
return record;
|
||||
return baby.getFamilyId();
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.babytracker.module.record;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class CreateFeedingRequest {
|
||||
@NotBlank
|
||||
private String babyId;
|
||||
@NotBlank
|
||||
private String feedingMethod;
|
||||
private LocalDateTime feedingTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer amountMl;
|
||||
private String breastSide;
|
||||
private String operatorName;
|
||||
private String note;
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public String getFeedingMethod() {
|
||||
return feedingMethod;
|
||||
}
|
||||
|
||||
public void setFeedingMethod(String feedingMethod) {
|
||||
this.feedingMethod = feedingMethod;
|
||||
}
|
||||
|
||||
public LocalDateTime getFeedingTime() {
|
||||
return feedingTime;
|
||||
}
|
||||
|
||||
public void setFeedingTime(LocalDateTime feedingTime) {
|
||||
this.feedingTime = feedingTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getAmountMl() {
|
||||
return amountMl;
|
||||
}
|
||||
|
||||
public void setAmountMl(Integer amountMl) {
|
||||
this.amountMl = amountMl;
|
||||
}
|
||||
|
||||
public String getBreastSide() {
|
||||
return breastSide;
|
||||
}
|
||||
|
||||
public void setBreastSide(String breastSide) {
|
||||
this.breastSide = breastSide;
|
||||
}
|
||||
|
||||
public String getOperatorName() {
|
||||
return operatorName;
|
||||
}
|
||||
|
||||
public void setOperatorName(String operatorName) {
|
||||
this.operatorName = operatorName;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.note = note;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.babytracker.module.record;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class ExcretionRequest {
|
||||
@NotBlank
|
||||
private String babyId;
|
||||
private LocalDateTime time;
|
||||
private String operatorName;
|
||||
private String note;
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public LocalDateTime getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(LocalDateTime time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getOperatorName() {
|
||||
return operatorName;
|
||||
}
|
||||
|
||||
public void setOperatorName(String operatorName) {
|
||||
this.operatorName = operatorName;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.note = note;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.babytracker.module.record;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class SleepRequest {
|
||||
@NotBlank
|
||||
private String babyId;
|
||||
private LocalDateTime time;
|
||||
private String operatorName;
|
||||
private String note;
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public LocalDateTime getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(LocalDateTime time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getOperatorName() {
|
||||
return operatorName;
|
||||
}
|
||||
|
||||
public void setOperatorName(String operatorName) {
|
||||
this.operatorName = operatorName;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.note = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.babytracker.module.record.dto;
|
||||
|
||||
import com.babytracker.module.record.CareRecord;
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class CareRecordConvert {
|
||||
|
||||
private CareRecordConvert() {}
|
||||
|
||||
public static CareRecordVO toVO(CareRecord entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
CareRecordVO vo = new CareRecordVO();
|
||||
vo.setRecordId(entity.getRecordId());
|
||||
vo.setFamilyId(entity.getFamilyId());
|
||||
vo.setBabyId(entity.getBabyId());
|
||||
vo.setRecordType(entity.getRecordType());
|
||||
vo.setStartTime(entity.getStartTime());
|
||||
vo.setEndTime(entity.getEndTime());
|
||||
vo.setDurationMinutes(entity.getDurationMinutes());
|
||||
vo.setFeedingMethod(entity.getFeedingMethod());
|
||||
vo.setAmountMl(entity.getAmountMl());
|
||||
vo.setExcretionType(entity.getExcretionType());
|
||||
vo.setOperatorName(entity.getOperatorName());
|
||||
vo.setOperatorUserId(entity.getOperatorUserId());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setNote(entity.getRemark());
|
||||
vo.setSource(entity.getSource());
|
||||
vo.setDeleted(entity.getDeleted());
|
||||
vo.setCreatedBy(entity.getCreatedBy());
|
||||
vo.setCreatedTime(entity.getCreatedTime());
|
||||
vo.setUpdatedBy(entity.getUpdatedBy());
|
||||
vo.setUpdatedTime(entity.getUpdatedTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public static List<CareRecordVO> toVOList(List<CareRecord> list) {
|
||||
if (list == null || list.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<CareRecordVO> voList = new ArrayList<>(list.size());
|
||||
for (CareRecord entity : list) {
|
||||
voList.add(toVO(entity));
|
||||
}
|
||||
return voList;
|
||||
}
|
||||
|
||||
public static CareRecordDTO toDTO(CareRecord entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
CareRecordDTO dto = new CareRecordDTO();
|
||||
dto.setRecordId(entity.getRecordId());
|
||||
dto.setFamilyId(entity.getFamilyId());
|
||||
dto.setBabyId(entity.getBabyId());
|
||||
dto.setRecordType(entity.getRecordType());
|
||||
dto.setStartTime(entity.getStartTime());
|
||||
dto.setEndTime(entity.getEndTime());
|
||||
dto.setDurationMinutes(entity.getDurationMinutes());
|
||||
dto.setFeedingMethod(entity.getFeedingMethod());
|
||||
dto.setAmountMl(entity.getAmountMl());
|
||||
dto.setExcretionType(entity.getExcretionType());
|
||||
dto.setOperatorName(entity.getOperatorName());
|
||||
dto.setOperatorUserId(entity.getOperatorUserId());
|
||||
dto.setRemark(entity.getRemark());
|
||||
dto.setSource(entity.getSource());
|
||||
dto.setDeleted(entity.getDeleted());
|
||||
dto.setCreatedBy(entity.getCreatedBy());
|
||||
dto.setCreatedTime(entity.getCreatedTime());
|
||||
dto.setUpdatedBy(entity.getUpdatedBy());
|
||||
dto.setUpdatedTime(entity.getUpdatedTime());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.babytracker.module.record.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class CareRecordDTO {
|
||||
private String recordId;
|
||||
private String familyId;
|
||||
private String babyId;
|
||||
private String recordType;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer durationMinutes;
|
||||
private String feedingMethod;
|
||||
private Integer amountMl;
|
||||
private String excretionType;
|
||||
private String operatorName;
|
||||
private String operatorUserId;
|
||||
private String remark;
|
||||
private String source;
|
||||
private Integer deleted;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.babytracker.module.record.mapper;
|
||||
|
||||
import com.babytracker.module.record.CareRecord;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface CareRecordMapper extends BaseMapper<CareRecord> {
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class CreateFeedingRO {
|
||||
@NotBlank(message = "宝宝ID不能为空")
|
||||
private String babyId;
|
||||
|
||||
@NotBlank(message = "喂养方式不能为空")
|
||||
private String feedingMethod;
|
||||
|
||||
private LocalDateTime feedingTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer amountMl;
|
||||
private String breastSide;
|
||||
private String operatorName;
|
||||
private String remark;
|
||||
|
||||
public String getNote() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.remark = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class CreateManualRecordRO {
|
||||
@NotBlank(message = "宝宝ID不能为空")
|
||||
private String babyId;
|
||||
|
||||
@NotBlank(message = "记录类型不能为空")
|
||||
private String recordType;
|
||||
|
||||
@NotNull(message = "开始时间不能为空")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
private LocalDateTime endTime;
|
||||
private Integer durationMinutes;
|
||||
private String feedingMethod;
|
||||
private Integer amountMl;
|
||||
private String excretionType;
|
||||
private String operatorName;
|
||||
private String remark;
|
||||
|
||||
public String getNote() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.remark = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class DeleteCareRecordRO {
|
||||
@NotBlank(message = "记录ID不能为空")
|
||||
private String recordId;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class ExcretionRO {
|
||||
@NotBlank(message = "宝宝ID不能为空")
|
||||
private String babyId;
|
||||
|
||||
private LocalDateTime time;
|
||||
private String operatorName;
|
||||
private String remark;
|
||||
|
||||
public String getNote() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.remark = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SleepRO {
|
||||
@NotBlank(message = "宝宝ID不能为空")
|
||||
private String babyId;
|
||||
|
||||
private LocalDateTime time;
|
||||
private String operatorName;
|
||||
private String remark;
|
||||
|
||||
public String getNote() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.remark = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.babytracker.module.record.ro;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class UpdateCareRecordRO {
|
||||
@NotBlank(message = "记录ID不能为空")
|
||||
private String recordId;
|
||||
|
||||
private String recordType;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer durationMinutes;
|
||||
private String feedingMethod;
|
||||
private Integer amountMl;
|
||||
private String excretionType;
|
||||
private String operatorName;
|
||||
private String remark;
|
||||
|
||||
public String getNote() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setNote(String note) {
|
||||
this.remark = note;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.babytracker.module.record.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class CareRecordVO {
|
||||
private String recordId;
|
||||
private String familyId;
|
||||
private String babyId;
|
||||
private String recordType;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer durationMinutes;
|
||||
private String feedingMethod;
|
||||
private Integer amountMl;
|
||||
private String excretionType;
|
||||
private String operatorName;
|
||||
private String operatorUserId;
|
||||
private String remark;
|
||||
private String note;
|
||||
private String source;
|
||||
private Integer deleted;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdTime;
|
||||
private String updatedBy;
|
||||
private LocalDateTime updatedTime;
|
||||
|
||||
public String getNote() {
|
||||
return remark != null ? remark : note;
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package com.babytracker.module.summary;
|
||||
|
||||
import com.babytracker.module.record.CareRecord;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DailySummary {
|
||||
private String babyId;
|
||||
private String date;
|
||||
private int feedingCount;
|
||||
private Map<String, Integer> feedingMethodCounts;
|
||||
private int sleepTotalMinutes;
|
||||
private int peeCount;
|
||||
private int poopCount;
|
||||
private CareRecord lastFeeding;
|
||||
private CareRecord activeFeeding;
|
||||
private CareRecord activeSleep;
|
||||
private List<CareRecord> timeline;
|
||||
|
||||
public String getBabyId() {
|
||||
return babyId;
|
||||
}
|
||||
|
||||
public void setBabyId(String babyId) {
|
||||
this.babyId = babyId;
|
||||
}
|
||||
|
||||
public String getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(String date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public int getFeedingCount() {
|
||||
return feedingCount;
|
||||
}
|
||||
|
||||
public void setFeedingCount(int feedingCount) {
|
||||
this.feedingCount = feedingCount;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getFeedingMethodCounts() {
|
||||
return feedingMethodCounts;
|
||||
}
|
||||
|
||||
public void setFeedingMethodCounts(Map<String, Integer> feedingMethodCounts) {
|
||||
this.feedingMethodCounts = feedingMethodCounts;
|
||||
}
|
||||
|
||||
public int getSleepTotalMinutes() {
|
||||
return sleepTotalMinutes;
|
||||
}
|
||||
|
||||
public void setSleepTotalMinutes(int sleepTotalMinutes) {
|
||||
this.sleepTotalMinutes = sleepTotalMinutes;
|
||||
}
|
||||
|
||||
public int getPeeCount() {
|
||||
return peeCount;
|
||||
}
|
||||
|
||||
public void setPeeCount(int peeCount) {
|
||||
this.peeCount = peeCount;
|
||||
}
|
||||
|
||||
public int getPoopCount() {
|
||||
return poopCount;
|
||||
}
|
||||
|
||||
public void setPoopCount(int poopCount) {
|
||||
this.poopCount = poopCount;
|
||||
}
|
||||
|
||||
public CareRecord getLastFeeding() {
|
||||
return lastFeeding;
|
||||
}
|
||||
|
||||
public void setLastFeeding(CareRecord lastFeeding) {
|
||||
this.lastFeeding = lastFeeding;
|
||||
}
|
||||
|
||||
public CareRecord getActiveSleep() {
|
||||
return activeSleep;
|
||||
}
|
||||
|
||||
public void setActiveSleep(CareRecord activeSleep) {
|
||||
this.activeSleep = activeSleep;
|
||||
}
|
||||
|
||||
public CareRecord getActiveFeeding() {
|
||||
return activeFeeding;
|
||||
}
|
||||
|
||||
public void setActiveFeeding(CareRecord activeFeeding) {
|
||||
this.activeFeeding = activeFeeding;
|
||||
}
|
||||
|
||||
public List<CareRecord> getTimeline() {
|
||||
return timeline;
|
||||
}
|
||||
|
||||
public void setTimeline(List<CareRecord> timeline) {
|
||||
this.timeline = timeline;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,39 @@
|
||||
package com.babytracker.module.summary;
|
||||
|
||||
import com.babytracker.common.response.ApiResponse;
|
||||
import com.babytracker.module.summary.ro.SummaryQueryRO;
|
||||
import com.babytracker.module.summary.vo.DailySummaryVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/summary")
|
||||
public class SummaryController {
|
||||
private final SummaryService summaryService;
|
||||
|
||||
public SummaryController(SummaryService summaryService) {
|
||||
this.summaryService = summaryService;
|
||||
}
|
||||
|
||||
@GetMapping("/daily")
|
||||
public ApiResponse<DailySummary> daily(
|
||||
@RequestParam String babyId,
|
||||
public ApiResponse<DailySummaryVO> daily(
|
||||
@RequestParam(required = false) String babyId,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
|
||||
) {
|
||||
return ApiResponse.ok(summaryService.daily(babyId, date));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/daily")
|
||||
public ApiResponse<DailySummaryVO> dailyByPost(@RequestBody(required = false) SummaryQueryRO request) {
|
||||
String babyId = request != null ? request.getBabyId() : null;
|
||||
LocalDate date = request != null ? request.getDate() : null;
|
||||
return ApiResponse.ok(summaryService.daily(babyId, date));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.babytracker.module.summary;
|
||||
|
||||
import com.babytracker.module.record.CareRecord;
|
||||
import com.babytracker.module.record.CareRecordService;
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
import com.babytracker.module.summary.vo.DailySummaryVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
@@ -10,31 +12,28 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SummaryService {
|
||||
private final CareRecordService careRecordService;
|
||||
|
||||
public SummaryService(CareRecordService careRecordService) {
|
||||
this.careRecordService = careRecordService;
|
||||
}
|
||||
|
||||
public DailySummary daily(String babyId, LocalDate date) {
|
||||
public DailySummaryVO daily(String babyId, LocalDate date) {
|
||||
LocalDate targetDate = date == null ? LocalDate.now() : date;
|
||||
List<CareRecord> timeline = careRecordService.list(babyId, targetDate);
|
||||
DailySummary summary = new DailySummary();
|
||||
List<CareRecordVO> timeline = careRecordService.list(babyId, targetDate);
|
||||
DailySummaryVO summary = new DailySummaryVO();
|
||||
summary.setBabyId(babyId);
|
||||
summary.setDate(targetDate.toString());
|
||||
summary.setTimeline(timeline);
|
||||
summary.setActiveSleep(careRecordService.findActiveSleep(babyId));
|
||||
summary.setActiveFeeding(careRecordService.findActiveFeeding(babyId));
|
||||
|
||||
Map<String, Integer> methodCounts = new LinkedHashMap<String, Integer>();
|
||||
Map<String, Integer> methodCounts = new LinkedHashMap<>();
|
||||
int feedingCount = 0;
|
||||
int sleepTotal = 0;
|
||||
int peeCount = 0;
|
||||
int poopCount = 0;
|
||||
CareRecord lastFeeding = null;
|
||||
CareRecordVO lastFeeding = null;
|
||||
|
||||
for (CareRecord record : timeline) {
|
||||
for (CareRecordVO record : timeline) {
|
||||
if ("feeding".equals(record.getRecordType())) {
|
||||
feedingCount++;
|
||||
String method = record.getFeedingMethod() == null ? "other" : record.getFeedingMethod();
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.babytracker.module.summary.dto;
|
||||
|
||||
import com.babytracker.module.record.dto.CareRecordDTO;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class DailySummaryDTO {
|
||||
private String babyId;
|
||||
private String date;
|
||||
private int feedingCount;
|
||||
private Map<String, Integer> feedingMethodCounts;
|
||||
private int sleepTotalMinutes;
|
||||
private int peeCount;
|
||||
private int poopCount;
|
||||
private CareRecordDTO lastFeeding;
|
||||
private CareRecordDTO activeFeeding;
|
||||
private CareRecordDTO activeSleep;
|
||||
private List<CareRecordDTO> timeline;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.babytracker.module.summary.dto;
|
||||
|
||||
import com.babytracker.module.summary.vo.DailySummaryVO;
|
||||
|
||||
public final class SummaryConvert {
|
||||
|
||||
private SummaryConvert() {}
|
||||
|
||||
public static DailySummaryVO toVO(DailySummaryDTO dto) {
|
||||
if (dto == null) {
|
||||
return null;
|
||||
}
|
||||
DailySummaryVO vo = new DailySummaryVO();
|
||||
vo.setBabyId(dto.getBabyId());
|
||||
vo.setDate(dto.getDate());
|
||||
vo.setFeedingCount(dto.getFeedingCount());
|
||||
vo.setFeedingMethodCounts(dto.getFeedingMethodCounts());
|
||||
vo.setSleepTotalMinutes(dto.getSleepTotalMinutes());
|
||||
vo.setPeeCount(dto.getPeeCount());
|
||||
vo.setPoopCount(dto.getPoopCount());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.babytracker.module.summary.ro;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
public class SummaryQueryRO {
|
||||
private String babyId;
|
||||
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
private LocalDate date;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.babytracker.module.summary.vo;
|
||||
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class DailySummaryVO {
|
||||
private String babyId;
|
||||
private String date;
|
||||
private int feedingCount;
|
||||
private Map<String, Integer> feedingMethodCounts;
|
||||
private int sleepTotalMinutes;
|
||||
private int peeCount;
|
||||
private int poopCount;
|
||||
private CareRecordVO lastFeeding;
|
||||
private CareRecordVO activeFeeding;
|
||||
private CareRecordVO activeSleep;
|
||||
private List<CareRecordVO> timeline;
|
||||
}
|
||||
@@ -22,6 +22,17 @@ spring:
|
||||
time-zone: Asia/Shanghai
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: input
|
||||
logic-delete-field: deleted
|
||||
logic-delete-value: 1
|
||||
logic-not-delete-value: 0
|
||||
|
||||
app:
|
||||
cors:
|
||||
allowed-origins:
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.babytracker;
|
||||
|
||||
import com.babytracker.module.baby.BabyService;
|
||||
import com.babytracker.module.baby.vo.BabyVO;
|
||||
import com.babytracker.module.family.FamilyService;
|
||||
import com.babytracker.module.family.vo.FamilyContextVO;
|
||||
import com.babytracker.module.record.CareRecordService;
|
||||
import com.babytracker.module.record.ro.CreateFeedingRO;
|
||||
import com.babytracker.module.record.vo.CareRecordVO;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest
|
||||
class BabyTrackerApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private BabyService babyService;
|
||||
|
||||
@Autowired
|
||||
private FamilyService familyService;
|
||||
|
||||
@Autowired
|
||||
private CareRecordService careRecordService;
|
||||
|
||||
@Test
|
||||
void testMyBatisPlusServicesAndAuditFields() {
|
||||
FamilyContextVO context = familyService.getCurrentContext();
|
||||
assertNotNull(context);
|
||||
assertNotNull(context.getFamily());
|
||||
assertNotNull(context.getMembers());
|
||||
|
||||
BabyVO currentBaby = babyService.getCurrentBaby();
|
||||
assertNotNull(currentBaby);
|
||||
assertNotNull(currentBaby.getBabyId());
|
||||
|
||||
List<CareRecordVO> records = careRecordService.list(currentBaby.getBabyId(), LocalDate.now());
|
||||
assertNotNull(records);
|
||||
|
||||
// 测试自动填充拦截器:创建一条记录并验证审计字段
|
||||
CreateFeedingRO feedingRO = new CreateFeedingRO();
|
||||
feedingRO.setBabyId(currentBaby.getBabyId());
|
||||
feedingRO.setFeedingMethod("bottle");
|
||||
feedingRO.setFeedingTime(LocalDateTime.now());
|
||||
feedingRO.setAmountMl(60);
|
||||
feedingRO.setRemark("自动化测试喂养");
|
||||
CareRecordVO created = careRecordService.createFeeding(feedingRO);
|
||||
|
||||
assertNotNull(created);
|
||||
assertNotNull(created.getRecordId());
|
||||
assertEquals("admin", created.getCreatedBy());
|
||||
assertEquals("admin", created.getUpdatedBy());
|
||||
assertNotNull(created.getCreatedTime());
|
||||
assertNotNull(created.getUpdatedTime());
|
||||
assertEquals("自动化测试喂养", created.getRemark());
|
||||
assertEquals(0, created.getDeleted());
|
||||
|
||||
// 测试逻辑删除
|
||||
careRecordService.delete(created.getRecordId());
|
||||
}
|
||||
}
|
||||
+29
-25
@@ -1,30 +1,34 @@
|
||||
# SQL 脚本说明
|
||||
# SQL 数据库脚本说明
|
||||
|
||||
本目录后续维护两类数据库脚本:
|
||||
本项目所有数据库脚本均**统一在本目录 (`/sql`) 下维护**,不再散落在各子工程内部。
|
||||
|
||||
1. `schema-full.sql`
|
||||
- 全新环境使用。
|
||||
- 包含当前最新完整表结构和最小种子数据。
|
||||
- 新部署、新开发库、测试库初始化时优先执行这一份。
|
||||
## 目录结构
|
||||
|
||||
2. `schema-evolution.sql`
|
||||
- 版本演进使用。
|
||||
- 按版本记录从 MVP 到后续功能的逐步变更。
|
||||
- 后续每次表结构变化都追加到这里,便于人工审查和数据库迁移工具拆分。
|
||||
```text
|
||||
sql/
|
||||
├── migration/ # Flyway 增量版本迁移脚本目录(由 Maven 打包自动装配至后端运行时)
|
||||
│ ├── V1__init_mvp_schema.sql # V1: MVP 基础表结构与最小种子数据
|
||||
│ └── V2__audit_fields_and_logic_delete.sql # V2: 通用审计字段(remark,deleted,created_by,created_time,updated_by,updated_time)与字段清理
|
||||
├── schema-full.sql # 当前最新完整建表与初始化数据脚本(全新环境初始化直接执行)
|
||||
├── schema-evolution.sql # 数据库结构版本演进与变更记录
|
||||
├── database.sql # 历史初始原型脚本(仅供归档参考)
|
||||
└── README.md # 本说明文件
|
||||
```
|
||||
|
||||
3. `database.sql`
|
||||
- 旧 Node 原型时期的历史脚本。
|
||||
- 暂时保留作为参考,不作为新架构的主入口。
|
||||
|
||||
## 当前建模原则
|
||||
|
||||
当前阶段聚焦“顺产 3 天新生儿每日照护记录”:
|
||||
|
||||
- 喂奶时间与喂奶方式。
|
||||
- 睡眠开始/结束时间。
|
||||
- 每日喂奶次数。
|
||||
- 每日小便次数。
|
||||
- 每日大便次数。
|
||||
|
||||
其他能力如复杂家庭权限、自定义指标、护理内容、导出、管理后台、小程序登录,后续按版本逐步加入。
|
||||
## 维护原则
|
||||
|
||||
1. **版本化迁移脚本 (`sql/migration/Vx__*.sql`)**:
|
||||
- 所有数据库结构变更(DDL、DML、历史数据迁移)必须以 Flyway 命名规范存放于 `sql/migration/`;
|
||||
- 后端 Maven 打包已通过 `<resources>` 自动将本目录映射并打包进 `target/classes/db/migration`,Spring Boot 启动时由 Flyway 自动执行增量迁移。
|
||||
2. **最新全量建表脚本 (`sql/schema-full.sql`)**:
|
||||
- 每次数据库表结构或核心字段变更后,需同步更新 `schema-full.sql`;
|
||||
- 新部署环境、本地或容器一键初始化数据库时,直接执行 `schema-full.sql` 即可获得最新的标准数据库。
|
||||
3. **字段规范**:
|
||||
- 所有表必须包含 6 大标准通用字段:
|
||||
- `remark`: 备注
|
||||
- `deleted`: 逻辑删除状态 (0-未删除, 1-已删除)
|
||||
- `created_by`: 创建人 (默认 admin)
|
||||
- `created_time`: 创建时间
|
||||
- `updated_by`: 修改人 (默认 admin)
|
||||
- `updated_time`: 修改时间
|
||||
- 不为 `deleted` 建立单独索引。
|
||||
File renamed without changes.
@@ -0,0 +1,55 @@
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
-- 1. app_user 表结构调整
|
||||
ALTER TABLE `app_user`
|
||||
ADD COLUMN `remark` VARCHAR(500) NULL COMMENT '备注' AFTER `avatar_url`,
|
||||
ADD COLUMN `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除' AFTER `status`,
|
||||
ADD COLUMN `created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人' AFTER `deleted`,
|
||||
RENAME COLUMN `created_at` TO `created_time`,
|
||||
ADD COLUMN `updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人' AFTER `created_time`,
|
||||
RENAME COLUMN `updated_at` TO `updated_time`;
|
||||
|
||||
-- 2. family 表结构调整
|
||||
ALTER TABLE `family`
|
||||
ADD COLUMN `remark` VARCHAR(500) NULL COMMENT '备注' AFTER `creator_user_id`,
|
||||
ADD COLUMN `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除' AFTER `status`,
|
||||
ADD COLUMN `created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人' AFTER `deleted`,
|
||||
RENAME COLUMN `created_at` TO `created_time`,
|
||||
ADD COLUMN `updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人' AFTER `created_time`,
|
||||
RENAME COLUMN `updated_at` TO `updated_time`;
|
||||
|
||||
-- 3. family_member 表结构调整
|
||||
ALTER TABLE `family_member`
|
||||
ADD COLUMN `remark` VARCHAR(500) NULL COMMENT '备注' AFTER `status`,
|
||||
ADD COLUMN `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除' AFTER `remark`,
|
||||
ADD COLUMN `created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人' AFTER `deleted`,
|
||||
RENAME COLUMN `created_at` TO `created_time`,
|
||||
ADD COLUMN `updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人' AFTER `created_time`,
|
||||
RENAME COLUMN `updated_at` TO `updated_time`;
|
||||
|
||||
-- 4. baby_profile 表结构调整
|
||||
ALTER TABLE `baby_profile`
|
||||
ADD COLUMN `remark` VARCHAR(500) NULL COMMENT '备注' AFTER `status`,
|
||||
ADD COLUMN `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除' AFTER `remark`,
|
||||
ADD COLUMN `created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人' AFTER `deleted`,
|
||||
RENAME COLUMN `created_at` TO `created_time`,
|
||||
ADD COLUMN `updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人' AFTER `created_time`,
|
||||
RENAME COLUMN `updated_at` TO `updated_time`;
|
||||
|
||||
-- 5. care_record 表结构调整
|
||||
ALTER TABLE `care_record`
|
||||
ADD COLUMN `remark` VARCHAR(500) NULL COMMENT '备注' AFTER `note`,
|
||||
ADD COLUMN `deleted` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除' AFTER `source`,
|
||||
ADD COLUMN `created_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人' AFTER `deleted`,
|
||||
RENAME COLUMN `created_at` TO `created_time`,
|
||||
ADD COLUMN `updated_by` VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人' AFTER `created_time`,
|
||||
RENAME COLUMN `updated_at` TO `updated_time`;
|
||||
|
||||
-- 同步 care_record 存量备注与删除状态
|
||||
UPDATE `care_record` SET `remark` = `note` WHERE `remark` IS NULL AND `note` IS NOT NULL;
|
||||
UPDATE `care_record` SET `deleted` = 1 WHERE `deleted_at` IS NOT NULL;
|
||||
|
||||
-- 删除 care_record 的 deleted_at 索引,并删除 note、deleted_at 字段
|
||||
ALTER TABLE `care_record` DROP INDEX `idx_care_record_deleted`;
|
||||
ALTER TABLE `care_record` DROP COLUMN `note`;
|
||||
ALTER TABLE `care_record` DROP COLUMN `deleted_at`;
|
||||
+42
-39
@@ -2,6 +2,8 @@
|
||||
-- Baby Tracker 当前最新完整数据库脚本
|
||||
-- 当前阶段: MVP,家庭-成员-宝宝 + 新生儿每日照护记录
|
||||
-- ID 规则: 所有新表主键 id 均为 32 位字符串,由程序雪花 ID 生成。
|
||||
-- 规范字段: 包含 备注(remark)、删除状态(deleted)、创建人(created_by)、创建时间(created_time)、修改人(updated_by)、修改时间(updated_time)
|
||||
-- 规范约束: 无 deleted 单独索引,care_record 表使用 remark 统一备注,不保留 note 与 deleted_at
|
||||
-- ============================================================================
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
@@ -23,8 +25,12 @@ CREATE TABLE `app_user` (
|
||||
`nickname` VARCHAR(50) NOT NULL DEFAULT '看护人' COMMENT '用户昵称',
|
||||
`avatar_url` VARCHAR(500) NULL COMMENT '头像地址',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active, disabled',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 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`),
|
||||
UNIQUE KEY `uk_app_user_openid` (`openid`),
|
||||
UNIQUE KEY `uk_app_user_phone` (`phone`)
|
||||
@@ -36,8 +42,12 @@ CREATE TABLE `family` (
|
||||
`invite_code` VARCHAR(32) NULL COMMENT '家庭邀请码',
|
||||
`creator_user_id` CHAR(32) NULL COMMENT '创建人用户ID',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active, archived',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 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`),
|
||||
UNIQUE KEY `uk_family_invite_code` (`invite_code`),
|
||||
KEY `idx_family_creator` (`creator_user_id`)
|
||||
@@ -52,8 +62,12 @@ CREATE TABLE `family_member` (
|
||||
`is_default_operator` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否默认记录人',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active, left, disabled',
|
||||
`joined_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 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_family_member_family` (`family_id`),
|
||||
KEY `idx_family_member_user` (`user_id`)
|
||||
@@ -68,8 +82,12 @@ CREATE TABLE `baby_profile` (
|
||||
`delivery_type` VARCHAR(20) NOT NULL DEFAULT 'natural' COMMENT '分娩方式: natural, c_section, unknown',
|
||||
`is_default` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否默认宝宝',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active, archived',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 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_baby_profile_family` (`family_id`),
|
||||
KEY `idx_baby_profile_default` (`family_id`, `is_default`)
|
||||
@@ -88,46 +106,31 @@ CREATE TABLE `care_record` (
|
||||
`excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop',
|
||||
`operator_name` VARCHAR(50) NOT NULL DEFAULT '看护人' COMMENT '记录人称谓',
|
||||
`operator_user_id` CHAR(32) NULL COMMENT '记录人用户ID',
|
||||
`note` VARCHAR(500) NULL COMMENT '备注',
|
||||
`source` VARCHAR(30) NOT NULL DEFAULT 'h5' COMMENT '来源: h5, miniapp, admin, system',
|
||||
`deleted_at` DATETIME NULL COMMENT '软删除时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 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_record_baby_time` (`baby_id`, `start_time`),
|
||||
KEY `idx_care_record_family_time` (`family_id`, `start_time`),
|
||||
KEY `idx_care_record_type_time` (`record_type`, `start_time`),
|
||||
KEY `idx_care_record_deleted` (`deleted_at`)
|
||||
KEY `idx_care_record_type_time` (`record_type`, `start_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='照护记录表';
|
||||
|
||||
CREATE TABLE `family_memo` (
|
||||
`id` CHAR(32) NOT NULL COMMENT '备忘ID,雪花ID字符串',
|
||||
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
|
||||
`content` VARCHAR(255) NOT NULL COMMENT '备忘内容',
|
||||
`due_period` VARCHAR(30) NOT NULL DEFAULT 'today' COMMENT '推荐时段',
|
||||
`is_completed` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否完成',
|
||||
`completed_at` DATETIME NULL COMMENT '完成时间',
|
||||
`created_by` VARCHAR(50) NOT NULL DEFAULT '看护人' COMMENT '创建人称谓',
|
||||
`deleted_at` DATETIME NULL COMMENT '软删除时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_family_memo_family_status` (`family_id`, `is_completed`),
|
||||
KEY `idx_family_memo_deleted` (`deleted_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭备忘表';
|
||||
INSERT IGNORE INTO `app_user` (`id`, `nickname`, `status`, `created_by`, `updated_by`)
|
||||
VALUES ('00000000000000361915955435016192', '默认看护人', 'active', 'admin', 'admin');
|
||||
|
||||
INSERT IGNORE INTO `app_user` (`id`, `nickname`, `status`)
|
||||
VALUES ('00000000000000361915955435016192', '默认看护人', 'active');
|
||||
INSERT IGNORE INTO `family` (`id`, `name`, `invite_code`, `creator_user_id`, `status`, `created_by`, `updated_by`)
|
||||
VALUES ('00000000000000361915955439210496', '新生儿照护家庭', 'BT2026', '00000000000000361915955435016192', 'active', 'admin', 'admin');
|
||||
|
||||
INSERT IGNORE INTO `family` (`id`, `name`, `invite_code`, `creator_user_id`, `status`)
|
||||
VALUES ('00000000000000361915955439210496', '新生儿照护家庭', 'BT2026', '00000000000000361915955435016192', 'active');
|
||||
|
||||
INSERT IGNORE INTO `family_member` (`id`, `family_id`, `user_id`, `role_name`, `role_type`, `is_default_operator`, `status`)
|
||||
INSERT IGNORE INTO `family_member` (`id`, `family_id`, `user_id`, `role_name`, `role_type`, `is_default_operator`, `status`, `created_by`, `updated_by`)
|
||||
VALUES
|
||||
('00000000000000361915955443404800', '00000000000000361915955439210496', '00000000000000361915955435016192', '宝妈', 'owner', 1, 'active'),
|
||||
('00000000000000361915955451793408', '00000000000000361915955439210496', NULL, '宝爸', 'caregiver', 0, 'active');
|
||||
('00000000000000361915955443404800', '00000000000000361915955439210496', '00000000000000361915955435016192', '宝妈', 'owner', 1, 'active', 'admin', 'admin'),
|
||||
('00000000000000361915955451793408', '00000000000000361915955439210496', NULL, '宝爸', 'caregiver', 0, 'active', 'admin', 'admin');
|
||||
|
||||
INSERT IGNORE INTO `baby_profile` (`id`, `family_id`, `name`, `gender`, `birth_date`, `delivery_type`, `is_default`, `status`)
|
||||
VALUES ('00000000000000361915955447599104', '00000000000000361915955439210496', '宝宝', 'boy', DATE_SUB(CURDATE(), INTERVAL 3 DAY), 'natural', 1, 'active');
|
||||
INSERT IGNORE INTO `baby_profile` (`id`, `family_id`, `name`, `gender`, `birth_date`, `delivery_type`, `is_default`, `status`, `created_by`, `updated_by`)
|
||||
VALUES ('00000000000000361915955447599104', '00000000000000361915955439210496', '宝宝', 'boy', DATE_SUB(CURDATE(), INTERVAL 3 DAY), 'natural', 1, 'active', 'admin', 'admin');
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
Reference in new issue
Block a user