启动与授权-初步优化
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
"""Add site_id to kickoff meetings.
|
||||
|
||||
Revision ID: 20250310_01
|
||||
Revises: 20250218_01
|
||||
Create Date: 2025-03-10
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = "20250310_01"
|
||||
down_revision = "20250218_01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
|
||||
columns = {col["name"] for col in inspector.get_columns("kickoff_meetings")}
|
||||
if "site_id" not in columns:
|
||||
op.add_column("kickoff_meetings", sa.Column("site_id", postgresql.UUID(as_uuid=True), nullable=True))
|
||||
|
||||
fks = {fk["name"] for fk in inspector.get_foreign_keys("kickoff_meetings")}
|
||||
if "fk_kickoff_meetings_site_id" not in fks:
|
||||
op.create_foreign_key(
|
||||
"fk_kickoff_meetings_site_id",
|
||||
"kickoff_meetings",
|
||||
"sites",
|
||||
["site_id"],
|
||||
["id"],
|
||||
ondelete="RESTRICT",
|
||||
)
|
||||
|
||||
indexes = {index["name"] for index in inspector.get_indexes("kickoff_meetings")}
|
||||
if "ix_kickoff_meetings_site_id" not in indexes:
|
||||
op.create_index("ix_kickoff_meetings_site_id", "kickoff_meetings", ["site_id"])
|
||||
|
||||
uniques = {uc["name"] for uc in inspector.get_unique_constraints("kickoff_meetings")}
|
||||
if "uq_kickoff_meetings_study_site" not in uniques:
|
||||
op.create_unique_constraint(
|
||||
"uq_kickoff_meetings_study_site",
|
||||
"kickoff_meetings",
|
||||
["study_id", "site_id"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
|
||||
uniques = {uc["name"] for uc in inspector.get_unique_constraints("kickoff_meetings")}
|
||||
if "uq_kickoff_meetings_study_site" in uniques:
|
||||
op.drop_constraint("uq_kickoff_meetings_study_site", "kickoff_meetings", type_="unique")
|
||||
|
||||
indexes = {index["name"] for index in inspector.get_indexes("kickoff_meetings")}
|
||||
if "ix_kickoff_meetings_site_id" in indexes:
|
||||
op.drop_index("ix_kickoff_meetings_site_id", table_name="kickoff_meetings")
|
||||
|
||||
fks = {fk["name"] for fk in inspector.get_foreign_keys("kickoff_meetings")}
|
||||
if "fk_kickoff_meetings_site_id" in fks:
|
||||
op.drop_constraint("fk_kickoff_meetings_site_id", "kickoff_meetings", type_="foreignkey")
|
||||
|
||||
columns = {col["name"] for col in inspector.get_columns("kickoff_meetings")}
|
||||
if "site_id" in columns:
|
||||
op.drop_column("kickoff_meetings", "site_id")
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Migrate fee_attachments into attachments.
|
||||
|
||||
Revision ID: 20250310_02
|
||||
Revises: 20250310_01
|
||||
Create Date: 2025-03-10
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "20250310_02"
|
||||
down_revision = "20250310_01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id,
|
||||
study_id,
|
||||
entity_type,
|
||||
entity_id,
|
||||
filename,
|
||||
file_path,
|
||||
file_size,
|
||||
content_type,
|
||||
uploaded_by,
|
||||
uploaded_at,
|
||||
is_deleted
|
||||
)
|
||||
SELECT
|
||||
fa.id,
|
||||
cf.project_id,
|
||||
'contract_fee_' || fa.file_type,
|
||||
fa.entity_id,
|
||||
fa.filename,
|
||||
fa.storage_key,
|
||||
fa.size,
|
||||
fa.mime_type,
|
||||
fa.uploaded_by,
|
||||
fa.uploaded_at,
|
||||
fa.is_deleted
|
||||
FROM fee_attachments fa
|
||||
JOIN contract_fees cf ON fa.entity_type = 'contract_fee' AND fa.entity_id = cf.id
|
||||
WHERE fa.storage_key IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.id = fa.id)
|
||||
"""
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id,
|
||||
study_id,
|
||||
entity_type,
|
||||
entity_id,
|
||||
filename,
|
||||
file_path,
|
||||
file_size,
|
||||
content_type,
|
||||
uploaded_by,
|
||||
uploaded_at,
|
||||
is_deleted
|
||||
)
|
||||
SELECT
|
||||
fa.id,
|
||||
cf.project_id,
|
||||
'contract_payment_' || fa.file_type,
|
||||
fa.entity_id,
|
||||
fa.filename,
|
||||
fa.storage_key,
|
||||
fa.size,
|
||||
fa.mime_type,
|
||||
fa.uploaded_by,
|
||||
fa.uploaded_at,
|
||||
fa.is_deleted
|
||||
FROM fee_attachments fa
|
||||
JOIN contract_fee_payments cp ON fa.entity_type = 'contract_payment' AND fa.entity_id = cp.id
|
||||
JOIN contract_fees cf ON cp.contract_fee_id = cf.id
|
||||
WHERE fa.storage_key IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.id = fa.id)
|
||||
"""
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id,
|
||||
study_id,
|
||||
entity_type,
|
||||
entity_id,
|
||||
filename,
|
||||
file_path,
|
||||
file_size,
|
||||
content_type,
|
||||
uploaded_by,
|
||||
uploaded_at,
|
||||
is_deleted
|
||||
)
|
||||
SELECT
|
||||
fa.id,
|
||||
se.project_id,
|
||||
'special_expense_' || fa.file_type,
|
||||
fa.entity_id,
|
||||
fa.filename,
|
||||
fa.storage_key,
|
||||
fa.size,
|
||||
fa.mime_type,
|
||||
fa.uploaded_by,
|
||||
fa.uploaded_at,
|
||||
fa.is_deleted
|
||||
FROM fee_attachments fa
|
||||
JOIN special_expenses se ON fa.entity_type = 'special_expense' AND fa.entity_id = se.id
|
||||
WHERE fa.storage_key IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.id = fa.id)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
DELETE FROM attachments a
|
||||
USING fee_attachments fa
|
||||
WHERE a.id = fa.id
|
||||
AND a.entity_type IN (
|
||||
'contract_fee_contract',
|
||||
'contract_fee_voucher',
|
||||
'contract_fee_invoice',
|
||||
'contract_payment_voucher',
|
||||
'contract_payment_invoice',
|
||||
'special_expense_voucher',
|
||||
'special_expense_invoice',
|
||||
'special_expense_other'
|
||||
)
|
||||
"""
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
import aiofiles
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status, Request
|
||||
@@ -23,6 +24,12 @@ global_router = APIRouter()
|
||||
UPLOAD_ROOT = Path(__file__).resolve().parent.parent.parent / "uploads"
|
||||
|
||||
|
||||
def _content_disposition(filename: str, disposition: str = "inline") -> str:
|
||||
fallback = "".join((ch if ord(ch) < 128 else "_") for ch in filename) or "download"
|
||||
quoted = quote(filename, safe="")
|
||||
return f"{disposition}; filename=\"{fallback}\"; filename*=UTF-8''{quoted}"
|
||||
|
||||
|
||||
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
|
||||
study = await study_crud.get(db, study_id)
|
||||
if not study:
|
||||
@@ -79,6 +86,7 @@ async def upload_attachment(
|
||||
id=attachment.id,
|
||||
filename=attachment.filename,
|
||||
file_size=attachment.file_size,
|
||||
content_type=attachment.content_type,
|
||||
uploaded_by=UserDisplay.model_validate(current_user) if current_user else None,
|
||||
uploaded_by_id=attachment.uploaded_by,
|
||||
uploaded_at=attachment.uploaded_at,
|
||||
@@ -108,6 +116,7 @@ async def list_attachments(
|
||||
id=a.id,
|
||||
filename=a.filename,
|
||||
file_size=a.file_size,
|
||||
content_type=a.content_type,
|
||||
uploaded_by=UserDisplay.model_validate(user) if user else None,
|
||||
uploaded_by_id=a.uploaded_by,
|
||||
uploaded_at=a.uploaded_at,
|
||||
@@ -137,7 +146,32 @@ async def download_attachment(
|
||||
path=attachment.file_path,
|
||||
filename=attachment.filename,
|
||||
media_type=attachment.content_type or "application/octet-stream",
|
||||
headers={"Content-Disposition": f'inline; filename="{attachment.filename}"'},
|
||||
headers={"Content-Disposition": _content_disposition(attachment.filename, disposition="attachment")},
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{attachment_id}/preview",
|
||||
dependencies=[Depends(require_study_member())],
|
||||
)
|
||||
async def preview_attachment(
|
||||
study_id: uuid.UUID,
|
||||
entity_type: str,
|
||||
entity_id: uuid.UUID,
|
||||
attachment_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
) -> FileResponse:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
attachment = await attachment_crud.get_attachment(db, attachment_id)
|
||||
if not attachment or attachment.study_id != study_id or attachment.entity_id != entity_id or attachment.entity_type != entity_type:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
if not os.path.exists(attachment.file_path):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="服务器未找到文件")
|
||||
return FileResponse(
|
||||
path=attachment.file_path,
|
||||
filename=attachment.filename,
|
||||
media_type=attachment.content_type or "application/octet-stream",
|
||||
headers={"Content-Disposition": _content_disposition(attachment.filename, disposition="inline")},
|
||||
)
|
||||
|
||||
|
||||
@@ -182,7 +216,31 @@ async def global_download_attachment(
|
||||
path=attachment.file_path,
|
||||
filename=attachment.filename,
|
||||
media_type=attachment.content_type or "application/octet-stream",
|
||||
headers={"Content-Disposition": f'inline; filename="{attachment.filename}"'},
|
||||
headers={"Content-Disposition": _content_disposition(attachment.filename, disposition="attachment")},
|
||||
)
|
||||
|
||||
|
||||
@global_router.get(
|
||||
"/{attachment_id}/preview",
|
||||
response_class=FileResponse,
|
||||
)
|
||||
async def global_preview_attachment(
|
||||
attachment_id: uuid.UUID,
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
attachment = await attachment_crud.get_attachment(db, attachment_id)
|
||||
if not attachment:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
await _ensure_study_exists(db, attachment.study_id)
|
||||
await _authorize_global(request, db, attachment.study_id)
|
||||
if not os.path.exists(attachment.file_path):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="服务器未找到文件")
|
||||
return FileResponse(
|
||||
path=attachment.file_path,
|
||||
filename=attachment.filename,
|
||||
media_type=attachment.content_type or "application/octet-stream",
|
||||
headers={"Content-Disposition": _content_disposition(attachment.filename, disposition="inline")},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@ from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import contract_fee as contract_fee_crud
|
||||
from app.crud import contract_fee_payment as payment_crud
|
||||
from app.crud import fee_attachment as fee_attachment_crud
|
||||
from app.crud import member as member_crud
|
||||
from app.crud import site as site_crud
|
||||
from app.crud import user as user_crud
|
||||
@@ -23,6 +23,7 @@ from app.schemas.contract_fee_payment import (
|
||||
from app.schemas.fee_common import FeeApiResponse
|
||||
from app.schemas.fee_attachment import FeeAttachmentRead
|
||||
from app.schemas.user import UserDisplay
|
||||
from app.models.attachment import Attachment
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -123,7 +124,15 @@ async def get_contract_fee(
|
||||
await _ensure_project_access(db, contract.project_id, current_user, write=False)
|
||||
|
||||
payments = await payment_crud.list_payments(db, contract.id)
|
||||
attachments = await fee_attachment_crud.list_attachments(db, entity_type="contract_fee", entity_id=contract.id)
|
||||
attachment_types = ["contract_fee_contract", "contract_fee_voucher", "contract_fee_invoice"]
|
||||
result = await db.execute(
|
||||
select(Attachment).where(
|
||||
Attachment.entity_id == contract.id,
|
||||
Attachment.entity_type.in_(attachment_types),
|
||||
Attachment.is_deleted.is_(False),
|
||||
)
|
||||
)
|
||||
attachments = result.scalars().all()
|
||||
user_ids = {a.uploaded_by for a in attachments if a.uploaded_by}
|
||||
users_map = await user_crud.get_users_by_ids(db, user_ids)
|
||||
|
||||
@@ -133,20 +142,20 @@ async def get_contract_fee(
|
||||
"invoice": [],
|
||||
}
|
||||
for attachment in attachments:
|
||||
key = attachment.file_type
|
||||
key = attachment.entity_type.replace("contract_fee_", "", 1)
|
||||
attachments_map.setdefault(key, [])
|
||||
user = users_map.get(attachment.uploaded_by)
|
||||
attachments_map[key].append(
|
||||
FeeAttachmentRead(
|
||||
id=attachment.id,
|
||||
entity_type=attachment.entity_type,
|
||||
entity_type="contract_fee",
|
||||
entity_id=attachment.entity_id,
|
||||
file_type=attachment.file_type,
|
||||
file_type=key,
|
||||
filename=attachment.filename,
|
||||
mime_type=attachment.mime_type,
|
||||
size=attachment.size,
|
||||
storage_key=attachment.storage_key,
|
||||
url=attachment.url,
|
||||
mime_type=attachment.content_type,
|
||||
size=attachment.file_size,
|
||||
storage_key=attachment.file_path,
|
||||
url=None,
|
||||
uploaded_by_id=attachment.uploaded_by,
|
||||
uploaded_by=UserDisplay.model_validate(user) if user else None,
|
||||
uploaded_at=attachment.uploaded_at,
|
||||
|
||||
@@ -358,34 +358,6 @@ async def update_kickoff(
|
||||
return KickoffMeetingRead.model_validate(meeting)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/kickoff/{meeting_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_roles(["PM", "CRA"]))],
|
||||
)
|
||||
async def delete_kickoff(
|
||||
study_id: uuid.UUID,
|
||||
meeting_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
current_user=Depends(get_current_user),
|
||||
) -> None:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
meeting = await startup_crud.get_kickoff(db, meeting_id)
|
||||
if not meeting or meeting.study_id != study_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="启动会记录不存在")
|
||||
await startup_crud.delete_kickoff(db, meeting)
|
||||
await audit_crud.log_action(
|
||||
db,
|
||||
study_id=study_id,
|
||||
entity_type="startup_kickoff",
|
||||
entity_id=meeting_id,
|
||||
action="DELETE_KICKOFF_MEETING",
|
||||
detail="启动会记录已删除",
|
||||
operator_id=current_user.id,
|
||||
operator_role=current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/training-authorizations",
|
||||
response_model=TrainingAuthorizationRead,
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Sequence
|
||||
from sqlalchemy import and_, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.fee_attachment import FeeAttachment
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.special_expense import SpecialExpense
|
||||
from app.models.site import Site
|
||||
from app.schemas.special_expense import SpecialExpenseCreate, SpecialExpenseUpdate
|
||||
@@ -48,7 +48,8 @@ async def list_special_expenses(
|
||||
date_from: date | None = None,
|
||||
date_to: date | None = None,
|
||||
) -> Sequence[tuple[SpecialExpense, str | None, int]]:
|
||||
attachment_count = func.count(FeeAttachment.id).label("attachments_count")
|
||||
attachment_count = func.count(Attachment.id).label("attachments_count")
|
||||
attachment_types = ["special_expense_voucher", "special_expense_invoice", "special_expense_other"]
|
||||
stmt = (
|
||||
select(
|
||||
SpecialExpense,
|
||||
@@ -57,11 +58,11 @@ async def list_special_expenses(
|
||||
)
|
||||
.outerjoin(Site, Site.id == SpecialExpense.center_id)
|
||||
.outerjoin(
|
||||
FeeAttachment,
|
||||
Attachment,
|
||||
and_(
|
||||
FeeAttachment.entity_type == "special_expense",
|
||||
FeeAttachment.entity_id == SpecialExpense.id,
|
||||
FeeAttachment.is_deleted.is_(False),
|
||||
Attachment.entity_type.in_(attachment_types),
|
||||
Attachment.entity_id == SpecialExpense.id,
|
||||
Attachment.is_deleted.is_(False),
|
||||
),
|
||||
)
|
||||
.where(SpecialExpense.project_id == project_id)
|
||||
|
||||
@@ -147,6 +147,7 @@ async def create_kickoff(
|
||||
) -> KickoffMeeting:
|
||||
meeting = KickoffMeeting(
|
||||
study_id=study_id,
|
||||
site_id=meeting_in.site_id,
|
||||
kickoff_date=meeting_in.kickoff_date,
|
||||
attendees=meeting_in.attendees,
|
||||
created_by=created_by,
|
||||
@@ -190,11 +191,6 @@ async def update_kickoff(
|
||||
return meeting
|
||||
|
||||
|
||||
async def delete_kickoff(db: AsyncSession, meeting: KickoffMeeting) -> None:
|
||||
await db.delete(meeting)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def create_training_authorization(
|
||||
db: AsyncSession,
|
||||
study_id: uuid.UUID,
|
||||
|
||||
@@ -13,6 +13,7 @@ class KickoffMeeting(Base):
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
study_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("studies.id"), index=True, nullable=False)
|
||||
site_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("sites.id"), index=True, nullable=True)
|
||||
kickoff_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
attendees: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=True)
|
||||
|
||||
@@ -10,6 +10,7 @@ class AttachmentRead(BaseModel):
|
||||
id: uuid.UUID
|
||||
filename: str
|
||||
file_size: int = Field(alias="size")
|
||||
content_type: str | None = None
|
||||
uploaded_by: UserDisplay | None = None
|
||||
uploaded_by_id: uuid.UUID | None = None
|
||||
uploaded_at: datetime
|
||||
|
||||
@@ -71,6 +71,7 @@ class StartupEthicsRead(BaseModel):
|
||||
|
||||
|
||||
class KickoffMeetingCreate(BaseModel):
|
||||
site_id: uuid.UUID
|
||||
kickoff_date: Optional[date] = None
|
||||
attendees: Optional[list[str]] = None
|
||||
|
||||
@@ -83,6 +84,7 @@ class KickoffMeetingUpdate(BaseModel):
|
||||
class KickoffMeetingRead(BaseModel):
|
||||
id: uuid.UUID
|
||||
study_id: uuid.UUID
|
||||
site_id: Optional[uuid.UUID]
|
||||
kickoff_date: Optional[date]
|
||||
attendees: Optional[list[str]]
|
||||
created_by: Optional[uuid.UUID]
|
||||
|
||||
Reference in New Issue
Block a user