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

+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');