This commit is contained in:
gs committed 2026-09-26 01:09:06 +08:00
1 parent dc23ea53ed
commit 8c7a9040d2
106 files changed
+5668 -9910

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
.git
.github
.gemini
openspec
*.log
.DS_Store
Thumbs.db
Dockerfile
deploy.sh
-6
View File
@@ -1,6 +0,0 @@
PORT=9898
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_mysql_password
DB_NAME=yyyy
+5
View File
@@ -1,9 +1,14 @@
# Dependencies # Dependencies
node_modules/ node_modules/
dist/
target/
*.tsbuildinfo
# Environment Variables & Secrets # Environment Variables & Secrets
.env .env
.env.local .env.local
deploy/.env
deploy/artifacts/
# Logs # Logs
*.log *.log
-18
View File
@@ -1,18 +0,0 @@
FROM node:22-alpine
WORKDIR /app
# 拷贝项目文件(包含宿主机提前安装好的 node_modules)
COPY . .
# 如果宿主机尚未预装 node_modules,则在镜像内进行兜底安装
RUN if [ ! -d "node_modules" ] || [ -z "$(ls -A node_modules 2>/dev/null)" ]; then \
npm install --omit=dev --no-audit; \
fi
EXPOSE 9898
ENV PORT=9898
ENV NODE_ENV=production
CMD ["node", "server/app.js"]
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>新生儿照护记录</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1344
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
{
"name": "@baby-tracker/web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "vue-tsc -b && vite build",
"preview": "vite preview --host 0.0.0.0"
},
"dependencies": {
"@vitejs/plugin-vue": "^5.1.4",
"pinia": "^2.2.6",
"vant": "^4.10.2",
"vite": "^5.4.10",
"vue": "^3.5.12",
"vue-router": "^4.4.5"
},
"devDependencies": {
"typescript": "^5.6.3",
"vue-tsc": "^2.1.8"
}
}
+22
View File
@@ -0,0 +1,22 @@
<script setup lang="ts">
const tabs = [
{ to: '/today', label: '今日' },
{ to: '/timeline', label: '流水' },
{ to: '/stats', label: '统计' },
{ to: '/settings', label: '设置' }
]
</script>
<template>
<div class="app-shell">
<main class="app-main">
<RouterView />
</main>
<nav class="bottom-nav">
<RouterLink v-for="tab in tabs" :key="tab.to" :to="tab.to" class="bottom-nav__item">
{{ tab.label }}
</RouterLink>
</nav>
</div>
</template>
+119
View File
@@ -0,0 +1,119 @@
import type { ApiResponse, BabyProfile, CareRecord, DailySummary, FamilyContext, FeedingMethod } from '../types/domain'
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...(options.headers || {})
},
...options
})
const body = (await response.json()) as ApiResponse<T>
if (!response.ok || !body.success) {
throw new Error(body.error?.message || '请求失败')
}
return body.data
}
export function getCurrentBaby() {
return request<BabyProfile>('/api/v1/babies/current')
}
export function getFamilyContext() {
return request<FamilyContext>('/api/v1/families/current-context')
}
export function updateCurrentBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
return request<BabyProfile>('/api/v1/babies/current', {
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)}`, {
method: 'PUT',
body: JSON.stringify(payload)
})
}
export function getDailySummary(babyId: string) {
return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`)
}
export function getRecords(babyId: string) {
return request<CareRecord[]>(`/api/v1/records?babyId=${encodeURIComponent(babyId)}`)
}
export function createFeeding(payload: {
babyId: string
feedingMethod: FeedingMethod
amountMl?: number
breastSide?: 'left' | 'right'
operatorName: string
}) {
return request<CareRecord>('/api/v1/records/feeding', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function startFeeding(payload: {
babyId: string
breastSide: 'left' | 'right'
operatorName: string
}) {
return request<CareRecord>('/api/v1/records/feeding/start', {
method: 'POST',
body: JSON.stringify({
...payload,
feedingMethod: 'breastfeed'
})
})
}
export function endFeeding(payload: {
babyId: string
breastSide: 'left' | 'right'
operatorName: string
}) {
return request<CareRecord>('/api/v1/records/feeding/end', {
method: 'POST',
body: JSON.stringify({
...payload,
feedingMethod: 'breastfeed'
})
})
}
export function startSleep(payload: { babyId: string; operatorName: string }) {
return request<CareRecord>('/api/v1/records/sleep/start', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function endSleep(payload: { babyId: string; operatorName: string }) {
return request<CareRecord>('/api/v1/records/sleep/end', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function createPee(payload: { babyId: string; operatorName: string }) {
return request<CareRecord>('/api/v1/records/pee', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function createPoop(payload: { babyId: string; operatorName: string }) {
return request<CareRecord>('/api/v1/records/poop', {
method: 'POST',
body: JSON.stringify(payload)
})
}
export function deleteRecord(recordId: string) {
return request<void>(`/api/v1/records/${recordId}`, { method: 'DELETE' })
}
+9
View File
@@ -0,0 +1,9 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import Vant from 'vant'
import 'vant/lib/index.css'
import App from './App.vue'
import router from './router'
import './style.css'
createApp(App).use(Vant).use(createPinia()).use(router).mount('#app')
+142
View File
@@ -0,0 +1,142 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { showToast } from 'vant'
import { useCareStore } from '../stores/careStore'
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}` : '未选择宝宝')
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>
<h1>家庭照护维护</h1>
<p>{{ currentBabyLabel }}</p>
</header>
<van-tabs v-model:active="activeTab" shrink>
<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>
</van-tab>
<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>
</van-tab>
<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>
</van-tab>
<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>
</van-tab>
</van-tabs>
</section>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { useCareStore } from '../stores/careStore'
import { formatMinutes } from '../utils/format'
const store = useCareStore()
onMounted(() => {
store.load()
})
</script>
<template>
<section class="page">
<header class="page-header">
<p class="eyebrow">每日统计</p>
<h1>今天是否记录完整</h1>
<p>当前只展示明确事实统计,不做医疗判断。</p>
</header>
<section class="panel">
<div class="stat-row">
<span>今日喂奶次数</span>
<strong>{{ store.summary?.feedingCount ?? 0 }} 次</strong>
</div>
<div class="stat-row">
<span>今日睡眠总时长</span>
<strong>{{ formatMinutes(store.summary?.sleepTotalMinutes ?? 0) }}</strong>
</div>
<div class="stat-row">
<span>今日小便次数</span>
<strong>{{ store.summary?.peeCount ?? 0 }} 次</strong>
</div>
<div class="stat-row">
<span>今日大便次数</span>
<strong>{{ store.summary?.poopCount ?? 0 }} 次</strong>
</div>
</section>
<section class="panel">
<div class="panel-title">
<h2>喂奶方式</h2>
</div>
<div class="stat-row" v-for="(count, method) in store.summary?.feedingMethodCounts || {}" :key="method">
<span>{{ method }}</span>
<strong>{{ count }} 次</strong>
</div>
<p v-if="!Object.keys(store.summary?.feedingMethodCounts || {}).length" class="empty">暂无喂奶记录。</p>
</section>
</section>
</template>
+43
View File
@@ -0,0 +1,43 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { deleteRecord } from '../api/client'
import { useCareStore } from '../stores/careStore'
import { formatMinutes, formatTime, recordLabel } from '../utils/format'
const store = useCareStore()
onMounted(() => {
store.load()
})
async function remove(recordId: string) {
await deleteRecord(recordId)
await store.refreshSummary()
}
</script>
<template>
<section class="page">
<header class="page-header">
<p class="eyebrow">今日记录</p>
<h1>照护流水</h1>
</header>
<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>
<p>
{{ formatTime(record.startTime) }}
<span v-if="record.durationMinutes"> · {{ formatMinutes(record.durationMinutes) }}</span>
<span v-if="record.amountMl"> · {{ record.amountMl }}ml</span>
</p>
<small>{{ record.operatorName }}</small>
</div>
<button class="text-button" @click="remove(record.recordId)">删除</button>
</article>
<p v-if="!store.summary?.timeline?.length" class="empty">今天还没有记录。</p>
</div>
</section>
</template>
+180
View File
@@ -0,0 +1,180 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { showToast } from 'vant'
import { useCareStore } from '../stores/careStore'
import { formatMinutes, formatTime } from '../utils/format'
const store = useCareStore()
const bottleAmount = ref(30)
const breastSide = ref<'left' | 'right'>('left')
const babyOptions = computed(() => store.babies.map(baby => ({
text: `${baby.name} · ${baby.ageText}`,
value: baby.babyId
})))
const memberOptions = computed(() => store.members.map(member => ({
text: member.roleName,
value: member.roleName
})))
const activeFeedingText = computed(() => {
const active = store.summary?.activeFeeding
return active ? `亲喂中 · ${formatTime(active.startTime)}` : '未计时'
})
onMounted(() => {
store.load()
})
async function runWithTip(action: () => Promise<void>, message: string) {
await action()
showToast({ message, type: 'success', duration: 1400 })
}
</script>
<template>
<section class="page">
<header class="hero clean-hero">
<div>
<p class="eyebrow">{{ store.context?.family.name || '新生儿照护家庭' }}</p>
<h1>{{ store.baby?.name || '宝宝' }}</h1>
<p>{{ store.baby?.ageText || '出生第 3 天' }} · {{ store.operatorName }}记录中</p>
</div>
</header>
<p v-if="store.error" class="notice error">{{ store.error }}</p>
<p v-if="store.loading" class="notice">正在加载今日记录...</p>
<section class="context-panel">
<van-dropdown-menu>
<van-dropdown-item
:model-value="store.baby?.babyId"
:options="babyOptions"
title="宝宝"
@update:model-value="value => store.selectBaby(String(value))"
/>
<van-dropdown-item
:model-value="store.operatorName"
:options="memberOptions"
title="记录人"
@update:model-value="value => store.setOperatorName(String(value))"
/>
</van-dropdown-menu>
</section>
<section class="summary-grid">
<article class="metric-card">
<span>喂奶</span>
<strong>{{ store.summary?.feedingCount ?? 0 }}</strong>
<small>今日次数</small>
</article>
<article class="metric-card">
<span>睡眠</span>
<strong>{{ formatMinutes(store.summary?.sleepTotalMinutes ?? 0) }}</strong>
<small>累计时长</small>
</article>
<article class="metric-card">
<span>小便</span>
<strong>{{ store.summary?.peeCount ?? 0 }}</strong>
<small>今日次数</small>
</article>
<article class="metric-card">
<span>大便</span>
<strong>{{ store.summary?.poopCount ?? 0 }}</strong>
<small>今日次数</small>
</article>
</section>
<section class="panel">
<div class="panel-title">
<h2>亲喂</h2>
<p>可以计时,也可以一键记录,之后再补调时间。</p>
</div>
<van-segmented v-model="breastSide" :options="[
{ label: '左侧', value: 'left' },
{ label: '右侧', value: 'right' }
]" />
<div class="feeding-status">
<span>{{ activeFeedingText }}</span>
<strong v-if="store.summary?.activeFeeding">{{ breastSide === 'left' ? '左侧' : '右侧' }}</strong>
</div>
<div class="two-actions">
<van-button
block
round
type="primary"
@click="runWithTip(() => store.toggleBreastfeedTimer(breastSide), store.summary?.activeFeeding ? '已结束本次亲喂,辛苦啦' : '已开始亲喂计时')"
>
{{ store.summary?.activeFeeding ? '结束亲喂' : '开始亲喂' }}
</van-button>
<van-button
block
round
plain
type="primary"
@click="runWithTip(() => store.logFeeding('breastfeed', undefined, breastSide), '已记录一次亲喂')"
>
一键记录
</van-button>
</div>
</section>
<section class="panel">
<div class="panel-title">
<h2>瓶喂</h2>
<p>奶量可调整,默认按当前数值记录。</p>
</div>
<div class="amount-row">
<span>奶量</span>
<van-stepper v-model="bottleAmount" :min="5" :max="300" :step="5" integer />
<strong>{{ bottleAmount }} ml</strong>
</div>
<van-button
block
round
type="success"
@click="runWithTip(() => store.logFeeding('bottle', bottleAmount), `已记录瓶喂 ${bottleAmount}ml`)"
>
记录瓶喂
</van-button>
</section>
<section class="panel">
<div class="panel-title">
<h2>快速记录</h2>
<p>尿尿、便便和睡眠优先保证动作清晰。</p>
</div>
<div class="action-grid compact-actions">
<button class="primary-action sleep" @click="runWithTip(() => store.toggleSleep(), store.summary?.activeSleep ? '已结束睡眠记录' : '已开始睡眠记录')">
<strong>{{ store.summary?.activeSleep ? '结束睡眠' : '开始睡眠' }}</strong>
<span>{{ store.summary?.activeSleep ? '自动计算时长' : '宝宝睡下了' }}</span>
</button>
<button class="primary-action pee" @click="runWithTip(() => store.logPee(), '已记录一次小便')">
<strong>小便</strong>
<span>记录一次</span>
</button>
<button class="primary-action poop" @click="runWithTip(() => store.logPoop(), '已记录一次大便')">
<strong>大便</strong>
<span>记录一次</span>
</button>
</div>
</section>
<section class="panel">
<div class="panel-title">
<h2>最近状态</h2>
</div>
<div class="status-list">
<div>
<span>上次喂奶</span>
<strong>{{ formatTime(store.summary?.lastFeeding?.startTime) }}</strong>
</div>
<div>
<span>睡眠状态</span>
<strong>{{ store.summary?.activeSleep ? `睡眠中 · ${formatTime(store.summary.activeSleep.startTime)}` : '清醒中' }}</strong>
</div>
</div>
</section>
</section>
</template>
+17
View File
@@ -0,0 +1,17 @@
import { createRouter, createWebHistory } from 'vue-router'
import TodayPage from './pages/TodayPage.vue'
import TimelinePage from './pages/TimelinePage.vue'
import StatsPage from './pages/StatsPage.vue'
import SettingsPage from './pages/SettingsPage.vue'
export default createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/today' },
{ path: '/today', component: TodayPage },
{ path: '/timeline', component: TimelinePage },
{ path: '/stats', component: StatsPage },
{ path: '/settings', component: SettingsPage }
]
})
+111
View File
@@ -0,0 +1,111 @@
import { defineStore } from 'pinia'
import {
createFeeding,
createPee,
createPoop,
endFeeding,
endSleep,
getFamilyContext,
getDailySummary,
startFeeding,
updateBaby,
startSleep,
updateCurrentBaby
} from '../api/client'
import type { BabyProfile, DailySummary, FamilyContext, FamilyMember, FeedingMethod } from '../types/domain'
export const useCareStore = defineStore('care', {
state: () => ({
context: null as FamilyContext | null,
babies: [] as BabyProfile[],
members: [] as FamilyMember[],
selectedBabyId: localStorage.getItem('selectedBabyId') || '',
baby: null as BabyProfile | null,
summary: null as DailySummary | null,
operatorName: localStorage.getItem('operatorName') || '宝妈',
loading: false,
error: ''
}),
actions: {
async load() {
this.loading = true
this.error = ''
try {
this.context = await getFamilyContext()
this.babies = this.context.babies
this.members = this.context.members
if (!this.selectedBabyId && this.babies[0]) {
this.selectedBabyId = this.babies[0].babyId
}
const selected = this.babies.find(baby => baby.babyId === this.selectedBabyId) || this.babies[0]
this.baby = selected || null
if (this.baby) {
localStorage.setItem('selectedBabyId', this.baby.babyId)
this.summary = await getDailySummary(this.baby.babyId)
}
} catch (error) {
this.error = error instanceof Error ? error.message : '加载失败'
} finally {
this.loading = false
}
},
async refreshSummary() {
if (!this.baby) return
this.summary = await getDailySummary(this.baby.babyId)
},
async selectBaby(babyId: string) {
this.selectedBabyId = babyId
localStorage.setItem('selectedBabyId', babyId)
this.baby = this.babies.find(baby => baby.babyId === babyId) || this.baby
await this.refreshSummary()
},
setOperatorName(name: string) {
this.operatorName = name || '宝妈'
localStorage.setItem('operatorName', this.operatorName)
},
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)
await this.refreshSummary()
},
async logFeeding(method: FeedingMethod, amountMl?: number, breastSide?: 'left' | 'right') {
if (!this.baby) return
await createFeeding({
babyId: this.baby.babyId,
feedingMethod: method,
amountMl,
breastSide,
operatorName: this.operatorName
})
await this.refreshSummary()
},
async toggleBreastfeedTimer(breastSide: 'left' | 'right') {
if (!this.baby) return
if (this.summary?.activeFeeding) {
await endFeeding({ babyId: this.baby.babyId, breastSide, operatorName: this.operatorName })
} else {
await startFeeding({ babyId: this.baby.babyId, breastSide, operatorName: this.operatorName })
}
await this.refreshSummary()
},
async toggleSleep() {
if (!this.baby) return
if (this.summary?.activeSleep) {
await endSleep({ babyId: this.baby.babyId, operatorName: this.operatorName })
} else {
await startSleep({ babyId: this.baby.babyId, operatorName: this.operatorName })
}
await this.refreshSummary()
},
async logPee() {
if (!this.baby) return
await createPee({ babyId: this.baby.babyId, operatorName: this.operatorName })
await this.refreshSummary()
},
async logPoop() {
if (!this.baby) return
await createPoop({ babyId: this.baby.babyId, operatorName: this.operatorName })
await this.refreshSummary()
}
}
})
+386
View File
@@ -0,0 +1,386 @@
:root {
color: #1f2933;
background: #f6f5f2;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button,
input,
select {
font: inherit;
}
button {
border: 0;
}
.app-shell {
min-height: 100vh;
max-width: 880px;
margin: 0 auto;
background: #fffdfa;
}
.app-main {
min-height: 100vh;
padding-bottom: 84px;
}
.page {
padding: 18px;
}
.hero {
display: flex;
justify-content: space-between;
gap: 16px;
padding: 22px;
border-radius: 24px;
background: linear-gradient(135deg, #fff4da, #e9f7f1);
border: 1px solid #efe3ca;
}
.clean-hero {
border-radius: 8px;
}
.hero h1,
.page-header h1 {
margin: 4px 0;
font-size: 28px;
}
.hero p,
.page-header p,
.panel-title p {
margin: 0;
color: #65707d;
}
.eyebrow {
font-size: 12px;
font-weight: 800;
color: #aa6b18;
}
.operator-pill {
align-self: flex-start;
padding: 8px 12px;
border-radius: 999px;
background: white;
font-weight: 800;
}
.context-panel {
margin: 12px 0 16px;
overflow: hidden;
border: 1px solid #ebe4d8;
border-radius: 8px;
background: white;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
margin: 16px 0;
}
.metric-card,
.panel {
border: 1px solid #ebe4d8;
border-radius: 18px;
background: white;
box-shadow: 0 10px 28px rgba(80, 64, 43, 0.06);
}
.metric-card {
padding: 16px;
}
.metric-card span,
.metric-card small,
.status-list span,
.stat-row span {
color: #65707d;
}
.metric-card strong {
display: block;
margin: 8px 0 2px;
font-size: 24px;
}
.panel {
margin-top: 14px;
padding: 16px;
}
.panel,
.metric-card {
border-radius: 8px;
}
.panel-title {
margin-bottom: 12px;
}
.panel-title h2 {
margin: 0 0 4px;
font-size: 18px;
}
.action-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.compact-actions {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.primary-action {
min-height: 92px;
padding: 14px;
border-radius: 8px;
text-align: left;
color: #17202a;
}
.primary-action strong {
display: block;
font-size: 20px;
}
.primary-action span {
display: block;
margin-top: 4px;
}
.feeding {
background: #fff1cf;
}
.sleep {
background: #eee9ff;
}
.pee {
background: #dff4ff;
}
.poop {
background: #e8f7df;
}
.status-list,
.settings-list,
.stat-row,
.timeline-item {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 12px 0;
border-bottom: 1px solid #f0ece5;
}
.status-list {
display: grid;
}
.settings-list {
display: grid;
}
.settings-list div {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 12px 0;
border-bottom: 1px solid #f0ece5;
}
.settings-list div:last-child {
border-bottom: 0;
}
.settings-list span {
color: #65707d;
}
.settings-list strong {
text-align: right;
}
.feeding-status,
.amount-row,
.two-actions {
display: grid;
gap: 10px;
margin-top: 12px;
}
.feeding-status,
.amount-row {
grid-template-columns: 1fr auto auto;
align-items: center;
padding: 12px;
border-radius: 8px;
background: #faf7f1;
}
.feeding-status span,
.amount-row span {
color: #65707d;
}
.two-actions {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.timeline-item:last-child,
.stat-row:last-child {
border-bottom: 0;
}
.timeline-item p,
.timeline-item small {
margin: 4px 0 0;
color: #65707d;
}
.page-header {
margin-bottom: 18px;
}
.bottom-nav {
position: fixed;
left: 50%;
bottom: 0;
width: min(880px, 100%);
transform: translateX(-50%);
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
padding: 10px 14px max(10px, env(safe-area-inset-bottom));
background: rgba(255, 253, 250, 0.96);
border-top: 1px solid #e7ded0;
backdrop-filter: blur(16px);
}
.bottom-nav__item {
padding: 10px;
border-radius: 14px;
color: #65707d;
text-align: center;
text-decoration: none;
font-weight: 800;
}
.bottom-nav__item.router-link-active {
color: #8a540d;
background: #fff1cf;
}
.notice {
padding: 10px 12px;
border-radius: 12px;
background: #eef6ff;
}
.notice.error {
background: #fff0f0;
color: #b42318;
}
.empty {
color: #65707d;
text-align: center;
}
.text-button {
align-self: center;
background: #fff0f0;
color: #b42318;
border-radius: 999px;
padding: 8px 12px;
font-weight: 800;
}
.form-panel {
display: grid;
gap: 14px;
}
.form-panel label {
display: grid;
gap: 6px;
color: #65707d;
font-weight: 800;
}
.form-panel input,
.form-panel select {
width: 100%;
border: 1px solid #ded6c8;
border-radius: 8px;
padding: 12px;
background: #fffdfa;
color: #1f2933;
}
.save-button {
padding: 14px;
border-radius: 14px;
background: #1f7a5c;
color: white;
font-weight: 900;
}
@media (min-width: 720px) {
.summary-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.action-grid {
grid-template-columns: repeat(5, minmax(0, 1fr));
}
.compact-actions {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 420px) {
.page {
padding: 12px;
}
.hero {
padding: 18px;
}
.hero h1,
.page-header h1 {
font-size: 24px;
}
.compact-actions,
.two-actions {
grid-template-columns: 1fr;
}
.feeding-status,
.amount-row {
grid-template-columns: 1fr;
}
}
+74
View File
@@ -0,0 +1,74 @@
export type FeedingMethod = 'breastfeed' | 'bottle' | 'formula' | 'mixed' | 'other'
export type RecordType = 'feeding' | 'sleep' | 'excretion'
export type ExcretionType = 'pee' | 'poop'
export interface BabyProfile {
babyId: string
familyId: string
name: string
gender: string
birthDate: string
deliveryType: string
ageDays: number
ageText: string
}
export interface FamilyInfo {
familyId: string
name: string
inviteCode?: string | null
}
export interface FamilyMember {
memberId: string
familyId: string
userId?: string | null
roleName: string
roleType: string
defaultOperator: boolean
}
export interface FamilyContext {
family: FamilyInfo
babies: BabyProfile[]
members: FamilyMember[]
}
export interface CareRecord {
recordId: string
familyId: string
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
createdAt: string
}
export interface DailySummary {
babyId: string
date: string
feedingCount: number
feedingMethodCounts: Record<string, number>
sleepTotalMinutes: number
peeCount: number
poopCount: number
lastFeeding?: CareRecord | null
activeFeeding?: CareRecord | null
activeSleep?: CareRecord | null
timeline: CareRecord[]
}
export interface ApiResponse<T> {
success: boolean
data: T
error?: {
code: string
message: string
}
}
+31
View File
@@ -0,0 +1,31 @@
export function formatTime(value?: string | null) {
if (!value) return '--'
const date = new Date(value)
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
export function formatMinutes(minutes: number) {
const h = Math.floor(minutes / 60)
const m = minutes % 60
if (h <= 0) return `${m} 分钟`
if (m === 0) return `${h} 小时`
return `${h} 小时 ${m} 分钟`
}
export function recordLabel(type: string, sub?: string | null) {
if (type === 'feeding') {
const map: Record<string, string> = {
breastfeed: '亲喂',
bottle: '瓶喂',
formula: '配方奶',
mixed: '混合',
other: '其他'
}
return `喂奶 · ${map[sub || 'other'] || '其他'}`
}
if (type === 'sleep') return '睡眠'
if (type === 'excretion' && sub === 'pee') return '小便'
if (type === 'excretion' && sub === 'poop') return '大便'
return '记录'
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"strict": true
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 9890,
proxy: {
'/api': 'http://localhost:9899'
}
}
})
-150
View File
@@ -1,150 +0,0 @@
#!/usr/bin/env bash
# ==============================================================================
# 新生儿记录系统 (Newborn Tracker) - Ubuntu 自动化构建与容器部署脚本
#
# 环境要求:
# - Ubuntu 20.04 / 22.04 / 24.04 LTS
# - 已安装 Docker 与 Node.js 22 (含 npm)
#
# 脚本特性:
# 1. 使用宿主机 Node.js 22 预先下载依赖,大幅加速 Docker 镜像构建
# 2. 自动生成「年月日时分」格式的镜像版本号 (如: 202609240245)
# 3. 自动停止并删除历史同名容器,完成平滑无感升级
# 4. 支持从 .env 自动注入数据库配置,开箱即用
# 5. 自动清理孤立虚悬镜像 (dangling images),防止服务器磁盘膨胀
# ==============================================================================
set -euo pipefail
# ------------------------------------------------------------------------------
# 1. 基础配置
# ------------------------------------------------------------------------------
APP_NAME="baby-tracker"
IMAGE_NAME="baby-tracker"
CONTAINER_NAME="baby-tracker-app"
HOST_PORT=9898
CONTAINER_PORT=9898
# 生成年月日时分版本号 (例如: 202609241430)
VERSION="$(date +'%Y%m%d%H%M')"
# 进入脚本所在根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${SCRIPT_DIR}"
echo "=================================================================="
echo "🚀 开始自动化构建与部署: ${APP_NAME}"
echo "📅 目标镜像版本号: ${VERSION}"
echo "📂 工作目录: ${SCRIPT_DIR}"
echo "=================================================================="
# ------------------------------------------------------------------------------
# 2. 宿主机环境检查
# ------------------------------------------------------------------------------
echo "==> 检查系统依赖..."
if ! command -v docker &> /dev/null; then
echo "❌ 错误: 未检测到 docker 命令,请确认 Docker 已正确安装并已启动守护进程。" >&2
exit 1
fi
if ! command -v node &> /dev/null; then
echo "❌ 错误: 未检测到 node 命令,请确认 Node.js 已安装。" >&2
exit 1
fi
NODE_VER="$(node -v)"
echo "✅ 宿主机 Node.js 版本: ${NODE_VER}"
echo "✅ 宿主机 Docker 版本: $(docker --version)"
# ------------------------------------------------------------------------------
# 3. 宿主机预下载依赖 (源码层加速)
# ------------------------------------------------------------------------------
echo ""
echo "==> [步骤 1/4] 在宿主机使用 Node.js 22 下载生产依赖 (npm install)..."
if [ -f "package.json" ]; then
# 优先使用国内淘宝镜像源加速(国内服务器极速),若国外服务器可直接用官方源
if [ -z "${NPM_CONFIG_REGISTRY:-}" ]; then
export npm_config_registry="https://registry.npmmirror.com"
fi
echo " 使用的 npm 源: ${npm_config_registry}"
npm install --omit=dev --no-audit --prefer-offline
echo "✅ 依赖下载完成!已生成/更新本地 node_modules 目录。"
else
echo "❌ 错误: 当前目录下未找到 package.json,请确认部署脚本位于项目根目录!" >&2
exit 1
fi
# ------------------------------------------------------------------------------
# 4. 构建 Docker 镜像 (打上「年月日时分」和「latest」双标签)
# ------------------------------------------------------------------------------
echo ""
echo "==> [步骤 2/4] 构建 Docker 镜像: ${IMAGE_NAME}:${VERSION} ..."
docker build \
-t "${IMAGE_NAME}:${VERSION}" \
-t "${IMAGE_NAME}:latest" \
.
echo "✅ Docker 镜像构建成功: ${IMAGE_NAME}:${VERSION} 及 ${IMAGE_NAME}:latest"
# ------------------------------------------------------------------------------
# 5. 停止并删除历史版本容器
# ------------------------------------------------------------------------------
echo ""
echo "==> [步骤 3/4] 检查并清理旧容器: ${CONTAINER_NAME} ..."
EXISTING_CONTAINER="$(docker ps -aq -f "name=^/${CONTAINER_NAME}$")"
if [ -n "${EXISTING_CONTAINER}" ]; then
echo " 发现历史版本容器 (ID: ${EXISTING_CONTAINER}),正在停止并移除..."
docker stop "${CONTAINER_NAME}" >/dev/null 2>&1 || true
docker rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true
echo "✅ 历史容器已成功停止并删除!"
else
echo "ℹ️ 未发现运行中的历史同名容器,准备直接创建新容器。"
fi
# ------------------------------------------------------------------------------
# 6. 启动新版本容器
# ------------------------------------------------------------------------------
echo ""
echo "==> [步骤 4/4] 启动新版本容器: ${CONTAINER_NAME} (版本: ${VERSION}) ..."
ENV_PARAM=""
if [ -f ".env" ]; then
echo " 检测到 .env 配置文件,自动挂载环境变量..."
ENV_PARAM="--env-file .env"
fi
docker run -d \
--name "${CONTAINER_NAME}" \
--restart always \
-p "${HOST_PORT}:${CONTAINER_PORT}" \
${ENV_PARAM} \
"${IMAGE_NAME}:${VERSION}"
# 等待 2 秒检查容器运行状态
sleep 2
if [ "$(docker inspect -f '{{.State.Running}}' "${CONTAINER_NAME}" 2>/dev/null)" = "true" ]; then
echo ""
echo "=================================================================="
echo "🎉 部署成功!"
echo "📌 容器名称: ${CONTAINER_NAME}"
echo "🏷️ 当前镜像: ${IMAGE_NAME}:${VERSION}"
echo "🌐 访问端口: http://0.0.0.0:${HOST_PORT}"
echo "=================================================================="
echo ""
echo "最近 10 行启动日志:"
docker logs --tail 10 "${CONTAINER_NAME}"
else
echo "❌ 容器启动后未能正常保持运行,请查看日志排查:" >&2
docker logs --tail 30 "${CONTAINER_NAME}" >&2
exit 1
fi
# ------------------------------------------------------------------------------
# 7. 清理虚悬镜像 (可选清理,保持磁盘整洁)
# ------------------------------------------------------------------------------
echo ""
echo "==> 清理无标签的虚悬构建缓存镜像..."
docker image prune -f >/dev/null 2>&1 || true
echo "✅ 部署全部完成!"
+8
View File
@@ -0,0 +1,8 @@
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY deploy/artifacts/server/app.jar /app/app.jar
EXPOSE 9899
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+10
View File
@@ -0,0 +1,10 @@
.git
.agents
openspec
doc
apps/web/node_modules
apps/web/dist
server-java/target
**/*.log
**/.env
deploy/.env
+6
View File
@@ -0,0 +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
EXPOSE 80
+10
View File
@@ -0,0 +1,10 @@
.git
.agents
openspec
doc
apps/web/node_modules
apps/web/dist
server-java/target
**/*.log
**/.env
deploy/.env
+82
View File
@@ -0,0 +1,82 @@
# 部署说明
本目录存放新架构部署文件:
- `Dockerfile.server`: 基于已编译好的 Spring Boot 可执行 jar 构建后端镜像。
- `Dockerfile.web`: 基于已编译好的 Vue H5/Web `dist` 目录构建前端镜像。
- `Dockerfile.*.dockerignore`: 控制 Docker 构建上下文,避免把本地依赖和构建产物打包进去。
- `nginx.conf`: Web 静态资源服务与 `/api` 反向代理配置。
- `docker-compose.yml`: 同时启动 Web 与后端。
- `deploy.sh`: Ubuntu 服务器一键停止旧容器、构建新镜像、启动新容器。
- `env.example`: 后端数据库连接环境变量示例。
## 服务端口
- Web/H5: `9898`
- Java API: 容器内部 `9899`
浏览器访问:
```text
http://服务器IP:9898
```
前端请求 `/api` 时会由 Nginx 转发到后端服务。
## 镜像版本
每次执行 `deploy.sh` 都会生成一个新镜像版本,格式为:
```text
yyMMdd_HHmm
```
示例:
```text
260923_0049
```
脚本会同时标记:
- `baby-tracker-server:<版本号>`
- `baby-tracker-web:<版本号>`
- `baby-tracker-server:latest`
- `baby-tracker-web:latest`
## 首次部署
先在本地或 CI 完成编译,并把产物上传到服务器:
```text
deploy/artifacts/server/app.jar
deploy/artifacts/web/dist/index.html
```
本地编译命令:
```bash
cd server-java
mvn -DskipTests package
cd ../apps/web
npm run build
```
上传时:
- 将 `server-java/target/baby-tracker-server-0.1.0.jar` 上传为 `deploy/artifacts/server/app.jar`
- 将 `apps/web/dist` 整个目录上传到 `deploy/artifacts/web/dist`
服务器执行:
```bash
cd deploy
cp env.example .env
vim .env
./deploy.sh
```
## 注意
当前后端默认仍兼容原数据库连接串。正式部署时建议使用 `.env` 管理数据库连接,避免把密码写入镜像或代码。
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
set -euo pipefail
APP_NAME="baby-tracker"
IMAGE_VERSION="$(date +'%y%m%d_%H%M')"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${SCRIPT_DIR}"
export IMAGE_VERSION
echo "============================================================"
echo "开始部署 ${APP_NAME}"
echo "镜像版本: ${IMAGE_VERSION}"
echo "部署目录: ${SCRIPT_DIR}"
echo "============================================================"
if ! command -v docker >/dev/null 2>&1; then
echo "未检测到 Docker,请先安装并启动 Docker。" >&2
exit 1
fi
if ! docker compose version >/dev/null 2>&1; then
echo "未检测到 docker compose,请确认 Docker Compose 插件已安装。" >&2
exit 1
fi
if [ ! -f ".env" ]; then
echo "未找到 deploy/.env,已从 env.example 生成一份,请先确认数据库密码。"
cp env.example .env
exit 1
fi
if [ ! -f "artifacts/server/app.jar" ]; then
echo "未找到后端产物: deploy/artifacts/server/app.jar" >&2
echo "请先上传已编译好的 Spring Boot 可执行 jar,并命名为 app.jar。" >&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
exit 1
fi
echo "停止并删除旧容器..."
docker compose down --remove-orphans
echo "基于已上传产物构建新镜像..."
docker compose build
echo "启动新容器..."
docker compose up -d
echo "标记 latest 镜像..."
docker tag "baby-tracker-server:${IMAGE_VERSION}" baby-tracker-server:latest
docker tag "baby-tracker-web:${IMAGE_VERSION}" baby-tracker-web:latest
docker image prune -f >/dev/null 2>&1 || true
echo "============================================================"
echo "部署完成"
echo "镜像版本: ${IMAGE_VERSION}"
echo "Web/H5: http://0.0.0.0:9898"
echo "API: http://0.0.0.0:9899"
echo "============================================================"
docker compose ps
+24
View File
@@ -0,0 +1,24 @@
services:
baby-tracker-server:
build:
context: ..
dockerfile: deploy/Dockerfile.server
image: baby-tracker-server:${IMAGE_VERSION:-latest}
container_name: baby-tracker-server
restart: always
env_file:
- .env
ports:
- "9899:9899"
baby-tracker-web:
build:
context: ..
dockerfile: deploy/Dockerfile.web
image: baby-tracker-web:${IMAGE_VERSION:-latest}
container_name: baby-tracker-web
restart: always
depends_on:
- baby-tracker-server
ports:
- "9898:80"
+3
View File
@@ -0,0 +1,3 @@
DB_URL=jdbc:mysql://39.107.119.209:3306/yyyy?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
DB_USER=yy_u
DB_PASSWORD=BBp5pjWr9LFiqua
+20
View File
@@ -0,0 +1,20 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://baby-tracker-server:9899/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+49
View File
@@ -0,0 +1,49 @@
# 2026-09-25 清理记录:仓库结构与部署脚本调整
## 背景
项目已确定进入新架构:
- H5/浏览器:`apps/web`,Vue 3 + Vite + TypeScript。
- 后端:`server-java`,Java 21 + Spring Boot。
- 数据库:复用原 MySQL,使用 Flyway 记录结构演进。
旧 Node 原型已经不再作为主运行入口,继续保留会让页面入口、部署方式和后端定位混乱。
## 本次清理内容
移除旧原型相关文件:
- 根目录旧 Node 部署入口:`Dockerfile`、`docker-compose.yml`、`deploy.sh`。
- 根目录旧 Node 包管理文件:`package.json`、`package-lock.json`。
- 旧 Node 后端目录:`server`。
- 旧静态页面目录:`public`。
- 旧辅助脚本目录:`scripts`。
- 旧临时脚本:`migrate_metric.js`、`test_api.js`。
保留内容:
- `sql/database.sql` 作为旧 Node 原型时期数据库结构参考。
- `openspec` 作为历史需求与规划资料。
## 新部署结构
新增 `deploy` 目录,集中存放部署相关文件:
- `deploy/Dockerfile.server`: Java 后端镜像。
- `deploy/Dockerfile.web`: Web/H5 镜像。
- `deploy/nginx.conf`: Web 静态资源与 `/api` 代理。
- `deploy/docker-compose.yml`: Web + 后端组合部署。
- `deploy/deploy.sh`: Ubuntu 一键部署脚本。
- `deploy/env.example`: 数据库环境变量示例。
部署后的访问方式:
- Web/H5: `http://服务器IP:9898`
- Java API: `http://服务器IP:9899`
浏览器端请求 `/api` 时,由 Nginx 转发到 Java 后端。
## 注意
`deploy/.env` 已加入忽略规则,正式数据库密码应放在服务器本地 `.env` 中,不提交到代码仓库。
+130
View File
@@ -0,0 +1,130 @@
# 2026-09-25 重构记录:MVP 架构落地
## 背景
根据 `architecture-adjustment-plan.md`,项目从 Node + 静态页面原型,开始调整为:
- 后端:Java 21 + Spring Boot 3。
- H5/浏览器端:Vue 3 + Vite + TypeScript。
- 当前 MVP 聚焦顺产 3 天新生儿每日照护记录。
## 本次完成内容
### 后端
新增 `server-java` 模块:
- Spring Boot 3.3.5。
- Java 21。
- 统一 API 响应结构。
- 全局异常处理。
- CORS 配置。
- 当前宝宝接口。
- 照护记录接口。
- 每日统计接口。
当前接口:
```text
GET /api/v1/babies/current
PUT /api/v1/babies/current
GET /api/v1/records?babyId=
POST /api/v1/records/feeding
POST /api/v1/records/sleep/start
POST /api/v1/records/sleep/end
POST /api/v1/records/pee
POST /api/v1/records/poop
DELETE /api/v1/records/{recordId}
GET /api/v1/summary/daily?babyId=
```
后端已接入原有 MySQL 连接串,并使用 Spring JDBC + Flyway 管理当前 MVP 数据结构。
当前数据库策略:
- 复用原库连接信息,但表结构按 Java 新架构标准执行。
- 新增 `care_record` 作为照护流水核心表。
- 不再兼容旧 Node 原型表结构;如继续使用原数据库,需要按 `sql/schema-full.sql` 或 Flyway 脚本迁移到新结构。
- Flyway 负责后续结构演进记录,完整 SQL 和演进 SQL 同步维护在 `sql` 目录。
### H5/Web
新增 `apps/web` 模块:
- Vue 3。
- Vite。
- TypeScript。
- Pinia。
- Vue Router。
页面结构:
```text
今日照护
照护流水
每日统计
基础设置
```
已实现主流程:
- 查看出生第 3 天宝宝。
- 记录亲喂。
- 记录瓶喂。
- 开始/结束睡眠。
- 记录小便。
- 记录大便。
- 查看今日喂奶次数、睡眠累计、小便次数、大便次数。
- 查看今日流水。
- 修改宝宝基础信息和当前记录人。
## 验证结果
后端:
```text
mvn -DskipTests package
```
已通过。
Web:
```text
npm run build
```
已通过。
运行验证:
- Spring Boot 服务启动成功:`http://localhost:9899`
- Vite H5/Web 启动成功:`http://localhost:5173`
- API 写入喂奶、小便、大便后,今日统计可正确更新。
## 已知限制
1. 暂未实现登录和家庭权限,当前默认读取原库中的默认宝宝档案。
2. 暂未实现补录编辑表单,仅保留删除。
3. 暂未实现小程序端。
4. 当前先使用 Spring JDBC,后续如果查询复杂度上升,可再引入 MyBatis Plus。
5. 旧 Node 原型仍保留在 `server` 与 `public` 中,作为参考,后续可逐步归档。
## 下一步建议
1. 增加补录和编辑记录能力。
2. 增加用户、家庭、看护人身份模型。
3. 根据小程序登录接入情况补充 openid/unionid 绑定。
4. 对旧 Node 原型做归档或移除决策。
## 2026-09-25 后端接库验证
使用原有 MySQL 连接串完成验证:
- `GET /api/v1/babies/current` 可读取原库已有宝宝档案。
- `POST /api/v1/records/feeding` 可写入喂奶记录。
- `POST /api/v1/records/pee` 可写入小便记录。
- `POST /api/v1/records/poop` 可写入大便记录。
- `GET /api/v1/summary/daily?babyId=baby-001` 可返回当日喂奶、小便、大便统计。
本次实际读取到的默认宝宝为 `baby-001`。验证记录已写入数据库,备注为“接口验证”。
+50
View File
@@ -0,0 +1,50 @@
# 2026-09-26 调整记录:家庭切换、喂奶行为与设置结构
## 背景
当前阶段无登录,但仍需要保留核心关系:
```text
家庭 -> 成员 -> 宝宝
```
一个家庭可以有多个宝宝和多个成员。无登录阶段允许在页面中切换宝宝和记录人;后续接入微信登录后,再将成员与微信身份绑定。
## 本次调整
### 后端
- 新增家庭上下文接口:`GET /api/v1/families/current-context`。
- 新增宝宝列表接口:`GET /api/v1/babies`。
- 新增按宝宝更新接口:`PUT /api/v1/babies/{babyId}`。
- 新增亲喂计时接口:
- `POST /api/v1/records/feeding/start`
- `POST /api/v1/records/feeding/end`
- 照护记录写入时按宝宝档案解析 `family_id`,不再固定写默认家庭。
- 不做旧 Node 原型表结构兼容,数据库以 Java 新架构 SQL 为准。
### 前端
- 引入 Vant 作为移动端友好的 UI 组件基础。
- 今日页增加宝宝切换和记录人切换。
- 亲喂支持:
- 左右侧切换。
- 开始/结束计时。
- 一键记录。
- 瓶喂支持奶量步进调整。
- 快速记录完成后显示温馨提示。
- 设置页调整为四个维护区:
- 宝宝信息。
- 家庭信息。
- 成员信息。
- 行为配置。
## 数据库原则
从本次开始,后端不再兼容旧原型表结构。旧库如果继续使用,需要先迁移或重建为 `sql/schema-full.sql` / Flyway V1 所定义的新结构。
补充 ID 规则:
- 所有新表主键统一为 `id CHAR(32)`。
- 后端通过雪花 ID 生成 32 位字符串。
- 原 `id + 业务id` 的双字段设计已合并为单一 `id`。
+38
View File
@@ -0,0 +1,38 @@
# 2026-09-26 调整记录:统一 32 位字符串 ID
## 背景
新架构数据库不再使用自增主键。所有新表统一使用 `id` 作为主键,类型为 32 位字符串,由后端程序通过雪花 ID 生成。
如果表中原先同时存在自增 `id` 和唯一业务 ID,例如 `baby_id`、`record_id`、`member_id`,统一合并为 `id`,避免双 ID 带来的维护成本。
## 本次调整
### 后端
- 新增 `SnowflakeIdGenerator`。
- 雪花 ID 输出为 32 位数字字符串。
- `baby_profile.id` 对外仍映射为 `babyId`。
- `family.id` 对外仍映射为 `familyId`。
- `family_member.id` 对外仍映射为 `memberId`。
- `care_record.id` 对外仍映射为 `recordId`。
- 记录写入时由程序生成 `care_record.id`。
### 数据库
已调整:
- `server-java/src/main/resources/db/migration/V1__init_mvp_schema.sql`
- `sql/schema-full.sql`
- `sql/schema-evolution.sql`
新表规则:
- 主键统一为 `id CHAR(32)`。
- 删除自增主键。
- 删除重复业务 ID 字段。
- 外键引用字段仍保留语义名称,例如 `family_id`、`baby_id`、`user_id`,但它们引用的都是对应表的 `id`。
## 注意
当前不再兼容旧 Node 原型表结构。如果使用已有数据库,需要先按新结构重建或迁移,再启动新版后端。
+20
View File
@@ -0,0 +1,20 @@
# 项目调整文档
本目录用于记录 baby-tracker 后续所有产品、架构、页面和数据模型调整。
后续每次较大的变更,都应在本目录补充或更新文档,避免需求、架构决策和实现细节散落在聊天记录或代码注释中。
## 当前文档
- [architecture-adjustment-plan.md](./architecture-adjustment-plan.md): 后端改为 Java + Spring Boot 后的总体架构调整方案,以及 H5/Web、小程序、页面功能主线规划。
- [2026-09-25-restructure-mvp.md](./2026-09-25-restructure-mvp.md): MVP 重构落地记录,包含 H5/Web、Spring Boot 后端、数据库接入和接口验证结果。
- [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 生成策略。
## 记录原则
1. 重要决策先写入文档,再进入实现。
2. 每次调整需要说明背景、目标、范围和暂不处理的内容。
3. 当前阶段始终以“顺产 3 天新生儿每日照护记录”为核心,不让低频配置和后期扩展功能干扰主流程。
4. 文档与代码不一致时,以最新文档作为下一步调整依据,并在实现时同步修正文档。
+517
View File
@@ -0,0 +1,517 @@
# Baby Tracker 架构与页面调整方案
## 1. 背景
当前仓库是一个可运行的全栈原型,已包含宝宝档案、家庭协同、喂养、睡眠、尿布、自定义指标、统计看板、备忘、护理视频、Excel 导出等能力。
但当前主要问题是:
- 页面功能堆叠较多,主操作不够清晰。
- 当前目标用户和核心场景不够聚焦。
- 前端文件结构集中在 `public/index.html` 与 `public/app.js`,后续维护成本高。
- 后端是 Node + Express 原型,业务逻辑和接口路由耦合较重。
- 后续计划支持 H5/浏览器、小程序、独立管理端,需要统一稳定的后端服务。
因此,后续架构调整方向确定为:
- 后端:Java + Spring Boot。
- 当前前端:H5/浏览器端,使用 Vue 3 + Vite + TypeScript。
- 后续小程序端:uni-app + Vue 3 + TypeScript。
- 后续管理端:可独立建设,优先服务配置、权限、导出和运营管理。
## 2. 当前阶段产品定位
当前阶段不做大而全的新生儿照护平台,先聚焦一个非常明确的 MVP:
> 面向顺产 3 天新生儿家庭的每日照护记录工具,帮助家人清楚记录每日喂奶、睡眠、大小便情况。
当前主要用户:
- 顺产 3 天的新生儿家庭。
- 主要记录人可能是宝妈、宝爸或其他照护人。
- 使用场景以手机 H5 为主,兼顾浏览器访问。
当前最重要的记录内容:
1. 每日喂奶时间。
2. 喂奶方式。
3. 睡眠开始与结束时间。
4. 每日喂奶次数。
5. 每日小便次数。
6. 每日大便次数。
当前阶段可以弱化或后置:
- 多宝宝复杂管理。
- 大量自定义指标。
- 护理视频内容体系。
- 复杂家庭权限。
- Excel 高级导出。
- 长周期趋势分析。
- 管理后台。
- 小程序上线适配。
## 3. 页面架构调整
当前页面应从“大而全仪表盘”调整为“新生儿今日照护记录台”。
### 3.1 页面结构
建议 H5/Web 端先拆为 4 个主页面:
```text
今日照护
记录流水
每日统计
设置
```
### 3.2 今日照护页
这是当前最重要页面,也是默认首页。
核心目标:
- 用户打开页面后,立刻知道宝宝今天喂了几次、睡了多久、尿了几次、拉了几次。
- 用户可以快速完成一次喂奶、睡眠、大小便记录。
建议内容顺序:
1. 顶部宝宝状态
- 宝宝昵称。
- 出生第几天。
- 今日日期。
- 当前记录人。
2. 今日核心摘要
- 今日喂奶次数。
- 今日小便次数。
- 今日大便次数。
- 今日累计睡眠时长。
3. 高频记录区
- 记录喂奶。
- 开始/结束睡眠。
- 记录小便。
- 记录大便。
4. 最近一次记录提示
- 上次喂奶时间。
- 当前睡眠状态。
- 上次小便/大便时间。
### 3.3 记录流水页
核心目标:
- 查看今天所有记录。
- 支持编辑误操作。
- 支持补录。
第一阶段功能:
- 按时间倒序展示记录。
- 类型标签:喂奶、睡眠、小便、大便。
- 支持删除与编辑。
- 支持补录历史时间。
### 3.4 每日统计页
核心目标:
- 不追求复杂分析,先把当天是否记录完整讲清楚。
第一阶段指标:
- 今日喂奶次数。
- 按方式统计喂奶次数。
- 今日睡眠总时长。
- 今日小便次数。
- 今日大便次数。
- 最近 3 天简单对比。
注意:
- 当前宝宝仅出生 3 天,不应过早展示复杂趋势和强医疗判断。
- 所有参考提示应使用“参考”“可留意”“如有异常请咨询医生”等表达。
### 3.5 设置页
设置页放低频操作,避免干扰主流程。
第一阶段设置:
- 宝宝昵称。
- 出生日期。
- 性别。
- 当前记录人称谓。
- 家庭名称。
后续再逐步加入:
- 家庭成员。
- 自定义记录项。
- 护理指南。
- 数据导出。
- 权限管理。
## 4. 后端架构调整
后端从当前 Node + Express 原型,调整为 Java + Spring Boot 服务。
### 4.1 推荐技术栈
```text
Java 21
Spring Boot 3
Spring Web
Spring Validation
Spring Security
MyBatis Plus
MySQL
Redis
Flyway
Knife4j 或 Springdoc OpenAPI
```
说明:
- Spring Boot 作为主后端框架,负责多端统一 API。
- MyBatis Plus 适合当前以业务表和 SQL 查询为主的项目。
- Flyway 管理数据库版本,避免启动时隐式改表。
- Spring Security 用于后续登录、权限、微信身份接入。
- Redis 可后置,用于 session、验证码、提醒、缓存等。
### 4.2 后端模块规划
```text
server-java/
src/main/java/
com/babytracker/
BabyTrackerApplication.java
common/
config/
exception/
response/
security/
validation/
module/
auth/
user/
family/
baby/
record/
summary/
memo/
guide/
src/main/resources/
application.yml
db/migration/
```
### 4.3 模块职责
#### auth
负责登录与身份识别。
第一阶段 H5 可使用简化身份方案,后续小程序接入微信登录。
后续能力:
- H5 登录。
- 微信 `code` 换 `openid`。
- token 签发与刷新。
- 当前用户信息。
#### family
负责家庭实体和成员关系。
当前阶段先简化:
- 默认家庭。
- 当前记录人称谓。
后续完善:
- 邀请码。
- 家庭成员。
- 成员权限。
#### baby
负责宝宝档案。
当前阶段重点:
- 宝宝昵称。
- 出生日期。
- 性别。
- 出生天数计算。
#### record
负责照护记录,是当前最核心模块。
第一阶段记录类型:
```text
feeding
sleep
pee
poop
```
其中喂奶记录包含:
```text
feeding_time
feeding_method
amount_ml 可选
duration_minutes 可选
operator_name
```
睡眠记录包含:
```text
start_time
end_time
duration_minutes
operator_name
```
大小便记录包含:
```text
event_time
excretion_type: pee | poop
operator_name
note 可选
```
#### summary
负责当天统计。
第一阶段只做明确统计:
- 今日喂奶次数。
- 今日不同喂奶方式次数。
- 今日睡眠总时长。
- 今日小便次数。
- 今日大便次数。
- 最近一次喂奶时间。
- 当前是否正在睡眠。
#### memo
备忘模块后置,不作为当前 MVP 主流程。
#### guide
护理指南后置,不作为当前 MVP 主流程。
## 5. API 设计方向
API 统一使用版本前缀:
```text
/api/v1
```
第一阶段建议接口:
```text
GET /api/v1/babies/current
PUT /api/v1/babies/{babyId}
GET /api/v1/records?babyId=&date=
POST /api/v1/records/feeding
POST /api/v1/records/sleep/start
POST /api/v1/records/sleep/end
POST /api/v1/records/pee
POST /api/v1/records/poop
PUT /api/v1/records/{recordId}
DELETE /api/v1/records/{recordId}
GET /api/v1/summary/daily?babyId=&date=
```
统一返回格式:
```json
{
"success": true,
"data": {}
}
```
错误格式:
```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "参数不合法"
}
}
```
## 6. 数据模型调整方向
当前数据库模型已有 family、baby、activity_record 等概念,但第一阶段可以简化业务表达。
推荐保留核心表:
```text
family
family_member
baby_profile
care_record
```
其中 `care_record` 可以统一承载喂奶、睡眠、大小便。
建议字段方向:
```text
id
record_id
family_id
baby_id
record_type
start_time
end_time
duration_minutes
feeding_method
amount_ml
excretion_type
operator_name
note
created_at
updated_at
deleted_at
```
说明:
- `record_type`: feeding, sleep, excretion。
- `excretion_type`: pee, poop。
- 第一阶段不必过度拆表,避免开发复杂度过高。
- 后续如果统计、查询和扩展变复杂,再拆 feeding_record、sleep_record、excretion_record。
## 7. 前端架构调整
当前先建设 H5/浏览器端:
```text
apps/web/
Vue 3
Vite
TypeScript
Pinia
Vue Router
```
后续小程序端:
```text
apps/miniapp/
uni-app
Vue 3
TypeScript
```
共享内容:
```text
packages/shared/
constants/
types/
schemas/
```
第一阶段不要求 Web 与小程序共用 UI 组件,但应尽量共享:
- 记录类型枚举。
- API 类型。
- 时间格式化规则。
- 表单校验规则。
- 新生儿日龄计算逻辑。
## 8. 实施阶段
### 阶段 1:文档和边界确认
- 建立 `doc` 目录。
- 固化技术路线。
- 固化 MVP 范围。
- 明确页面主线。
### 阶段 2:后端 Spring Boot 骨架
- 新建 `server-java`。
- 建立基础模块结构。
- 配置 MySQL。
- 引入 Flyway。
- 建立统一响应与异常处理。
- 实现 baby、record、summary 三个核心模块。
### 阶段 3:H5/Web 新前端
- 新建 `apps/web`。
- 实现今日照护页。
- 实现记录流水页。
- 实现每日统计页。
- 实现基础设置页。
### 阶段 4:迁移核心数据与接口
- 对照旧 Node 接口迁移必要数据。
- 暂停扩展功能。
- 以顺产 3 天新生儿记录闭环为验收标准。
### 阶段 5:小程序准备
- 等 H5/Web 功能稳定后,新建 `apps/miniapp`。
- 复用后端 API。
- 接入微信登录。
- 适配小程序端页面。
## 9. 当前阶段验收标准
第一阶段完成后,应满足:
1. 可以创建或维护一个 3 天新生儿档案。
2. 可以记录每次喂奶时间。
3. 可以选择喂奶方式。
4. 可以开始和结束睡眠记录。
5. 可以记录小便。
6. 可以记录大便。
7. 可以查看今天所有记录。
8. 可以查看今日喂奶次数、睡眠总时长、小便次数、大便次数。
9. 页面默认主流程清晰,不出现大量后期功能干扰。
10. 后续变更均记录在 `doc` 目录。
## 10. 暂不处理事项
以下内容不进入当前阶段主线:
- 复杂家庭权限。
- 多家庭切换。
- 多宝宝复杂场景。
- 自定义指标。
- 护理视频体系。
- 管理后台。
- Excel 导出。
- 医疗判断或异常诊断。
- 小程序上线。
- 订阅提醒。
这些能力可以在核心记录链路稳定后,以独立文档和独立阶段逐步加入。
-16
View File
@@ -1,16 +0,0 @@
version: '3.8'
services:
baby-tracker:
build: .
container_name: baby-tracker-app
restart: always
ports:
- "9898:9898"
environment:
- PORT=9898
- DB_HOST=39.107.119.209
- DB_PORT=3306
- DB_USER=yy_u
- DB_PASSWORD=BBp5pjWr9LFiqua
- DB_NAME=yyyy
-27
View File
@@ -1,27 +0,0 @@
const { pool } = require('./server/db');
async function migrate() {
try {
const [cols] = await pool.query('SHOW COLUMNS FROM custom_metric LIKE "default_value"');
if (cols.length === 0) {
await pool.query("ALTER TABLE custom_metric ADD COLUMN default_value VARCHAR(30) DEFAULT '1' COMMENT '默认打卡数值' AFTER unit");
console.log('Added default_value column to custom_metric');
} else {
console.log('default_value column already exists');
}
// Update existing metrics with proper defaults if needed
await pool.query("UPDATE custom_metric SET default_value = '1' WHERE metric_id = 'metric-d3' AND (default_value IS NULL OR default_value = '')");
await pool.query("UPDATE custom_metric SET default_value = '15' WHERE metric_id = 'metric-tummy' AND (default_value IS NULL OR default_value = '')");
await pool.query("UPDATE custom_metric SET default_value = '1' WHERE metric_id = 'metric-massage' AND (default_value IS NULL OR default_value = '')");
await pool.query("UPDATE custom_metric SET default_value = '36.5' WHERE metric_id = 'metric-temp' AND (default_value IS NULL OR default_value = '')");
console.log('Migration finished successfully!');
process.exit(0);
} catch (e) {
console.error('Migration failed:', e);
process.exit(1);
}
}
migrate();
-1148
View File
File diff suppressed because it is too large. Load diff
-21
View File
@@ -1,21 +0,0 @@
{
"name": "yyyy",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node server/app.js",
"dev": "node server/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"cors": "^2.8.6",
"dotenv": "^18.0.3",
"express": "^5.2.1",
"mysql2": "^3.24.4",
"xlsx": "^0.18.5"
}
}
-3327
View File
File diff suppressed because it is too large. Load diff
-40
View File
@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-bath.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#CCFBF1" />
<stop offset="100%" stop-color="#14B8A6" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-bath.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#CCFBF1" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">🛁</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">新生儿安全盆浴与脐带护理</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#0F766E" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">快速盆浴 · 75% 酒精消毒</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#0F766E" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-40
View File
@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-bottle.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FEF3C7" />
<stop offset="100%" stop-color="#F59E0B" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-bottle.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#FEF3C7" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">🍼</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">45° 防胀气瓶喂指南</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#B45309" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">节律喂养 · 杜绝呛奶吞气</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#B45309" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-breastfeed.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FFE4E6" />
<stop offset="100%" stop-color="#F43F5E" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-breastfeed.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#FFE4E6" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">🤱</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">新生儿深吸含乳技巧</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#BE123C" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">深层含乳 · 预防乳头皲裂</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#BE123C" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-40
View File
@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-burping.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#EDE9FE" />
<stop offset="100%" stop-color="#8B5CF6" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-burping.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#EDE9FE" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">💨</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">空心掌拍嗝防胀气实操</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#6D28D9" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">端坐与过肩拍嗝 · 排净胃气</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#6D28D9" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-40
View File
@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-diaper.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#E0F2FE" />
<stop offset="100%" stop-color="#0EA5E9" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-diaper.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#E0F2FE" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">💧</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">防红屁屁换尿布全流程</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#0369A1" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">温水清洗 · 隔离护臀膏涂法</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#0369A1" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-40
View File
@@ -1,40 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-poster-sleep.svg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#F1F5F9" />
<stop offset="100%" stop-color="#64748B" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-poster-sleep.svg)" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="#F1F5F9" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">😴</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">安全襁褓裹法与入睡安抚</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="#334155" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">防惊跳反射 · 建立自主入睡</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="#334155" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-1618
View File
File diff suppressed because it is too large. Load diff
-152
View File
@@ -1,152 +0,0 @@
/* Base system font & layout reset to guarantee graceful display under any circumstance */
*, ::before, ::after {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
button, input, select, textarea {
font-family: inherit;
}
img, video {
max-width: 100%;
height: auto;
}
/* Custom styles and mobile touch interactions */
/* Hide scrollbars for neat mobile pills */
.no-scrollbar::-webkit-scrollbar {
display: none;
}
.no-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
/* Squeeze animation on button press */
.active\:scale-98:active {
transform: scale(0.98);
}
.action-card {
transition: transform 0.12s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.12s;
-webkit-tap-highlight-color: transparent;
}
.action-card:active {
transform: scale(0.97);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
/* Smooth Tab transitions */
.view-panel {
animation: fadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Toast entrance */
.toast-msg {
animation: slideDown 0.25s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Gantt blocks */
.gantt-block {
transition: transform 0.15s, opacity 0.15s;
cursor: pointer;
}
.gantt-block:hover {
filter: brightness(0.95);
transform: translateY(-1px);
}
/* Warm & Soft Theme Tokens (方案 1 温暖治愈系) */
:root {
--color-warm-bg: #FAF7F2;
--color-card-bg: #FFFFFF;
}
body {
background-color: #F8F5EE;
background-image:
radial-gradient(at 0% 0%, rgba(254, 243, 199, 0.35) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(243, 232, 255, 0.35) 0px, transparent 50%),
radial-gradient(at 50% 50%, rgba(240, 249, 255, 0.25) 0px, transparent 50%);
background-attachment: fixed;
}
/* Soft Ambient Diffuse Shadows */
.shadow-soft {
box-shadow: 0 10px 30px -4px rgba(160, 140, 120, 0.08), 0 4px 12px -2px rgba(160, 140, 120, 0.04);
}
.shadow-soft-lg {
box-shadow: 0 20px 40px -6px rgba(160, 140, 120, 0.12), 0 8px 16px -4px rgba(160, 140, 120, 0.06);
}
.shadow-focus {
box-shadow: 0 0 50px rgba(245, 158, 11, 0.25);
}
/* Floating Dock for Mobile */
.floating-dock {
box-shadow: 0 12px 36px rgba(100, 90, 80, 0.14), 0 2px 8px rgba(100, 90, 80, 0.06);
}
/* Checkbox strikethrough animation */
.memo-done-text {
text-decoration: line-through;
color: #94A3B8;
transition: all 0.2s ease;
}
/* Fullscreen Focus Overlay Animations */
.focus-glow-ring {
filter: drop-shadow(0 0 16px rgba(245, 158, 11, 0.4));
transition: stroke-dashoffset 0.8s ease;
}
.focus-sleep-glow {
filter: drop-shadow(0 0 18px rgba(139, 92, 246, 0.5));
}
.focus-tummy-glow {
filter: drop-shadow(0 0 18px rgba(16, 185, 129, 0.45));
}
@keyframes pulseGlow {
0%, 100% {
transform: scale(1);
opacity: 0.95;
}
50% {
transform: scale(1.02);
opacity: 1;
}
}
.animate-focus-pulse {
animation: pulseGlow 3s infinite ease-in-out;
}
-83
View File
@@ -1,83 +0,0 @@
(()=>{var qv=Object.create;var Hi=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var Mv=Object.getPrototypeOf,Nv=Object.prototype.hasOwnProperty;var df=r=>Hi(r,"__esModule",{value:!0});var hf=r=>{if(typeof require!="undefined")return require(r);throw new Error('Dynamic require of "'+r+'" is not supported')};var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var x=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ge=(r,e)=>{df(r);for(var t in e)Hi(r,t,{get:e[t],enumerable:!0})},Bv=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lv(e))!Nv.call(r,i)&&i!=="default"&&Hi(r,i,{get:()=>e[i],enumerable:!(t=$v(e,i))||t.enumerable});return r},pe=r=>Bv(df(Hi(r!=null?qv(Mv(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var m,u=P(()=>{m={platform:"",env:{},versions:{node:"14.17.6"}}});var Fv,be,ft=P(()=>{u();Fv=0,be={readFileSync:r=>self[r]||"",statSync:()=>({mtimeMs:Fv++}),promises:{readFile:r=>Promise.resolve(self[r]||"")}}});var Fs=x((oP,gf)=>{u();"use strict";var mf=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||1/0,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[t,i]of e)this.onEviction(t,i.value)}_deleteIfExpired(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,t.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,t){if(this._deleteIfExpired(e,t)===!1)return t.value}_getItemValue(e,t){return t.expiry?this._getOrDeleteIfExpired(e,t):t.value}_peek(e,t){let i=t.get(e);return this._getItemValue(e,i)}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,t){this.oldCache.delete(e),this._set(e,t)}*_entriesAscending(){for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield e)}for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let t=this.cache.get(e);return this._getItemValue(e,t)}if(this.oldCache.has(e)){let t=this.oldCache.get(e);if(this._deleteIfExpired(e,t)===!1)return this._moveToRecent(e,t),t.value}}set(e,t,{maxAge:i=this.maxAge===1/0?void 0:Date.now()+this.maxAge}={}){this.cache.has(e)?this.cache.set(e,{value:t,maxAge:i}):this._set(e,{value:t,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this._entriesAscending()],i=t.length-e;i<0?(this.cache=new Map(t),this.oldCache=new Map,this._size=t.length):(i>0&&this._emitEvictions(t.slice(0,i)),this.oldCache=new Map(t.slice(i)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}}*entriesDescending(){let e=[...this.cache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}e=[...this.oldCache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this.cache.has(n)||this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}}*entriesAscending(){for(let[e,t]of this._entriesAscending())yield[e,t.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};gf.exports=mf});var yf,bf=P(()=>{u();yf=r=>r&&r._hash});function Wi(r){return yf(r,{ignoreUnknown:!0})}var wf=P(()=>{u();bf()});function xt(r){if(r=`${r}`,r==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(r))return r.replace(/^[+-]?/,t=>t==="-"?"":"-");let e=["var","calc","min","max","clamp"];for(let t of e)if(r.includes(`${t}(`))return`calc(${r} * -1)`}var Gi=P(()=>{u()});var vf,xf=P(()=>{u();vf=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","size","height","maxHeight"Line truncated
`+S+n("^")}let b=i(h.replace(/\d/g," "))+f.slice(0,this.column-1).replace(/[^\t]/g," ");return n(">")+i(h)+s(f)+`
`+b+n("^")}return" "+i(h)+s(f)}).join(`
`)}toString(){let e=this.showSourceCode();return e&&(e=`
`+e+`
`),this.name+": "+this.message+e}};cc.exports=Jt;Jt.default=Jt});var fa=x((x3,dc)=>{u();"use strict";var pc={after:`
`,beforeClose:`
`,beforeComment:`
`,beforeDecl:`
`,beforeOpen:" ",beforeRule:`
`,colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};function vx(r){return r[0].toUpperCase()+r.slice(1)}var on=class{constructor(e){this.builder=e}atrule(e,t){let i="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(typeof e.raws.afterName!="undefined"?i+=e.raws.afterName:n&&(i+=" "),e.nodes)this.block(e,i+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(i+n+s,e)}}beforeAfter(e,t){let i;e.type==="decl"?i=this.raw(e,null,"beforeDecl"):e.type==="comment"?i=this.raw(e,null,"beforeComment"):t==="before"?i=this.raw(e,null,"beforeRule"):i=this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&n.type!=="root";)s+=1,n=n.parent;if(i.includes(`
`)){let a=this.raw(e,null,"indent");if(a.length)for(let o=0;o<s;o++)i+=a}return i}block(e,t){let i=this.raw(e,"between","beforeOpen");this.builder(t+i+"{",e,"start");let n;e.nodes&&e.nodes.length?(this.body(e),n=this.raw(e,"after")):n=this.raw(e,"after","emptyBody"),n&&this.builder(n),this.builder("}",e,"end")}body(e){let t=e.nodes.length-1;for(;t>0&&e.nodes[t].type==="comment";)t-=1;let i=this.raw(e,"semicolon");for(let n=0;n<e.nodes.length;n++){let s=e.nodes[n],a=this.raw(s,"before");a&&this.builder(a),this.stringify(s,t!==n||i)}}comment(e){let t=this.raw(e,"left","commentLeft"),i=this.raw(e,"right","commentRight");this.builder("/*"+t+e.text+i+"*/",e)}decl(e,t){let i=this.raw(e,"between","colon"),n=e.prop+i+this.rawValue(e,"value");e.important&&(n+=e.raws.important||" !important"),t&&(n+=";"),this.builder(n,e)}document(e){this.body(e)}raw(e,t,i){let n;if(i||(i=t),t&&(n=e.raws[t],typeof n!="undefined"))return n;let s=e.parent;if(i==="before"&&(!s||s.type==="root"&&s.first===e||s&&s.type==="document"))return"";if(!s)return pc[i];let a=e.root();if(a.rawCache||(a.rawCache={}),typeof a.rawCache[i]!="undefined")return a.rawCache[i];if(i==="before"||i==="after")return this.beforeAfter(e,i);{let o="raw"+vx(i);this[o]?n=this[o](a,e):a.walk(l=>{if(n=l.raws[t],typeof n!="undefined")return!1})}return typeof n=="undefined"&&(n=pc[i]),a.rawCache[i]=n,n}rawBeforeClose(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length>0&&typeof i.raws.after!="undefined")return t=i.raws.after,t.includes(`
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let i;return e.walkComments(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeDecl"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeDecl(e,t){let i;return e.walkDecls(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeRule"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeOpen(e){let t;return e.walk(i=>{if(i.type!=="decl"&&(t=i.raws.between,typeof t!="undefined"))return!1}),t}rawBeforeRule(e){let t;return e.walk(i=>{if(i.nodes&&(i.parent!==e||e.first!==i)&&typeof i.raws.before!="undefined")return t=i.raws.before,t.includes(`
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(i=>{if(typeof i.raws.between!="undefined")return t=i.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length===0&&(t=i.raws.after,typeof t!="undefined"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(i=>{let n=i.parent;if(n&&n!==e&&n.parent&&n.parent===e&&typeof i.raws.before!="undefined"){let s=i.raws.before.split(`
`);return t=s[s.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length&&i.last.type==="decl"&&(t=i.raws.semicolon,typeof t!="undefined"))return!1}),t}rawValue(e,t){let i=e[t],n=e.raws[t];return n&&n.value===i?n.raw:i}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};dc.exports=on;on.default=on});var Vr=x((k3,hc)=>{u();"use strict";var xx=fa();function ca(r,e){new xx(e).stringify(r)}hc.exports=ca;ca.default=ca});var ln=x((S3,pa)=>{u();"use strict";pa.exports.isClean=Symbol("isClean");pa.exports.my=Symbol("my")});var Gr=x((A3,mc)=>{u();"use strict";var kx=an(),Sx=fa(),Ax=Vr(),{isClean:Hr,my:Cx}=ln();function da(r,e){let t=new r.constructor;for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i)||i==="proxyCache")continue;let n=r[i],s=typeof n;i==="parent"&&s==="object"?e&&(t[i]=e):i==="source"?t[i]=n:Array.isArray(n)?t[i]=n.map(a=>da(a,t)):(s==="object"&&n!==null&&(n=da(n)),t[i]=n)}return t}function Wr(r,e){if(e&&typeof e.offset!="undefined")return e.offset;let t=1,i=1,n=0;for(let s=0;s<r.length;s++){if(i===e.line&&t===e.column){n=s;break}r[s]===`
`?(t=1,i+=1):t+=1}return n}var un=class{constructor(e={}){this.raws={},this[Hr]=!1,this[Cx]=!0;for(let t in e)if(t==="nodes"){this.nodes=[];for(let i of e[t])typeof i.clone=="function"?this.append(i.clone()):this.append(i)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=da(this);for(let i in e)t[i]=e[i];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:i,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:i.column,line:i.line},t)}return new kx(e)}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:t==="root"?()=>e.root().toProxy():e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="prop"||t==="value"||t==="name"||t==="params"||t==="important"||t==="text")&&e.markDirty()),!0}}}markClean(){this[Hr]=!0}markDirty(){if(this[Hr]){this[Hr]=!1;let e=this;for(;e=e.parent;)e[Hr]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e){let t=this.source.start;if(e.index)t=this.positionInside(e.index);else if(e.word){let n=this.source.input.css.slice(Wr(this.source.input.css,this.source.start),Wr(this.source.input.css,this.source.end)).indexOf(e.word);n!==-1&&(t=this.positionInside(n))}return t}positionInside(e){let t=this.source.start.column,i=this.source.start.line,n=Wr(this.source.input.css,this.source.start),s=n+e;for(let a=n;a<s;a++)this.source.input.css[a]===`
`?(t=1,i+=1):t+=1;return{column:t,line:i}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e){let t={column:this.source.start.column,line:this.source.start.line},i=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){let s=this.source.input.css.slice(Wr(this.source.input.css,this.source.start),Wr(this.source.input.css,this.source.end)).indexOf(e.word);s!==-1&&(t=this.positionInside(s),i=this.positionInside(s+e.word.length))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?i={column:e.end.column,line:e.end.line}:typeof e.endIndex=="number"?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<t.line||i.line===t.line&&i.column<=t.column)&&(i={column:t.column+1,line:t.line}),{end:i,start:t}}raw(e,t){return new Sx().raw(this,e,t)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let t=this,i=!1;for(let n of e)n===this?i=!0:i?(this.parent.insertAfter(t,n),t=n):this.parent.insertBefore(t,n);i||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}toJSON(e,t){let i={},n=t==null;t=t||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))i[a]=o.map(l=>typeof l=="object"&&l.toJSON?l.toJSON(null,t):l);else if(typeof o=="object"&&o.toJSON)i[a]=o.toJSON(null,t);else if(a==="source"){let l=t.get(o.input);l==null&&(l=s,t.set(o.input,s),s++),i[a]={end:o.end,inputId:l,start:o.start}}else i[a]=o}return n&&(i.inputs=[...t.keys()].map(a=>a.toJSON())),i}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Ax){e.stringify&&(e=e.stringify);let t="";return e(this,i=>{t+=i}),t}warn(e,t,i){let n={node:this};for(let s in i)n[s]=i[s];return e.warn(t,n)}get proxyOf(){return this}};mc.exports=un;un.default=un});var Qr=x((C3,gc)=>{u();"use strict";var _x=Gr(),fn=class extends _x{constructor(e){super(e);this.type="comment"}};gc.exports=fn;fn.default=fn});var Yr=x((_3,yc)=>{u();"use strict";var Ex=Gr(),cn=class extends Ex{constructor(e){e&&typeof e.value!="undefined"&&typeof e.value!="string"&&(e={...e,value:String(e.value)});super(e);this.type="decl"}get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}};yc.exports=cn;cn.default=cn});var Et=x((E3,_c)=>{u();"use strict";var bc=Qr(),wc=Yr(),Ox=Gr(),{isClean:vc,my:xc}=ln(),ha,kc,Sc,ma;function Ac(r){return r.map(e=>(e.nodes&&(e.nodes=Ac(e.nodes)),delete e.source,e))}function Cc(r){if(r[vc]=!1,r.proxyOf.nodes)for(let e of r.proxyOf.nodes)Cc(e)}var Fe=class extends Ox{append(...e){for(let t of e){let i=this.normalize(t,this.last);for(let n of i)this.proxyOf.nodes.push(n)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),i,n;for(;this.indexes[t]<this.proxyOf.nodes.length&&(i=this.indexes[t],n=e(this.proxyOf.nodes[i],i),n!==!1);)this.indexes[t]+=1;return delete this.indexes[t],n}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:e[t]?t==="each"||typeof t=="string"&&t.startsWith("walk")?(...i)=>e[t](...i.map(n=>typeof n=="function"?(s,a)=>n(s.toProxy(),a):n)):t==="every"||t==="some"?i=>e[t]((n,...s)=>i(n.toProxy(),...s)):t==="root"?()=>e.root().toProxy():t==="nodes"?e.nodes.map(i=>i.toProxy()):t==="first"||t==="last"?e[t].toProxy():e[t]:e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="name"||t==="params"||t==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let i=this.index(e),n=this.normalize(t,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of n)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i<s&&(this.indexes[a]=s+n.length);return this.markDirty(),this}insertBefore(e,t){let i=this.index(e),n=i===0?"prepend":!1,s=this.normalize(t,this.proxyOf.nodes[i],n).reverse();i=this.index(e);for(let o of s)this.proxyOf.nodes.splice(i,0,o);let a;for(let o in this.indexes)a=this.indexes[o],i<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,t){if(typeof e=="string")e=Ac(kc(e).nodes);else if(typeof e=="undefined")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value=="undefined")throw new Error("Value fie Line truncated
`);i=new Array(s.length);let a=0;for(let o=0,l=s.length;o<l;o++)i[o]=a,a+=s[o].length+1;this[va]=i}t=i[i.length-1];let n=0;if(e>=t)n=i.length-1;else{let s=i.length-2,a;for(;n<s;)if(a=n+(s-n>>1),e<i[a])s=a-1;else if(e>=i[a+1])n=a+1;else{n=a;break}}return{col:e-i[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:ba(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,i,n){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;let o;typeof i=="number"&&(o=s.originalPositionFor({column:n,line:i}));let l;ya(a.source)?l=hn(a.source):l=new URL(a.source,this.map.consumer().sourceRoot||hn(this.map.mapFile));let c={column:a.column,endColumn:o&&o.column,endLine:o&&o.line,line:a.line,url:l.toString()};if(l.protocol==="file:")if(Lc)c.file=Lc(l);else throw new Error("file: protocol is not available in this PostCSS build");let f=s.sourceContentFor(a.source);return f&&(c.source=f),c}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};Bc.exports=Xr;Xr.default=Xr;wa&&wa.registerInput&&wa.registerInput(Xr)});var tr=x(($3,Uc)=>{u();"use strict";var Fc=Et(),jc,zc,Ut=class extends Fc{constructor(e){super(e);this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,i){let n=super.normalize(e);if(t){if(i==="prepend")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let s of n)s.raws.before=t.raws.before}return n}removeChild(e,t){let i=this.index(e);return!t&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}toResult(e={}){return new jc(new zc,this,e).stringify()}};Ut.registerLazyResult=r=>{jc=r};Ut.registerProcessor=r=>{zc=r};Uc.exports=Ut;Ut.default=Ut;Fc.registerRoot(Ut)});var xa=x((L3,Vc)=>{u();"use strict";var Zr={comma(r){return Zr.split(r,[","],!0)},space(r){let e=[" ",`
`," "];return Zr.split(r,e)},split(r,e,t){let i=[],n="",s=!1,a=0,o=!1,l="",c=!1;for(let f of r)c?c=!1:f==="\\"?c=!0:o?f===l&&(o=!1):f==='"'||f==="'"?(o=!0,l=f):f==="("?a+=1:f===")"?a>0&&(a-=1):a===0&&e.includes(f)&&(s=!0),s?(n!==""&&i.push(n.trim()),n="",s=!1):n+=f;return(t||n!=="")&&i.push(n.trim()),i}};Vc.exports=Zr;Zr.default=Zr});var gn=x((M3,Wc)=>{u();"use strict";var Hc=Et(),Nx=xa(),Jr=class extends Hc{constructor(e){super(e);this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Nx.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,i=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}};Wc.exports=Jr;Jr.default=Jr;Hc.registerRule(Jr)});var Qc=x((N3,Gc)=>{u();"use strict";var Bx=pn(),Fx=Qr(),jx=Yr(),zx=mn(),Ux=ga(),Vx=tr(),Hx=gn();function ei(r,e){if(Array.isArray(r))return r.map(n=>ei(n));let{inputs:t,...i}=r;if(t){e=[];for(let n of t){let s={...n,__proto__:zx.prototype};s.map&&(s.map={...s.map,__proto__:Ux.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=r.nodes.map(n=>ei(n,e))),i.source){let{inputId:n,...s}=i.source;i.source=s,n!=null&&(i.source.input=e[n])}if(i.type==="root")return new Vx(i);if(i.type==="decl")return new jx(i);if(i.type==="rule")return new Hx(i);if(i.type==="comment")return new Fx(i);if(i.type==="atrule")return new Bx(i);throw new Error("Unknown node type: "+r.type)}Gc.exports=ei;ei.default=ei});var ka=x((B3,Yc)=>{u();Yc.exports=function(r,e){return{generate:()=>{let t="";return r(e,i=>{t+=i}),[t]}}}});var ep=x((F3,Jc)=>{u();"use strict";var Sa="'".charCodeAt(0),Kc='"'.charCodeAt(0),yn="\\".charCodeAt(0),Xc="/".charCodeAt(0),bn=`
`.charCodeAt(0),ti=" ".charCodeAt(0),wn="\f".charCodeAt(0),vn=" ".charCodeAt(0),xn="\r".charCodeAt(0),Wx="[".charCodeAt(0),Gx="]".charCodeAt(0),Qx="(".charCodeAt(0),Yx=")".charCodeAt(0),Kx="{".charCodeAt(0),Xx="}".charCodeAt(0),Zx=";".charCodeAt(0),Jx="*".charCodeAt(0),e1=":".charCodeAt(0),t1="@".charCodeAt(0),kn=/[\t\n\f\r "#'()/;[\\\]{}]/g,Sn=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,r1=/.[\r\n"'(/\\]/,Zc=/[\da-f]/i;Jc.exports=function(e,t={}){let i=e.css.valueOf(),n=t.ignoreErrors,s,a,o,l,c,f,d,p,h,b,v=i.length,y=0,w=[],k=[];function S(){return y}function E(R){throw e.error("Unclosed "+R,y)}function T(){return k.length===0&&y>=v}function B(R){if(k.length)return k.pop();if(y>=v)return;let F=R?R.ignoreUnclosed:!1;switch(s=i.charCodeAt(y),s){case bn:case ti:case vn:case xn:case wn:{l=y;do l+=1,s=i.charCodeAt(l);while(s===ti||s===bn||s===vn||s===xn||s===wn);f=["space",i.slice(y,l)],y=l-1;break}case Wx:case Gx:case Kx:case Xx:case e1:case Zx:case Yx:{let Y=String.fromCharCode(s);f=[Y,Y,y];break}case Qx:{if(b=w.length?w.pop()[1]:"",h=i.charCodeAt(y+1),b==="url"&&h!==Sa&&h!==Kc&&h!==ti&&h!==bn&&h!==vn&&h!==wn&&h!==xn){l=y;do{if(d=!1,l=i.indexOf(")",l+1),l===-1)if(n||F){l=y;break}else E("bracket");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["brackets",i.slice(y,l+1),y,l],y=l}else l=i.indexOf(")",y+1),a=i.slice(y,l+1),l===-1||r1.test(a)?f=["(","(",y]:(f=["brackets",a,y,l],y=l);break}case Sa:case Kc:{c=s===Sa?"'":'"',l=y;do{if(d=!1,l=i.indexOf(c,l+1),l===-1)if(n||F){l=y+1;break}else E("string");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["string",i.slice(y,l+1),y,l],y=l;break}case t1:{kn.lastIndex=y+1,kn.test(i),kn.lastIndex===0?l=i.length-1:l=kn.lastIndex-2,f=["at-word",i.slice(y,l+1),y,l],y=l;break}case yn:{for(l=y,o=!0;i.charCodeAt(l+1)===yn;)l+=1,o=!o;if(s=i.charCodeAt(l+1),o&&s!==Xc&&s!==ti&&s!==bn&&s!==vn&&s!==xn&&s!==wn&&(l+=1,Zc.test(i.charAt(l)))){for(;Zc.test(i.charAt(l+1));)l+=1;i.charCodeAt(l+1)===ti&&(l+=1)}f=["word",i.slice(y,l+1),y,l],y=l;break}default:{s===Xc&&i.charCodeAt(y+1)===Jx?(l=i.indexOf("*/",y+2)+1,l===0&&(n||F?l=i.length:E("comment")),f=["comment",i.slice(y,l+1),y,l],y=l):(Sn.lastIndex=y+1,Sn.test(i),Sn.lastIndex===0?l=i.length-1:l=Sn.lastIndex-2,f=["word",i.slice(y,l+1),y,l],w.push(f),y=l);break}}return y++,f}function N(R){k.push(R)}return{back:N,endOfFile:T,nextToken:B,position:S}}});var sp=x((j3,np)=>{u();"use strict";var i1=pn(),n1=Qr(),s1=Yr(),a1=tr(),tp=gn(),o1=ep(),rp={empty:!0,space:!0};function l1(r){for(let e=r.length-1;e>=0;e--){let t=r[e],i=t[3]||t[2];if(i)return i}}var ip=class{constructor(e){this.input=e,this.root=new a1,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new i1;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,n,s,a=!1,o=!1,l=[],c=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?c.push(i==="("?")":"]"):i==="{"&&c.length>0?c.push("}"):i===c[c.length-1]&&c.pop(),c.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(l.length>0){for(s=l.length-1,n=l[s];n&&n[0]==="space";)n=l[--s];n&&(t.source.end=this.getPosition(n[3]||n[2]),t.source.end.offset++)}this.end(e);break}else l.push(e);else l.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(l),l.length?(t.raws.afterName=this.spacesAndCommentsFromStart(l),this.raw(t,"params",l),a&&(e=l[l.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between="")):(t.raws.afterName="",t.params=""),o&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let i=0,n;for(let s=t-1;s>=0&&(n=e[s],!(n[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",n[0]==="word"?n[3]+1:n[2])}colon(e){let t=0,i,n,s;for(let[a,o]of e.entries()){if(n=o,s=n[0],s==="("&&(t+=1),s===")"&&(t-=1),t===0&&s===":")if(!i)this.doubleColon(n);else{if(i[0]==="word"&&i[1]==="progid")continue;return a}i=n}return!1}comment(e){let t=new n1;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let i=e[1].slice(2,-2);if(/^\s*$/.test(i))t.text="",t.raws.left=i,t.raws.right="";else{let n=i.match(/^(\s*)([^]*\S)(\s*)$/);t.text=n[2],t.raws.left=n[1],t.raws.right=n[3]}}createTokenizer(){this.tokenizer=o1(this.input)}decl(e,t){let i=new s1;this.init(i,e[0][2]);let n=e[e.length-1];for(n[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(n[3]||n[2]||l1(e)),i.source.end.offset++;e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let c=e[0][0];if(c===":"||c==="space"||c==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1 Line truncated
https://evilmartians.com/chronicles/postcss-8-plugin-migration`),m.env.LANG&&m.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new Ta().version,o}let s;return Object.defineProperty(n,"postcss",{get(){return s||(s=n()),s}}),n.process=function(a,o,l){return J([n(l)]).process(a,o)},n};J.stringify=F1;J.parse=N1;J.fromJSON=D1;J.list=L1;J.comment=r=>new vp(r);J.atRule=r=>new wp(r);J.decl=r=>new xp(r);J.rule=r=>new Ap(r);J.root=r=>new Sp(r);J.document=r=>new kp(r);J.CssSyntaxError=I1;J.Declaration=xp;J.Container=P1;J.Processor=Ta;J.Document=kp;J.Comment=vp;J.Warning=j1;J.AtRule=wp;J.Result=B1;J.Input=q1;J.Rule=Ap;J.Root=Sp;J.Node=M1;$1.registerPostcss(J);Cp.exports=J;J.default=J});var re,ee,Z3,J3,eI,tI,rI,iI,nI,sI,aI,oI,lI,uI,fI,cI,pI,dI,hI,mI,gI,yI,bI,wI,vI,xI,Ot=P(()=>{u();re=pe($e()),ee=re.default,Z3=re.default.stringify,J3=re.default.fromJSON,eI=re.default.plugin,tI=re.default.parse,rI=re.default.list,iI=re.default.document,nI=re.default.comment,sI=re.default.atRule,aI=re.default.rule,oI=re.default.decl,lI=re.default.root,uI=re.default.CssSyntaxError,fI=re.default.Declaration,cI=re.default.Container,pI=re.default.Processor,dI=re.default.Document,hI=re.default.Comment,mI=re.default.Warning,gI=re.default.AtRule,yI=re.default.Result,bI=re.default.Input,wI=re.default.Rule,vI=re.default.Root,xI=re.default.Node});var Ra=x((SI,_p)=>{u();_p.exports=function(r,e,t,i,n){for(e=e.split?e.split("."):e,i=0;i<e.length;i++)r=r?r[e[i]]:n;return r===n?t:r}});var Pn=x((Rn,Ep)=>{u();"use strict";Rn.__esModule=!0;Rn.default=V1;function z1(r){for(var e=r.toLowerCase(),t="",i=!1,n=0;n<6&&e[n]!==void 0;n++){var s=e.charCodeAt(n),a=s>=97&&s<=102||s>=48&&s<=57;if(i=s===32,!a)break;t+=e[n]}if(t.length!==0){var o=parseInt(t,16),l=o>=55296&&o<=57343;return l||o===0||o>1114111?["\uFFFD",t.length+(i?1:0)]:[String.fromCodePoint(o),t.length+(i?1:0)]}}var U1=/\\/;function V1(r){var e=U1.test(r);if(!e)return r;for(var t="",i=0;i<r.length;i++){if(r[i]==="\\"){var n=z1(r.slice(i+1,i+7));if(n!==void 0){t+=n[0],i+=n[1];continue}if(r[i+1]==="\\"){t+="\\",i++;continue}r.length===i+1&&(t+=r[i]);continue}t+=r[i]}return t}Ep.exports=Rn.default});var Tp=x((In,Op)=>{u();"use strict";In.__esModule=!0;In.default=H1;function H1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i<e;i++)t[i-1]=arguments[i];for(;t.length>0;){var n=t.shift();if(!r[n])return;r=r[n]}return r}Op.exports=In.default});var Pp=x((Dn,Rp)=>{u();"use strict";Dn.__esModule=!0;Dn.default=W1;function W1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i<e;i++)t[i-1]=arguments[i];for(;t.length>0;){var n=t.shift();r[n]||(r[n]={}),r=r[n]}}Rp.exports=Dn.default});var Dp=x((qn,Ip)=>{u();"use strict";qn.__esModule=!0;qn.default=G1;function G1(r){for(var e="",t=r.indexOf("/*"),i=0;t>=0;){e=e+r.slice(i,t);var n=r.indexOf("*/",t+2);if(n<0)return e;i=n+2,t=r.indexOf("/*",i)}return e=e+r.slice(i),e}Ip.exports=qn.default});var ii=x(rt=>{u();"use strict";rt.__esModule=!0;rt.unesc=rt.stripComments=rt.getProp=rt.ensureObject=void 0;var Q1=$n(Pn());rt.unesc=Q1.default;var Y1=$n(Tp());rt.getProp=Y1.default;var K1=$n(Pp());rt.ensureObject=K1.default;var X1=$n(Dp());rt.stripComments=X1.default;function $n(r){return r&&r.__esModule?r:{default:r}}});var dt=x((ni,Lp)=>{u();"use strict";ni.__esModule=!0;ni.default=void 0;var qp=ii();function $p(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function Z1(r,e,t){return e&&$p(r.prototype,e),t&&$p(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var J1=function r(e,t){if(typeof e!="object"||e===null)return e;var i=new e.constructor;for(var n in e)if(!!e.hasOwnProperty(n)){var s=e[n],a=typeof s;n==="parent"&&a==="object"?t&&(i[n]=t):s instanceof Array?i[n]=s.map(function(o){return r(o,i)}):i[n]=r(s,i)}return i},ek=function(){function r(t){t===void 0&&(t={}),Object.assign(this,t),this.spaces=this.spaces||{},this.spaces.before=this.spaces.before||"",this.spaces.after=this.spaces.after||""}var e=r.prototype;return e.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},e.replaceWith=function(){if(this.parent){for(var i in arguments)this.parent.insertBefore(this,arguments[i]);this.remove()}return this},e.next=function(){return this.parent.at(this.parent.index(this)+1)},e.prev=function(){return this.parent.at(this.parent.index(this)-1)},e.clone=function(i){i===void 0&&(i={});var n=J1(this);for(var s in i)n[s]=i[s];return n},e.appendToPropertyAndEscape=function(i,n,s){this.raws||(this.raws={});var a=this[i],o=this.raws[i];this[i]=a+n,o||s!==n?this.raws[i]=(o||a)+s:delete this.raws[i]},e.setPropertyAndEscape=function(i,n,s){this.raws||(this.raws={}),this[i]=n,this.raws[i]=s},e.setPropertyWithoutEscape=function(i,n){this[i]=n,this.raws&&delete this.raws[i]},e.isAtPosition=function(i,n){if(this.source&&this.source.start&&this.source.end)return!(this.source.start.line>i||this.source.end.line<i||this.source.start.line===i&&this.source.start.col Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yk(r,e){if(!!r){if(typeof r=="string")return Np(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Np(r,e)}}function Np(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,i=new Array(e);t<e;t++)i[t]=r[t];return i}function Bp(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function bk(r,e,t){return e&&Bp(r.prototype,e),t&&Bp(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function wk(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Pa(r,e)}function Pa(r,e){return Pa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Pa(r,e)}var vk=function(r){wk(e,r);function e(i){var n;return n=r.call(this,i)||this,n.nodes||(n.nodes=[]),n}var t=e.prototype;return t.append=function(n){return n.parent=this,this.nodes.push(n),this},t.prepend=function(n){return n.parent=this,this.nodes.unshift(n),this},t.at=function(n){return this.nodes[n]},t.index=function(n){return typeof n=="number"?n:this.nodes.indexOf(n)},t.removeChild=function(n){n=this.index(n),this.at(n).parent=void 0,this.nodes.splice(n,1);var s;for(var a in this.indexes)s=this.indexes[a],s>=n&&(this.indexes[a]=s-1);return this},t.removeAll=function(){for(var n=gk(this.nodes),s;!(s=n()).done;){var a=s.value;a.parent=void 0}return this.nodes=[],this},t.empty=function(){return this.removeAll()},t.insertAfter=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a+1,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],a<=o&&(this.indexes[l]=o+1);return this},t.insertBefore=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],o<=a&&(this.indexes[l]=o+1);return this},t._findChildAtPosition=function(n,s){var a=void 0;return this.each(function(o){if(o.atPosition){var l=o.atPosition(n,s);if(l)return a=l,!1}else if(o.isAtPosition(n,s))return a=o,!1}),a},t.atPosition=function(n,s){if(this.isAtPosition(n,s))return this._findChildAtPosition(n,s)||this},t._inferEndPosition=function(){this.last&&this.last.source&&this.last.source.end&&(this.source=this.source||{},this.source.end=this.source.end||{},Object.assign(this.source.end,this.last.source.end))},t.each=function(n){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach++;var s=this.lastEach;if(this.indexes[s]=0,!!this.length){for(var a,o;this.indexes[s]<this.length&&(a=this.indexes[s],o=n(this.at(a),a),o!==!1);)this.indexes[s]+=1;if(delete this.indexes[s],o===!1)return!1}},t.walk=function(n){return this.each(function(s,a){var o=n(s,a);if(o!==!1&&s.length&&(o=s.walk(n)),o===!1)return!1})},t.walkAttributes=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ATTRIBUTE)return n.call(s,a)})},t.walkClasses=function(n){var s=this;return this.walk(function(a){if(a.type===ht.CLASS)return n.call(s,a)})},t.walkCombinators=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMBINATOR)return n.call(s,a)})},t.walkComments=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMMENT)return n.call(s,a)})},t.walkIds=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ID)return n.call(s,a)})},t.walkNesting=function(n){var s=this;return this.walk(function(a){if(a.type===ht.NESTING)return n.call(s,a)})},t.walkPseudos=function(n){var s=this;return this.walk(function(a){if(a.type===ht.PSEUDO)return n.call(s,a)})},t.walkTags=function(n){var s=this;return this.walk(function(a){if(a.type===ht.TAG)return n.call(s,a)})},t.walkUniversals=function(n){var s=this;return this.walk(function(a){if(a.type===ht.UNIVERSAL)return n.call(s,a)})},t.split=function(n){var s=this,a=[];return this.reduce(function(o,l,c){var f=n.call(s,l);return a.push(l),f?(o.push(a),a=[]):c===s.length-1&&o.push(a),o},[])},t.map=function(n){return this.nodes.map(n)},t.reduce=function(n,s){return this.nodes.reduce(n,s)},t.every=function(n){return this.nodes.every(n)},t.some=function(n){return this.nodes.some(n)},t.filter=function(n){return this.nodes.filter(n)},t.sort=function(n){return this.nodes.sort(n)},t.toString=function(){return this.map(String).join("")},bk(e,[{key:"first",get:function(){return this.at(0)}},{key:"last",get:function(){return this.at(this.length-1)}},{key:"length",get:function(){return this.nodes.length}}]),e}(dk.default);si.default=vk;Fp.exports=si.default});var Da=x((ai,zp)=>{u();"use strict";ai.__esModule=!0;ai.default=void 0;var xk=Sk(Ln()),kk=Se();function Sk(r){return r&&r.__esModule?r:{default:r}}function jp(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable Line truncated
`),v=y.length-1,v>0?(k=a+v,S=w-y[v].length):(k=a,S=s),T=D.comment,a=k,p=k,d=w-S):c===D.slash?(w=o,T=c,p=a,d=o-s,l=w+1):(w=OA(t,o),T=D.word,p=a,d=w-s),l=w+1;break}e.push([T,a,o-s,p,d,o,l]),S&&(s=S,S=null),o=l}return e}});var kd=x((ki,xd)=>{u();"use strict";ki.__esModule=!0;ki.default=void 0;var IA=je(Da()),fo=je($a()),DA=je(Na()),md=je(Fa()),qA=je(za()),$A=je(Ha()),co=je(Ga()),LA=je(Ya()),gd=Vn(to()),MA=je(io()),po=je(so()),NA=je(oo()),BA=je(fd()),O=Vn(hd()),q=Vn(lo()),FA=Vn(Se()),ue=ii(),Vt,ho;function yd(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(yd=function(n){return n?t:e})(r)}function Vn(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=yd(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}function je(r){return r&&r.__esModule?r:{default:r}}function bd(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function jA(r,e,t){return e&&bd(r.prototype,e),t&&bd(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var mo=(Vt={},Vt[q.space]=!0,Vt[q.cr]=!0,Vt[q.feed]=!0,Vt[q.newline]=!0,Vt[q.tab]=!0,Vt),zA=Object.assign({},mo,(ho={},ho[q.comment]=!0,ho));function wd(r){return{line:r[O.FIELDS.START_LINE],column:r[O.FIELDS.START_COL]}}function vd(r){return{line:r[O.FIELDS.END_LINE],column:r[O.FIELDS.END_COL]}}function Ht(r,e,t,i){return{start:{line:r,column:e},end:{line:t,column:i}}}function sr(r){return Ht(r[O.FIELDS.START_LINE],r[O.FIELDS.START_COL],r[O.FIELDS.END_LINE],r[O.FIELDS.END_COL])}function go(r,e){if(!!r)return Ht(r[O.FIELDS.START_LINE],r[O.FIELDS.START_COL],e[O.FIELDS.END_LINE],e[O.FIELDS.END_COL])}function ar(r,e){var t=r[e];if(typeof t=="string")return t.indexOf("\\")!==-1&&((0,ue.ensureObject)(r,"raws"),r[e]=(0,ue.unesc)(t),r.raws[e]===void 0&&(r.raws[e]=t)),r}function yo(r,e){for(var t=-1,i=[];(t=r.indexOf(e,t+1))!==-1;)i.push(t);return i}function UA(){var r=Array.prototype.concat.apply([],arguments);return r.filter(function(e,t){return t===r.indexOf(e)})}var VA=function(){function r(t,i){i===void 0&&(i={}),this.rule=t,this.options=Object.assign({lossy:!1,safe:!1},i),this.position=0,this.css=typeof this.rule=="string"?this.rule:this.rule.selector,this.tokens=(0,O.default)({css:this.css,error:this._errorGenerator(),safe:this.options.safe});var n=go(this.tokens[0],this.tokens[this.tokens.length-1]);this.root=new IA.default({source:n}),this.root.errorGenerator=this._errorGenerator();var s=new fo.default({source:{start:{line:1,column:1}},sourceIndex:0});this.root.append(s),this.current=s,this.loop()}var e=r.prototype;return e._errorGenerator=function(){var i=this;return function(n,s){return typeof i.rule=="string"?new Error(n):i.rule.error(n,s)}},e.attribute=function(){var i=[],n=this.currToken;for(this.position++;this.position<this.tokens.length&&this.currToken[O.FIELDS.TYPE]!==q.closeSquare;)i.push(this.currToken),this.position++;if(this.currToken[O.FIELDS.TYPE]!==q.closeSquare)return this.expected("closing square bracket",this.currToken[O.FIELDS.START_POS]);var s=i.length,a={source:Ht(n[1],n[2],this.currToken[3],this.currToken[4]),sourceIndex:n[O.FIELDS.START_POS]};if(s===1&&!~[q.word].indexOf(i[0][O.FIELDS.TYPE]))return this.expected("attribute",i[0][O.FIELDS.START_POS]);for(var o=0,l="",c="",f=null,d=!1;o<s;){var p=i[o],h=this.content(p),b=i[o+1];switch(p[O.FIELDS.TYPE]){case q.space:if(d=!0,this.options.lossy)break;if(f){(0,ue.ensureObject)(a,"spaces",f);var v=a.spaces[f].after||"";a.spaces[f].after=v+h;var y=(0,ue.getProp)(a,"raws","spaces",f,"after")||null;y&&(a.raws.spaces[f].after=y+h)}else l=l+h,c=c+h;break;case q.asterisk:if(b[O.FIELDS.TYPE]===q.equals)a.operator=h,f="operator";else if((!a.namespace||f==="namespace"&&!d)&&b){l&&((0,ue.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=l,l=""),c&&((0,ue.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=l,c=""),a.namespace=(a.namespace||"")+h;var w=(0,ue.getProp)(a,"raws","namespace")||null;w&&(a.raws.namespace+=h),f="namespace"}d=!1;break;case q.dollar:if(f==="value"){var k=(0,ue.getProp)(a,"raws","value");a.value+="$",k&&(a.raws.value=k+"$");break}case q.caret:b[O.FIELDS.TYPE]===q.equals&&(a.operator=h,f="operator"),d=!1;break;case q.combinator:if(h==="~"&&b[O.FIELDS.TYPE]===q.equals&&(a.operator=h,f="operator"),h!=="|"){d=!1;break}b[O.FIELDS.TYPE]===q.equals?(a.operator=h,f="operator"):!a.namespace&&!a.attribute&&(a.namespace=!0),d=!1;break;case q.word:if(b&&this.content(b)==="|"&&i[o+2]&&i[o+2][O.FIELDS.TYPE]!==q.equals&&!a.operator&&!a.namespace)a.namespace=h,f="namespace";else if(!a.attribute||f==="attribute"&&!d){l&&((0,ue. Line truncated
`).slice(1,-1).map(N=>N.trim()).map(N=>` ${N}`).join(`
`)).join(`
`);w.push(` Use \`${r.replace("[",`[${E}:`)}\` for \`${T.trim()}\``);break}G.warn([`The class \`${r}\` is ambiguous and matches multiple utilities.`,...w,`If this is content and not a class, replace it with \`${r.replace("[","&lsqb;").replace("]","&rsqb;")}\` to silence this warning.`]);continue}}o=o.map(p=>p.filter(h=>Eh(h[1])))}o=o.flat(),o=Array.from(P_(o,i)),o=k_(o,e),s&&(o=S_(o,i));for(let p of n)o=A_(p,o,e);for(let p of o)p[1].raws.tailwind={...p[1].raws.tailwind,candidate:r},p=I_(p,{context:e,candidate:r}),p!==null&&(yield p)}}function I_(r,{context:e,candidate:t}){if(!r[0].collectedFormats)return r;let i=!0,n;try{n=dr(r[0].collectedFormats,{context:e,candidate:t})}catch{return null}let s=ee.root({nodes:[r[1].clone()]});return s.walkRules(a=>{if(!ss(a))try{let o=rs(a.selector,n,{candidate:t,context:e});if(o===null){a.remove();return}a.selector=o}catch{return i=!1,!1}}),!i||s.nodes.length===0?null:(r[1]=s.nodes[0],r)}function ss(r){return r.parent&&r.parent.type==="atrule"&&r.parent.name==="keyframes"}function D_(r){if(r===!0)return e=>{ss(e)||e.walkDecls(t=>{t.parent.type==="rule"&&!ss(t.parent)&&(t.important=!0)})};if(typeof r=="string")return e=>{ss(e)||(e.selectors=e.selectors.map(t=>is(t,r)))}}function as(r,e,t=!1){let i=[],n=D_(e.tailwindConfig.important);for(let s of r){if(e.notClassCache.has(s))continue;if(e.candidateRuleCache.has(s)){i=i.concat(Array.from(e.candidateRuleCache.get(s)));continue}let a=Array.from(Yo(s,e));if(a.length===0){e.notClassCache.add(s);continue}e.classCache.set(s,a);let o=e.candidateRuleCache.get(s)??new Set;e.candidateRuleCache.set(s,o);for(let l of a){let[{sort:c,options:f},d]=l;if(f.respectImportant&&n){let h=ee.root({nodes:[d.clone()]});h.walkRules(n),d=h.nodes[0]}let p=[c,t?d.clone():d];o.add(p),e.ruleCache.add(p),i.push(p)}}return i}function Ko(r){return r.startsWith("[")&&r.endsWith("]")}var ns,v_,C_,os=P(()=>{u();Ot();ns=pe(it());qo();Kt();Gn();Fr();Be();It();Vo();Lo();Br();Oi();Bo();zt();ct();Wo();v_=(0,ns.default)(r=>r.first.filter(({type:e})=>e==="class").pop().value);C_=/^[a-z_-]/});var Th,Rh=P(()=>{u();Th={}});function q_(r){try{return Th.createHash("md5").update(r,"utf-8").digest("binary")}catch(e){return""}}function Ph(r,e){let t=e.toString();if(!t.includes("@tailwind"))return!1;let i=No.get(r),n=q_(t),s=i!==n;return No.set(r,n),s}var Ih=P(()=>{u();Rh();It()});function us(r){return(r>0n)-(r<0n)}var Dh=P(()=>{u()});function qh(r,e){let t=0n,i=0n;for(let[n,s]of e)r&n&&(t=t|n,i=i|s);return r&~t|i}var $h=P(()=>{u()});function Lh(r){let e=null;for(let t of r)e=e??t,e=e>t?e:t;return e}function $_(r,e){let t=r.length,i=e.length,n=t<i?t:i;for(let s=0;s<n;s++){let a=r.charCodeAt(s)-e.charCodeAt(s);if(a!==0)return a}return t-i}var Xo,Mh=P(()=>{u();Dh();$h();Xo=class{constructor(){this.offsets={defaults:0n,base:0n,components:0n,utilities:0n,variants:0n,user:0n},this.layerPositions={defaults:0n,base:1n,components:2n,utilities:3n,user:4n,variants:5n},this.reservedVariantBits=0n,this.variantOffsets=new Map}create(e){return{layer:e,parentLayer:e,arbitrary:0n,variants:0n,parallelIndex:0n,index:this.offsets[e]++,propertyOffset:0n,property:"",options:[]}}arbitraryProperty(e){return{...this.create("utilities"),arbitrary:1n,property:e}}forVariant(e,t=0){let i=this.variantOffsets.get(e);if(i===void 0)throw new Error(`Cannot find offset for unknown variant ${e}`);return{...this.create("variants"),variants:i<<BigInt(t)}}applyVariantOffset(e,t,i){return i.variant=t.variants,{...e,layer:"variants",parentLayer:e.layer==="variants"?e.parentLayer:e.layer,variants:e.variants|t.variants,options:i.sort?[].concat(i,e.options):e.options,parallelIndex:Lh([e.parallelIndex,t.parallelIndex])}}applyParallelOffset(e,t){return{...e,parallelIndex:BigInt(t)}}recordVariants(e,t){for(let i of e)this.recordVariant(i,t(i))}recordVariant(e,t=1){return this.variantOffsets.set(e,1n<<this.reservedVariantBits),this.reservedVariantBits+=BigInt(t),{...this.create("variants"),variants:this.variantOffsets.get(e)}}compare(e,t){if(e.layer!==t.layer)return this.layerPositions[e.layer]-this.layerPositions[t.layer];if(e.parentLayer!==t.parentLayer)return this.layerPositions[e.parentLayer]-this.layerPositions[t.parentLayer];for(let i of e.options)for(let n of t.options){if(i.id!==n.id||!i.sort||!n.sort)continue;let s=Lh([i.variant,n.variant])??0n,a=~(s|s-1n),o=e.variants&a,l=t.variants&a;if(o!==l)continue;let c=i.sort({value:i.value,modifier:i.modifier},{value:n.value,modifier:n.modifier});if(c!==0)return c}return e.variants!==t.variants?e.variants-t.variants:e.parallelIndex!==t.parallelIndex?e.parallelIndex-t.parallelIndex:e.arbitrary!==t.arbitrary?e.arbitrary-t.arbitrary:e.propertyOffset!==t.propertyOffset?e.propertyOffset-t.propertyOffset:e.index-t.index}recalculateVariantOffsets(){let e=Array.from(this.variantOffsets.entries()).filter(([n])=>n.startsWith("[")).sort(([n],[s])=>$_(n,s)),t=e.map(([,n])=>n).sort((n,s)=>us(n-s));return e.map(([,n],s)=>[n,t[s]]).filter(([n,s])=>n!==s)}remapArbitraryVariantOffsets(eLine truncated
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nm=x((s6,Mm)=>{u();"use strict";var mE=hs(),{MAX_LENGTH:qm,CHAR_BACKSLASH:dl,CHAR_BACKTICK:gE,CHAR_COMMA:yE,CHAR_DOT:bE,CHAR_LEFT_PARENTHESES:wE,CHAR_RIGHT_PARENTHESES:vE,CHAR_LEFT_CURLY_BRACE:xE,CHAR_RIGHT_CURLY_BRACE:kE,CHAR_LEFT_SQUARE_BRACKET:$m,CHAR_RIGHT_SQUARE_BRACKET:Lm,CHAR_DOUBLE_QUOTE:SE,CHAR_SINGLE_QUOTE:AE,CHAR_NO_BREAK_SPACE:CE,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_E}=Dm(),EE=(r,e={})=>{if(typeof r!="string")throw new TypeError("Expected a string");let t=e||{},i=typeof t.maxLength=="number"?Math.min(qm,t.maxLength):qm;if(r.length>i)throw new SyntaxError(`Input length (${r.length}), exceeds max characters (${i})`);let n={type:"root",input:r,nodes:[]},s=[n],a=n,o=n,l=0,c=r.length,f=0,d=0,p,h=()=>r[f++],b=v=>{if(v.type==="text"&&o.type==="dot"&&(o.type="text"),o&&o.type==="text"&&v.type==="text"){o.value+=v.value;return}return a.nodes.push(v),v.parent=a,v.prev=o,o=v,v};for(b({type:"bos"});f<c;)if(a=s[s.length-1],p=h(),!(p===_E||p===CE)){if(p===dl){b({type:"text",value:(e.keepEscaping?p:"")+h()});continue}if(p===Lm){b({type:"text",value:"\\"+p});continue}if(p===$m){l++;let v;for(;f<c&&(v=h());){if(p+=v,v===$m){l++;continue}if(v===dl){p+=h();continue}if(v===Lm&&(l--,l===0))break}b({type:"text",value:p});continue}if(p===wE){a=b({type:"paren",nodes:[]}),s.push(a),b({type:"text",value:p});continue}if(p===vE){if(a.type!=="paren"){b({type:"text",value:p});continue}a=s.pop(),b({type:"text",value:p}),a=s[s.length-1];continue}if(p===SE||p===AE||p===gE){let v=p,y;for(e.keepQuotes!==!0&&(p="");f<c&&(y=h());){if(y===dl){p+=y+h();continue}if(y===v){e.keepQuotes===!0&&(p+=y);break}p+=y}b({type:"text",value:p});continue}if(p===xE){d++;let v=o.value&&o.value.slice(-1)==="$"||a.dollar===!0;a=b({type:"brace",open:!0,close:!1,dollar:v,depth:d,commas:0,ranges:0,nodes:[]}),s.push(a),b({type:"open",value:p});continue}if(p===kE){if(a.type!=="brace"){b({type:"text",value:p});continue}let v="close";a=s.pop(),a.close=!0,b({type:v,value:p}),d--,a=s[s.length-1];continue}if(p===yE&&d>0){if(a.ranges>0){a.ranges=0;let v=a.nodes.shift();a.nodes=[v,{type:"text",value:mE(a)}]}b({type:"comma",value:p}),a.commas++;continue}if(p===bE&&d>0&&a.commas===0){let v=a.nodes;if(d===0||v.length===0){b({type:"text",value:p});continue}if(o.type==="dot"){if(a.range=[],o.value+=p,o.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,o.type="text";continue}a.ranges++,a.args=[];continue}if(o.type==="range"){v.pop();let y=v[v.length-1];y.value+=o.value+p,o=y,a.ranges--;continue}b({type:"dot",value:p});continue}b({type:"text",value:p})}do if(a=s.pop(),a.type!=="root"){a.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let v=s[s.length-1],y=v.nodes.indexOf(a);v.nodes.splice(y,1,...a.nodes)}while(s.length>0);return b({type:"eos"}),n};Mm.exports=EE});var jm=x((a6,Fm)=>{u();"use strict";var Bm=hs(),OE=Om(),TE=Pm(),RE=Nm(),Le=(r,e={})=>{let t=[];if(Array.isArray(r))for(let i of r){let n=Le.create(i,e);Array.isArray(n)?t.push(...n):t.push(n)}else t=[].concat(Le.create(r,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Le.parse=(r,e={})=>RE(r,e);Le.stringify=(r,e={})=>typeof r=="string"?Bm(Le.parse(r,e),e):Bm(r,e);Le.compile=(r,e={})=>(typeof r=="string"&&(r=Le.parse(r,e)),OE(r,e));Le.expand=(r,e={})=>{typeof r=="string"&&(r=Le.parse(r,e));let t=TE(r,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Le.create=(r,e={})=>r===""||r.length<3?[r]:e.expand!==!0?Le.compile(r,e):Le.expand(r,e);Fm.exports=Le});var Di=x((o6,Wm)=>{u();"use strict";var PE=(et(),Ur),at="\\\\/",zm=`[^${at}]`,yt="\\.",IE="\\+",DE="\\?",ys="\\/",qE="(?=.)",Um="[^/]",hl=`(?:${ys}|$)`,Vm=`(?:^|${ys})`,ml=`${yt}{1,2}${hl}`,$E=`(?!${yt})`,LE=`(?!${Vm}${ml})`,ME=`(?!${yt}{0,1}${hl})`,NE=`(?!${ml})`,BE=`[^.${ys}]`,FE=`${Um}*?`,Hm={DOT_LITERAL:yt,PLUS_LITERAL:IE,QMARK_LITERAL:DE,SLASH_LITERAL:ys,ONE_CHAR:qE,QMARK:Um,END_ANCHOR:hl,DOTS_SLASH:ml,NO_DOT:$E,NO_DOTS:LE,NO_DOT_SLASH:ME,NO_DOTS_SLASH:NE,QMARK_NO_DOT:BE,STAR:FE,START_ANCHOR:Vm},jE={...Hm,SLASH_LITERAL:`[${at}]`,QMARK:zm,STAR:`${zm}*?`,DOTS_SLASH:`${yt}{1,2}(?:[${at}]|$)`,NO_DOT:`(?!${yt})`,NO_DOTS:`(?!(?:^|[${at}])${yt}{1,2}(?:[${at}]|$))`,NO_DOT_SLASH:`(?!${yt}{0,1}(?:[${at}]|$))`,NO_DOTS_SLASH:`(?!${yt}{1,2}(?:[${at}]|$))`,QMARK_NO_DOT:`[^.${at}]`,START_ANCHOR:`(?:^|[${at}])`,END_ANCHOR:`(?:[${at}]|$)`},zE={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_Line truncated
`))if(n=n.trim(),!i.has(n))if(i.add(n),Li.get(e).has(n))for(let s of Li.get(e).get(n))t.add(s);else{let s=e(n).filter(o=>o!=="!*"),a=new Set(s);for(let o of a)t.add(o);Li.get(e).set(n,a)}}function T2(r,e){let t=e.offsets.sort(r),i={base:new Set,defaults:new Set,components:new Set,utilities:new Set,variants:new Set};for(let[n,s]of t)i[n.layer].add(s);return i}function Pl(r){return async e=>{let t={base:null,components:null,utilities:null,variants:null};if(e.walkAtRules(y=>{y.name==="tailwind"&&Object.keys(t).includes(y.params)&&(t[y.params]=y)}),Object.values(t).every(y=>y===null))return e;let i=new Set([...r.candidates??[],gt]),n=new Set;bt.DEBUG&&console.time("Reading changed files");let s=[];for(let y of r.changedContent){let w=E2(r.tailwindConfig,y.extension),k=_2(r,y.extension);s.push([y,{transformer:w,extractor:k}])}let a=500;for(let y=0;y<s.length;y+=a){let w=s.slice(y,y+a);await Promise.all(w.map(async([{file:k,content:S},{transformer:E,extractor:T}])=>{S=k?await be.promises.readFile(k,"utf8"):S,O2(E(S),T,i,n)}))}bt.DEBUG&&console.timeEnd("Reading changed files");let o=r.classCache.size;bt.DEBUG&&console.time("Generate rules"),bt.DEBUG&&console.time("Sorting candidates");let l=new Set([...i].sort((y,w)=>y===w?0:y<w?-1:1));bt.DEBUG&&console.timeEnd("Sorting candidates"),as(l,r),bt.DEBUG&&console.timeEnd("Generate rules"),bt.DEBUG&&console.time("Build stylesheet"),(r.stylesheetCache===null||r.classCache.size!==o)&&(r.stylesheetCache=T2([...r.ruleCache],r)),bt.DEBUG&&console.timeEnd("Build stylesheet");let{defaults:c,base:f,components:d,utilities:p,variants:h}=r.stylesheetCache;t.base&&(t.base.before(Qt([...c,...f],t.base.source,{layer:"base"})),t.base.remove()),t.components&&(t.components.before(Qt([...d],t.components.source,{layer:"components"})),t.components.remove()),t.utilities&&(t.utilities.before(Qt([...p],t.utilities.source,{layer:"utilities"})),t.utilities.remove());let b=Array.from(h).filter(y=>{let w=y.raws.tailwind?.parentLayer;return w==="components"?t.components!==null:w==="utilities"?t.utilities!==null:!0});t.variants?(t.variants.before(Qt(b,t.variants.source,{layer:"variants"})),t.variants.remove()):b.length>0&&e.append(Qt(b,e.source,{layer:"variants"})),e.source.end=e.source.end??e.source.start;let v=b.some(y=>y.raws.tailwind?.parentLayer==="utilities");t.utilities&&p.size===0&&!v&&G.warn("content-problems",["No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.","https://tailwindcss.com/docs/content-configuration"]),bt.DEBUG&&(console.log("Potential classes: ",i.size),console.log("Active contexts: ",es.size)),r.changedContent=[],e.walkAtRules("layer",y=>{Object.keys(t).includes(y.params)&&y.remove()})}}var Lg,bt,Mg,Ng,Li,Bg=P(()=>{u();ft();Lg=pe(Fs());It();os();Be();Rg();$g();bt=Ze,Mg={DEFAULT:qg},Ng={DEFAULT:r=>r,svelte:r=>r.replace(/(?:^|\s)class:/g," ")};Li=new WeakMap});function xs(r){let e=new Map;ee.root({nodes:[r.clone()]}).walkRules(s=>{(0,vs.default)(a=>{a.walkClasses(o=>{let l=o.parent.toString(),c=e.get(l);c||e.set(l,c=new Set),c.add(o.value)})}).processSync(s.selector)});let i=Array.from(e.values(),s=>Array.from(s)),n=i.flat();return Object.assign(n,{groups:i})}function Il(r){return R2.astSync(r)}function Fg(r,e){let t=new Set;for(let i of r)t.add(i.split(e).pop());return Array.from(t)}function jg(r,e){let t=r.tailwindConfig.prefix;return typeof t=="function"?t(e):t+e}function*zg(r){for(yield r;r.parent;)yield r.parent,r=r.parent}function P2(r,e={}){let t=r.nodes;r.nodes=[];let i=r.clone(e);return r.nodes=t,i}function I2(r){for(let e of zg(r))if(r!==e){if(e.type==="root")break;r=P2(e,{nodes:[r]})}return r}function D2(r,e){let t=new Map;return r.walkRules(i=>{for(let a of zg(i))if(a.raws.tailwind?.layer!==void 0)return;let n=I2(i),s=e.offsets.create("user");for(let a of xs(i)){let o=t.get(a)||[];t.set(a,o),o.push([{layer:"user",sort:s,important:!1},n])}}),t}function q2(r,e){for(let t of r){if(e.notClassCache.has(t)||e.applyClassCache.has(t))continue;if(e.classCache.has(t)){e.applyClassCache.set(t,e.classCache.get(t).map(([n,s])=>[n,s.clone()]));continue}let i=Array.from(Yo(t,e));if(i.length===0){e.notClassCache.add(t);continue}e.applyClassCache.set(t,i)}return e.applyClassCache}function $2(r){let e=null;return{get:t=>(e=e||r(),e.get(t)),has:t=>(e=e||r(),e.has(t))}}function L2(r){return{get:e=>r.flatMap(t=>t.get(e)||[]),has:e=>r.some(t=>t.has(e))}}function Ug(r){let e=r.split(/[\s\t\n]+/g);return e[e.length-1]==="!important"?[e.slice(0,-1),!0]:[e,!1]}function Vg(r,e,t){let i=new Set,n=[];if(r.walkAtRules("apply",l=>{let[c]=Ug(l.params);for(let f of c)i.add(f);n.push(l)}),n.length===0)return;let s=L2([t,q2(i,e)]);function a(l,c,f){let d=Il(l),p=Il(c),b=Il(`.${Te(f)}`).nodes[0].nodes[0];return d.each(v=>{let y=new Set;p.each(w=>{let k=!1;w=w.clone(),w.walkClasses(S=>{S.value===b.value&&(k||(S.replaceWith(...v.nodes.map(E=>E.clone())),y.add(w),k=!0))})});for(let w of y){let k=[[]];for( Line truncated
`))});c.push([p,d,h])}}for(let[l,[c,f]]of o){let d=[];for(let[h,b,v]of c){let y=[h,...Fg([h],e.tailwindConfig.separator)];for(let[w,k]of v){let S=xs(l),E=xs(k);if(E=E.groups.filter(R=>R.some(F=>y.includes(F))).flat(),E=E.concat(Fg(E,e.tailwindConfig.separator)),S.some(R=>E.includes(R)))throw k.error(`You cannot \`@apply\` the \`${h}\` utility here because it creates a circular dependency.`);let B=ee.root({nodes:[k.clone()]});B.walk(R=>{R.source=f}),(k.type!=="atrule"||k.type==="atrule"&&k.name!=="keyframes")&&B.walkRules(R=>{if(!xs(R).some(U=>U===h)){R.remove();return}let F=typeof e.tailwindConfig.important=="string"?e.tailwindConfig.important:null,_=l.raws.tailwind!==void 0&&F&&l.selector.indexOf(F)===0?l.selector.slice(F.length):l.selector;_===""&&(_=l.selector),R.selector=a(_,R.selector,h),F&&_!==l.selector&&(R.selector=is(R.selector,F)),R.walkDecls(U=>{U.important=w.important||b});let Q=(0,vs.default)().astSync(R.selector);Q.each(U=>pr(U)),R.selector=Q.toString()}),!!B.nodes[0]&&d.push([w.sort,B.nodes[0]])}}let p=e.offsets.sort(d).map(h=>h[1]);l.after(p)}for(let l of n)l.parent.nodes.length>1?l.remove():l.parent.remove();Vg(r,e,t)}function Dl(r){return e=>{let t=$2(()=>D2(e,r));Vg(e,r,t)}}var vs,R2,Hg=P(()=>{u();Ot();vs=pe(it());os();fr();Wo();ts();R2=(0,vs.default)()});var Wg=x((nq,ks)=>{u();(function(){"use strict";function r(i,n,s){if(!i)return null;r.caseSensitive||(i=i.toLowerCase());var a=r.threshold===null?null:r.threshold*i.length,o=r.thresholdAbsolute,l;a!==null&&o!==null?l=Math.min(a,o):a!==null?l=a:o!==null?l=o:l=null;var c,f,d,p,h,b=n.length;for(h=0;h<b;h++)if(f=n[h],s&&(f=f[s]),!!f&&(r.caseSensitive?d=f:d=f.toLowerCase(),p=t(i,d,l),(l===null||p<l)&&(l=p,s&&r.returnWinningObject?c=n[h]:c=f,r.returnFirstMatch)))return c;return c||r.nullResultValue}r.threshold=.4,r.thresholdAbsolute=20,r.caseSensitive=!1,r.nullResultValue=null,r.returnWinningObject=null,r.returnFirstMatch=!1,typeof ks!="undefined"&&ks.exports?ks.exports=r:window.didYouMean=r;var e=Math.pow(2,32)-1;function t(i,n,s){s=s||s===0?s:e;var a=i.length,o=n.length;if(a===0)return Math.min(s+1,o);if(o===0)return Math.min(s+1,a);if(Math.abs(a-o)>s)return s+1;var l=[],c,f,d,p,h;for(c=0;c<=o;c++)l[c]=[c];for(f=0;f<=a;f++)l[0][f]=f;for(c=1;c<=o;c++){for(d=e,p=1,c>s&&(p=c-s),h=o+1,h>s+c&&(h=s+c),f=1;f<=a;f++)f<p||f>h?l[c][f]=s+1:n.charAt(c-1)===i.charAt(f-1)?l[c][f]=l[c-1][f-1]:l[c][f]=Math.min(l[c-1][f-1]+1,Math.min(l[c][f-1]+1,l[c-1][f]+1)),l[c][f]<d&&(d=l[c][f]);if(d>s)return s+1}return l[o][a]}})()});var Qg=x((sq,Gg)=>{u();var ql="(".charCodeAt(0),$l=")".charCodeAt(0),Ss="'".charCodeAt(0),Ll='"'.charCodeAt(0),Ml="\\".charCodeAt(0),yr="/".charCodeAt(0),Nl=",".charCodeAt(0),Bl=":".charCodeAt(0),As="*".charCodeAt(0),M2="u".charCodeAt(0),N2="U".charCodeAt(0),B2="+".charCodeAt(0),F2=/^[a-f0-9?-]+$/i;Gg.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d<h;)if(p<=32){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);a=t.slice(d,i),s=e[e.length-1],p===$l&&v?S=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):p===Nl||p===Bl||p===yr&&t.charCodeAt(i+1)!==As&&(!y||y&&y.type==="function"&&!1)?k=a:e.push({type:"space",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}else if(p===Ss||p===Ll){i=d,n=p===Ss?"'":'"',a={type:"string",sourceIndex:d,quote:n};do if(o=!1,i=t.indexOf(n,i+1),~i)for(l=i;t.charCodeAt(l-1)===Ml;)l-=1,o=!o;else t+=n,i=t.length-1,a.unclosed=!0;while(o);a.value=t.slice(d+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),d=i+1,p=t.charCodeAt(d)}else if(p===yr&&t.charCodeAt(d+1)===As)i=t.indexOf("*/",d),a={type:"comment",sourceIndex:d,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=t.length,a.sourceEndIndex=i),a.value=t.slice(d+2,i),e.push(a),d=i+2,p=t.charCodeAt(d);else if((p===yr||p===As)&&y&&y.type==="function")a=t[d],e.push({type:"word",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a}),d+=1,p=t.charCodeAt(d);else if(p===yr||p===Nl||p===Bl)a=t[d],e.push({type:"div",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a,before:k,after:""}),k="",d+=1,p=t.charCodeAt(d);else if(ql===p){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);if(f=d,a={type:"function",sourceIndex:d-w.length,value:w,before:t.slice(f+1,i)},d=i,w==="url"&&p!==Ss&&p!==Ll){i-=1;do if(o=!1,i=t.indexOf(")",i+1),~i)for(l=i;t.charCodeAt(l-1)===Ml;)l-=1,o=!o;else t+=")",i=t.length-1,a.unclosed=!0;while(o);c=i;do c-=1,p=t.charCodeAt(c);while(p<=32);f<c?(d!==c+1?a.nodes=[{type:"word",sourceIndex:d,sourceEndIndex:c+1,value:t.slice(d,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:t.slice(c+1,i)})):(a.after=t.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),d=i+1,a.sourceEndIndex=a.unclosed?i:d,p=t.charCodeAt(d),e.push(a)}else v+=1,a.after="",a.sourceEndIndex=d+1,e.push(a),b.push(a),e=a.nodes=[],y=a;w=""}else if($l===p&&v)d+=1,p=t.charCodeAt(d),y.after=S,y.sourceEndIndex+=S.length,S="",v-=1,b[b.length-1].sourceEndIndex=d,b.pop(),y=bLine truncated
`),console.time("JIT TOTAL"),t},async function(t,i){e=ky(t,i)??e;let n=El(e);if(t.type==="document"){let s=t.nodes.filter(a=>a.type==="root");for(let a of s)a.type==="root"&&await Ts(n)(a,i);return}await Ts(n)(t,i)},Ze.DEBUG&&function(t){return console.timeEnd("JIT TOTAL"),console.log(`
`),t}].filter(Boolean)}};Ql.exports.postcss=!0});var _y=x((Gq,Cy)=>{u();Cy.exports=Ay()});var Yl=x((Qq,Ey)=>{u();Ey.exports=()=>["and_chr 114","and_uc 15.5","chrome 114","chrome 113","chrome 109","edge 114","firefox 114","ios_saf 16.5","ios_saf 16.4","ios_saf 16.3","ios_saf 16.1","opera 99","safari 16.5","samsung 21"]});var Rs={};Ge(Rs,{agents:()=>nO,feature:()=>sO});function sO(){return{status:"cr",title:"CSS Feature Queries",stats:{ie:{"6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","5.5":"n"},edge:{"12":"y","13":"y","14":"y","15":"y","16":"y","17":"y","18":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y"},firefox:{"2":"n","3":"n","4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y","3.5":"n","3.6":"n"},chrome:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"n","23":"n","24":"n","25":"n","26":"n","27":"n","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y"},safari:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"y","10":"y","11":"y","12":"y","13":"y","14":"y","15":"y","17":"y","9.1":"y","10.1":"y","11.1":"y","12.1":"y","13.1":"y","14.1":"y","15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y",TP:"y","3.1":"n","3.2":"n","5.1":"n","6.1":"n","7.1":"n"},opera:{"9":"n","11":"n","12":"n","15":"y","16":"y","17":"y","18":"y","19":"y","20":"y","21":"y","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","60":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","12.1":"y","9.5-9.6":"n","10.0-10.1":"n","10.5":"n","10.6":"n","11.1":"n","11.5":"n","11.6":"n"},ios_saf:{"8":"n","17":"y","9.0-9.2":"y","9.3":"y","10.0-10.2":"y","10.3":"y","11.0-11.2":"y","11.3-11.4":"y","12.0-12.1":"y","12.2-12.5":"y","13.0-13.1":"y","13.2":"y","13.3":"y","13.4-13.7":"y","14.0-14.4":"y","14.5-14.8":"y","15.0-15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y","3.2":"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0-7.1":"n","8.1-8.4":"n"},op_mini:{all:"y"},android:{"3":"n","4":"n","114":"y","4.4":"y","4.4.3-4.4.4":"y","2.1":"n","2.2":"n","2.3":"n","4.1":"n","4.2-4.3":"n"},bb:{"7":"n","10":"n"},op_mob:{"10":"n","11":"n","12":"n","73":"y","11.1":"n","11.5":"n","12.1":"n"},and_chr: Line truncated
`)),e._autoprefixerCascade}maxPrefixed(e,t){if(t._autoprefixerMax)return t._autoprefixerMax;let i=0;for(let n of e)n=$y.removeNote(n),n.length>i&&(i=n.length);return t._autoprefixerMax=i,t._autoprefixerMax}calcBefore(e,t,i=""){let s=this.maxPrefixed(e,t)-$y.removeNote(i).length,a=t.raw("before");return s>0&&(a+=Array(s).fill(" ").join("")),a}restoreBefore(e){let t=e.raw("before").split(`
`),i=t[t.length-1];this.all.group(e).up(n=>{let s=n.raw("before").split(`
`),a=s[s.length-1];a.length<i.length&&(i=a)}),t[t.length-1]=i,e.raws.before=t.join(`
`)}insert(e,t,i){let n=this.set(this.clone(e),t);if(!(!n||e.parent.some(a=>a.prop===n.prop&&a.value===n.value)))return this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,n)}isAlready(e,t){let i=this.all.group(e).up(n=>n.prop===t);return i||(i=this.all.group(e).down(n=>n.prop===t)),i}add(e,t,i,n){let s=this.prefixed(e.prop,t);if(!(this.isAlready(e,s)||this.otherPrefixes(e.value,t)))return this.insert(e,t,i,n)}process(e,t){if(!this.needCascade(e)){super.process(e,t);return}let i=super.process(e,t);!i||!i.length||(this.restoreBefore(e),e.raws.before=this.calcBefore(i,e))}old(e,t){return[this.prefixed(e,t)]}};My.exports=Ly});var By=x((r$,Ny)=>{u();Ny.exports=function r(e){return{mul:t=>new r(e*t),div:t=>new r(e/t),simplify:()=>new r(e),toString:()=>e.toString()}}});var zy=x((i$,jy)=>{u();var pO=By(),dO=wr(),Zl=_e(),hO=/(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpcm|dpi|x)/gi,mO=/(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpcm|dpi|x)/i,Fy=class extends dO{prefixName(e,t){return e==="-moz-"?t+"--moz-device-pixel-ratio":e+t+"-device-pixel-ratio"}prefixQuery(e,t,i,n,s){return n=new pO(n),s==="dpi"?n=n.div(96):s==="dpcm"&&(n=n.mul(2.54).div(96)),n=n.simplify(),e==="-o-"&&(n=n.n+"/"+n.d),this.prefixName(e,t)+i+n}clean(e){if(!this.bad){this.bad=[];for(let t of this.prefixes)this.bad.push(this.prefixName(t,"min")),this.bad.push(this.prefixName(t,"max"))}e.params=Zl.editList(e.params,t=>t.filter(i=>this.bad.every(n=>!i.includes(n))))}process(e){let t=this.parentPrefix(e),i=t?[t]:this.prefixes;e.params=Zl.editList(e.params,(n,s)=>{for(let a of n){if(!a.includes("min-resolution")&&!a.includes("max-resolution")){s.push(a);continue}for(let o of i){let l=a.replace(hO,c=>{let f=c.match(mO);return this.prefixQuery(o,f[1],f[2],f[3],f[4])});s.push(l)}s.push(a)}return Zl.uniq(s)})}};jy.exports=Fy});var Vy=x((n$,Uy)=>{u();var Jl="(".charCodeAt(0),eu=")".charCodeAt(0),Ds="'".charCodeAt(0),tu='"'.charCodeAt(0),ru="\\".charCodeAt(0),vr="/".charCodeAt(0),iu=",".charCodeAt(0),nu=":".charCodeAt(0),qs="*".charCodeAt(0),gO="u".charCodeAt(0),yO="U".charCodeAt(0),bO="+".charCodeAt(0),wO=/^[a-f0-9?-]+$/i;Uy.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d<h;)if(p<=32){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);a=t.slice(d,i),s=e[e.length-1],p===eu&&v?S=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):p===iu||p===nu||p===vr&&t.charCodeAt(i+1)!==qs&&(!y||y&&y.type==="function"&&y.value!=="calc")?k=a:e.push({type:"space",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}else if(p===Ds||p===tu){i=d,n=p===Ds?"'":'"',a={type:"string",sourceIndex:d,quote:n};do if(o=!1,i=t.indexOf(n,i+1),~i)for(l=i;t.charCodeAt(l-1)===ru;)l-=1,o=!o;else t+=n,i=t.length-1,a.unclosed=!0;while(o);a.value=t.slice(d+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),d=i+1,p=t.charCodeAt(d)}else if(p===vr&&t.charCodeAt(d+1)===qs)i=t.indexOf("*/",d),a={type:"comment",sourceIndex:d,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=t.length,a.sourceEndIndex=i),a.value=t.slice(d+2,i),e.push(a),d=i+2,p=t.charCodeAt(d);else if((p===vr||p===qs)&&y&&y.type==="function"&&y.value==="calc")a=t[d],e.push({type:"word",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a}),d+=1,p=t.charCodeAt(d);else if(p===vr||p===iu||p===nu)a=t[d],e.push({type:"div",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a,before:k,after:""}),k="",d+=1,p=t.charCodeAt(d);else if(Jl===p){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);if(f=d,a={type:"function",sourceIndex:d-w.length,value:w,before:t.slice(f+1,i)},d=i,w==="url"&&p!==Ds&&p!==tu){i-=1;do if(o=!1,i=t.indexOf(")",i+1),~i)for(l=i;t.charCodeAt(l-1)===ru;)l-=1,o=!o;else t+=")",i=t.length-1,a.unclosed=!0;while(o);c=i;do c-=1,p=t.charCodeAt(c);while(p<=32);f<c?(d!==c+1?a.nodes=[{type:"word",sourceIndex:d,sourceEndIndex:c+1,value:t.slice(d,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:t.slice(c+1,i)})):(a.after=t.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),d=i+1,a.sourceEndIndex=a.unclosed?i:d,p=t.charCodeAt(d),e.push(a)}else v+=1,a.after="",a.sourceEndIndex=d+1,e.push(a),b.push(a),e=a.nodes=[],y=a;w=""}else if(eu===p&&v)d+=1,p=t.charCodeAt(d),y.after=S,y.sourceEndIndex+=S.length,S="",v-=1,b[b.length-1].sourceEndIndex=d,b.pop(),y=b[v],e=y.nodes;else{i=d;do p===ru&&(i+=1),i+=1,p=t.charCodeAt(i);while(i<h&&!(p<=32||p===Ds||p===tu||p===iu||p===nu||p===vr||p===Jl||p===qs&&y&&y.type==="function"&&y.value==="calc"||p===vr&&y.type==="function"&&y.value==="calc"||p===eu&&v));a=t.slice(d,i),Jl===p?w=a:(gO===a.charCodeAt(0)||yO===a.charCodeAt(0))&&bO===a.charCodeAt(1)&&wO.test(a.slice(2))?e.push({type:"unicode-range",sourceIndex:d,sourceEndIndex:i,value:a}):e.push({type:"word",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}for(d=b.length-1;d;d-=1)b[d].unclosed=!0,b[d].sourceEndIndex=t.length;return b[0].nodes}});var Wy=x((s$,Hy)=>{u();Hy.exports=function r(e,t,i){var n,s Line truncated
`)&&this.reduceSpaces(n),a.removeChild(s);return}}for(let l of this.prefixes.values("remove",o)){if(!l.check||!l.check(n.value))continue;if(o=l.unprefixed,this.prefixes.group(n).down(f=>f.value.includes(o))){a.removeChild(s);return}}})}withHackValue(e){return e.prop==="-webkit-background-clip"&&e.value==="text"}disabledValue(e,t){return this.gridStatus(e,t)===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("grid")||this.prefixes.options.flexbox===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("flex")||e.type==="decl"&&e.prop==="content"?!0:this.disabled(e,t)}disabledDecl(e,t){if(this.gridStatus(e,t)===!1&&e.type==="decl"&&(e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.prefixes.options.flexbox===!1&&e.type==="decl"){let i=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||i.includes(e.prop))return!0}return this.disabled(e,t)}disabled(e,t){if(!e)return!1;if(e._autoprefixerDisabled!==void 0)return e._autoprefixerDisabled;if(e.parent){let n=e.prev();if(n&&n.type==="comment"&&$O.test(n.text))return e._autoprefixerDisabled=!0,e._autoprefixerSelfDisabled=!0,!0}let i=null;if(e.nodes){let n;e.each(s=>{s.type==="comment"&&/(!\s*)?autoprefixer:\s*(off|on)/i.test(s.text)&&(typeof n!="undefined"?t.warn("Second Autoprefixer control comment was ignored. Autoprefixer applies control comment to whole block, not to next rules.",{node:s}):n=/on/i.test(s.text))}),n!==void 0&&(i=!n)}if(!e.nodes||i===null)if(e.parent){let n=this.disabled(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else i=!1;return e._autoprefixerDisabled=i,i}reduceSpaces(e){let t=!1;if(this.prefixes.group(e).up(()=>(t=!0,!0)),t)return;let i=e.raw("before").split(`
`),n=i[i.length-1].length,s=!1;this.prefixes.group(e).down(a=>{i=a.raw("before").split(`
`);let o=i.length-1;i[o].length>n&&(s===!1&&(s=i[o].length-n),i[o]=i[o].slice(0,-s),a.raws.before=i.join(`
`))})}displayType(e){for(let t of e.parent.nodes)if(t.prop==="display"){if(t.value.includes("flex"))return"flex";if(t.value.includes("grid"))return"grid"}return!1}gridStatus(e,t){if(!e)return!1;if(e._autoprefixerGridStatus!==void 0)return e._autoprefixerGridStatus;let i=null;if(e.nodes){let n;e.each(s=>{if(s.type==="comment"&&LO.test(s.text)){let a=/:\s*autoplace/i.test(s.text),o=/no-autoplace/i.test(s.text);typeof n!="undefined"?t.warn("Second Autoprefixer grid control comment was ignored. Autoprefixer applies control comments to the whole block, not to the next rules.",{node:s}):a?n="autoplace":o?n=!0:n=/on/i.test(s.text)}}),n!==void 0&&(i=n)}if(e.type==="atrule"&&e.name==="supports"){let n=e.params;n.includes("grid")&&n.includes("auto")&&(i=!1)}if(!e.nodes||i===null)if(e.parent){let n=this.gridStatus(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else typeof this.prefixes.options.grid!="undefined"?i=this.prefixes.options.grid:typeof m.env.AUTOPREFIXER_GRID!="undefined"?m.env.AUTOPREFIXER_GRID==="autoplace"?i="autoplace":i=!0:i=!1;return e._autoprefixerGridStatus=i,i}};hb.exports=db});var gb=x((h$,mb)=>{u();mb.exports={A:{A:{"2":"K E F G A B JC"},B:{"1":"C L M H N D O P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I"},C:{"1":"2 3 4 5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 KC zB J K E F G A B C L M H N D O k l LC MC"},D:{"1":"8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 2 3 4 5 6 7 J K E F G A B C L M H N D O k l"},E:{"1":"G A B C L M H D RC 6B vB wB 7B SC TC 8B 9B xB AC yB BC CC DC EC FC GC UC","2":"0 J K E F NC 5B OC PC QC"},F:{"1":"1 2 3 4 5 6 7 8 9 H N D O k l AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j wB","2":"G B C VC WC XC YC vB HC ZC"},G:{"1":"D fC gC hC iC jC kC lC mC nC oC pC qC rC sC tC 8B 9B xB AC yB BC CC DC EC FC GC","2":"F 5B aC IC bC cC dC eC"},H:{"1":"uC"},I:{"1":"I zC 0C","2":"zB J vC wC xC yC IC"},J:{"2":"E A"},K:{"1":"m","2":"A B C vB HC wB"},L:{"1":"I"},M:{"1":"uB"},N:{"2":"A B"},O:{"1":"xB"},P:{"1":"J k l 1C 2C 3C 4C 5C 6B 6C 7C 8C 9C AD yB BD CD DD"},Q:{"1":"7B"},R:{"1":"ED"},S:{"1":"FD GD"}},B:4,C:"CSS Feature Queries"}});var vb=x((m$,wb)=>{u();function yb(r){return r[r.length-1]}var bb={parse(r){let e=[""],t=[e];for(let i of r){if(i==="("){e=[""],yb(t).push(e),t.push(e);continue}if(i===")"){t.pop(),e=yb(t),e.push("");continue}e[e.length-1]+=i}return t[0]},stringify(r){let e="";for(let t of r){if(typeof t=="object"){e+=`(${bb.stringify(t)})`;continue}e+=t}return e}};wb.exports=bb});var Cb=x((g$,Ab)=>{u();var BO=gb(),{feature:FO}=(Ps(),Rs),{parse:jO}=$e(),zO=Mt(),lu=vb(),UO=He(),VO=_e(),xb=FO(BO),kb=[];for(let r in xb.stats){let e=xb.stats[r];for(let t in e){let i=e[t];/y/.test(i)&&kb.push(r+" "+t)}}var Sb=class{constructor(e,t){this.Prefixes=e,this.all=t}prefixer(){if(this.prefixerCache)return this.prefixerCache;let e=this.all.browsers.selected.filter(i=>kb.includes(i)),t=new zO(this.all.browsers.data,e,this.all.options);return this.prefixerCache=new this.Prefixes(this.all.data,t,this.all.options),this.prefixerCache}parse(e){let t=e.split(":"),i=t[0],n=t[1];return n||(n=""),[i.trim(),n.trim()]}virtual(e){let[t,i]=this.parse(e),n=jO("a{}").first;return n.append({prop:t,value:i,raws:{before:""}}),n}prefixed(e){let t=this.virtual(e);if(this.disabled(t.first))return t.nodes;let i={warn:()=>null},n=this.prefixer().add[t.first.prop];n&&n.process&&n.process(t.first,i);for(let s of t.nodes){for(let a of this.prefixer().values("add",t.first.prop))a.process(s);UO.save(this.all,s)}return t.nodes}isNot(e){return typeof e=="string"&&/not\s*/i.test(e)}isOr(e){return typeof e=="string"&&/\s*or\s*/i.test(e)}isProp(e){return typeof e=="object"&&e.length===1&&typeof e[0]=="string"}isHack(e,t){return!new RegExp(`(\\(|\\s)${VO.escapeRegexp(t)}:`).test(e)}toRemove(e,t){let[i,n]=this.parse(e),s=this.all.unprefixed(i),a=this.all.cleaner();if(a.remove[i]&&a.remove[i].remove&&!this.isHack(t,s))return!0;for(let o of a.values("remove",s))if(o.check(n))return!0;return!1}remove(e,t){let i=0;for(;i<e.length;){if(!this.isNot(e[i-1])&&this.isProp(e[i])&&this.isOr(e[i+1])){if(this.toRemove(e[i][0],t)){e.splice(i,2);continue}i+=2;continue}typeof e[i]=="object"&&(e[i]=this.remove(e[i],t)),i+=1}return e}cleanBrackets(e){return e.map(t=>typeof t!="object"?t:t.length===1&&typeof t[0]=="object"?this.cleanBrackets(t[0]):this.cleanBrackets(t))}convert(e){let t=[""];for(let i of e)t.push([`${i.prop}: ${i.value}`]),t.push(" or ");return t[t.length-1]="",t}n Line truncated
Replace Autoprefixer \`browsers\` option to Browserslist config.
Use \`browserslist\` key in \`package.json\` or \`.browserslistrc\` file.
Using \`browsers\` option can cause errors. Browserslist config can
be used for Babel, Autoprefixer, postcss-normalize and other tools.
If you really need to use option, rename it to \`overrideBrowserslist\`.
Learn more at:
https://github.com/browserslist/browserslist#readme
https://twitter.com/browserslist
`;function V5(r){return Object.prototype.toString.apply(r)==="[object Object]"}var lf=new Map;function H5(r,e){e.browsers.selected.length!==0&&(e.add.selectors.length>0||Object.keys(e.add).length>2||r.warn(`Autoprefixer target browsers do not need any prefixes.You do not need Autoprefixer anymore.
Check your Browserslist config to be sure that your targets are set up correctly.
Learn more at:
https://github.com/postcss/autoprefixer#readme
https://github.com/browserslist/browserslist#readme
`))}gv.exports=Dr;function Dr(...r){let e;if(r.length===1&&V5(r[0])?(e=r[0],r=void 0):r.length===0||r.length===1&&!r[0]?r=void 0:r.length<=2&&(Array.isArray(r[0])||!r[0])?(e=r[1],r=r[0]):typeof r[r.length-1]=="object"&&(e=r.pop()),e||(e={}),e.browser)throw new Error("Change `browser` option to `overrideBrowserslist` in Autoprefixer");if(e.browserslist)throw new Error("Change `browserslist` option to `overrideBrowserslist` in Autoprefixer");e.overrideBrowserslist?r=e.overrideBrowserslist:e.browsers&&(typeof console!="undefined"&&console.warn&&(of.red?console.warn(of.red(mv.replace(/`[^`]+`/g,n=>of.yellow(n.slice(1,-1))))):console.warn(mv)),r=e.browsers);let t={ignoreUnknownVersions:e.ignoreUnknownVersions,stats:e.stats,env:e.env};function i(n){let s=hv,a=new F5(s.browsers,r,n,t),o=a.selected.join(", ")+JSON.stringify(e);return lf.has(o)||lf.set(o,new j5(s.prefixes,a,e)),lf.get(o)}return{postcssPlugin:"autoprefixer",prepare(n){let s=i({from:n.opts.from,env:e.env});return{OnceExit(a){H5(n,s),e.remove!==!1&&s.processor.remove(a,n),e.add!==!1&&s.processor.add(a,n)}}},info(n){return n=n||{},n.from=n.from||m.cwd(),U5(i(n))},options:e,browsers:r}}Dr.postcss=!0;Dr.data=hv;Dr.defaults=N5.defaults;Dr.info=()=>Dr().info()});var bv={};Ge(bv,{default:()=>W5});var W5,wv=P(()=>{u();W5=[]});var xv={};Ge(xv,{default:()=>G5});var vv,G5,kv=P(()=>{u();Xi();vv=pe(rn()),G5=St(vv.default.theme)});var Av={};Ge(Av,{default:()=>Q5});var Sv,Q5,Cv=P(()=>{u();Xi();Sv=pe(rn()),Q5=St(Sv.default)});u();"use strict";var Y5=vt(_y()),K5=vt($e()),X5=vt(yv()),Z5=vt((wv(),bv)),J5=vt((kv(),xv)),eP=vt((Cv(),Av)),tP=vt((Vs(),_f)),rP=vt((al(),sl)),iP=vt((sa(),sc));function vt(r){return r&&r.__esModule?r:{default:r}}console.warn("cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation");var Ns="tailwind",uf="text/tailwindcss",_v="/template.html",Yt,Ev=!0,Ov=0,ff=new Set,cf,Tv="",Rv=(r=!1)=>({get(e,t){return(!r||t==="config")&&typeof e[t]=="object"&&e[t]!==null?new Proxy(e[t],Rv()):e[t]},set(e,t,i){return e[t]=i,(!r||t==="config")&&pf(!0),!0}});window[Ns]=new Proxy({config:{},defaultTheme:J5.default,defaultConfig:eP.default,colors:tP.default,plugin:rP.default,resolveConfig:iP.default},Rv(!0));function Pv(r){cf.observe(r,{attributes:!0,attributeFilter:["type"],characterData:!0,subtree:!0,childList:!0})}new MutationObserver(async r=>{let e=!1;if(!cf){cf=new MutationObserver(async()=>await pf(!0));for(let t of document.querySelectorAll(`style[type="${uf}"]`))Pv(t)}for(let t of r)for(let i of t.addedNodes)i.nodeType===1&&i.tagName==="STYLE"&&i.getAttribute("type")===uf&&(Pv(i),e=!0);await pf(e)}).observe(document.documentElement,{attributes:!0,attributeFilter:["class"],childList:!0,subtree:!0});async function pf(r=!1){r&&(Ov++,ff.clear());let e="";for(let i of document.querySelectorAll(`style[type="${uf}"]`))e+=i.textContent;let t=new Set;for(let i of document.querySelectorAll("[class]"))for(let n of i.classList)ff.has(n)||t.add(n);if(document.body&&(Ev||t.size>0||e!==Tv||!Yt||!Yt.isConnected)){for(let n of t)ff.add(n);Ev=!1,Tv=e,self[_v]=Array.from(t).join(" ");let{css:i}=await(0,K5.default)([(0,Y5.default)({...window[Ns].config,_hash:Ov,content:{files:[_v],extract:{html:n=>n.split(" ")}},plugins:[...Z5.default,...Array.isArray(window[Ns].config.plugins)?window[Ns].config.plugins:[]]}),(0,X5.default)({remove:!1})]).process(`@tailwind base;@tailwind components;@tailwind utilities;${e}`);(!Yt||!Yt.isConnected)&&(Yt=document.createElement("style"),document.head.append(Yt)),Yt.textContent=i}}})();
/*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Licensed under the MIT License.
*/
/*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Released under the MIT License.
*/
/*!
* to-regex-range <https://github.com/micromatch/to-regex-range>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*/
/*! https://mths.be/cssesc v3.0.0 by @mathias */
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-409
View File
@@ -1,409 +0,0 @@
# -*- coding: utf-8 -*-
"""
Generate professional, lightweight pediatric care demonstration videos (MP4)
with animated steps, typography, badges, progress bars and audio.
"""
import os
import sys
import subprocess
import tempfile
import math
from PIL import Image, ImageDraw, ImageFont
VIDEOS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../public/videos'))
os.makedirs(VIDEOS_DIR, exist_ok=True)
FONT_PATH = "C:\\Windows\\Fonts\\msyh.ttc"
if not os.path.exists(FONT_PATH):
FONT_PATH = "C:\\Windows\\Fonts\\simhei.ttf"
def get_font(size, bold=False):
try:
return ImageFont.truetype(FONT_PATH, size)
except:
return ImageFont.load_default()
GUIDE_SCRIPTS = [
{
'id': 'guide-bottle',
'title': '45°防胀气瓶喂姿势与拍嗝衔接',
'badge': '🍼 喂养护理指南',
'theme_color': (245, 158, 11), # Amber
'accent_color': (217, 119, 6),
'bg_gradient': [(30, 24, 16), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '手腕内侧测试奶温',
'detail': '冲调后滴在手腕内侧感受温热不烫\n儿科推荐最佳温度:37℃ ~ 40℃\n切勿直接给宝宝喂过烫奶水',
'icon': '🌡️',
'tip': '💡 提示:温度过高易烫伤口腔,过低易引起肠绞痛'
},
{
'step': '第 2 步 / 共 4 步',
'action': '45° 半坐卧位抱姿',
'detail': '一手托稳宝宝颈背,身体抬高约 45°\n头部略高于胃部,保持气道畅通\n严禁完全平躺仰卧喝奶,防止呛咳',
'icon': '👶',
'tip': '⚠️ 警示:平躺喝奶极易逆流进入中耳引发中耳炎'
},
{
'step': '第 3 步 / 共 4 步',
'action': '奶瓶保持 45° 倾角',
'detail': '轻触宝宝下唇诱导自然张大嘴\n瓶身倾斜 45°,奶嘴前部必须充满奶水\n避免残留气泡被婴儿吞咽入胃',
'icon': '🍼',
'tip': '💡 技巧:吸吮过程中注意奶嘴不要被压扁'
},
{
'step': '第 4 步 / 共 4 步',
'action': 'Paced Feeding 节奏喂养与拍嗝',
'detail': '每喝 30~50ml 稍稍倾立奶瓶放慢节奏\n让宝宝自主吞咽并换气\n喝完后立即竖抱,空心掌自下而上轻柔拍嗝',
'icon': '✨',
'tip': '✅ 标准:拍出 1~2 声响嗝,防止吐奶与腹胀'
}
]
},
{
'id': 'guide-breastfeed',
'title': '新生儿深吸含乳技巧与姿势调整',
'badge': '🤱 母乳亲喂指导',
'theme_color': (236, 72, 153), # Pink
'accent_color': (219, 39, 119),
'bg_gradient': [(38, 18, 30), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '妈妈身体放松与支撑',
'detail': '背后手臂垫好哺乳枕,肩颈放松不耸肩\n把宝宝贴近乳房,切忌大人弯腰去凑宝宝\n母婴腹部贴腹部,身体呈一直线',
'icon': '🪑',
'tip': '💡 要点:妈妈姿势舒适才能持久不疲劳'
},
{
'step': '第 2 步 / 共 4 步',
'action': '乳头轻触人中引导张大嘴',
'detail': '让乳头轻触宝宝人中或上嘴唇\n等待宝宝像打哈欠一样充分张大嘴巴\n切勿在宝宝嘴半张时强行塞入',
'icon': '👄',
'tip': '💡 秘诀:宝宝嘴张至 130°~140° 为最佳含乳时机'
},
{
'step': '第 3 步 / 共 4 步',
'action': '下巴先贴紧,深含大部分下乳晕',
'detail': '迅速将宝宝贴近乳房,下颌先抵住乳房\n下唇深含大部分下乳晕,上唇含少部分\n上下唇呈外翻的“小花”喇叭状',
'icon': '🤱',
'tip': '⚠️ 警示:只咬乳头会造成严重皲裂剧痛且吃不到奶'
},
{
'step': '第 4 步 / 共 4 步',
'action': '确认有效吞咽与安全退奶',
'detail': '观察面颊圆润不内凹,有缓慢吞咽声\n若需中断喂养,用小指探入口角解开负压\n切不可生拉硬拽拉出乳头',
'icon': '✅',
'tip': '💡 达标:每次亲喂 15~20 分钟后宝宝满足松口'
}
]
},
{
'id': 'guide-burping',
'title': '空心掌正确手法与端坐/过肩拍嗝实操',
'badge': '💨 拍嗝防胀气指南',
'theme_color': (16, 185, 129), # Emerald
'accent_color': (5, 150, 105),
'bg_gradient': [(16, 35, 28), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '正确手型:弯曲成“空心掌”',
'detail': '五指并拢,掌心微弯微拱呈空杯状\n拍击时形成空气气垫减震缓冲\n发出“嘭嘭”沉闷空心声,切勿用实心巴掌!',
'icon': '✋',
'tip': '⚠️ 警示:实心巴掌拍击会震伤婴儿内脏与脊椎!'
},
{
'step': '第 2 步 / 共 4 步',
'action': '端坐式拍嗝法(适合低月龄)',
'detail': '一手虎口稳托宝宝下巴与前胸\n让宝宝身体稍稍前倾坐于大人腿上\n另一手空心掌自背下方向上规律轻叩',
'icon': '🪑',
'tip': '💡 技巧:手腕放松发力,自腰部往颈肩单向叩打'
},
{
'step': '第 3 步 / 共 4 步',
'action': '竖抱过肩式拍嗝法',
'detail': '宝宝竖抱,下巴轻轻靠在大人肩窝软肉处\n大人肩头提前垫好防吐奶口水巾\n空心掌轻柔由下至上拍打宝宝背部中心',
'icon': '🤱',
'tip': '💡 建议:拍打 5~8 分钟直到听到响亮饱嗝'
},
{
'step': '第 4 步 / 共 4 步',
'action': '拍不出嗝时的应对:竖抱与飞机抱',
'detail': '若 10 分钟未拍出嗝,可保持竖抱 15 分钟\n利用重力气体自然上浮排出\n易胀气宝宝可配合飞机抱托腹轻摇排气',
'icon': '✈️',
'tip': '✅ 提示:拍嗝完毕放下时建议头颈稍高右侧卧'
}
]
},
{
'id': 'guide-diaper',
'title': '防红屁屁换尿布全流程与温水冲洗法',
'badge': '💧 换尿布护臀要领',
'theme_color': (14, 165, 233), # Sky Blue
'accent_color': (2, 132, 199),
'bg_gradient': [(15, 30, 45), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '轻托臀部,严禁倒提双腿',
'detail': '一手托住婴儿臀部下方或大腿腹部轻抬\n严禁双手倒提脚踝悬空小腿!\n避免拉扯娇嫩髋关节造成发育性脱位',
'icon': '🤲',
'tip': '⚠️ 警示:绝对不要用力倒吊婴儿双腿换尿布'
},
{
'step': '第 2 步 / 共 4 步',
'action': '温水冲洗,由前往后单向清洁',
'detail': '大便后优先用 37℃ 温水冲洗臀部\n用棉柔巾“由前往后”单向轻柔拭净\n切勿来回打圈擦抹,尤其女宝必须防逆行感染',
'icon': '🚿',
'tip': '💡 要点:避免湿纸巾反复用力摩擦脆弱表皮'
},
{
'step': '第 3 步 / 共 4 步',
'action': '充分蘸干与空气晾臀 1~2 分钟',
'detail': '用干柔巾轻轻按压吸干皮肤水分,勿大力摩擦\n让小屁屁在空气中自然晾干 1~2 分钟\n保持皮肤彻底干爽是预防红臀最关键一步',
'icon': '🌬️',
'tip': '💡 秘诀:皮肤未干就穿尿布极易潮湿焖出湿疹'
},
{
'step': '第 4 步 / 共 4 步',
'action': '厚涂护臀膏隔离与松紧度调节',
'detail': '在肛周及腹沟厚涂含氧化锌的护臀霜\n厚度如奶油般盖住原本肤色以隔绝尿便刺激\n穿新尿布腰围留出一指空隙,理顺防漏荷叶边',
'icon': '🛡️',
'tip': '✅ 标准:腰围宽松适度,腿围立体护围翻出'
}
]
},
{
'id': 'guide-sleep',
'title': '新生儿安全襁褓裹法与入睡安抚手法',
'badge': '😴 安全睡眠守护',
'theme_color': (147, 51, 234), # Purple
'accent_color': (126, 34, 206),
'bg_gradient': [(28, 16, 45), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '唯一安全睡姿:坚实仰卧平躺',
'detail': '1 岁以内唯一安全的推荐睡姿为平躺仰卧\n床垫平整坚实,不可使用柔软羽绒床垫\n婴儿床内必须“空无一物”:严禁放枕头/玩偶/厚被',
'icon': '🛏️',
'tip': '⚠️ 警示:严禁未满周岁婴儿趴睡,谨防窒息与 SIDS'
},
{
'step': '第 2 步 / 共 4 步',
'action': '科学襁褓包裹:上紧下松',
'detail': '双臂自然贴于身侧包紧,抑制莫罗惊跳反射\n下半身必须留足活动空间呈自然“青蛙腿”\n禁止捆绑双腿(蜡烛包)以防髋关节脱位',
'icon': '📦',
'tip': '💡 黄金法则:上身紧如子宫包裹,下肢松展自如'
},
{
'step': '第 3 步 / 共 4 步',
'action': '营造入睡安全环境与仪式',
'detail': '室温保持 22~24℃,湿度 50%~60%\n调暗卧室内灯光,播放 50dB 以下持续白噪音\n如雨声、海浪声或心跳音,模拟子宫听觉',
'icon': '🌙',
'tip': '💡 技巧:白噪音音量不宜过大,距离婴儿床 1 米以上'
},
{
'step': '第 4 步 / 共 4 步',
'action': '轻拍胸口安抚与自主入睡衔接',
'detail': '手掌心轻贴宝宝胸口有节律轻轻按抚\n宝宝昏昏欲睡尚未全睡着时放入婴儿床\n培养宝宝不依赖奶嘴或抱摇的自主接觉能力',
'icon': '⭐',
'tip': '⚠️ 警示:宝宝一旦出现翻身迹象立即停止裹双臂襁褓'
}
]
},
{
'id': 'guide-bath',
'title': '新生儿快速安全盆浴与脐带消毒步骤',
'badge': '🛁 日常洗护要领',
'theme_color': (20, 184, 166), # Teal
'accent_color': (13, 148, 136),
'bg_gradient': [(15, 35, 38), (15, 23, 42)],
'scenes': [
{
'step': '第 1 步 / 共 4 步',
'action': '环境与水温准备(手肘试温)',
'detail': '室温保持 26~28℃,关好门窗避风\n水温 37~38℃(大人用手肘内侧试水感觉温热)\n浴巾、干爽衣物与纸尿裤提前完全展开备用',
'icon': '🌡️',
'tip': '💡 提示:洗澡全程严格控制在 5~8 分钟内防止受凉'
},
{
'step': '第 2 步 / 共 4 步',
'action': '橄榄球式托抱与耳部防水保护',
'detail': '左手臂夹稳宝宝身体,左手稳稳托托住头颈\n用大拇指和中指将宝宝耳朵向前折按紧贴脸颊\n防止洗头洗脸时水流流入外耳道',
'icon': '🏈',
'tip': '⚠️ 警示:任何时候大人的手不可离开婴儿身体!'
},
{
'step': '第 3 步 / 共 4 步',
'action': '轻柔清洗皱褶处与快速包裹擦干',
'detail': '先洗脸和头,擦干后再放入澡盆清洗躯干\n着重清洗颈部、腋下、腹股沟等皮褶处\n洗完立刻用大浴巾包裹全身,轻轻按压吸干水分',
'icon': '🧼',
'tip': '💡 技巧:不要用力擦拭,按压蘸干即可保护皮脂膜'
},
{
'step': '第 4 步 / 共 4 步',
'action': '脐带根部规范消毒与防尿浸染',
'detail': '用 75% 酒精或碘伏医用棉签消毒脐带\n一手轻提脐带残端,棉签自根部由内向外旋转消毒\n穿尿布时将前部边缘向下反折,彻底露出口脐根部',
'icon': '🩹',
'tip': '✅ 标准:保持脐窝干燥透气,若发红发臭需及时就医'
}
]
}
]
WIDTH = 640
HEIGHT = 360
FPS = 25
SCENE_DURATION_SEC = 4.0 # Each scene lasts 4 seconds -> 16 seconds total
def draw_rounded_rect(draw, bbox, radius, fill, outline=None, width=1):
x0, y0, x1, y1 = bbox
draw.rounded_rectangle([x0, y0, x1, y1], radius=radius, fill=fill, outline=outline, width=width)
def generate_video(guide):
guide_id = guide['id']
output_mp4 = os.path.join(VIDEOS_DIR, f"{guide_id}.mp4")
print(f"Generating video for: {guide_id} ({guide['title']})...")
temp_dir = tempfile.mkdtemp(prefix=f"frames_{guide_id}_")
scenes = guide['scenes']
total_scenes = len(scenes)
frames_per_scene = int(SCENE_DURATION_SEC * FPS)
total_frames = total_scenes * frames_per_scene
font_title = get_font(20, bold=True)
font_badge = get_font(12, bold=True)
font_step = get_font(12, bold=True)
font_action = get_font(22, bold=True)
font_detail = get_font(14)
font_tip = get_font(12, bold=True)
font_icon = get_font(36)
font_footer = get_font(10)
theme_color = guide['theme_color']
accent_color = guide['accent_color']
frame_idx = 0
for s_idx, scene in enumerate(scenes):
for f_in_s in range(frames_per_scene):
t = f_in_s / frames_per_scene # 0.0 to 1.0 progress in scene
overall_progress = frame_idx / total_frames
# Fade in transition at start of scene (first 10 frames)
alpha_scene = min(1.0, f_in_s / 10.0)
# Create base image with deep slate gradient
img = Image.new('RGB', (WIDTH, HEIGHT), color=(15, 23, 42))
draw = ImageDraw.Draw(img)
# Gradient background bars
for y in range(HEIGHT):
ratio = y / HEIGHT
r = int(guide['bg_gradient'][0][0] * (1 - ratio) + guide['bg_gradient'][1][0] * ratio)
g = int(guide['bg_gradient'][0][1] * (1 - ratio) + guide['bg_gradient'][1][1] * ratio)
b = int(guide['bg_gradient'][0][2] * (1 - ratio) + guide['bg_gradient'][1][2] * ratio)
draw.line([(0, y), (WIDTH, y)], fill=(r, g, b))
# Header Top Bar
# Badge pill
draw_rounded_rect(draw, (20, 14, 150, 36), radius=11, fill=theme_color)
draw.text((28, 17), guide['badge'], font=font_badge, fill=(255, 255, 255))
# Guide Title
draw.text((160, 15), guide['title'], font=font_title, fill=(241, 245, 249))
# Main Card Box in Center
card_bbox = (20, 48, WIDTH - 20, HEIGHT - 38)
draw_rounded_rect(draw, card_bbox, radius=18, fill=(30, 41, 59), outline=(51, 65, 85), width=1)
# Inner subtle highlight top
draw.line([(35, 49), (WIDTH - 35, 49)], fill=(255, 255, 255, 30))
# Left Big Emoji / Icon Circle
# Smooth floating bounce
bounce_y = int(math.sin(t * math.pi * 2) * 3)
icon_cx, icon_cy = 75, 115 + bounce_y
draw.ellipse([icon_cx - 36, icon_cy - 36, icon_cx + 36, icon_cy + 36], fill=(51, 65, 85))
draw.ellipse([icon_cx - 32, icon_cy - 32, icon_cx + 32, icon_cy + 32], fill=(15, 23, 42), outline=theme_color, width=2)
draw.text((icon_cx - 18, icon_cy - 20), scene['icon'], font=font_icon, fill=(255, 255, 255))
# Step Tag
draw_rounded_rect(draw, (130, 68, 235, 88), radius=6, fill=theme_color)
draw.text((138, 71), scene['step'], font=font_step, fill=(255, 255, 255))
# Action Headline
draw.text((130, 96), scene['action'], font=font_action, fill=(255, 255, 255))
# Detailed Points (multiline text)
detail_lines = scene['detail'].split('\n')
y_text = 138
for line in detail_lines:
draw.text((130, y_text), f"• {line}", font=font_detail, fill=(203, 213, 225))
y_text += 22
# Bottom Tip / Safety Banner inside Card
tip_bbox = (35, HEIGHT - 84, WIDTH - 35, HEIGHT - 50)
is_warning = '⚠️' in scene['tip']
tip_bg = (69, 26, 26) if is_warning else (22, 54, 46)
tip_border = (239, 68, 68) if is_warning else theme_color
draw_rounded_rect(draw, tip_bbox, radius=10, fill=tip_bg, outline=tip_border, width=1)
draw.text((45, HEIGHT - 76), scene['tip'], font=font_tip, fill=(255, 255, 255))
# Bottom Global Progress Bar
progress_y = HEIGHT - 18
draw_rounded_rect(draw, (20, progress_y, WIDTH - 20, progress_y + 6), radius=3, fill=(51, 65, 85))
bar_w = int((WIDTH - 40) * overall_progress)
if bar_w > 4:
draw_rounded_rect(draw, (20, progress_y, 20 + bar_w, progress_y + 6), radius=3, fill=theme_color)
# Footer timer
curr_sec = int(frame_idx / FPS)
tot_sec = int(total_frames / FPS)
timer_str = f"{curr_sec:02d}:{int((frame_idx % FPS)/FPS * 100):02d} / {tot_sec:02d}:00 儿科标准护理规范教学"
draw.text((22, HEIGHT - 32), timer_str, font=font_footer, fill=(148, 163, 184))
# Save frame
frame_path = os.path.join(temp_dir, f"frame_{frame_idx:05d}.png")
img.save(frame_path)
frame_idx += 1
print(f"Generated {frame_idx} frames. Encoding with FFmpeg...")
# FFmpeg command to compile frames to H.264 MP4 with pleasant chime audio
# Audio synth: gentle calming ambient drone/chimes
ffmpeg_cmd = [
"ffmpeg", "-y",
"-r", str(FPS),
"-i", os.path.join(temp_dir, "frame_%05d.png"),
"-f", "lavfi",
"-i", f"sine=frequency=440:beep_factor=4:duration={int(total_frames/FPS)}",
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-profile:v", "baseline",
"-level", "3.0",
"-movflags", "+faststart",
"-c:a", "aac",
"-b:a", "64k",
"-shortest",
output_mp4
]
res = subprocess.run(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if res.returncode == 0:
file_size = os.path.getsize(output_mp4)
print(f"Successfully generated: {output_mp4} ({file_size / 1024:.1f} KB)")
else:
print(f"FFmpeg error: {res.stderr.decode('utf-8', errors='ignore')}")
# Cleanup temp frames
for f in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, f))
os.rmdir(temp_dir)
if __name__ == '__main__':
for guide in GUIDE_SCRIPTS:
generate_video(guide)
print("\nAll 6 care guide demonstration videos generated successfully!")
-112
View File
@@ -1,112 +0,0 @@
const fs = require('fs');
const path = require('path');
const postersDir = path.join(__dirname, '../public/images/posters');
if (!fs.existsSync(postersDir)) {
fs.mkdirSync(postersDir, { recursive: true });
}
const posters = [
{
id: 'poster-bottle.svg',
title: '45° 防胀气瓶喂指南',
subtitle: '节律喂养 · 杜绝呛奶吞气',
icon: '🍼',
bg1: '#FEF3C7',
bg2: '#F59E0B',
accent: '#B45309'
},
{
id: 'poster-breastfeed.svg',
title: '新生儿深吸含乳技巧',
subtitle: '深层含乳 · 预防乳头皲裂',
icon: '🤱',
bg1: '#FFE4E6',
bg2: '#F43F5E',
accent: '#BE123C'
},
{
id: 'poster-burping.svg',
title: '空心掌拍嗝防胀气实操',
subtitle: '端坐与过肩拍嗝 · 排净胃气',
icon: '💨',
bg1: '#EDE9FE',
bg2: '#8B5CF6',
accent: '#6D28D9'
},
{
id: 'poster-diaper.svg',
title: '防红屁屁换尿布全流程',
subtitle: '温水清洗 · 隔离护臀膏涂法',
icon: '💧',
bg1: '#E0F2FE',
bg2: '#0EA5E9',
accent: '#0369A1'
},
{
id: 'poster-sleep.svg',
title: '安全襁褓裹法与入睡安抚',
subtitle: '防惊跳反射 · 建立自主入睡',
icon: '😴',
bg1: '#F1F5F9',
bg2: '#64748B',
accent: '#334155'
},
{
id: 'poster-bath.svg',
title: '新生儿安全盆浴与脐带护理',
subtitle: '快速盆浴 · 75% 酒精消毒',
icon: '🛁',
bg1: '#CCFBF1',
bg2: '#14B8A6',
accent: '#0F766E'
}
];
posters.forEach(p => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360" width="100%" height="100%">
<defs>
<linearGradient id="grad-${p.id}" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="${p.bg1}" />
<stop offset="100%" stop-color="${p.bg2}" stop-opacity="0.85" />
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-opacity="0.15" />
</filter>
</defs>
<!-- Background -->
<rect width="600" height="360" rx="24" fill="url(#grad-${p.id})" />
<!-- Background subtle circles -->
<circle cx="520" cy="60" r="100" fill="white" opacity="0.15" />
<circle cx="80" cy="300" r="80" fill="white" opacity="0.1" />
<!-- Center Card -->
<g transform="translate(60, 50)" filter="url(#shadow)">
<rect width="480" height="260" rx="20" fill="white" fill-opacity="0.92" backdrop-filter="blur(10px)" />
<!-- Icon circle -->
<circle cx="240" cy="80" r="44" fill="${p.bg1}" />
<text x="240" y="94" font-size="44" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">${p.icon}</text>
<!-- Title -->
<text x="240" y="165" font-size="22" font-weight="900" fill="#1E293B" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">${p.title}</text>
<!-- Subtitle -->
<text x="240" y="198" font-size="14" font-weight="600" fill="${p.accent}" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif">${p.subtitle}</text>
<!-- Video play indicator pill -->
<g transform="translate(195, 218)">
<rect width="90" height="24" rx="12" fill="${p.accent}" />
<polygon points="234,225 244,230 234,235" fill="white" />
<text x="250" y="234" font-size="10" font-weight="700" fill="white" font-family="-apple-system, BlinkMacSystemFont, sans-serif">教学视频</text>
</g>
</g>
</svg>`;
fs.writeFileSync(path.join(postersDir, p.id), svg, 'utf8');
console.log(`Generated local poster: ${p.id}`);
});
console.log('All 6 local SVG posters created successfully!');
-70
View File
@@ -1,70 +0,0 @@
const { pool } = require('../server/db');
async function migrate() {
const conn = await pool.getConnection();
try {
console.log('Running V1.3 & V1.4 DB migration...');
await conn.query(`
CREATE TABLE IF NOT EXISTS \`family_memo\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`memo_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '备忘唯一业务ID',
\`family_id\` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID',
\`content\` VARCHAR(255) NOT NULL COMMENT '待办备忘内容',
\`due_period\` VARCHAR(30) DEFAULT 'today' COMMENT '推荐时段',
\`is_completed\` TINYINT(1) DEFAULT 0 COMMENT '是否已完成',
\`completed_at\` DATETIME NULL COMMENT '完成时刻',
\`created_by\` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_memo_family\` (\`family_id\`, \`is_completed\`),
INDEX \`idx_memo_created\` (\`created_at\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭日常备忘待办清单表';
`);
console.log('✅ Table family_memo ensured.');
try {
await conn.query("ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好'");
console.log('✅ Column preferences added to family_member.');
} catch (e) {
if (e.code === 'ER_DUP_FIELDNAME') {
console.log('ℹ️ Column preferences already exists in family_member.');
} else {
console.warn('family_member column warning:', e.message);
}
}
try {
await conn.query("ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置'");
console.log('✅ Column default_config added to baby_profile.');
} catch (e) {
if (e.code === 'ER_DUP_FIELDNAME') {
console.log('ℹ️ Column default_config already exists in baby_profile.');
} else {
console.warn('baby_profile column warning:', e.message);
}
}
// Insert sample initial memo if none exists
const [memos] = await conn.query("SELECT COUNT(*) as count FROM `family_memo` WHERE `family_id` = 'family-001'");
if (memos[0].count === 0) {
await conn.query(`
INSERT INTO \`family_memo\` (\`memo_id\`, \`family_id\`, \`content\`, \`due_period\`, \`is_completed\`, \`created_by\`)
VALUES
('memo-001', 'family-001', '下午3点:准备45℃温水洗澡', 'afternoon', 0, '宝妈'),
('memo-002', 'family-001', '睡前:喂服维生素 D3 滴剂', 'evening', 0, '宝爸'),
('memo-003', 'family-001', '消毒所有奶瓶及吸奶器配件', 'morning', 1, '奶奶')
`);
console.log('✅ Seed memos initialized for family-001.');
}
console.log('Migration finished successfully!');
} finally {
conn.release();
process.exit(0);
}
}
migrate().catch(err => {
console.error('Migration failed:', err);
process.exit(1);
});
+79
View File
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.babytracker</groupId>
<artifactId>baby-tracker-server</artifactId>
<version>0.1.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
<relativePath/>
</parent>
<properties>
<java.version>21</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<release>${java.version}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,12 @@
package com.babytracker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BabyTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(BabyTrackerApplication.class, args);
}
}
@@ -0,0 +1,19 @@
package com.babytracker.common;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(false)
.maxAge(3600);
}
}
@@ -0,0 +1,15 @@
package com.babytracker.common.exception;
public class BusinessException extends RuntimeException {
private final String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}
@@ -0,0 +1,31 @@
package com.babytracker.common.exception;
import com.babytracker.common.response.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<Void> handleBusiness(BusinessException ex) {
return ApiResponse.fail(ex.getCode(), ex.getMessage());
}
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiResponse<Void> handleValidation(Exception ex) {
return ApiResponse.fail("VALIDATION_ERROR", "参数不合法");
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiResponse<Void> handleException(Exception ex) {
return ApiResponse.fail("INTERNAL_ERROR", ex.getMessage());
}
}
@@ -0,0 +1,55 @@
package com.babytracker.common.id;
import org.springframework.stereotype.Component;
@Component
public class SnowflakeIdGenerator {
private static final long EPOCH = 1704067200000L;
private static final long WORKER_ID_BITS = 10L;
private static final long SEQUENCE_BITS = 12L;
private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
private static final long SEQUENCE_MASK = (1L << SEQUENCE_BITS) - 1;
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
private final long workerId;
private long lastTimestamp = -1L;
private long sequence = 0L;
public SnowflakeIdGenerator() {
this.workerId = 1L;
if (workerId > MAX_WORKER_ID) {
throw new IllegalArgumentException("workerId exceeds max worker id");
}
}
public synchronized String nextId() {
long timestamp = currentTime();
if (timestamp < lastTimestamp) {
throw new IllegalStateException("Clock moved backwards");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & SEQUENCE_MASK;
if (sequence == 0) {
timestamp = waitNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
long id = ((timestamp - EPOCH) << TIMESTAMP_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence;
return String.format("%032d", id);
}
private long waitNextMillis(long timestamp) {
long now = currentTime();
while (now <= timestamp) {
now = currentTime();
}
return now;
}
private long currentTime() {
return System.currentTimeMillis();
}
}
@@ -0,0 +1,31 @@
package com.babytracker.common.response;
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;
}
}
@@ -0,0 +1,46 @@
package com.babytracker.common.response;
public class ApiResponse<T> {
private boolean success;
private T data;
private ApiError error;
public static <T> ApiResponse<T> ok(T data) {
ApiResponse<T> response = new ApiResponse<T>();
response.success = true;
response.data = data;
return response;
}
public static <T> ApiResponse<T> fail(String code, String message) {
ApiResponse<T> response = new ApiResponse<T>();
response.success = false;
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,44 @@
package com.babytracker.module.baby;
import com.babytracker.common.response.ApiResponse;
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.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
@RequestMapping("/api/v1/babies")
public class BabyController {
private final BabyService babyService;
public BabyController(BabyService babyService) {
this.babyService = babyService;
}
@GetMapping("/current")
public ApiResponse<BabyProfile> current() {
return ApiResponse.ok(babyService.getCurrentBaby());
}
@GetMapping
public ApiResponse<List<BabyProfile>> list() {
return ApiResponse.ok(babyService.listBabies());
}
@PutMapping("/current")
public ApiResponse<BabyProfile> update(@Valid @RequestBody UpdateBabyRequest 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));
}
}
@@ -0,0 +1,80 @@
package com.babytracker.module.baby;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class BabyProfile {
private String babyId;
private String familyId;
private String name;
private String gender;
private LocalDate birthDate;
private String deliveryType;
public static BabyProfile defaultBaby() {
BabyProfile baby = new BabyProfile();
baby.babyId = "00000000000000361915955447599104";
baby.familyId = "00000000000000361915955439210496";
baby.name = "宝宝";
baby.gender = "boy";
baby.birthDate = LocalDate.now().minusDays(3);
baby.deliveryType = "natural";
return baby;
}
public long getAgeDays() {
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;
}
}
@@ -0,0 +1,90 @@
package com.babytracker.module.baby;
import com.babytracker.common.id.SnowflakeIdGenerator;
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.util.List;
@Service
public class BabyService {
private final JdbcTemplate jdbcTemplate;
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)
);
if (!babies.isEmpty()) {
return babies.get(0);
}
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;
}
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)
);
if (babies.isEmpty()) {
return List.of(getCurrentBaby());
}
return babies;
}
public BabyProfile updateCurrentBaby(UpdateBabyRequest request) {
BabyProfile currentBaby = getCurrentBaby();
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
);
return findByBabyId(babyId);
}
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();
}
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;
}
}
@@ -0,0 +1,46 @@
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,34 @@
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;
}
}
@@ -0,0 +1,21 @@
package com.babytracker.module.family;
import com.babytracker.common.response.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@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() {
return ApiResponse.ok(familyService.getCurrentContext());
}
}
@@ -0,0 +1,31 @@
package com.babytracker.module.family;
public class FamilyInfo {
private String familyId;
private String name;
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;
}
}
@@ -0,0 +1,58 @@
package com.babytracker.module.family;
public class FamilyMember {
private String memberId;
private String familyId;
private String userId;
private String roleName;
private String roleType;
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;
}
}
@@ -0,0 +1,80 @@
package com.babytracker.module.family;
import com.babytracker.module.baby.BabyProfile;
import com.babytracker.module.baby.BabyService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FamilyService {
private final JdbcTemplate jdbcTemplate;
private final BabyService babyService;
public FamilyService(JdbcTemplate jdbcTemplate, BabyService babyService) {
this.jdbcTemplate = jdbcTemplate;
this.babyService = babyService;
}
public FamilyContext getCurrentContext() {
FamilyContext context = new FamilyContext();
context.setFamily(getDefaultFamily());
context.setBabies(babyService.listBabies());
context.setMembers(listMembers(context.getFamily().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);
}
FamilyInfo family = new FamilyInfo();
family.setFamilyId("00000000000000361915955439210496");
family.setName("新生儿照护家庭");
family.setInviteCode("BT2026");
return 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
);
if (!members.isEmpty()) {
return members;
}
return defaultMembers(familyId);
}
private List<FamilyMember> defaultMembers(String familyId) {
FamilyMember mom = new FamilyMember();
mom.setMemberId("00000000000000361915955443404800");
mom.setFamilyId(familyId);
mom.setRoleName("宝妈");
mom.setRoleType("owner");
mom.setDefaultOperator(true);
return List.of(mom);
}
}
@@ -0,0 +1,131 @@
package com.babytracker.module.record;
import java.time.Duration;
import java.time.LocalDateTime;
public class CareRecord {
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 note;
private LocalDateTime createdAt;
public void recalculateDuration() {
if (startTime != null && endTime != null) {
durationMinutes = (int) Math.max(0, Duration.between(startTime, endTime).toMinutes());
}
}
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;
}
public void setNote(String note) {
this.note = note;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
}
@@ -0,0 +1,77 @@
package com.babytracker.module.record;
import com.babytracker.common.response.ApiResponse;
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.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
@RequestMapping("/api/v1/records")
public class CareRecordController {
private final CareRecordService careRecordService;
public CareRecordController(CareRecordService careRecordService) {
this.careRecordService = careRecordService;
}
@GetMapping
public ApiResponse<List<CareRecord>> list(
@RequestParam String babyId,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
) {
return ApiResponse.ok(careRecordService.list(babyId, date));
}
@PostMapping("/feeding")
public ApiResponse<CareRecord> feeding(@Valid @RequestBody CreateFeedingRequest request) {
return ApiResponse.ok(careRecordService.createFeeding(request));
}
@PostMapping("/feeding/start")
public ApiResponse<CareRecord> startFeeding(@Valid @RequestBody CreateFeedingRequest request) {
return ApiResponse.ok(careRecordService.startFeeding(request));
}
@PostMapping("/feeding/end")
public ApiResponse<CareRecord> endFeeding(@Valid @RequestBody CreateFeedingRequest request) {
return ApiResponse.ok(careRecordService.endFeeding(request));
}
@PostMapping("/sleep/start")
public ApiResponse<CareRecord> startSleep(@Valid @RequestBody SleepRequest request) {
return ApiResponse.ok(careRecordService.startSleep(request));
}
@PostMapping("/sleep/end")
public ApiResponse<CareRecord> endSleep(@Valid @RequestBody SleepRequest request) {
return ApiResponse.ok(careRecordService.endSleep(request));
}
@PostMapping("/pee")
public ApiResponse<CareRecord> pee(@Valid @RequestBody ExcretionRequest request) {
return ApiResponse.ok(careRecordService.createPee(request));
}
@PostMapping("/poop")
public ApiResponse<CareRecord> poop(@Valid @RequestBody ExcretionRequest request) {
return ApiResponse.ok(careRecordService.createPoop(request));
}
@DeleteMapping("/{recordId}")
public ApiResponse<Void> delete(@PathVariable String recordId) {
careRecordService.delete(recordId);
return ApiResponse.ok(null);
}
}
@@ -0,0 +1,245 @@
package com.babytracker.module.record;
import com.babytracker.common.exception.BusinessException;
import com.babytracker.common.id.SnowflakeIdGenerator;
import org.springframework.jdbc.core.JdbcTemplate;
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
public class CareRecordService {
private final JdbcTemplate jdbcTemplate;
private final SnowflakeIdGenerator idGenerator;
public CareRecordService(JdbcTemplate jdbcTemplate, SnowflakeIdGenerator idGenerator) {
this.jdbcTemplate = jdbcTemplate;
this.idGenerator = idGenerator;
}
public List<CareRecord> 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())
);
}
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));
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.recalculateDuration();
}
insert(record);
return record;
}
public CareRecord startFeeding(CreateFeedingRequest request) {
CareRecord activeFeeding = findActiveFeeding(request.getBabyId());
if (activeFeeding != null) {
throw new BusinessException("FEEDING_ALREADY_STARTED", "当前已有进行中的亲喂记录");
}
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingNote(request));
record.setFeedingMethod("breastfeed");
insert(record);
return record;
}
public CareRecord endFeeding(CreateFeedingRequest request) {
CareRecord activeFeeding = findActiveFeeding(request.getBabyId());
if (activeFeeding == null) {
throw new BusinessException("NO_ACTIVE_FEEDING", "当前没有进行中的亲喂记录");
}
LocalDateTime end = request.getEndTime() == null ? LocalDateTime.now() : request.getEndTime();
if (end.isBefore(activeFeeding.getStartTime())) {
throw new BusinessException("INVALID_FEEDING_TIME", "喂奶结束时间不能早于开始时间");
}
activeFeeding.setEndTime(end);
activeFeeding.setNote(request.getNote() == null ? activeFeeding.getNote() : buildFeedingNote(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;
}
public CareRecord startSleep(SleepRequest request) {
CareRecord activeSleep = findActiveSleep(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;
}
public CareRecord endSleep(SleepRequest request) {
CareRecord activeSleep = findActiveSleep(request.getBabyId());
if (activeSleep == null) {
throw new BusinessException("NO_ACTIVE_SLEEP", "当前没有进行中的睡眠记录");
}
LocalDateTime end = request.getTime() == null ? LocalDateTime.now() : request.getTime();
if (end.isBefore(activeSleep.getStartTime())) {
throw new BusinessException("INVALID_SLEEP_TIME", "睡眠结束时间不能早于开始时间");
}
activeSleep.setEndTime(end);
activeSleep.setNote(request.getNote() == null ? activeSleep.getNote() : request.getNote());
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;
}
public CareRecord createPee(ExcretionRequest request) {
return createExcretion(request, "pee");
}
public CareRecord createPoop(ExcretionRequest 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) {
throw new BusinessException("RECORD_NOT_FOUND", "记录不存在");
}
}
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
);
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
);
return active.isEmpty() ? null : active.get(0);
}
private String buildFeedingNote(CreateFeedingRequest request) {
String side = request.getBreastSide();
String note = request.getNote();
if (side == null || side.trim().isEmpty()) {
return note;
}
String sideText = "left".equals(side) ? "左侧" : "right".equals(side) ? "右侧" : side.trim();
if (note == null || note.trim().isEmpty()) {
return "亲喂侧: " + sideText;
}
return "亲喂侧: " + sideText + ";" + note.trim();
}
private CareRecord createExcretion(ExcretionRequest request, String excretionType) {
CareRecord record = baseRecord(request.getBabyId(), "excretion", request.getTime(), request.getOperatorName(), request.getNote());
record.setExcretionType(excretionType);
insert(record);
return record;
}
private CareRecord baseRecord(String babyId, String type, LocalDateTime time, String operatorName, String note) {
CareRecord record = new CareRecord();
record.setRecordId(idGenerator.nextId());
record.setFamilyId(resolveFamilyId(babyId));
record.setBabyId(babyId);
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());
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
);
if (familyIds.isEmpty()) {
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;
}
}
@@ -0,0 +1,81 @@
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;
}
}
@@ -0,0 +1,44 @@
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;
}
}
@@ -0,0 +1,44 @@
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,108 @@
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;
}
}
@@ -0,0 +1,29 @@
package com.babytracker.module.summary;
import com.babytracker.common.response.ApiResponse;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
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;
@RestController
@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,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
) {
return ApiResponse.ok(summaryService.daily(babyId, date));
}
}
@@ -0,0 +1,67 @@
package com.babytracker.module.summary;
import com.babytracker.module.record.CareRecord;
import com.babytracker.module.record.CareRecordService;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Service
public class SummaryService {
private final CareRecordService careRecordService;
public SummaryService(CareRecordService careRecordService) {
this.careRecordService = careRecordService;
}
public DailySummary daily(String babyId, LocalDate date) {
LocalDate targetDate = date == null ? LocalDate.now() : date;
List<CareRecord> timeline = careRecordService.list(babyId, targetDate);
DailySummary summary = new DailySummary();
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>();
int feedingCount = 0;
int sleepTotal = 0;
int peeCount = 0;
int poopCount = 0;
CareRecord lastFeeding = null;
for (CareRecord record : timeline) {
if ("feeding".equals(record.getRecordType())) {
feedingCount++;
String method = record.getFeedingMethod() == null ? "other" : record.getFeedingMethod();
methodCounts.put(method, methodCounts.getOrDefault(method, 0) + 1);
if (lastFeeding == null || record.getStartTime().isAfter(lastFeeding.getStartTime())) {
lastFeeding = record;
}
}
if ("sleep".equals(record.getRecordType()) && record.getDurationMinutes() != null) {
sleepTotal += record.getDurationMinutes();
}
if ("excretion".equals(record.getRecordType())) {
if ("pee".equals(record.getExcretionType())) {
peeCount++;
}
if ("poop".equals(record.getExcretionType())) {
poopCount++;
}
}
}
summary.setFeedingCount(feedingCount);
summary.setFeedingMethodCounts(methodCounts);
summary.setSleepTotalMinutes(sleepTotal);
summary.setPeeCount(peeCount);
summary.setPoopCount(poopCount);
summary.setLastFeeding(lastFeeding);
return summary;
}
}
@@ -0,0 +1,29 @@
server:
port: 9899
spring:
application:
name: baby-tracker-server
datasource:
url: ${DB_URL:jdbc:mysql://39.107.119.209:3306/yyyy?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai}
username: ${DB_USER:yy_u}
password: ${DB_PASSWORD:BBp5pjWr9LFiqua}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 10
minimum-idle: 2
connection-timeout: 10000
flyway:
enabled: true
baseline-on-migrate: true
baseline-version: 0
locations: classpath:db/migration
jackson:
time-zone: Asia/Shanghai
date-format: yyyy-MM-dd HH:mm:ss
app:
cors:
allowed-origins:
- http://localhost:5173
- http://127.0.0.1:5173
@@ -0,0 +1,100 @@
SET NAMES utf8mb4;
CREATE TABLE IF NOT EXISTS `app_user` (
`id` CHAR(32) NOT NULL COMMENT '用户ID,雪花ID字符串',
`openid` VARCHAR(128) NULL COMMENT '微信小程序 openid',
`unionid` VARCHAR(128) NULL COMMENT '微信 unionid',
`phone` VARCHAR(32) NULL COMMENT '手机号',
`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 '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_app_user_openid` (`openid`),
UNIQUE KEY `uk_app_user_phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
CREATE TABLE IF NOT EXISTS `family` (
`id` CHAR(32) NOT NULL COMMENT '家庭ID,雪花ID字符串',
`name` VARCHAR(100) NOT NULL COMMENT '家庭名称',
`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 '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_family_invite_code` (`invite_code`),
KEY `idx_family_creator` (`creator_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭表';
CREATE TABLE IF NOT EXISTS `family_member` (
`id` CHAR(32) NOT NULL COMMENT '成员ID,雪花ID字符串',
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
`user_id` CHAR(32) NULL COMMENT '用户ID',
`role_name` VARCHAR(50) NOT NULL COMMENT '看护人称谓',
`role_type` VARCHAR(30) NOT NULL DEFAULT 'caregiver' COMMENT '角色类型: owner, caregiver, viewer',
`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 '更新时间',
PRIMARY KEY (`id`),
KEY `idx_family_member_family` (`family_id`),
KEY `idx_family_member_user` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭成员表';
CREATE TABLE IF NOT EXISTS `baby_profile` (
`id` CHAR(32) NOT NULL COMMENT '宝宝ID,雪花ID字符串',
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
`name` VARCHAR(50) NOT NULL COMMENT '宝宝昵称',
`gender` VARCHAR(20) NOT NULL DEFAULT 'boy' COMMENT '性别: boy, girl, unknown',
`birth_date` DATE NOT NULL COMMENT '出生日期',
`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 '更新时间',
PRIMARY KEY (`id`),
KEY `idx_baby_profile_family` (`family_id`),
KEY `idx_baby_profile_default` (`family_id`, `is_default`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='宝宝档案表';
CREATE TABLE IF NOT EXISTS `care_record` (
`id` CHAR(32) NOT NULL COMMENT '记录ID,雪花ID字符串',
`family_id` CHAR(32) NOT NULL COMMENT '家庭ID',
`baby_id` CHAR(32) NOT NULL COMMENT '宝宝ID',
`record_type` VARCHAR(30) NOT NULL COMMENT '记录类型: feeding, sleep, excretion',
`start_time` DATETIME NOT NULL COMMENT '开始/发生时间',
`end_time` DATETIME NULL COMMENT '结束时间',
`duration_minutes` INT NULL COMMENT '持续分钟数',
`feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式',
`amount_ml` INT NULL COMMENT '奶量 ml,可选',
`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 '更新时间',
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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='照护记录表';
INSERT IGNORE INTO `app_user` (`id`, `nickname`, `status`)
VALUES ('00000000000000361915955435016192', '默认看护人', 'active');
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`)
VALUES
('00000000000000361915955443404800', '00000000000000361915955439210496', '00000000000000361915955435016192', '宝妈', 'owner', 1, 'active'),
('00000000000000361915955451793408', '00000000000000361915955439210496', NULL, '宝爸', 'caregiver', 0, 'active');
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');
-79
View File
@@ -1,79 +0,0 @@
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const { initDatabase } = require('./db');
const babiesRouter = require('./routes/babies');
const recordsRouter = require('./routes/records');
const summaryRouter = require('./routes/summary');
const careGuidesRouter = require('./routes/careGuides');
const exportRouter = require('./routes/export');
const customMetricsRouter = require('./routes/customMetrics');
const familiesRouter = require('./routes/families');
const memosRouter = require('./routes/memos');
const { router: sseRouter } = require('./routes/sse');
const app = express();
const PORT = process.env.PORT || 9898;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static frontend assets
app.use(express.static(path.join(__dirname, '../public')));
// API Routes
app.use('/api/babies', babiesRouter);
app.use('/api/families', familiesRouter);
app.use('/api/records', recordsRouter);
app.use('/api/summary', summaryRouter);
app.use('/api/care-guides', careGuidesRouter);
app.use('/api/export', exportRouter);
app.use('/api/custom-metrics', customMetricsRouter);
app.use('/api/memos', memosRouter);
app.use('/api/events', sseRouter);
// Fallback to index.html for SPA
app.use((req, res, next) => {
if (req.method === 'GET' && !req.path.startsWith('/api')) {
return res.sendFile(path.join(__dirname, '../public/index.html'));
}
next();
});
// 全局 API 错误处理中间件
app.use((err, req, res, next) => {
console.error(`[API Error] ${req.method} ${req.url}:`, err);
if (!res.headersSent) {
res.status(500).json({ success: false, error: err.message || 'Internal Server Error' });
}
});
process.on('uncaughtException', (err) => {
console.error('[Process Uncaught Exception]:', err);
});
process.on('unhandledRejection', (reason) => {
console.error('[Process Unhandled Rejection]:', reason);
});
async function start() {
try {
await initDatabase();
app.listen(PORT, '0.0.0.0', () => {
console.log(`=======================================================`);
console.log(` Baby Tracker & Analytics Server Running!`);
console.log(` Local access: http://localhost:${PORT}`);
console.log(` Mobile LAN access: http://<Your-LAN-IP>:${PORT}`);
console.log(` Connected to MySQL: ${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`);
console.log(`=======================================================`);
});
} catch (err) {
console.error('Fatal: Failed to start server:', err);
process.exit(1);
}
}
start();
-130
View File
@@ -1,130 +0,0 @@
/**
* Newborn Care Guides and Instructional Video Metadata
* Standard pediatric care instructions with authentic baby care demonstration media
* Localized posters and videos to ensure 100% offline availability with 0 CORS errors
*/
const CARE_GUIDES = [
{
id: 'guide-bottle',
category: 'feeding',
categoryName: '喂养护理',
title: '45°防胀气瓶喂姿势与拍嗝衔接',
subtitle: '掌握 Paced Feeding 节律喂养,杜绝呛奶与吞气',
durationText: '00:16',
videoUrl: '/videos/guide-bottle.mp4',
posterUrl: '/images/posters/poster-bottle.svg',
keyPoints: [
'奶温测试:冲调后在大人手腕内侧滴几滴,感受温热不烫(37~40℃最佳)。',
'抱姿倾斜:宝宝头部自然垫高成约 45° 半坐卧位,保持呼吸道通畅。',
'奶瓶倾角:握持奶瓶倾斜 45°,确保奶嘴前部充满奶水,切勿残留大半空气。',
'节奏喂养:每喝 30~50ml 或宝宝主动松口时,稍停数秒斜立奶瓶,让宝宝自主换气。'
],
cautions: [
'⚠️ 严禁让宝宝完全仰卧平躺喝奶,极易引发呛奶窒息或奶水逆流进入咽鼓管导致中耳炎!',
'⚠️ 喝完奶后务必竖抱或端坐轻柔拍嗝,切勿立即将宝宝平放至床上。'
]
},
{
id: 'guide-breastfeed',
category: 'feeding',
categoryName: '喂养护理',
title: '新生儿深吸含乳技巧与姿势调整',
subtitle: '避免浅含乳头皲裂,提升有效吞咽效率',
durationText: '00:16',
videoUrl: '/videos/guide-breastfeed.mp4',
posterUrl: '/images/posters/poster-breastfeed.svg',
keyPoints: [
'妈妈舒适:背后和手臂垫好哺乳枕,肩颈放松不耸肩,把宝宝贴近乳房而非弯腰凑宝宝。',
'鼻尖对乳头:让乳头轻触宝宝上唇或人中,等待宝宝像打哈欠一样张大嘴巴。',
'深吸贴合:迅速将宝宝下颌先贴紧乳房,下唇深含大部分下乳晕,乳头自然滑入咽部。',
'吞咽确认:观察宝宝面颊圆润不内陷,喉头有明显的“吞咽-换气”咕咚节律。'
],
cautions: [
'⚠️ 若感到乳头刀割般刺痛,说明含乳过浅!请轻压宝宝下巴或用小指探入口角解开负压重新含乳。',
'⚠️ 每次亲喂左右侧尽量轮换,保证后奶充分摄入。'
]
},
{
id: 'guide-burping',
category: 'burping',
categoryName: '拍嗝防胀气',
title: '空心掌正确手法与端坐/过肩拍嗝实操',
subtitle: '排净胃内气体,预防吐奶与肠绞痛',
durationText: '00:16',
videoUrl: '/videos/guide-burping.mp4',
posterUrl: '/images/posters/poster-burping.svg',
keyPoints: [
'手型气垫:五指并拢、手心弯曲微拱形成“空心掌”,拍击时产生类似空气减震音。',
'端坐式:一手虎口稳稳托住宝宝下巴与前胸,让宝宝身体稍稍前倾,另一手自下而上轻拍后背。',
'过肩式:宝宝竖直靠在大人肩头,下巴垫在大人肩软肉上(垫口水巾),空心掌轻拍中背部。',
'飞机抱辅助:手臂穿过宝宝双腿托住胸腹,头偏向外侧,适合傍晚胀气哭闹时排气。'
],
cautions: [
'⚠️ 绝对不能用平坦实心掌直接拍打婴儿后背!',
'⚠️ 连续轻拍 5~10 分钟若未听到饱嗝,竖抱 15 分钟亦可利用重力让气体自然排出。'
]
},
{
id: 'guide-diaper',
category: 'diaper',
categoryName: '排泄护臀',
title: '防红屁屁换尿布全流程与温水冲洗法',
subtitle: '保护娇嫩皮肤与髋关节发育的安全手法',
durationText: '00:16',
videoUrl: '/videos/guide-diaper.mp4',
posterUrl: '/images/posters/poster-diaper.svg',
keyPoints: [
'抬臀姿势:一手托住宝宝臀部下方或大腿腹部轻抬,切勿双手提拉细弱脚踝。',
'单向清洁:用温水或温湿巾“由前往后”单向轻拭,绝不可来回擦抹(女宝尤其注意防感染)。',
'彻底晾干:排便后最好用温水冲洗,用棉柔巾轻轻按压吸干水分,暴露于空气中晾干 1~2 分钟。',
'厚涂护臀霜:在肛周及腹股沟褶皱处厚涂含氧化锌的护臀霜(像涂蛋糕奶油般盖住肤色)。'
],
cautions: [
'⚠️ 严禁猛力倒提双腿悬空换尿布,会对婴儿脆弱的髋关节造成损伤,增加髋关节脱位风险!',
'⚠️ 护臀霜必须在皮肤完全干燥后涂抹,潮湿时涂抹反会将水分锁在皮下加重红屁屁。'
]
},
{
id: 'guide-sleep',
category: 'sleep',
categoryName: '安全睡眠',
title: '新生儿安全襁褓裹法与入睡安抚手法',
subtitle: '抑制惊跳反射,营造子宫般包裹安全感',
durationText: '00:16',
videoUrl: '/videos/guide-sleep.mp4',
posterUrl: '/images/posters/poster-sleep.svg',
keyPoints: [
'安全仰卧:平躺仰卧是 1 岁以内唯一安全的推荐睡姿,床垫必须坚实平整。',
'婴儿床净空:床上严禁放置任何枕头、羽绒被、防撞软包或毛绒玩具(避免窒息隐患)。',
'上紧下松裹包:双臂紧贴身体两侧包紧以抑制莫罗惊跳反射;下半身双腿留出足够空间呈自然“M”型青蛙腿弯曲。',
'睡眠仪式:调暗灯光、播放 50 分贝以下的白噪音(如雨声/海浪)、轻拍胸口安抚。'
],
cautions: [
'⚠️ 严禁在未满周岁前让婴儿趴睡(俯卧),趴睡是婴儿猝死综合征 (SIDS) 的最高风险诱因!',
'⚠️ 一旦宝宝展现出尝试翻身的迹象(通常在 2~3 个月),必须立即停止包裹双臂襁褓!'
]
},
{
id: 'guide-bath',
category: 'daily',
categoryName: '日常护理',
title: '新生儿快速安全盆浴与脐带消毒步骤',
subtitle: '保温、防呛水与肚脐根部干燥护理要领',
durationText: '00:16',
videoUrl: '/videos/guide-bath.mp4',
posterUrl: '/images/posters/poster-bath.svg',
keyPoints: [
'水温环境:室温维持 26~28℃,水温 37~38℃(大人用手肘内侧试水温感觉温润即可)。',
'橄榄球托抱:左手臂夹稳宝宝身体,左手掌稳固托住宝宝后颈与头部,用大拇指和中指将宝宝耳朵向前压住贴脸防进水。',
'洗澡限时:全过程控制在 5~8 分钟内,避免宝宝受凉感冒。',
'脐带消毒:洗完用棉签擦干水分,用 75% 医用酒精或碘伏棉签,自脐带根部中心向外打圈消毒干燥。'
],
cautions: [
'⚠️ 洗澡期间大人的手绝对不能离开婴儿身体,严禁哪怕 1 秒钟留宝宝单独在水盆中!',
'⚠️ 脐带脱落前尽量避免长时间在水中浸泡肚脐,尿布上缘应向下折叠避开脐带根部防止尿液浸染。'
]
}
];
module.exports = { CARE_GUIDES };
-287
View File
@@ -1,287 +0,0 @@
require('dotenv').config();
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: process.env.DB_HOST || '39.107.119.209',
port: parseInt(process.env.DB_PORT || '3306'),
user: process.env.DB_USER || 'yy_u',
password: process.env.DB_PASSWORD || 'BBp5pjWr9LFiqua',
database: process.env.DB_NAME || 'yyyy',
waitForConnections: true,
connectionLimit: 10,
maxIdle: 2,
idleTimeout: 30000,
enableKeepAlive: true,
keepAliveInitialDelay: 5000,
queueLimit: 0,
connectTimeout: 10000,
dateStrings: true
});
// 监听底层连接错误,防止空闲断开的 Socket 触发未捕获异常
if (pool.pool) {
pool.pool.on('connection', (connection) => {
connection.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
console.warn('[DB] Stale connection dropped by remote server, pool will reconnect.');
} else {
console.error('[DB] Connection error:', err.message);
}
});
});
}
// 封装带自动重试的 query 与 execute,抵御云端 MySQL/NAT 偶发断连
const originalQuery = pool.query.bind(pool);
const originalExecute = pool.execute.bind(pool);
async function executeWithRetry(fn, args, maxRetries = 3) {
let attempt = 0;
while (true) {
try {
return await fn(...args);
} catch (err) {
attempt++;
const isConnectionLost = err && (
err.code === 'PROTOCOL_CONNECTION_LOST' ||
err.code === 'ECONNRESET' ||
err.code === 'ETIMEDOUT' ||
err.code === 'EPIPE' ||
err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR' ||
err.fatal
);
if (isConnectionLost && attempt <= maxRetries) {
console.warn(`[DB] MySQL connection lost (${err.code || err.message}). Auto-retrying attempt ${attempt}/${maxRetries}...`);
await new Promise(res => setTimeout(res, 250 * attempt));
continue;
}
throw err;
}
}
}
pool.query = function(...args) {
return executeWithRetry(originalQuery, args);
};
pool.execute = function(...args) {
return executeWithRetry(originalExecute, args);
};
// 心跳探针:每 25 秒自动执行一次 SELECT 1,防止云端防火墙丢弃空闲长连接
const heartbeatTimer = setInterval(async () => {
try {
await pool.query('SELECT 1');
} catch (err) {
console.warn('[DB] Heartbeat ping error:', err.message);
}
}, 25000);
if (heartbeatTimer.unref) {
heartbeatTimer.unref();
}
/**
* 数据库初始化
*
* 架构规范说明:
* 1. 采用【家庭 (family)】为顶层实体维护体系:
* - 1 个家庭对应多个看护人员 (family_member)
* - 1 个家庭对应多个宝宝档案 (baby_profile)
* - 日常打卡行为 (activity_record) 关联所属宝宝,并由看护人执行记录
* 2. 程序中仅维护当前最新且完整的表结构 (CREATE TABLE IF NOT EXISTS)。
* 3. 严禁在应用程序中编写动态 ALTER / 结构迁移逻辑。
* 4. 独立 SQL 脚本文件请见项目根目录: sql/database.sql
* 后续如有任何表结构或字段变更,由用户/管理员在数据库客户端手动执行增量变更部分。
*/
async function initDatabase() {
console.log('Connecting to MySQL and ensuring table schemas...');
const conn = await pool.getConnection();
try {
// 1. 家庭信息表 (family - 顶层核心实体)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`family\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`family_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '家庭唯一业务ID',
\`name\` VARCHAR(100) NOT NULL COMMENT '家庭名称',
\`invite_code\` VARCHAR(32) NOT NULL UNIQUE COMMENT '家庭加入邀请码',
\`creator_name\` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
\`is_default\` TINYINT(1) DEFAULT 0 COMMENT '是否为系统默认家庭',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_family_default\` (\`is_default\`),
INDEX \`idx_family_invite\` (\`invite_code\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭核心信息表';
`);
// 2. 家庭看护人员成员表 (family_member - 1个家庭对应多个看护人)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`family_member\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`family_id\` VARCHAR(64) NOT NULL COMMENT '所属家庭ID (关联 family.family_id)',
\`role_name\` VARCHAR(50) NOT NULL COMMENT '看护人身份称谓',
\`user_id\` VARCHAR(64) NULL COMMENT '关联系统用户ID',
\`is_owner\` TINYINT(1) DEFAULT 0 COMMENT '是否为创建者/主看护人',
\`joined_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX \`idx_family_member\` (\`family_id\`),
INDEX \`idx_member_user\` (\`user_id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭看护人员成员表';
`);
// 3. 宝宝档案表 (baby_profile - 1个家庭对应多个宝宝)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`baby_profile\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`baby_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '业务唯一ID',
\`family_id\` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID',
\`name\` VARCHAR(50) NOT NULL COMMENT '宝宝昵称',
\`gender\` ENUM('boy', 'girl') NOT NULL DEFAULT 'boy' COMMENT '性别',
\`birth_date\` DATE NOT NULL COMMENT '出生日期',
\`theme_color\` VARCHAR(20) DEFAULT '#3B82F6' COMMENT '主题识别色',
\`is_default\` TINYINT(1) DEFAULT 0 COMMENT '是否默认选中',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_baby_family\` (\`family_id\`),
INDEX \`idx_baby_default\` (\`is_default\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='宝宝档案表';
`);
// 4. 行为事件流水表 (activity_record - 归属宝宝,由看护人记录)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`activity_record\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`record_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '记录唯一ID',
\`baby_id\` VARCHAR(64) NOT NULL COMMENT '所属宝宝ID',
\`activity_type\` ENUM('bottle', 'breastfeed', 'sleep', 'diaper', 'custom') NOT NULL COMMENT '行为类型',
\`start_time\` DATETIME NOT NULL COMMENT '发生/开始时间',
\`end_time\` DATETIME NULL COMMENT '结束时间',
\`duration_minutes\` INT DEFAULT 0 COMMENT '持续总分钟数',
\`payload\` JSON NULL COMMENT '行为扩展属性(奶量ml, 左右侧时长, 尿布颜色性状等)',
\`operator_name\` VARCHAR(50) DEFAULT '宝妈' COMMENT '操作人称呼',
\`operator_user_id\` VARCHAR(64) NULL COMMENT '操作人用户ID (二阶段备用)',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_baby_start\` (\`baby_id\`, \`start_time\`),
INDEX \`idx_type_start\` (\`activity_type\`, \`start_time\`),
INDEX \`idx_start_time\` (\`start_time\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='行为打卡流水表';
`);
// 5. 用户私人自定义目标与打卡项表 (custom_metric)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`custom_metric\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`metric_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '自定义项唯一ID',
\`baby_id\` VARCHAR(64) NOT NULL DEFAULT 'global' COMMENT '所属宝宝或通用',
\`name\` VARCHAR(50) NOT NULL COMMENT '项目名称',
\`icon\` VARCHAR(20) DEFAULT '✨' COMMENT '图标',
\`type\` ENUM('count', 'duration', 'value') DEFAULT 'count' COMMENT '计次/时长/数值',
\`unit\` VARCHAR(20) DEFAULT '次' COMMENT '单位',
\`default_value\` VARCHAR(30) DEFAULT '1' COMMENT '默认打卡数值',
\`target_daily\` INT DEFAULT 1 COMMENT '每日目标量',
\`is_active\` TINYINT(1) DEFAULT 1 COMMENT '是否启用',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_metric_baby\` (\`baby_id\`),
INDEX \`idx_metric_active\` (\`is_active\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='自定义打卡项目配置表';
`);
// 6. 用户体系预留表 (user - 二阶段微信登录预留)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`user\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY,
\`user_id\` VARCHAR(64) NOT NULL UNIQUE,
\`openid\` VARCHAR(128) NULL UNIQUE COMMENT '微信 openid',
\`unionid\` VARCHAR(128) NULL COMMENT '微信 unionid',
\`phone\` VARCHAR(20) NULL,
\`nickname\` VARCHAR(50) DEFAULT '看护人',
\`avatar_url\` VARCHAR(255) NULL,
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='看护人用户表(预留)';
`);
// 7. 家庭日常备忘待办清单表 (family_memo - 家庭看护团队协同清单)
await conn.query(`
CREATE TABLE IF NOT EXISTS \`family_memo\` (
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
\`memo_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '备忘唯一业务ID',
\`family_id\` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID',
\`content\` VARCHAR(255) NOT NULL COMMENT '待办备忘内容',
\`due_period\` VARCHAR(30) DEFAULT 'today' COMMENT '推荐时段',
\`is_completed\` TINYINT(1) DEFAULT 0 COMMENT '是否已完成',
\`completed_at\` DATETIME NULL COMMENT '完成时刻',
\`created_by\` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX \`idx_memo_family\` (\`family_id\`, \`is_completed\`),
INDEX \`idx_memo_created\` (\`created_at\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭日常备忘待办清单表';
`);
// 增量字段安全检测 (preferences & default_config)
try {
await conn.query("ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好'");
} catch (e) {}
try {
await conn.query("ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置'");
} catch (e) {}
// 预置默认家庭 (如果无家庭)
const [existingFamilies] = await conn.query('SELECT COUNT(*) as count FROM `family`');
if (existingFamilies[0].count === 0) {
console.log('Seeding initial family (小花园之家, YY8888)...');
await conn.query(`
INSERT INTO \`family\` (\`family_id\`, \`name\`, \`invite_code\`, \`creator_name\`, \`is_default\`)
VALUES ('family-001', '小花园之家', 'YY8888', '宝妈', 1)
`);
await conn.query(`
INSERT INTO \`family_member\` (\`family_id\`, \`role_name\`, \`is_owner\`)
VALUES
('family-001', '宝妈', 1),
('family-001', '宝爸', 0),
('family-001', '爷爷', 0),
('family-001', '奶奶', 0),
('family-001', '外公', 0),
('family-001', '外婆', 0),
('family-001', '舅舅', 0),
('family-001', '舅妈', 0)
`);
}
// 首次冷启动时,如无宝宝档案则预置初始化默认宝宝 (嘟嘟)
const [existingBabies] = await conn.query('SELECT COUNT(*) as count FROM `baby_profile`');
if (existingBabies[0].count === 0) {
console.log('Seeding initial baby profile (嘟嘟)...');
const d1 = new Date(Date.now() - 42 * 24 * 3600 * 1000).toISOString().split('T')[0];
await conn.query(`
INSERT INTO \`baby_profile\` (\`baby_id\`, \`family_id\`, \`name\`, \`gender\`, \`birth_date\`, \`theme_color\`, \`is_default\`)
VALUES
('baby-001', 'family-001', '嘟嘟', 'boy', ?, '#3B82F6', 1)
`, [d1]);
}
// 首次冷启动时,如无自定义项目则预置通用目标 (维D3、俯趴等)
const [existingMetrics] = await conn.query('SELECT COUNT(*) as count FROM `custom_metric`');
if (existingMetrics[0].count === 0) {
await conn.query(`
INSERT INTO \`custom_metric\` (\`metric_id\`, \`baby_id\`, \`name\`, \`icon\`, \`unit\`, \`target_daily\`)
VALUES
('metric-d3', 'global', '补充维生素 D3', '💊', '滴', 1),
('metric-tummy', 'global', '俯趴 Tummy Time', '🐢', '分钟', 15),
('metric-massage', 'global', '抚触 / 湿疹护肤', '🧴', '次', 2),
('metric-temp', 'global', '体温监测', '🌡', '℃', 1)
`);
}
console.log('Database initialization complete! Family, caregivers, babies and records are ready.');
} finally {
conn.release();
}
}
module.exports = { pool, initDatabase };
-178
View File
@@ -1,178 +0,0 @@
/**
* Pediatric Age-Adaptive Milestone Engine
* Calculates age-specific clinical baselines and wake window sleep predictors.
*/
const PEDIATRIC_BASELINES = [
{
minDays: 0,
maxDays: 28,
stageName: '新生儿期 (0-1月)',
feedingIntervalHours: 2.5,
wakeWindowMinutes: 60,
dailyMilkMlMin: 550,
dailyMilkMlMax: 750,
targetSleepHoursMin: 16,
targetSleepHoursMax: 18,
diaperCountMin: 8,
diaperCountMax: 10,
tips: '胃容量小,以按需喂养为主,清醒时间不宜超过1小时防过度疲劳。'
},
{
minDays: 29,
maxDays: 90,
stageName: '婴儿早期 (2-3月)',
feedingIntervalHours: 3.2,
wakeWindowMinutes: 80,
dailyMilkMlMin: 700,
dailyMilkMlMax: 850,
targetSleepHoursMin: 14,
targetSleepHoursMax: 16,
diaperCountMin: 6,
diaperCountMax: 8,
tips: '夜间开始出现4~5小时较长睡眠,傍晚容易肠绞痛与黄昏闹,多做飞机抱。'
},
{
minDays: 91,
maxDays: 180,
stageName: '规律过渡期 (4-6月)',
feedingIntervalHours: 3.8,
wakeWindowMinutes: 120,
dailyMilkMlMin: 800,
dailyMilkMlMax: 950,
targetSleepHoursMin: 13,
targetSleepHoursMax: 15,
diaperCountMin: 5,
diaperCountMax: 6,
tips: '面临4月龄睡眠倒退期(睡眠周期成人化),白天小睡逐渐规律为晨/午/傍晚3觉。'
},
{
minDays: 181,
maxDays: 270,
stageName: '辅食添加期 (7-9月)',
feedingIntervalHours: 4.0,
wakeWindowMinutes: 180,
dailyMilkMlMin: 600,
dailyMilkMlMax: 800,
targetSleepHoursMin: 12,
targetSleepHoursMax: 14,
diaperCountMin: 4,
diaperCountMax: 6,
tips: '辅食从高铁米粉过渡到肉泥菜泥,白天小睡逐渐合并为上午觉与下午觉。'
},
{
minDays: 271,
maxDays: 365,
stageName: '学步转化期 (10-12月)',
feedingIntervalHours: 4.2,
wakeWindowMinutes: 210,
dailyMilkMlMin: 500,
dailyMilkMlMax: 600,
targetSleepHoursMin: 11,
targetSleepHoursMax: 13,
diaperCountMin: 4,
diaperCountMax: 5,
tips: '三餐辅食逐渐成为热量主要来源,夜间可达10~11小时整觉。'
}
];
function getBabyAgeContext(birthDateStr) {
const birth = new Date(birthDateStr).getTime();
const now = Date.now();
const diffDays = Math.max(0, Math.floor((now - birth) / (1000 * 60 * 60 * 24)));
const months = Math.floor(diffDays / 30.4375);
const remainingDays = Math.floor(diffDays % 30.4375);
let baseline = PEDIATRIC_BASELINES[PEDIATRIC_BASELINES.length - 1];
for (const b of PEDIATRIC_BASELINES) {
if (diffDays <= b.maxDays) {
baseline = b;
break;
}
}
let ageText = '';
if (months === 0) {
ageText = `出生 ${diffDays} 天`;
} else {
ageText = `${months} 个月 ${remainingDays} 天 (出生 ${diffDays} 天)`;
}
return {
diffDays,
months,
remainingDays,
ageText,
baseline
};
}
/**
* Calculates wake window and sleep prediction
* @param {string|null} lastSleepEndTime - ISO string or YYYY-MM-DD HH:mm:ss of when last sleep ended
* @param {boolean} isCurrentlySleeping
* @param {object} baseline
*/
function calculateWakeWindow(lastSleepEndTime, isCurrentlySleeping, baseline) {
if (isCurrentlySleeping) {
return {
isSleeping: true,
awakeMinutes: 0,
maxWakeMinutes: baseline.wakeWindowMinutes,
progressPercent: 0,
phase: 'sleeping',
phaseText: '睡眠中',
hintText: '宝宝正在香甜睡眠中,生长激素正在高效分泌。'
};
}
if (!lastSleepEndTime) {
return {
isSleeping: false,
awakeMinutes: 45,
maxWakeMinutes: baseline.wakeWindowMinutes,
progressPercent: 50,
phase: 'energetic',
phaseText: '精力充沛',
hintText: '适宜开展亲子互动、Tummy Time 俯趴抬头练习。'
};
}
const lastEnd = new Date(lastSleepEndTime).getTime();
const now = Date.now();
const awakeMinutes = Math.max(0, Math.floor((now - lastEnd) / (1000 * 60)));
const maxWakeMinutes = baseline.wakeWindowMinutes;
const progressPercent = Math.min(100, Math.round((awakeMinutes / maxWakeMinutes) * 100));
let phase = 'energetic';
let phaseText = '精力充沛';
let hintText = '状态良好,适度进行黑白卡、抚触与发音互动。';
if (progressPercent >= 70 && progressPercent <= 100) {
phase = 'golden_window';
phaseText = '黄金哄睡期';
const remainMin = Math.max(0, maxWakeMinutes - awakeMinutes);
hintText = `预计还有约 ${remainMin} 分钟达到疲劳极限。请留心揉眼、抓耳朵、打哈欠等睡眠信号,适时安排安抚入睡!`;
} else if (progressPercent > 100) {
phase = 'overtired';
phaseText = '放电过度预警';
const overMin = awakeMinutes - maxWakeMinutes;
hintText = `已超时清醒 ${overMin} 分钟!警惕过度疲劳引发歇斯底里闹觉,建议立即调暗光线、开启白噪音轻拍安抚!`;
}
return {
isSleeping: false,
awakeMinutes,
maxWakeMinutes,
progressPercent,
phase,
phaseText,
hintText
};
}
module.exports = {
getBabyAgeContext,
calculateWakeWindow,
PEDIATRIC_BASELINES
};
-131
View File
@@ -1,131 +0,0 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const { getBabyAgeContext } = require('../pediatricEngine');
// GET /api/babies - List all babies (supports optional ?family_id= filter)
router.get('/', async (req, res) => {
try {
const { family_id } = req.query;
let query = 'SELECT * FROM `baby_profile`';
const params = [];
if (family_id) {
query += ' WHERE `family_id` = ?';
params.push(family_id);
}
query += ' ORDER BY `is_default` DESC, `id` ASC';
const [rows] = await pool.query(query, params);
const babiesWithContext = rows.map(b => {
const ageContext = getBabyAgeContext(b.birth_date);
return {
...b,
ageDays: ageContext.diffDays,
ageMonths: ageContext.months,
ageText: ageContext.ageText,
baseline: ageContext.baseline
};
});
res.json({ success: true, data: babiesWithContext });
} catch (err) {
console.error('Error fetching babies:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// POST /api/babies - Create or update baby profile
router.post('/', async (req, res) => {
const { babyId, familyId, name, gender, birthDate, themeColor } = req.body;
if (!name || !birthDate) {
return res.status(400).json({ success: false, error: '姓名与出生日期必填' });
}
const id = babyId || 'baby-' + Date.now();
const color = themeColor || '#3B82F6';
const targetFamilyId = familyId || 'family-001';
try {
if (babyId) {
// Update
await pool.query(`
UPDATE \`baby_profile\`
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
WHERE \`baby_id\` = ?
`, [name, gender || 'boy', birthDate, color, babyId]);
} else {
// Insert with family_id
await pool.query(`
INSERT INTO \`baby_profile\` (\`baby_id\`, \`family_id\`, \`name\`, \`gender\`, \`birth_date\`, \`theme_color\`, \`is_default\`)
VALUES (?, ?, ?, ?, ?, ?, 0)
`, [id, targetFamilyId, name, gender || 'boy', birthDate, color]);
}
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [id]);
res.json({ success: true, data: updated[0] });
} catch (err) {
console.error('Error saving baby:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// PUT /api/babies/:babyId - Update baby profile
router.put('/:babyId', async (req, res) => {
const { babyId } = req.params;
const { name, gender, birthDate, themeColor, defaultConfig } = req.body;
if (!name || !birthDate) {
return res.status(400).json({ success: false, error: '姓名与出生日期必填' });
}
const color = themeColor || '#3B82F6';
try {
const configJson = defaultConfig ? (typeof defaultConfig === 'string' ? defaultConfig : JSON.stringify(defaultConfig)) : null;
if (configJson !== null) {
await pool.query(`
UPDATE \`baby_profile\`
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?, \`default_config\` = ?
WHERE \`baby_id\` = ?
`, [name, gender || 'boy', birthDate, color, configJson, babyId]);
} else {
await pool.query(`
UPDATE \`baby_profile\`
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
WHERE \`baby_id\` = ?
`, [name, gender || 'boy', birthDate, color, babyId]);
}
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
res.json({ success: true, data: updated[0] });
} catch (err) {
console.error('Error updating baby:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// PUT /api/babies/:babyId/defaults - Update default config for baby
router.put('/:babyId/defaults', async (req, res) => {
const { babyId } = req.params;
const { defaultConfig } = req.body;
try {
const configJson = typeof defaultConfig === 'string' ? defaultConfig : JSON.stringify(defaultConfig || {});
await pool.query('UPDATE `baby_profile` SET `default_config` = ? WHERE `baby_id` = ?', [configJson, babyId]);
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
res.json({ success: true, message: '宝宝默认行为配置已更新', data: updated[0] });
} catch (err) {
console.error('Error updating baby defaults:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// POST /api/babies/:babyId/default - Set as default baby
router.post('/:babyId/default', async (req, res) => {
const { babyId } = req.params;
try {
await pool.query('UPDATE `baby_profile` SET `is_default` = 0');
await pool.query('UPDATE `baby_profile` SET `is_default` = 1 WHERE `baby_id` = ?', [babyId]);
res.json({ success: true });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;
-26
View File
@@ -1,26 +0,0 @@
const express = require('express');
const router = express.Router();
const { CARE_GUIDES } = require('../careGuidesData');
// GET /api/care-guides - List all care guides
router.get('/', (req, res) => {
const { category } = req.query;
if (category) {
return res.json({
success: true,
data: CARE_GUIDES.filter(g => g.category === category)
});
}
res.json({ success: true, data: CARE_GUIDES });
});
// GET /api/care-guides/:id - Get specific guide
router.get('/:id', (req, res) => {
const guide = CARE_GUIDES.find(g => g.id === req.params.id);
if (!guide) {
return res.status(404).json({ success: false, error: '未找到该指导项目' });
}
res.json({ success: true, data: guide });
});
module.exports = router;
-94
View File
@@ -1,94 +0,0 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
// GET /api/custom-metrics
router.get('/', async (req, res) => {
const { babyId } = req.query;
try {
const [rows] = await pool.query(`
SELECT * FROM \`custom_metric\`
WHERE \`is_active\` = 1 AND (\`baby_id\` = 'global' OR \`baby_id\` = ?)
ORDER BY \`id\` ASC
`, [babyId || '']);
res.json({ success: true, data: rows });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// POST /api/custom-metrics - Create new metric
router.post('/', async (req, res) => {
const { babyId, name, icon, unit, targetDaily, defaultValue, type } = req.body;
if (!name) {
return res.status(400).json({ success: false, error: '名称必填' });
}
const metricId = 'metric-' + Date.now();
const target = parseInt(targetDaily) || 1;
const unitStr = unit || '次';
const iconStr = icon || '✨';
const defValStr = String(defaultValue !== undefined && defaultValue !== null && defaultValue !== '' ? defaultValue : '1');
const typeStr = type || 'count';
const bId = babyId || 'global';
try {
await pool.query(`
INSERT INTO \`custom_metric\` (\`metric_id\`, \`baby_id\`, \`name\`, \`icon\`, \`type\`, \`unit\`, \`default_value\`, \`target_daily\`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`, [metricId, bId, name, iconStr, typeStr, unitStr, defValStr, target]);
const [created] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
res.json({ success: true, data: created[0] });
} catch (err) {
console.error('Error creating custom metric:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// PUT /api/custom-metrics/:metricId - Update metric configuration including default value
router.put('/:metricId', async (req, res) => {
const { metricId } = req.params;
const { name, icon, unit, targetDaily, defaultValue, type, isActive } = req.body;
try {
const [existing] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
if (existing.length === 0) {
return res.status(404).json({ success: false, error: '未找到该自定义指标' });
}
const cur = existing[0];
const newName = name !== undefined ? name : cur.name;
const newIcon = icon !== undefined ? icon : cur.icon;
const newUnit = unit !== undefined ? unit : cur.unit;
const newDefVal = defaultValue !== undefined ? String(defaultValue) : cur.default_value;
const newTarget = targetDaily !== undefined ? parseInt(targetDaily) : cur.target_daily;
const newType = type !== undefined ? type : cur.type;
const newActive = isActive !== undefined ? (isActive ? 1 : 0) : cur.is_active;
await pool.query(`
UPDATE \`custom_metric\`
SET \`name\` = ?, \`icon\` = ?, \`unit\` = ?, \`default_value\` = ?, \`target_daily\` = ?, \`type\` = ?, \`is_active\` = ?
WHERE \`metric_id\` = ?
`, [newName, newIcon, newUnit, newDefVal, newTarget, newType, newActive, metricId]);
const [updated] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
res.json({ success: true, data: updated[0] });
} catch (err) {
console.error('Error updating custom metric:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// DELETE /api/custom-metrics/:metricId
router.delete('/:metricId', async (req, res) => {
const { metricId } = req.params;
try {
await pool.query('UPDATE `custom_metric` SET `is_active` = 0 WHERE `metric_id` = ?', [metricId]);
res.json({ success: true });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;
-98
View File
@@ -1,98 +0,0 @@
const express = require('express');
const router = express.Router();
const XLSX = require('xlsx');
const { pool } = require('../db');
router.get('/excel', async (req, res) => {
const { babyId } = req.query;
if (!babyId) {
return res.status(400).json({ success: false, error: '缺少 babyId 参数' });
}
try {
const [babies] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
const babyName = babies.length > 0 ? babies[0].name : '宝宝';
const [rows] = await pool.query(`
SELECT * FROM \`activity_record\`
WHERE \`baby_id\` = ?
ORDER BY \`start_time\` DESC
`, [babyId]);
// Format Sheet 1: Detail logs
const detailData = rows.map(r => {
const payload = typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {});
let detailDesc = '';
if (r.activity_type === 'bottle') {
detailDesc = `瓶喂 ${payload.amountMl || 0}ml (${payload.milkType === 'formula' ? '配方奶' : '母乳'})`;
} else if (r.activity_type === 'breastfeed') {
detailDesc = `母乳亲喂 (左侧${payload.leftMinutes || 0}分 / 右侧${payload.rightMinutes || 0}分)`;
} else if (r.activity_type === 'sleep') {
detailDesc = `睡眠时长: ${r.duration_minutes || 0}分钟`;
} else if (r.activity_type === 'diaper') {
const t = payload.diaperType === 'poop' ? '便便' : (payload.diaperType === 'both' ? '尿+便' : '嘘嘘');
detailDesc = `换尿布: ${t} (${payload.poopColor || ''} ${payload.poopTexture || ''})`;
} else {
detailDesc = payload.note || '日常记录';
}
const typeMap = {
bottle: '瓶喂',
breastfeed: '亲喂',
sleep: '睡眠',
diaper: '换尿布',
custom: '其他'
};
return {
'发生时间': r.start_time,
'行为分类': typeMap[r.activity_type] || r.activity_type,
'操作详情': detailDesc,
'持续时长(分钟)': r.duration_minutes || 0,
'记录人/看护人': r.operator_name || '宝妈',
'备注说明': payload.note || ''
};
});
// Format Sheet 2: Daily Aggregation
const [dailyRows] = await pool.query(`
SELECT
DATE(\`start_time\`) as logDate,
COUNT(*) as totalEvents,
SUM(CASE WHEN \`activity_type\` = 'bottle' THEN CAST(JSON_EXTRACT(\`payload\`, '$.amountMl') AS UNSIGNED) ELSE 0 END) as totalMilk,
SUM(CASE WHEN \`activity_type\` = 'sleep' THEN \`duration_minutes\` ELSE 0 END) as totalSleepMin,
SUM(CASE WHEN \`activity_type\` = 'diaper' THEN 1 ELSE 0 END) as diaperCount
FROM \`activity_record\`
WHERE \`baby_id\` = ?
GROUP BY DATE(\`start_time\`)
ORDER BY logDate DESC
`, [babyId]);
const summaryData = dailyRows.map(d => ({
'日期': d.logDate,
'今日总奶量(ml)': d.totalMilk || 0,
'总睡眠时长': `${Math.floor((d.totalSleepMin || 0) / 60)}小时${(d.totalSleepMin || 0) % 60}分`,
'换尿布次数': d.diaperCount || 0,
'总打卡记录数': d.totalEvents
}));
const wb = XLSX.utils.book_new();
const ws1 = XLSX.utils.json_to_sheet(detailData);
const ws2 = XLSX.utils.json_to_sheet(summaryData);
XLSX.utils.book_append_sheet(wb, ws1, '行为流水明细');
XLSX.utils.book_append_sheet(wb, ws2, '每日数据汇总');
const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
const fileName = encodeURIComponent(`${babyName}_新生儿日常记录表.xlsx`);
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"; filename*=UTF-8''${fileName}`);
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.send(buffer);
} catch (err) {
console.error('Error generating Excel export:', err);
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;
-279
View File
@@ -1,279 +0,0 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
function generateInviteCode() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = 'YY';
for (let i = 0; i < 4; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
// 1. 获取所有家庭列表(聚合各自的宝宝与看护人成员)
router.get('/', async (req, res) => {
try {
const [families] = await pool.query(
'SELECT family_id, name, invite_code, creator_name, is_default, created_at, updated_at FROM `family` ORDER BY is_default DESC, id ASC'
);
if (families.length === 0) {
return res.json({ success: true, data: [] });
}
const familyIds = families.map(f => f.family_id);
const placeholders = familyIds.map(() => '?').join(',');
// 批量查询宝宝
const [babies] = await pool.query(
`SELECT baby_id, family_id, name, gender, birth_date, theme_color, is_default
FROM \`baby_profile\`
WHERE family_id IN (${placeholders})
ORDER BY is_default DESC, id ASC`,
familyIds
);
// 批量查询家庭成员
const [members] = await pool.query(
`SELECT id, family_id, role_name, is_owner, preferences, joined_at
FROM \`family_member\`
WHERE family_id IN (${placeholders})
ORDER BY is_owner DESC, id ASC`,
familyIds
);
const result = families.map(f => {
return {
...f,
babies: babies.filter(b => b.family_id === f.family_id),
members: members.filter(m => m.family_id === f.family_id)
};
});
res.json({ success: true, data: result });
} catch (err) {
console.error('Failed to get families:', err);
res.status(500).json({ success: false, message: '获取家庭列表失败', error: err.message });
}
});
// 2. 创建新家庭
router.post('/', async (req, res) => {
try {
const { name, creatorName = '宝妈' } = req.body;
if (!name || !name.trim()) {
return res.status(400).json({ success: false, message: '家庭名称不能为空' });
}
const familyId = `family-${Date.now().toString(36)}-${Math.random().toString(36).substring(2, 6)}`;
let inviteCode = generateInviteCode();
// 确保邀请码唯一
for (let i = 0; i < 5; i++) {
const [existing] = await pool.query('SELECT id FROM `family` WHERE invite_code = ?', [inviteCode]);
if (existing.length === 0) break;
inviteCode = generateInviteCode();
}
await pool.query(
'INSERT INTO `family` (family_id, name, invite_code, creator_name, is_default) VALUES (?, ?, ?, ?, 0)',
[familyId, name.trim(), inviteCode, creatorName]
);
// 默认加入创建者成员
await pool.query(
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 1)',
[familyId, creatorName]
);
// 默认补充常用协同看护人 (如宝爸)
if (creatorName === '宝妈') {
await pool.query(
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
[familyId, '宝爸']
);
}
res.json({
success: true,
message: '家庭创建成功',
data: {
family_id: familyId,
name: name.trim(),
invite_code: inviteCode,
creator_name: creatorName,
is_default: 0
}
});
} catch (err) {
console.error('Failed to create family:', err);
res.status(500).json({ success: false, message: '创建家庭失败', error: err.message });
}
});
// 3. 修改家庭基础信息 (如家庭名称)
router.put('/:familyId', async (req, res) => {
try {
const { familyId } = req.params;
const { name } = req.body;
if (!name || !name.trim()) {
return res.status(400).json({ success: false, message: '家庭名称不能为空' });
}
const [result] = await pool.query(
'UPDATE `family` SET name = ? WHERE family_id = ?',
[name.trim(), familyId]
);
if (result.affectedRows === 0) {
return res.status(404).json({ success: false, message: '未找到指定家庭' });
}
res.json({ success: true, message: '家庭名称修改成功' });
} catch (err) {
console.error('Failed to update family:', err);
res.status(500).json({ success: false, message: '修改家庭失败', error: err.message });
}
});
// 4. 输入邀请码加入家庭 (为微信邀请/口令加入打通)
router.post('/join', async (req, res) => {
try {
const { inviteCode, roleName = '看护人' } = req.body;
if (!inviteCode || !inviteCode.trim()) {
return res.status(400).json({ success: false, message: '请输入家庭邀请码' });
}
const cleanCode = inviteCode.trim().toUpperCase();
const [families] = await pool.query(
'SELECT family_id, name, invite_code, creator_name FROM `family` WHERE UPPER(invite_code) = ?',
[cleanCode]
);
if (families.length === 0) {
return res.status(400).json({
success: false,
message: '邀请码不存在或已失效,请向家庭管理员索取正确的 6 位邀请码'
});
}
const family = families[0];
// 检查该角色成员是否已在该家庭中
const [existingMember] = await pool.query(
'SELECT id FROM `family_member` WHERE family_id = ? AND role_name = ?',
[family.family_id, roleName]
);
if (existingMember.length === 0) {
await pool.query(
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
[family.family_id, roleName]
);
}
res.json({
success: true,
message: `恭喜!已成功加入【${family.name}】`,
data: family
});
} catch (err) {
console.error('Failed to join family:', err);
res.status(500).json({ success: false, message: '加入家庭失败', error: err.message });
}
});
// 5. 获取家庭看护人成员列表
router.get('/:familyId/members', async (req, res) => {
try {
const { familyId } = req.params;
const [members] = await pool.query(
'SELECT id, family_id, role_name, is_owner, preferences, joined_at FROM `family_member` WHERE family_id = ? ORDER BY is_owner DESC, id ASC',
[familyId]
);
res.json({ success: true, data: members });
} catch (err) {
console.error('Failed to get family members:', err);
res.status(500).json({ success: false, message: '获取家庭成员失败', error: err.message });
}
});
// 6. 为家庭新增看护人员成员
router.post('/:familyId/members', async (req, res) => {
try {
const { familyId } = req.params;
const { roleName } = req.body;
if (!roleName || !roleName.trim()) {
return res.status(400).json({ success: false, message: '看护人身份称谓不能为空' });
}
const [existing] = await pool.query(
'SELECT id FROM `family_member` WHERE family_id = ? AND role_name = ?',
[familyId, roleName.trim()]
);
if (existing.length > 0) {
return res.status(400).json({ success: false, message: '该看护人身份已在家庭中' });
}
const [result] = await pool.query(
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
[familyId, roleName.trim()]
);
res.json({
success: true,
message: '添加看护人员成功',
data: {
id: result.insertId,
family_id: familyId,
role_name: roleName.trim(),
is_owner: 0
}
});
} catch (err) {
console.error('Failed to add family member:', err);
res.status(500).json({ success: false, message: '添加家庭成员失败', error: err.message });
}
});
// 7. 更新指定看护人专属行为记忆偏好
router.put('/:familyId/members/:roleName/preferences', async (req, res) => {
try {
const { familyId, roleName } = req.params;
const { preferences } = req.body;
const [member] = await pool.query(
'SELECT id, preferences FROM `family_member` WHERE family_id = ? AND role_name = ?',
[familyId, roleName]
);
if (member.length === 0) {
return res.status(404).json({ success: false, message: '该看护人成员不存在' });
}
const prefJson = typeof preferences === 'string' ? preferences : JSON.stringify(preferences || {});
await pool.query(
'UPDATE `family_member` SET `preferences` = ? WHERE family_id = ? AND role_name = ?',
[prefJson, familyId, roleName]
);
res.json({
success: true,
message: '角色偏好已保存',
data: {
familyId,
roleName,
preferences: typeof preferences === 'string' ? JSON.parse(preferences) : preferences
}
});
} catch (err) {
console.error('Failed to update member preferences:', err);
res.status(500).json({ success: false, message: '更新角色偏好失败', error: err.message });
}
});
module.exports = router;
-206
View File
@@ -1,206 +0,0 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const { broadcastEvent } = require('./sse');
/**
* GET /api/memos
* 获取指定家庭的备忘待办清单
*/
router.get('/', async (req, res) => {
try {
const familyId = req.query.familyId || 'family-001';
const { status, search, period } = req.query;
let query = 'SELECT * FROM family_memo WHERE family_id = ?';
const params = [familyId];
if (status === 'pending') {
query += ' AND is_completed = 0';
} else if (status === 'completed') {
query += ' AND is_completed = 1';
}
if (period && period !== 'all') {
query += ' AND due_period = ?';
params.push(period);
}
if (search && search.trim()) {
query += ' AND (content LIKE ? OR created_by LIKE ?)';
params.push(`%${search.trim()}%`, `%${search.trim()}%`);
}
query += ' ORDER BY is_completed ASC, created_at DESC';
const [rows] = await pool.query(query, params);
res.json({
success: true,
data: rows
});
} catch (err) {
console.error('Failed to get memos:', err);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* POST /api/memos/clear-completed
* 清理指定家庭已完成的历史备忘
*/
router.post('/clear-completed', async (req, res) => {
try {
const { familyId = 'family-001' } = req.body;
const [result] = await pool.query(
'DELETE FROM family_memo WHERE family_id = ? AND is_completed = 1',
[familyId]
);
broadcastEvent({
type: 'memos_cleared',
familyId,
clearedCount: result.affectedRows
});
res.json({
success: true,
message: `已成功清理 ${result.affectedRows} 项已完成备忘`,
affectedRows: result.affectedRows
});
} catch (err) {
console.error('Failed to clear completed memos:', err);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* POST /api/memos
* 新增备忘待办事项
*/
router.post('/', async (req, res) => {
try {
const { familyId = 'family-001', content, duePeriod = 'today', operatorName = '家人' } = req.body;
if (!content || !content.trim()) {
return res.status(400).json({ success: false, error: '备忘待办内容不能为空' });
}
const memoId = `memo-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
await pool.query(
`INSERT INTO family_memo (memo_id, family_id, content, due_period, is_completed, created_by)
VALUES (?, ?, ?, ?, 0, ?)`,
[memoId, familyId, content.trim(), duePeriod, operatorName]
);
const [created] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
broadcastEvent({
type: 'memo_created',
familyId,
memo: created[0]
});
res.json({
success: true,
data: created[0]
});
} catch (err) {
console.error('Failed to create memo:', err);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* PUT /api/memos/:memoId
* 更新备忘事项(勾选完成/修改内容)
*/
router.put('/:memoId', async (req, res) => {
try {
const { memoId } = req.params;
const { isCompleted, content, duePeriod } = req.body;
const [rows] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
if (rows.length === 0) {
return res.status(404).json({ success: false, error: '备忘事项不存在' });
}
const updates = [];
const params = [];
if (isCompleted !== undefined) {
updates.push('is_completed = ?');
params.push(isCompleted ? 1 : 0);
if (isCompleted) {
updates.push('completed_at = CURRENT_TIMESTAMP');
} else {
updates.push('completed_at = NULL');
}
}
if (content !== undefined && content.trim()) {
updates.push('content = ?');
params.push(content.trim());
}
if (duePeriod !== undefined) {
updates.push('due_period = ?');
params.push(duePeriod);
}
if (updates.length > 0) {
params.push(memoId);
await pool.query(
`UPDATE family_memo SET ${updates.join(', ')} WHERE memo_id = ?`,
params
);
}
const [updated] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
broadcastEvent({
type: 'memo_updated',
familyId: rows[0].family_id,
memo: updated[0]
});
res.json({
success: true,
data: updated[0]
});
} catch (err) {
console.error('Failed to update memo:', err);
res.status(500).json({ success: false, error: err.message });
}
});
/**
* DELETE /api/memos/:memoId
* 删除备忘事项
*/
router.delete('/:memoId', async (req, res) => {
try {
const { memoId } = req.params;
const [rows] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
if (rows.length === 0) {
return res.status(404).json({ success: false, error: '备忘事项不存在' });
}
await pool.query('DELETE FROM family_memo WHERE memo_id = ?', [memoId]);
broadcastEvent({
type: 'memo_deleted',
familyId: rows[0].family_id,
memoId
});
res.json({
success: true,
message: '备忘事项已删除'
});
} catch (err) {
console.error('Failed to delete memo:', err);
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;
-196
View File
@@ -1,196 +0,0 @@
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const { broadcastEvent } = require('./sse');
function formatDateTime(d = new Date()) {
const pad = n => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
// GET /api/records - Get records for a baby
router.get('/', async (req, res) => {
const { babyId, date, limit } = req.query;
if (!babyId) {
return res.status(400).json({ success: false, error: '缺少 babyId 参数' });
}
try {
let query = 'SELECT * FROM `activity_record` WHERE `baby_id` = ?';
const params = [babyId];
if (date) {
query += ' AND DATE(`start_time`) = ?';
params.push(date);
}
query += ' ORDER BY `start_time` DESC';
if (limit) {
query += ' LIMIT ?';
params.push(parseInt(limit));
}
const [rows] = await pool.query(query, params);
const parsed = rows.map(r => ({
...r,
payload: typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {})
}));
res.json({ success: true, data: parsed });
} catch (err) {
console.error('Error fetching records:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// POST /api/records - Create a record (One-tap log)
router.post('/', async (req, res) => {
const {
babyId,
activityType,
startTime,
endTime,
durationMinutes,
payload,
operatorName,
operatorUserId
} = req.body;
if (!babyId || !activityType) {
return res.status(400).json({ success: false, error: 'babyId 与 activityType 必填' });
}
const recordId = 'rec-' + Date.now() + '-' + Math.random().toString(36).substring(2, 6);
const nowStr = formatDateTime();
const start = startTime || nowStr;
const end = endTime || null;
const duration = durationMinutes || 0;
const operator = operatorName || '宝妈';
const payloadJson = JSON.stringify(payload || {});
try {
// Check recent duplicate tap (within 3 minutes)
const [recent] = await pool.query(`
SELECT * FROM \`activity_record\`
WHERE \`baby_id\` = ?
AND \`activity_type\` = ?
AND \`start_time\` >= DATE_SUB(NOW(), INTERVAL 3 MINUTE)
ORDER BY \`start_time\` DESC LIMIT 1
`, [babyId, activityType]);
let duplicateWarning = null;
if (recent.length > 0 && !req.body.forceConfirm) {
duplicateWarning = `${recent[0].operator_name} 在刚刚(${recent[0].start_time.substring(11, 16)})已记录过该行为`;
}
await pool.query(`
INSERT INTO \`activity_record\`
(\`record_id\`, \`baby_id\`, \`activity_type\`, \`start_time\`, \`end_time\`, \`duration_minutes\`, \`payload\`, \`operator_name\`, \`operator_user_id\`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`, [recordId, babyId, activityType, start, end, duration, payloadJson, operator, operatorUserId || null]);
const [created] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
const recordObj = {
...created[0],
payload: typeof created[0].payload === 'string' ? JSON.parse(created[0].payload || '{}') : (created[0].payload || {})
};
// Broadcast SSE to all other mobile devices!
broadcastEvent({
type: 'record_created',
babyId,
activityType,
operatorName: operator,
record: recordObj
});
res.json({
success: true,
data: recordObj,
duplicateWarning
});
} catch (err) {
console.error('Error creating record:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// PUT /api/records/:recordId - Update record
router.put('/:recordId', async (req, res) => {
const { recordId } = req.params;
const { startTime, endTime, durationMinutes, payload, operatorName } = req.body;
try {
const fields = [];
const params = [];
if (startTime !== undefined) {
fields.push('`start_time` = ?');
params.push(startTime);
}
if (endTime !== undefined) {
fields.push('`end_time` = ?');
params.push(endTime);
}
if (durationMinutes !== undefined) {
fields.push('`duration_minutes` = ?');
params.push(durationMinutes);
}
if (payload !== undefined) {
fields.push('`payload` = ?');
params.push(JSON.stringify(payload));
}
if (operatorName !== undefined) {
fields.push('`operator_name` = ?');
params.push(operatorName);
}
if (fields.length === 0) {
return res.json({ success: true });
}
params.push(recordId);
await pool.query(`UPDATE \`activity_record\` SET ${fields.join(', ')} WHERE \`record_id\` = ?`, params);
const [updated] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
if (updated.length > 0) {
broadcastEvent({
type: 'record_updated',
babyId: updated[0].baby_id,
record: updated[0]
});
}
res.json({ success: true, data: updated[0] });
} catch (err) {
console.error('Error updating record:', err);
res.status(500).json({ success: false, error: err.message });
}
});
// DELETE /api/records/:recordId - Delete record
router.delete('/:recordId', async (req, res) => {
const { recordId } = req.params;
try {
const [existing] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
if (existing.length === 0) {
return res.status(404).json({ success: false, error: '记录不存在' });
}
await pool.query('DELETE FROM `activity_record` WHERE `record_id` = ?', [recordId]);
broadcastEvent({
type: 'record_deleted',
babyId: existing[0].baby_id,
recordId
});
res.json({ success: true });
} catch (err) {
console.error('Error deleting record:', err);
res.status(500).json({ success: false, error: err.message });
}
});
module.exports = router;
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more