feat(health): 日常监测后端 + 积分商城 PC 管理页面 (Chunk 3 V2 迭代)
后端 - 日常监测: - 新增 daily_monitoring 表 (血压/体重/血糖/出入量/备注) - Entity/DTO/Service/Handler 完整 CRUD - 唯一约束 (patient_id, record_date) 防重复上报 前端 - 积分商城管理 (3 页面): - PointsRuleList: 积分规则增删改 + 启用禁用 - PointsProductList: 商品管理 + 库存 + 类型筛选 - PointsOrderList: 订单列表 + 扫码核销 - API 模块 points.ts 对接 6 个管理端接口 - 侧边栏新增积分规则/商品管理/订单管理入口
This commit is contained in:
72
crates/erp-health/src/dto/daily_monitoring_dto.rs
Normal file
72
crates/erp-health/src/dto/daily_monitoring_dto.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use chrono::NaiveDate;
|
||||
use erp_core::sanitize::sanitize_option;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use uuid::Uuid;
|
||||
|
||||
type Decimal = f64;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 日常监测
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct CreateDailyMonitoringReq {
|
||||
pub patient_id: Uuid,
|
||||
pub record_date: NaiveDate,
|
||||
pub morning_bp_systolic: Option<i32>,
|
||||
pub morning_bp_diastolic: Option<i32>,
|
||||
pub evening_bp_systolic: Option<i32>,
|
||||
pub evening_bp_diastolic: Option<i32>,
|
||||
pub weight: Option<Decimal>,
|
||||
pub blood_sugar: Option<Decimal>,
|
||||
pub fluid_intake: Option<i32>,
|
||||
pub urine_output: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes: Option<String>,
|
||||
}
|
||||
|
||||
impl CreateDailyMonitoringReq {
|
||||
pub fn sanitize(&mut self) {
|
||||
self.notes = sanitize_option(self.notes.take());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UpdateDailyMonitoringReq {
|
||||
pub record_date: Option<NaiveDate>,
|
||||
pub morning_bp_systolic: Option<i32>,
|
||||
pub morning_bp_diastolic: Option<i32>,
|
||||
pub evening_bp_systolic: Option<i32>,
|
||||
pub evening_bp_diastolic: Option<i32>,
|
||||
pub weight: Option<Decimal>,
|
||||
pub blood_sugar: Option<Decimal>,
|
||||
pub fluid_intake: Option<i32>,
|
||||
pub urine_output: Option<i32>,
|
||||
pub notes: Option<String>,
|
||||
}
|
||||
|
||||
impl UpdateDailyMonitoringReq {
|
||||
pub fn sanitize(&mut self) {
|
||||
self.notes = sanitize_option(self.notes.take());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct DailyMonitoringResp {
|
||||
pub id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
pub record_date: NaiveDate,
|
||||
pub morning_bp_systolic: Option<i32>,
|
||||
pub morning_bp_diastolic: Option<i32>,
|
||||
pub evening_bp_systolic: Option<i32>,
|
||||
pub evening_bp_diastolic: Option<i32>,
|
||||
pub weight: Option<Decimal>,
|
||||
pub blood_sugar: Option<Decimal>,
|
||||
pub fluid_intake: Option<i32>,
|
||||
pub urine_output: Option<i32>,
|
||||
pub notes: Option<String>,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
pub version: i32,
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod appointment_dto;
|
||||
pub mod article_dto;
|
||||
pub mod consultation_dto;
|
||||
pub mod daily_monitoring_dto;
|
||||
pub mod dialysis_dto;
|
||||
pub mod doctor_dto;
|
||||
pub mod follow_up_dto;
|
||||
|
||||
57
crates/erp-health/src/entity/daily_monitoring.rs
Normal file
57
crates/erp-health/src/entity/daily_monitoring.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "daily_monitoring")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
pub record_date: chrono::NaiveDate,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub morning_bp_systolic: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub morning_bp_diastolic: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub evening_bp_systolic: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub evening_bp_diastolic: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub weight: Option<Decimal>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub blood_sugar: Option<Decimal>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub fluid_intake: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub urine_output: Option<i32>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub notes: Option<String>,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub created_by: Option<Uuid>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub updated_by: Option<Uuid>,
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
pub version: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::patient::Entity",
|
||||
from = "Column::PatientId",
|
||||
to = "super::patient::Column::Id"
|
||||
)]
|
||||
Patient,
|
||||
}
|
||||
|
||||
impl Related<super::patient::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Patient.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -2,6 +2,7 @@ pub mod appointment;
|
||||
pub mod article;
|
||||
pub mod consultation_message;
|
||||
pub mod consultation_session;
|
||||
pub mod daily_monitoring;
|
||||
pub mod dialysis_record;
|
||||
pub mod doctor_profile;
|
||||
pub mod doctor_schedule;
|
||||
|
||||
@@ -26,6 +26,9 @@ pub enum HealthError {
|
||||
#[error("透析记录不存在")]
|
||||
DialysisRecordNotFound,
|
||||
|
||||
#[error("日常监测记录不存在")]
|
||||
DailyMonitoringNotFound,
|
||||
|
||||
#[error("兑换商品不存在")]
|
||||
PointsProductNotFound,
|
||||
|
||||
@@ -85,7 +88,8 @@ impl From<HealthError> for AppError {
|
||||
| HealthError::ArticleNotFound
|
||||
| HealthError::PointsProductNotFound
|
||||
| HealthError::PointsOrderNotFound
|
||||
| HealthError::OfflineEventNotFound => AppError::NotFound(err.to_string()),
|
||||
| HealthError::OfflineEventNotFound
|
||||
| HealthError::DailyMonitoringNotFound => AppError::NotFound(err.to_string()),
|
||||
HealthError::ScheduleFull => AppError::Validation(err.to_string()),
|
||||
HealthError::InvalidStatusTransition(s) => AppError::Validation(s),
|
||||
HealthError::VersionMismatch => AppError::VersionMismatch,
|
||||
|
||||
121
crates/erp-health/src/handler/daily_monitoring_handler.rs
Normal file
121
crates/erp-health/src/handler/daily_monitoring_handler.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use axum::Extension;
|
||||
use axum::extract::{FromRef, Json, Path, Query, State};
|
||||
use serde::Deserialize;
|
||||
use utoipa::IntoParams;
|
||||
use uuid::Uuid;
|
||||
|
||||
use erp_core::error::AppError;
|
||||
use erp_core::rbac::require_permission;
|
||||
use erp_core::types::{ApiResponse, PaginatedResponse, TenantContext};
|
||||
|
||||
use crate::dto::daily_monitoring_dto::*;
|
||||
use crate::dto::DeleteWithVersion;
|
||||
use crate::service::daily_monitoring_service;
|
||||
use crate::state::HealthState;
|
||||
|
||||
#[derive(Debug, Deserialize, IntoParams)]
|
||||
pub struct PaginationParams {
|
||||
pub page: Option<u64>,
|
||||
pub page_size: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateDailyMonitoringWithVersion {
|
||||
#[serde(flatten)]
|
||||
pub data: UpdateDailyMonitoringReq,
|
||||
pub version: i32,
|
||||
}
|
||||
|
||||
pub async fn list_daily_monitoring<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(patient_id): Path<Uuid>,
|
||||
Query(params): Query<PaginationParams>,
|
||||
) -> Result<Json<ApiResponse<PaginatedResponse<DailyMonitoringResp>>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.list")?;
|
||||
let page = params.page.unwrap_or(1);
|
||||
let page_size = params.page_size.unwrap_or(20);
|
||||
let result = daily_monitoring_service::list_daily_monitoring(
|
||||
&state, ctx.tenant_id, patient_id, page, page_size,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
pub async fn get_daily_monitoring<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<Uuid>,
|
||||
) -> Result<Json<ApiResponse<DailyMonitoringResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.list")?;
|
||||
let result = daily_monitoring_service::get_daily_monitoring(
|
||||
&state, ctx.tenant_id, record_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
pub async fn create_daily_monitoring<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Json(req): Json<CreateDailyMonitoringReq>,
|
||||
) -> Result<Json<ApiResponse<DailyMonitoringResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.manage")?;
|
||||
let mut req = req;
|
||||
req.sanitize();
|
||||
let result = daily_monitoring_service::create_daily_monitoring(
|
||||
&state, ctx.tenant_id, Some(ctx.user_id), req,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
pub async fn update_daily_monitoring<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<Uuid>,
|
||||
Json(req): Json<UpdateDailyMonitoringWithVersion>,
|
||||
) -> Result<Json<ApiResponse<DailyMonitoringResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.manage")?;
|
||||
let mut data = req.data;
|
||||
data.sanitize();
|
||||
let result = daily_monitoring_service::update_daily_monitoring(
|
||||
&state, ctx.tenant_id, record_id, Some(ctx.user_id), data, req.version,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
pub async fn delete_daily_monitoring<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<Uuid>,
|
||||
Json(req): Json<DeleteWithVersion>,
|
||||
) -> Result<Json<ApiResponse<()>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.manage")?;
|
||||
daily_monitoring_service::delete_daily_monitoring(
|
||||
&state, ctx.tenant_id, record_id, Some(ctx.user_id), req.version,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(())))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod appointment_handler;
|
||||
pub mod article_handler;
|
||||
pub mod consultation_handler;
|
||||
pub mod daily_monitoring_handler;
|
||||
pub mod dialysis_handler;
|
||||
pub mod doctor_handler;
|
||||
pub mod follow_up_handler;
|
||||
|
||||
@@ -6,7 +6,7 @@ use erp_core::events::EventBus;
|
||||
use erp_core::module::{ErpModule, PermissionDescriptor};
|
||||
|
||||
use crate::handler::{
|
||||
appointment_handler, article_handler, consultation_handler, dialysis_handler, doctor_handler, follow_up_handler,
|
||||
appointment_handler, article_handler, consultation_handler, daily_monitoring_handler, dialysis_handler, doctor_handler, follow_up_handler,
|
||||
health_data_handler, patient_handler, points_handler,
|
||||
};
|
||||
|
||||
@@ -163,6 +163,21 @@ impl HealthModule {
|
||||
"/health/dialysis-records/{id}/review",
|
||||
axum::routing::put(dialysis_handler::review_dialysis_record),
|
||||
)
|
||||
// 日常监测
|
||||
.route(
|
||||
"/health/patients/{id}/daily-monitoring",
|
||||
axum::routing::get(daily_monitoring_handler::list_daily_monitoring),
|
||||
)
|
||||
.route(
|
||||
"/health/daily-monitoring",
|
||||
axum::routing::post(daily_monitoring_handler::create_daily_monitoring),
|
||||
)
|
||||
.route(
|
||||
"/health/daily-monitoring/{id}",
|
||||
axum::routing::get(daily_monitoring_handler::get_daily_monitoring)
|
||||
.put(daily_monitoring_handler::update_daily_monitoring)
|
||||
.delete(daily_monitoring_handler::delete_daily_monitoring),
|
||||
)
|
||||
// 化验报告审阅
|
||||
.route(
|
||||
"/health/patients/{id}/lab-reports/{rid}/review",
|
||||
|
||||
221
crates/erp-health/src/service/daily_monitoring_service.rs
Normal file
221
crates/erp-health/src/service/daily_monitoring_service.rs
Normal file
@@ -0,0 +1,221 @@
|
||||
//! 日常监测 Service — 患者每日血压/体重/血糖/出入量 CRUD
|
||||
|
||||
use chrono::Utc;
|
||||
use erp_core::audit::AuditLog;
|
||||
use erp_core::audit_service;
|
||||
use num_traits::ToPrimitive;
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::{ActiveValue::Set, QueryOrder, QuerySelect};
|
||||
use uuid::Uuid;
|
||||
|
||||
use erp_core::error::check_version;
|
||||
use erp_core::types::PaginatedResponse;
|
||||
|
||||
use crate::dto::daily_monitoring_dto::*;
|
||||
use crate::entity::{daily_monitoring, patient};
|
||||
use crate::error::{HealthError, HealthResult};
|
||||
use crate::state::HealthState;
|
||||
|
||||
pub async fn list_daily_monitoring(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
patient_id: Uuid,
|
||||
page: u64,
|
||||
page_size: u64,
|
||||
) -> HealthResult<PaginatedResponse<DailyMonitoringResp>> {
|
||||
let limit = page_size.min(100);
|
||||
let offset = page.saturating_sub(1) * limit;
|
||||
|
||||
let query = daily_monitoring::Entity::find()
|
||||
.filter(daily_monitoring::Column::TenantId.eq(tenant_id))
|
||||
.filter(daily_monitoring::Column::PatientId.eq(patient_id))
|
||||
.filter(daily_monitoring::Column::DeletedAt.is_null());
|
||||
|
||||
let total = query.clone().count(&state.db).await?;
|
||||
let models = query
|
||||
.order_by_desc(daily_monitoring::Column::RecordDate)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all(&state.db)
|
||||
.await?;
|
||||
|
||||
let total_pages = total.div_ceil(limit.max(1));
|
||||
let data: Vec<DailyMonitoringResp> = models.into_iter().map(to_resp).collect();
|
||||
|
||||
Ok(PaginatedResponse { data, total, page, page_size: limit, total_pages })
|
||||
}
|
||||
|
||||
pub async fn get_daily_monitoring(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
) -> HealthResult<DailyMonitoringResp> {
|
||||
let m = daily_monitoring::Entity::find()
|
||||
.filter(daily_monitoring::Column::Id.eq(record_id))
|
||||
.filter(daily_monitoring::Column::TenantId.eq(tenant_id))
|
||||
.filter(daily_monitoring::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::DailyMonitoringNotFound)?;
|
||||
|
||||
Ok(to_resp(m))
|
||||
}
|
||||
|
||||
pub async fn create_daily_monitoring(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
req: CreateDailyMonitoringReq,
|
||||
) -> HealthResult<DailyMonitoringResp> {
|
||||
// 验证患者存在且属于当前租户
|
||||
patient::Entity::find()
|
||||
.filter(patient::Column::Id.eq(req.patient_id))
|
||||
.filter(patient::Column::TenantId.eq(tenant_id))
|
||||
.filter(patient::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::PatientNotFound)?;
|
||||
|
||||
// 唯一约束检查: 同一患者同一日期不能有两条记录
|
||||
let existing = daily_monitoring::Entity::find()
|
||||
.filter(daily_monitoring::Column::PatientId.eq(req.patient_id))
|
||||
.filter(daily_monitoring::Column::RecordDate.eq(req.record_date))
|
||||
.filter(daily_monitoring::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?;
|
||||
|
||||
if existing.is_some() {
|
||||
return Err(HealthError::Validation("该日期已有日常监测记录".to_string()));
|
||||
}
|
||||
|
||||
let now = Utc::now();
|
||||
let active = daily_monitoring::ActiveModel {
|
||||
id: Set(Uuid::now_v7()),
|
||||
tenant_id: Set(tenant_id),
|
||||
patient_id: Set(req.patient_id),
|
||||
record_date: Set(req.record_date),
|
||||
morning_bp_systolic: Set(req.morning_bp_systolic),
|
||||
morning_bp_diastolic: Set(req.morning_bp_diastolic),
|
||||
evening_bp_systolic: Set(req.evening_bp_systolic),
|
||||
evening_bp_diastolic: Set(req.evening_bp_diastolic),
|
||||
weight: Set(req.weight.map(|v| Decimal::from_f64_retain(v).unwrap_or_default())),
|
||||
blood_sugar: Set(req.blood_sugar.map(|v| Decimal::from_f64_retain(v).unwrap_or_default())),
|
||||
fluid_intake: Set(req.fluid_intake),
|
||||
urine_output: Set(req.urine_output),
|
||||
notes: Set(req.notes),
|
||||
created_at: Set(now),
|
||||
updated_at: Set(now),
|
||||
created_by: Set(operator_id),
|
||||
updated_by: Set(operator_id),
|
||||
deleted_at: Set(None),
|
||||
version: Set(1),
|
||||
};
|
||||
let m = active.insert(&state.db).await?;
|
||||
|
||||
audit_service::record(
|
||||
AuditLog::new(tenant_id, operator_id, "daily_monitoring.created", "daily_monitoring")
|
||||
.with_resource_id(m.id),
|
||||
&state.db,
|
||||
).await;
|
||||
|
||||
Ok(to_resp(m))
|
||||
}
|
||||
|
||||
pub async fn update_daily_monitoring(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
req: UpdateDailyMonitoringReq,
|
||||
expected_version: i32,
|
||||
) -> HealthResult<DailyMonitoringResp> {
|
||||
let model = daily_monitoring::Entity::find()
|
||||
.filter(daily_monitoring::Column::Id.eq(record_id))
|
||||
.filter(daily_monitoring::Column::TenantId.eq(tenant_id))
|
||||
.filter(daily_monitoring::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::DailyMonitoringNotFound)?;
|
||||
|
||||
let next_ver = check_version(expected_version, model.version)
|
||||
.map_err(|_| HealthError::VersionMismatch)?;
|
||||
|
||||
let mut active: daily_monitoring::ActiveModel = model.into();
|
||||
if let Some(v) = req.record_date { active.record_date = Set(v); }
|
||||
if let Some(v) = req.morning_bp_systolic { active.morning_bp_systolic = Set(Some(v)); }
|
||||
if let Some(v) = req.morning_bp_diastolic { active.morning_bp_diastolic = Set(Some(v)); }
|
||||
if let Some(v) = req.evening_bp_systolic { active.evening_bp_systolic = Set(Some(v)); }
|
||||
if let Some(v) = req.evening_bp_diastolic { active.evening_bp_diastolic = Set(Some(v)); }
|
||||
if let Some(v) = req.weight { active.weight = Set(Some(Decimal::from_f64_retain(v).unwrap_or_default())); }
|
||||
if let Some(v) = req.blood_sugar { active.blood_sugar = Set(Some(Decimal::from_f64_retain(v).unwrap_or_default())); }
|
||||
if let Some(v) = req.fluid_intake { active.fluid_intake = Set(Some(v)); }
|
||||
if let Some(v) = req.urine_output { active.urine_output = Set(Some(v)); }
|
||||
if let Some(v) = req.notes { active.notes = Set(Some(v)); }
|
||||
active.updated_at = Set(Utc::now());
|
||||
active.updated_by = Set(operator_id);
|
||||
active.version = Set(next_ver);
|
||||
|
||||
let m = active.update(&state.db).await?;
|
||||
|
||||
audit_service::record(
|
||||
AuditLog::new(tenant_id, operator_id, "daily_monitoring.updated", "daily_monitoring")
|
||||
.with_resource_id(m.id),
|
||||
&state.db,
|
||||
).await;
|
||||
|
||||
Ok(to_resp(m))
|
||||
}
|
||||
|
||||
pub async fn delete_daily_monitoring(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
expected_version: i32,
|
||||
) -> HealthResult<()> {
|
||||
let model = daily_monitoring::Entity::find()
|
||||
.filter(daily_monitoring::Column::Id.eq(record_id))
|
||||
.filter(daily_monitoring::Column::TenantId.eq(tenant_id))
|
||||
.filter(daily_monitoring::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::DailyMonitoringNotFound)?;
|
||||
|
||||
let next_ver = check_version(expected_version, model.version)
|
||||
.map_err(|_| HealthError::VersionMismatch)?;
|
||||
|
||||
let mut active: daily_monitoring::ActiveModel = model.into();
|
||||
active.deleted_at = Set(Some(Utc::now()));
|
||||
active.updated_at = Set(Utc::now());
|
||||
active.updated_by = Set(operator_id);
|
||||
active.version = Set(next_ver);
|
||||
active.update(&state.db).await?;
|
||||
|
||||
audit_service::record(
|
||||
AuditLog::new(tenant_id, operator_id, "daily_monitoring.deleted", "daily_monitoring")
|
||||
.with_resource_id(record_id),
|
||||
&state.db,
|
||||
).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_resp(m: daily_monitoring::Model) -> DailyMonitoringResp {
|
||||
DailyMonitoringResp {
|
||||
id: m.id,
|
||||
patient_id: m.patient_id,
|
||||
record_date: m.record_date,
|
||||
morning_bp_systolic: m.morning_bp_systolic,
|
||||
morning_bp_diastolic: m.morning_bp_diastolic,
|
||||
evening_bp_systolic: m.evening_bp_systolic,
|
||||
evening_bp_diastolic: m.evening_bp_diastolic,
|
||||
weight: m.weight.map(|d| d.to_f64().unwrap_or(0.0)),
|
||||
blood_sugar: m.blood_sugar.map(|d| d.to_f64().unwrap_or(0.0)),
|
||||
fluid_intake: m.fluid_intake,
|
||||
urine_output: m.urine_output,
|
||||
notes: m.notes,
|
||||
created_at: m.created_at,
|
||||
updated_at: m.updated_at,
|
||||
version: m.version,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod appointment_service;
|
||||
pub mod article_service;
|
||||
pub mod consultation_service;
|
||||
pub mod daily_monitoring_service;
|
||||
pub mod dialysis_service;
|
||||
pub mod doctor_service;
|
||||
pub mod follow_up_service;
|
||||
|
||||
@@ -53,6 +53,7 @@ mod m20260425_00050_add_doctor_name_column;
|
||||
mod m20260425_000051_dialysis_and_lab_enhance;
|
||||
mod m20260425_000052_create_ai_tables;
|
||||
mod m20260425_000053_create_points_tables;
|
||||
mod m20260425_000054_create_daily_monitoring;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
@@ -113,6 +114,7 @@ impl MigratorTrait for Migrator {
|
||||
Box::new(m20260425_000051_dialysis_and_lab_enhance::Migration),
|
||||
Box::new(m20260425_000052_create_ai_tables::Migration),
|
||||
Box::new(m20260425_000053_create_points_tables::Migration),
|
||||
Box::new(m20260425_000054_create_daily_monitoring::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
/// V2 日常监测表: daily_monitoring — 患者每日血压/体重/血糖/出入量记录
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Alias::new("daily_monitoring"))
|
||||
.if_not_exists()
|
||||
.col(ColumnDef::new(Alias::new("id")).uuid().not_null().primary_key())
|
||||
.col(ColumnDef::new(Alias::new("tenant_id")).uuid().not_null())
|
||||
.col(ColumnDef::new(Alias::new("patient_id")).uuid().not_null())
|
||||
.col(ColumnDef::new(Alias::new("record_date")).date().not_null())
|
||||
// 晨起血压
|
||||
.col(ColumnDef::new(Alias::new("morning_bp_systolic")).integer())
|
||||
.col(ColumnDef::new(Alias::new("morning_bp_diastolic")).integer())
|
||||
// 晚间血压
|
||||
.col(ColumnDef::new(Alias::new("evening_bp_systolic")).integer())
|
||||
.col(ColumnDef::new(Alias::new("evening_bp_diastolic")).integer())
|
||||
// 体重 (Decimal 5,1)
|
||||
.col(ColumnDef::new(Alias::new("weight")).decimal().extra("CHECK(weight IS NULL OR weight >= 0)"))
|
||||
// 血糖 (Decimal 4,1)
|
||||
.col(ColumnDef::new(Alias::new("blood_sugar")).decimal().extra("CHECK(blood_sugar IS NULL OR blood_sugar >= 0)"))
|
||||
// 出入量
|
||||
.col(ColumnDef::new(Alias::new("fluid_intake")).integer())
|
||||
.col(ColumnDef::new(Alias::new("urine_output")).integer())
|
||||
// 备注
|
||||
.col(ColumnDef::new(Alias::new("notes")).text())
|
||||
// 标准字段
|
||||
.col(ColumnDef::new(Alias::new("created_at")).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(Alias::new("updated_at")).timestamp_with_time_zone().not_null().default(Expr::current_timestamp()))
|
||||
.col(ColumnDef::new(Alias::new("created_by")).uuid())
|
||||
.col(ColumnDef::new(Alias::new("updated_by")).uuid())
|
||||
.col(ColumnDef::new(Alias::new("deleted_at")).timestamp_with_time_zone())
|
||||
.col(ColumnDef::new(Alias::new("version")).integer().not_null().default(1))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 唯一约束: (patient_id, record_date) — 每位患者每天最多一条记录
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.if_not_exists()
|
||||
.name("uk_daily_monitoring_patient_date")
|
||||
.table(Alias::new("daily_monitoring"))
|
||||
.col(Alias::new("patient_id"))
|
||||
.col(Alias::new("record_date"))
|
||||
.unique()
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 索引: (tenant_id, record_date) — 按租户+日期范围查询
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.if_not_exists()
|
||||
.name("idx_daily_monitoring_tenant_date")
|
||||
.table(Alias::new("daily_monitoring"))
|
||||
.col(Alias::new("tenant_id"))
|
||||
.col(Alias::new("record_date"))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Alias::new("daily_monitoring")).if_exists().to_owned())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user