feat(health): 用药记录实体 — CRUD 全栈
- 迁移 080: medication_record 表(18 字段 + 频率/给药途径校验)
- Entity/DTO/Service/Handler 全链路
- 端点: GET/POST/PUT/DELETE /health/medications + /health/patients/{id}/medications
- 软删除 + 乐观锁 + 审计日志
This commit is contained in:
128
crates/erp-health/src/dto/medication_record_dto.rs
Normal file
128
crates/erp-health/src/dto/medication_record_dto.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
/// 创建用药记录请求
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct CreateMedicationRecordReq {
|
||||
pub patient_id: uuid::Uuid,
|
||||
/// 药品名称(商品名)
|
||||
pub medication_name: String,
|
||||
/// 通用名
|
||||
pub generic_name: Option<String>,
|
||||
/// 剂量
|
||||
pub dosage: Option<String>,
|
||||
/// 单位
|
||||
pub unit: Option<String>,
|
||||
/// 用药频率: daily/bid/tid/qid/prn
|
||||
#[serde(default)]
|
||||
pub frequency: Option<String>,
|
||||
/// 给药途径: oral/injection/topical/inhalation
|
||||
#[serde(default)]
|
||||
pub route: Option<String>,
|
||||
/// 开始日期
|
||||
pub start_date: Option<chrono::NaiveDate>,
|
||||
/// 结束日期
|
||||
pub end_date: Option<chrono::NaiveDate>,
|
||||
/// 是否当前用药(默认 true)
|
||||
#[serde(default = "default_true")]
|
||||
pub is_current: Option<bool>,
|
||||
/// 开方医生 ID
|
||||
pub prescribed_by: Option<uuid::Uuid>,
|
||||
/// 备注
|
||||
pub notes: Option<String>,
|
||||
}
|
||||
|
||||
/// 更新用药记录请求(所有字段可选)
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct UpdateMedicationRecordReq {
|
||||
pub medication_name: Option<String>,
|
||||
pub generic_name: Option<String>,
|
||||
pub dosage: Option<String>,
|
||||
pub unit: Option<String>,
|
||||
pub frequency: Option<String>,
|
||||
pub route: Option<String>,
|
||||
pub start_date: Option<chrono::NaiveDate>,
|
||||
pub end_date: Option<chrono::NaiveDate>,
|
||||
pub is_current: Option<bool>,
|
||||
pub prescribed_by: Option<uuid::Uuid>,
|
||||
pub notes: Option<String>,
|
||||
}
|
||||
|
||||
/// 用药记录响应
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct MedicationRecordResp {
|
||||
pub id: uuid::Uuid,
|
||||
pub patient_id: uuid::Uuid,
|
||||
pub medication_name: String,
|
||||
pub generic_name: Option<String>,
|
||||
pub dosage: Option<String>,
|
||||
pub unit: Option<String>,
|
||||
pub frequency: Option<String>,
|
||||
pub route: Option<String>,
|
||||
pub start_date: Option<chrono::NaiveDate>,
|
||||
pub end_date: Option<chrono::NaiveDate>,
|
||||
pub is_current: bool,
|
||||
pub prescribed_by: Option<uuid::Uuid>,
|
||||
pub notes: Option<String>,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
pub version: i32,
|
||||
}
|
||||
|
||||
/// 创建请求的输入清洗
|
||||
impl CreateMedicationRecordReq {
|
||||
/// 清洗用户输入:去除首尾空白,截断超长字段
|
||||
pub fn sanitize(&mut self) {
|
||||
self.medication_name = self.medication_name.trim().to_string();
|
||||
if let Some(ref mut v) = self.generic_name {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.dosage {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.unit {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.frequency {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.route {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.notes {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新请求的输入清洗
|
||||
impl UpdateMedicationRecordReq {
|
||||
/// 清洗用户输入:去除首尾空白
|
||||
pub fn sanitize(&mut self) {
|
||||
if let Some(ref mut v) = self.medication_name {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.generic_name {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.dosage {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.unit {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.frequency {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.route {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
if let Some(ref mut v) = self.notes {
|
||||
*v = v.trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> Option<bool> {
|
||||
Some(true)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub mod consent_dto;
|
||||
pub mod consultation_dto;
|
||||
pub mod daily_monitoring_dto;
|
||||
pub mod diagnosis_dto;
|
||||
pub mod medication_record_dto;
|
||||
pub mod dialysis_dto;
|
||||
pub mod doctor_dto;
|
||||
pub mod follow_up_dto;
|
||||
|
||||
70
crates/erp-health/src/entity/medication_record.rs
Normal file
70
crates/erp-health/src/entity/medication_record.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// 用药记录实体 — 记录患者当前和历史的用药情况
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "medication_record")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
/// 药品名称(商品名)
|
||||
pub medication_name: String,
|
||||
/// 通用名
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub generic_name: Option<String>,
|
||||
/// 剂量(如 500mg)
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub dosage: Option<String>,
|
||||
/// 单位(如 mg/ml/片)
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub unit: Option<String>,
|
||||
/// 用药频率: daily/bid/tid/qid/prn
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub frequency: Option<String>,
|
||||
/// 给药途径: oral/injection/topical/inhalation
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub route: Option<String>,
|
||||
/// 开始日期
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub start_date: Option<chrono::NaiveDate>,
|
||||
/// 结束日期
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub end_date: Option<chrono::NaiveDate>,
|
||||
/// 是否当前用药
|
||||
pub is_current: bool,
|
||||
/// 开方医生 ID
|
||||
#[sea_orm(skip_serializing_if = "Option::is_none")]
|
||||
pub prescribed_by: Option<Uuid>,
|
||||
/// 备注(PII 加密存储)
|
||||
#[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 {}
|
||||
@@ -35,5 +35,6 @@ pub mod points_rule;
|
||||
pub mod points_transaction;
|
||||
pub mod offline_event;
|
||||
pub mod offline_event_registration;
|
||||
pub mod medication_record;
|
||||
pub mod vital_signs;
|
||||
pub mod vital_signs_hourly;
|
||||
|
||||
130
crates/erp-health/src/handler/medication_record_handler.rs
Normal file
130
crates/erp-health/src/handler/medication_record_handler.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
use axum::Extension;
|
||||
use axum::extract::{FromRef, Json, Path, Query, State};
|
||||
use serde::Deserialize;
|
||||
use erp_core::error::AppError;
|
||||
use erp_core::rbac::require_permission;
|
||||
use erp_core::types::{ApiResponse, PaginatedResponse, TenantContext};
|
||||
|
||||
use crate::dto::medication_record_dto::*;
|
||||
use crate::dto::DeleteWithVersion;
|
||||
use crate::service::medication_record_service;
|
||||
use crate::state::HealthState;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct PaginationParams {
|
||||
pub page: Option<u64>,
|
||||
pub page_size: Option<u64>,
|
||||
}
|
||||
|
||||
/// GET /health/patients/{id}/medications — 查询患者用药记录列表
|
||||
pub async fn list_medications<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(patient_id): Path<uuid::Uuid>,
|
||||
Query(params): Query<PaginationParams>,
|
||||
) -> Result<Json<ApiResponse<PaginatedResponse<MedicationRecordResp>>>, 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 = medication_record_service::list_medications(
|
||||
&state, ctx.tenant_id, patient_id, page, page_size,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
/// GET /health/medications/{id} — 获取单条用药记录
|
||||
pub async fn get_medication<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<uuid::Uuid>,
|
||||
) -> Result<Json<ApiResponse<MedicationRecordResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.list")?;
|
||||
let result =
|
||||
medication_record_service::get_medication(&state, ctx.tenant_id, record_id).await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
/// POST /health/medications — 创建用药记录
|
||||
pub async fn create_medication<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Json(req): Json<CreateMedicationRecordReq>,
|
||||
) -> Result<Json<ApiResponse<MedicationRecordResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.manage")?;
|
||||
let result = medication_record_service::create_medication(
|
||||
&state,
|
||||
ctx.tenant_id,
|
||||
Some(ctx.user_id),
|
||||
req,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
/// PUT /health/medications/{id} — 更新用药记录
|
||||
pub async fn update_medication<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<uuid::Uuid>,
|
||||
Json(req): Json<UpdateMedicationRecordWithVersion>,
|
||||
) -> Result<Json<ApiResponse<MedicationRecordResp>>, AppError>
|
||||
where
|
||||
HealthState: FromRef<S>,
|
||||
S: Clone + Send + Sync + 'static,
|
||||
{
|
||||
require_permission(&ctx, "health.health-data.manage")?;
|
||||
let result = medication_record_service::update_medication(
|
||||
&state,
|
||||
ctx.tenant_id,
|
||||
record_id,
|
||||
Some(ctx.user_id),
|
||||
req.data,
|
||||
req.version,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(result)))
|
||||
}
|
||||
|
||||
/// DELETE /health/medications/{id} — 软删除用药记录
|
||||
pub async fn delete_medication<S>(
|
||||
State(state): State<HealthState>,
|
||||
Extension(ctx): Extension<TenantContext>,
|
||||
Path(record_id): Path<uuid::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")?;
|
||||
medication_record_service::delete_medication(
|
||||
&state,
|
||||
ctx.tenant_id,
|
||||
record_id,
|
||||
Some(ctx.user_id),
|
||||
req.version,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(ApiResponse::ok(())))
|
||||
}
|
||||
|
||||
/// 更新请求包装 — 携带 version 用于乐观锁
|
||||
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
|
||||
pub struct UpdateMedicationRecordWithVersion {
|
||||
#[serde(flatten)]
|
||||
pub data: UpdateMedicationRecordReq,
|
||||
pub version: i32,
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod critical_value_threshold_handler;
|
||||
pub mod daily_monitoring_handler;
|
||||
pub mod device_reading_handler;
|
||||
pub mod diagnosis_handler;
|
||||
pub mod medication_record_handler;
|
||||
pub mod dialysis_handler;
|
||||
pub mod doctor_handler;
|
||||
pub mod follow_up_handler;
|
||||
|
||||
@@ -8,7 +8,7 @@ use erp_core::module::{ErpModule, PermissionDescriptor};
|
||||
use crate::handler::{
|
||||
alert_handler, alert_rule_handler,
|
||||
appointment_handler, article_category_handler, article_handler, article_tag_handler, consultation_handler, consent_handler, critical_value_threshold_handler, daily_monitoring_handler, device_reading_handler, diagnosis_handler, dialysis_handler, doctor_handler, follow_up_handler,
|
||||
health_data_handler, patient_handler, points_handler, stats_handler,
|
||||
health_data_handler, medication_record_handler, patient_handler, points_handler, stats_handler,
|
||||
};
|
||||
|
||||
pub struct HealthModule;
|
||||
@@ -141,6 +141,21 @@ impl HealthModule {
|
||||
axum::routing::put(diagnosis_handler::update_diagnosis)
|
||||
.delete(diagnosis_handler::delete_diagnosis),
|
||||
)
|
||||
// 用药记录
|
||||
.route(
|
||||
"/health/patients/{id}/medications",
|
||||
axum::routing::get(medication_record_handler::list_medications),
|
||||
)
|
||||
.route(
|
||||
"/health/medications",
|
||||
axum::routing::post(medication_record_handler::create_medication),
|
||||
)
|
||||
.route(
|
||||
"/health/medications/{id}",
|
||||
axum::routing::get(medication_record_handler::get_medication)
|
||||
.put(medication_record_handler::update_medication)
|
||||
.delete(medication_record_handler::delete_medication),
|
||||
)
|
||||
.route(
|
||||
"/health/patients/{id}/vital-signs/{vid}",
|
||||
axum::routing::put(health_data_handler::update_vital_signs)
|
||||
|
||||
316
crates/erp-health/src/service/medication_record_service.rs
Normal file
316
crates/erp-health/src/service/medication_record_service.rs
Normal file
@@ -0,0 +1,316 @@
|
||||
use chrono::Utc;
|
||||
use sea_orm::{
|
||||
ActiveModelTrait, ActiveValue::Set, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter,
|
||||
QueryOrder, QuerySelect,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use erp_core::audit::AuditLog;
|
||||
use erp_core::audit_service;
|
||||
use erp_core::crypto as pii;
|
||||
use erp_core::error::check_version;
|
||||
use erp_core::types::PaginatedResponse;
|
||||
|
||||
use crate::dto::medication_record_dto::*;
|
||||
use crate::entity::medication_record;
|
||||
use crate::entity::patient;
|
||||
use crate::error::{HealthError, HealthResult};
|
||||
use crate::state::HealthState;
|
||||
|
||||
/// 分页查询患者的用药记录
|
||||
pub async fn list_medications(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
patient_id: Uuid,
|
||||
page: u64,
|
||||
page_size: u64,
|
||||
) -> HealthResult<PaginatedResponse<MedicationRecordResp>> {
|
||||
let limit = page_size.min(100);
|
||||
let offset = page.saturating_sub(1) * limit;
|
||||
|
||||
let query = medication_record::Entity::find()
|
||||
.filter(medication_record::Column::TenantId.eq(tenant_id))
|
||||
.filter(medication_record::Column::PatientId.eq(patient_id))
|
||||
.filter(medication_record::Column::DeletedAt.is_null());
|
||||
|
||||
let total = query.clone().count(&state.db).await?;
|
||||
let models = query
|
||||
.order_by_desc(medication_record::Column::CreatedAt)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all(&state.db)
|
||||
.await?;
|
||||
|
||||
let total_pages = total.div_ceil(limit.max(1));
|
||||
let crypto = &state.crypto;
|
||||
let data = models.into_iter().map(|m| to_resp(crypto, m)).collect();
|
||||
|
||||
Ok(PaginatedResponse {
|
||||
data,
|
||||
total,
|
||||
page,
|
||||
page_size: limit,
|
||||
total_pages,
|
||||
})
|
||||
}
|
||||
|
||||
/// 获取单条用药记录
|
||||
pub async fn get_medication(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
) -> HealthResult<MedicationRecordResp> {
|
||||
let model = medication_record::Entity::find()
|
||||
.filter(medication_record::Column::Id.eq(record_id))
|
||||
.filter(medication_record::Column::TenantId.eq(tenant_id))
|
||||
.filter(medication_record::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::Validation("用药记录不存在".into()))?;
|
||||
|
||||
Ok(to_resp(&state.crypto, model))
|
||||
}
|
||||
|
||||
/// 创建用药记录
|
||||
pub async fn create_medication(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
mut req: CreateMedicationRecordReq,
|
||||
) -> HealthResult<MedicationRecordResp> {
|
||||
req.sanitize();
|
||||
|
||||
// 校验患者存在
|
||||
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)?;
|
||||
|
||||
// 校验用药频率
|
||||
if let Some(ref freq) = req.frequency {
|
||||
if !validate_frequency(freq) {
|
||||
return Err(HealthError::Validation(
|
||||
"用药频率无效,可选: daily/bid/tid/qid/prn".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 校验给药途径
|
||||
if let Some(ref route) = req.route {
|
||||
if !validate_route(route) {
|
||||
return Err(HealthError::Validation(
|
||||
"给药途径无效,可选: oral/injection/topical/inhalation".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// PII 加密备注
|
||||
let kek = state.crypto.kek();
|
||||
let encrypted_notes = req
|
||||
.notes
|
||||
.as_ref()
|
||||
.map(|n| pii::encrypt(kek, n))
|
||||
.transpose()?;
|
||||
|
||||
let now = Utc::now();
|
||||
let active = medication_record::ActiveModel {
|
||||
id: Set(Uuid::now_v7()),
|
||||
tenant_id: Set(tenant_id),
|
||||
patient_id: Set(req.patient_id),
|
||||
medication_name: Set(req.medication_name),
|
||||
generic_name: Set(req.generic_name),
|
||||
dosage: Set(req.dosage),
|
||||
unit: Set(req.unit),
|
||||
frequency: Set(req.frequency),
|
||||
route: Set(req.route),
|
||||
start_date: Set(req.start_date),
|
||||
end_date: Set(req.end_date),
|
||||
is_current: Set(req.is_current.unwrap_or(true)),
|
||||
prescribed_by: Set(req.prescribed_by.or(operator_id)),
|
||||
notes: Set(encrypted_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, "medication_record.created", "medication_record")
|
||||
.with_resource_id(m.id),
|
||||
&state.db,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(to_resp(&state.crypto, m))
|
||||
}
|
||||
|
||||
/// 更新用药记录
|
||||
pub async fn update_medication(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
mut req: UpdateMedicationRecordReq,
|
||||
expected_version: i32,
|
||||
) -> HealthResult<MedicationRecordResp> {
|
||||
req.sanitize();
|
||||
|
||||
let model = medication_record::Entity::find()
|
||||
.filter(medication_record::Column::Id.eq(record_id))
|
||||
.filter(medication_record::Column::TenantId.eq(tenant_id))
|
||||
.filter(medication_record::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::Validation("用药记录不存在".into()))?;
|
||||
|
||||
let next_ver = check_version(expected_version, model.version)
|
||||
.map_err(|_| HealthError::VersionMismatch)?;
|
||||
|
||||
// 校验用药频率
|
||||
if let Some(ref freq) = req.frequency {
|
||||
if !validate_frequency(freq) {
|
||||
return Err(HealthError::Validation("用药频率无效".into()));
|
||||
}
|
||||
}
|
||||
|
||||
// 校验给药途径
|
||||
if let Some(ref route) = req.route {
|
||||
if !validate_route(route) {
|
||||
return Err(HealthError::Validation("给药途径无效".into()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut active: medication_record::ActiveModel = model.into();
|
||||
if let Some(v) = req.medication_name {
|
||||
active.medication_name = Set(v);
|
||||
}
|
||||
if let Some(v) = req.generic_name {
|
||||
active.generic_name = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.dosage {
|
||||
active.dosage = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.unit {
|
||||
active.unit = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.frequency {
|
||||
active.frequency = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.route {
|
||||
active.route = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.start_date {
|
||||
active.start_date = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.end_date {
|
||||
active.end_date = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.is_current {
|
||||
active.is_current = Set(v);
|
||||
}
|
||||
if let Some(v) = req.prescribed_by {
|
||||
active.prescribed_by = Set(Some(v));
|
||||
}
|
||||
if let Some(v) = req.notes {
|
||||
let kek = state.crypto.kek();
|
||||
let encrypted = pii::encrypt(kek, &v)?;
|
||||
active.notes = Set(Some(encrypted));
|
||||
}
|
||||
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, "medication_record.updated", "medication_record")
|
||||
.with_resource_id(m.id),
|
||||
&state.db,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(to_resp(&state.crypto, m))
|
||||
}
|
||||
|
||||
/// 软删除用药记录
|
||||
pub async fn delete_medication(
|
||||
state: &HealthState,
|
||||
tenant_id: Uuid,
|
||||
record_id: Uuid,
|
||||
operator_id: Option<Uuid>,
|
||||
expected_version: i32,
|
||||
) -> HealthResult<()> {
|
||||
let model = medication_record::Entity::find()
|
||||
.filter(medication_record::Column::Id.eq(record_id))
|
||||
.filter(medication_record::Column::TenantId.eq(tenant_id))
|
||||
.filter(medication_record::Column::DeletedAt.is_null())
|
||||
.one(&state.db)
|
||||
.await?
|
||||
.ok_or(HealthError::Validation("用药记录不存在".into()))?;
|
||||
|
||||
let next_ver = check_version(expected_version, model.version)
|
||||
.map_err(|_| HealthError::VersionMismatch)?;
|
||||
|
||||
let mut active: medication_record::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, "medication_record.deleted", "medication_record")
|
||||
.with_resource_id(record_id),
|
||||
&state.db,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Model → Resp 转换(解密 PII 字段)
|
||||
fn to_resp(crypto: &erp_core::crypto::PiiCrypto, m: medication_record::Model) -> MedicationRecordResp {
|
||||
let kek = crypto.kek();
|
||||
|
||||
// 解密备注
|
||||
let notes = m
|
||||
.notes
|
||||
.as_ref()
|
||||
.map(|n| pii::decrypt(kek, n).unwrap_or_else(|_| n.clone()))
|
||||
.or(m.notes);
|
||||
|
||||
MedicationRecordResp {
|
||||
id: m.id,
|
||||
patient_id: m.patient_id,
|
||||
medication_name: m.medication_name,
|
||||
generic_name: m.generic_name,
|
||||
dosage: m.dosage,
|
||||
unit: m.unit,
|
||||
frequency: m.frequency,
|
||||
route: m.route,
|
||||
start_date: m.start_date,
|
||||
end_date: m.end_date,
|
||||
is_current: m.is_current,
|
||||
prescribed_by: m.prescribed_by,
|
||||
notes,
|
||||
created_at: m.created_at,
|
||||
updated_at: m.updated_at,
|
||||
version: m.version,
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验用药频率
|
||||
fn validate_frequency(freq: &str) -> bool {
|
||||
matches!(freq, "daily" | "bid" | "tid" | "qid" | "prn")
|
||||
}
|
||||
|
||||
/// 校验给药途径
|
||||
fn validate_route(route: &str) -> bool {
|
||||
matches!(route, "oral" | "injection" | "topical" | "inhalation")
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod critical_value_threshold_service;
|
||||
pub mod daily_monitoring_service;
|
||||
pub mod device_reading_service;
|
||||
pub mod diagnosis_service;
|
||||
pub mod medication_record_service;
|
||||
pub mod dialysis_service;
|
||||
pub mod doctor_service;
|
||||
pub mod follow_up_service;
|
||||
|
||||
@@ -79,6 +79,7 @@ mod m20260426_000076_create_alert_rules;
|
||||
mod m20260426_000077_create_alerts;
|
||||
mod m20260427_000078_normalize_follow_up_types;
|
||||
mod m20260427_000079_add_vital_signs_fields;
|
||||
mod m20260427_000080_create_medication_record;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
@@ -165,6 +166,7 @@ impl MigratorTrait for Migrator {
|
||||
Box::new(m20260426_000077_create_alerts::Migration),
|
||||
Box::new(m20260427_000078_normalize_follow_up_types::Migration),
|
||||
Box::new(m20260427_000079_add_vital_signs_fields::Migration),
|
||||
Box::new(m20260427_000080_create_medication_record::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Alias::new("medication_record"))
|
||||
.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("medication_name")).string_len(200).not_null())
|
||||
.col(ColumnDef::new(Alias::new("generic_name")).string_len(200).null())
|
||||
.col(ColumnDef::new(Alias::new("dosage")).string_len(50).null())
|
||||
.col(ColumnDef::new(Alias::new("unit")).string_len(20).null())
|
||||
.col(ColumnDef::new(Alias::new("frequency")).string_len(20).null())
|
||||
.col(ColumnDef::new(Alias::new("route")).string_len(20).null())
|
||||
.col(ColumnDef::new(Alias::new("start_date")).date().null())
|
||||
.col(ColumnDef::new(Alias::new("end_date")).date().null())
|
||||
.col(ColumnDef::new(Alias::new("is_current")).boolean().not_null().default(true))
|
||||
.col(ColumnDef::new(Alias::new("prescribed_by")).uuid().null())
|
||||
.col(ColumnDef::new(Alias::new("notes")).text().null())
|
||||
.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().null())
|
||||
.col(ColumnDef::new(Alias::new("updated_by")).uuid().null())
|
||||
.col(ColumnDef::new(Alias::new("deleted_at")).timestamp_with_time_zone().null())
|
||||
.col(
|
||||
ColumnDef::new(Alias::new("version"))
|
||||
.integer()
|
||||
.not_null()
|
||||
.default(1),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 租户+患者复合索引 — 最常用的查询维度
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.if_not_exists()
|
||||
.name("idx_medication_record_tenant_patient")
|
||||
.table(Alias::new("medication_record"))
|
||||
.col(Alias::new("tenant_id"))
|
||||
.col(Alias::new("patient_id"))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 软删除索引 — 过滤已删除记录
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.if_not_exists()
|
||||
.name("idx_medication_record_deleted_at")
|
||||
.table(Alias::new("medication_record"))
|
||||
.col(Alias::new("deleted_at"))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Alias::new("medication_record")).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user