diff --git a/backend/alembic/versions/20250310_01_add_site_id_to_kickoff_meetings.py b/backend/alembic/versions/20250310_01_add_site_id_to_kickoff_meetings.py new file mode 100644 index 00000000..eecce0a6 --- /dev/null +++ b/backend/alembic/versions/20250310_01_add_site_id_to_kickoff_meetings.py @@ -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") diff --git a/backend/alembic/versions/20250310_02_migrate_fee_attachments_to_attachments.py b/backend/alembic/versions/20250310_02_migrate_fee_attachments_to_attachments.py new file mode 100644 index 00000000..544babcd --- /dev/null +++ b/backend/alembic/versions/20250310_02_migrate_fee_attachments_to_attachments.py @@ -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' + ) + """ + ) diff --git a/backend/app/api/v1/attachments.py b/backend/app/api/v1/attachments.py index f44c7d73..0d01f77d 100644 --- a/backend/app/api/v1/attachments.py +++ b/backend/app/api/v1/attachments.py @@ -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")}, ) diff --git a/backend/app/api/v1/fees_contracts.py b/backend/app/api/v1/fees_contracts.py index f7973769..8f754403 100644 --- a/backend/app/api/v1/fees_contracts.py +++ b/backend/app/api/v1/fees_contracts.py @@ -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, diff --git a/backend/app/api/v1/startup.py b/backend/app/api/v1/startup.py index 2814183a..67566a16 100644 --- a/backend/app/api/v1/startup.py +++ b/backend/app/api/v1/startup.py @@ -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, diff --git a/backend/app/crud/special_expense.py b/backend/app/crud/special_expense.py index a148da81..f191ac2b 100644 --- a/backend/app/crud/special_expense.py +++ b/backend/app/crud/special_expense.py @@ -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) diff --git a/backend/app/crud/startup.py b/backend/app/crud/startup.py index 8b5d8f4b..58d82bae 100644 --- a/backend/app/crud/startup.py +++ b/backend/app/crud/startup.py @@ -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, diff --git a/backend/app/models/kickoff_meeting.py b/backend/app/models/kickoff_meeting.py index e3f39709..704143ed 100644 --- a/backend/app/models/kickoff_meeting.py +++ b/backend/app/models/kickoff_meeting.py @@ -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) diff --git a/backend/app/schemas/attachment.py b/backend/app/schemas/attachment.py index a71e7f71..98c7fd1d 100644 --- a/backend/app/schemas/attachment.py +++ b/backend/app/schemas/attachment.py @@ -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 diff --git a/backend/app/schemas/startup.py b/backend/app/schemas/startup.py index e1d67729..4dc4da5f 100644 --- a/backend/app/schemas/startup.py +++ b/backend/app/schemas/startup.py @@ -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] diff --git a/database/init.sql b/database/init.sql index f4f26947..f5a336c4 100644 --- a/database/init.sql +++ b/database/init.sql @@ -361,12 +361,14 @@ CREATE TABLE IF NOT EXISTS public.startup_ethics ( CREATE TABLE IF NOT EXISTS public.kickoff_meetings ( id uuid PRIMARY KEY, study_id uuid NOT NULL, + site_id uuid, kickoff_date date, attendees json, created_by uuid, created_at timestamp with time zone NOT NULL DEFAULT now(), updated_at timestamp with time zone NOT NULL DEFAULT now(), CONSTRAINT fk_kickoff_meetings_study_id FOREIGN KEY (study_id) REFERENCES public.studies(id) ON DELETE RESTRICT, + CONSTRAINT fk_kickoff_meetings_site_id FOREIGN KEY (site_id) REFERENCES public.sites(id) ON DELETE RESTRICT, CONSTRAINT fk_kickoff_meetings_created_by FOREIGN KEY (created_by) REFERENCES public.users(id) ON DELETE RESTRICT ); diff --git a/frontend/src/api/feeAttachments.ts b/frontend/src/api/feeAttachments.ts deleted file mode 100644 index 1c301e84..00000000 --- a/frontend/src/api/feeAttachments.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { apiDelete, apiGet, apiPost } from "./axios"; -import type { FeeApiResponse } from "../types/api"; - -export const listFeeAttachments = (entityType: string, entityId: string) => - apiGet>("/api/v1/fees/attachments", { params: { entity_type: entityType, entity_id: entityId } }); - -export const uploadFeeAttachment = ( - entityType: string, - entityId: string, - fileType: string, - file: File, - options?: Record -) => { - const formData = new FormData(); - formData.append("file", file); - formData.append("entity_type", entityType); - formData.append("entity_id", entityId); - formData.append("file_type", fileType); - return apiPost>("/api/v1/fees/attachments", formData, { - headers: { "Content-Type": "multipart/form-data" }, - ...options, - }); -}; - -export const deleteFeeAttachment = (attachmentId: string) => apiDelete(`/api/v1/fees/attachments/${attachmentId}`); - -export const getFeeAttachmentDownloadUrl = (attachmentId: string) => { - const token = localStorage.getItem("ctms_token"); - return token - ? `/api/v1/fees/attachments/${attachmentId}/download?token=${token}` - : `/api/v1/fees/attachments/${attachmentId}/download`; -}; diff --git a/frontend/src/api/startup.ts b/frontend/src/api/startup.ts index e93876ce..de92d54d 100644 --- a/frontend/src/api/startup.ts +++ b/frontend/src/api/startup.ts @@ -42,9 +42,6 @@ export const createKickoff = (studyId: string, payload: Record) => export const updateKickoff = (studyId: string, id: string, payload: Record) => apiPatch(`/api/v1/studies/${studyId}/startup/kickoff/${id}`, payload); -export const deleteKickoff = (studyId: string, id: string) => - apiDelete(`/api/v1/studies/${studyId}/startup/kickoff/${id}`); - export const listTrainingAuthorizations = (studyId: string, params?: Record) => apiGet(`/api/v1/studies/${studyId}/startup/training-authorizations`, { params }); diff --git a/frontend/src/components/attachments/AttachmentList.vue b/frontend/src/components/attachments/AttachmentList.vue index ad6758ef..75ce80b1 100644 --- a/frontend/src/components/attachments/AttachmentList.vue +++ b/frontend/src/components/attachments/AttachmentList.vue @@ -1,7 +1,7 @@