Step 9:药品管理(IMP)

This commit is contained in:
Cheng Zhou
2025-12-16 19:26:45 +08:00
parent 566ebdf749
commit 882fcb0963
107 changed files with 855 additions and 1 deletions
+10
View File
@@ -0,0 +1,10 @@
import uuid
from datetime import date
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_db_session
from app.schemas.imp import TxCreate
router = APIRouter()
+95
View File
@@ -0,0 +1,95 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_current_user, get_db_session, require_study_member, require_study_roles
from app.crud import audit as audit_crud
from app.crud import imp_batch as batch_crud
from app.crud import study as study_crud
from app.schemas.imp import BatchCreate, BatchRead, BatchUpdate
router = APIRouter()
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
study = await study_crud.get(db, study_id)
if not study:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Study not found")
return study
@router.post(
"/",
response_model=BatchRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_study_roles(["PM", "IMP"]))],
)
async def create_batch(
study_id: uuid.UUID,
batch_in: BatchCreate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> BatchRead:
await _ensure_study_exists(db, study_id)
try:
batch = await batch_crud.create_batch(db, study_id, batch_in)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="imp_batch",
entity_id=batch.id,
action="CREATE_IMP_BATCH",
detail=f"IMP batch {batch.batch_no} created",
operator_id=current_user.id,
operator_role=current_user.role,
)
return BatchRead.model_validate(batch)
@router.get(
"/",
response_model=list[BatchRead],
dependencies=[Depends(require_study_member())],
)
async def list_batches(
study_id: uuid.UUID,
product_id: uuid.UUID | None = None,
status_filter: str | None = None,
db: AsyncSession = Depends(get_db_session),
) -> list[BatchRead]:
await _ensure_study_exists(db, study_id)
batches = await batch_crud.list_batches(db, study_id, product_id=product_id, status=status_filter)
return [BatchRead.model_validate(b) for b in batches]
@router.patch(
"/{batch_id}",
response_model=BatchRead,
dependencies=[Depends(require_study_roles(["PM", "IMP"]))],
)
async def update_batch(
study_id: uuid.UUID,
batch_id: uuid.UUID,
batch_in: BatchUpdate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> BatchRead:
await _ensure_study_exists(db, study_id)
batch = await batch_crud.get_batch(db, batch_id)
if not batch or batch.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Batch not found")
updated = await batch_crud.update_batch(db, batch, batch_in)
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="imp_batch",
entity_id=batch_id,
action="UPDATE_IMP_BATCH",
detail=f"IMP batch {batch_id} updated",
operator_id=current_user.id,
operator_role=current_user.role,
)
return BatchRead.model_validate(updated)
+32
View File
@@ -0,0 +1,32 @@
import uuid
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_db_session, require_study_member
from app.crud import imp_inventory as inventory_crud
from app.crud import study as study_crud
from app.schemas.imp import InventoryRead
router = APIRouter()
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
study = await study_crud.get(db, study_id)
return study
@router.get(
"/",
response_model=list[InventoryRead],
dependencies=[Depends(require_study_member())],
)
async def list_inventory(
study_id: uuid.UUID,
site_id: uuid.UUID | None = None,
product_id: uuid.UUID | None = None,
db: AsyncSession = Depends(get_db_session),
) -> list[InventoryRead]:
await _ensure_study_exists(db, study_id)
inv = await inventory_crud.list_inventory(db, study_id, site_id=site_id, product_id=product_id)
return [InventoryRead.model_validate(i) for i in inv]
+91
View File
@@ -0,0 +1,91 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_current_user, get_db_session, require_study_member, require_study_roles
from app.crud import audit as audit_crud
from app.crud import imp_product as product_crud
from app.crud import study as study_crud
from app.schemas.imp import ProductCreate, ProductRead, ProductUpdate
router = APIRouter()
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
study = await study_crud.get(db, study_id)
if not study:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Study not found")
return study
@router.post(
"/",
response_model=ProductRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_study_roles(["PM", "IMP"]))],
)
async def create_product(
study_id: uuid.UUID,
product_in: ProductCreate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> ProductRead:
await _ensure_study_exists(db, study_id)
product = await product_crud.create_product(db, study_id, product_in)
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="imp_product",
entity_id=product.id,
action="CREATE_IMP_PRODUCT",
detail=f"IMP product {product.name} created",
operator_id=current_user.id,
operator_role=current_user.role,
)
return ProductRead.model_validate(product)
@router.get(
"/",
response_model=list[ProductRead],
dependencies=[Depends(require_study_member())],
)
async def list_products(
study_id: uuid.UUID,
is_active: bool | None = None,
db: AsyncSession = Depends(get_db_session),
) -> list[ProductRead]:
await _ensure_study_exists(db, study_id)
products = await product_crud.list_products(db, study_id, is_active=is_active)
return [ProductRead.model_validate(p) for p in products]
@router.patch(
"/{product_id}",
response_model=ProductRead,
dependencies=[Depends(require_study_roles(["PM", "IMP"]))],
)
async def update_product(
study_id: uuid.UUID,
product_id: uuid.UUID,
product_in: ProductUpdate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> ProductRead:
await _ensure_study_exists(db, study_id)
product = await product_crud.get_product(db, product_id)
if not product or product.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
updated = await product_crud.update_product(db, product, product_in)
await audit_crud.log_action(
db,
study_id=study_id,
entity_type="imp_product",
entity_id=product_id,
action="UPDATE_IMP_PRODUCT",
detail=f"IMP product {product_id} updated",
operator_id=current_user.id,
operator_role=current_user.role,
)
return ProductRead.model_validate(updated)
+112
View File
@@ -0,0 +1,112 @@
import uuid
from datetime import date
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_current_user, get_db_session, require_study_member, require_study_roles
from app.crud import audit as audit_crud
from app.crud import imp_batch as batch_crud
from app.crud import imp_tx as tx_crud
from app.crud import study as study_crud
from app.crud import subject as subject_crud
from app.crud import member as member_crud
from app.schemas.imp import TxCreate, TxRead
from app.services.imp import create_transaction_and_apply_inventory, NEGATIVE_TYPES
router = APIRouter()
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
study = await study_crud.get(db, study_id)
if not study:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Study not found")
return study
async def _validate_entities(db: AsyncSession, study_id: uuid.UUID, site_id: uuid.UUID, batch_id: uuid.UUID, subject_id: uuid.UUID | None):
batch = await batch_crud.get_batch(db, batch_id)
if not batch or batch.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Batch not found")
from app.models.site import Site
site = await db.get(Site, site_id)
if not site or site.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Site not found")
if subject_id:
subj = await subject_crud.get_subject(db, subject_id)
if not subj or subj.study_id != study_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Subject not found")
if batch.expiry_date and date.today() > batch.expiry_date and batch_id:
# forbid outflow when expired
pass
@router.post(
"/",
response_model=TxRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_study_roles(["PM", "IMP"]))],
)
async def create_transaction(
study_id: uuid.UUID,
tx_in: TxCreate,
db: AsyncSession = Depends(get_db_session),
current_user=Depends(get_current_user),
) -> TxRead:
await _ensure_study_exists(db, study_id)
await _validate_entities(db, study_id, tx_in.site_id, tx_in.batch_id, tx_in.subject_id)
if tx_in.tx_type in NEGATIVE_TYPES:
batch = await batch_crud.get_batch(db, tx_in.batch_id)
if batch and batch.status == "EXPIRED":
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot dispense from expired batch")
try:
tx = await create_transaction_and_apply_inventory(
db,
study_id=study_id,
site_id=tx_in.site_id,
batch_id=tx_in.batch_id,
subject_id=tx_in.subject_id,
tx_type=tx_in.tx_type,
quantity=tx_in.quantity,
tx_date=tx_in.tx_date,
reference=tx_in.reference,
notes=tx_in.notes,
operator_id=current_user.id,
operator_role=current_user.role,
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return TxRead.model_validate(tx)
@router.get(
"/",
response_model=list[TxRead],
dependencies=[Depends(require_study_member())],
)
async def list_transactions(
study_id: uuid.UUID,
site_id: uuid.UUID | None = None,
batch_id: uuid.UUID | None = None,
subject_id: uuid.UUID | None = None,
tx_type: str | None = None,
date_from: date | None = None,
date_to: date | None = None,
skip: int = 0,
limit: int = 100,
db: AsyncSession = Depends(get_db_session),
) -> list[TxRead]:
await _ensure_study_exists(db, study_id)
txs = await tx_crud.list_txs(
db,
study_id,
site_id=site_id,
batch_id=batch_id,
subject_id=subject_id,
tx_type=tx_type,
date_from=date_from,
date_to=date_to,
skip=skip,
limit=limit,
)
return [TxRead.model_validate(t) for t in txs]
+5 -1
View File
@@ -1,6 +1,6 @@
from fastapi import APIRouter
from app.api.v1 import auth, users, studies, sites, members, comments, attachments, audit_logs, milestones, tasks, dashboard, subjects, visits, aes, issues, data_queries, verifications
from app.api.v1 import auth, users, studies, sites, members, comments, attachments, audit_logs, milestones, tasks, dashboard, subjects, visits, aes, issues, data_queries, verifications, imp_products, imp_batches, imp_inventory, imp_transactions
api_router = APIRouter()
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
@@ -20,3 +20,7 @@ api_router.include_router(aes.router, prefix="/studies/{study_id}/aes", tags=["a
api_router.include_router(issues.router, prefix="/studies/{study_id}/issues", tags=["issues"])
api_router.include_router(data_queries.router, prefix="/studies/{study_id}/data-queries", tags=["data-queries"])
api_router.include_router(verifications.router, prefix="/studies/{study_id}/verifications", tags=["verifications"])
api_router.include_router(imp_products.router, prefix="/studies/{study_id}/imp/products", tags=["imp-products"])
api_router.include_router(imp_batches.router, prefix="/studies/{study_id}/imp/batches", tags=["imp-batches"])
api_router.include_router(imp_inventory.router, prefix="/studies/{study_id}/imp/inventory", tags=["imp-inventory"])
api_router.include_router(imp_transactions.router, prefix="/studies/{study_id}/imp/transactions", tags=["imp-transactions"])