Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions alembic/versions/7af566a6091b_修改note.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""修改note

Revision ID: 7af566a6091b
Revises: 949e5fc5dfc4
Create Date: 2025-05-11 22:56:54.523911

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '7af566a6091b'
down_revision: Union[str, None] = '949e5fc5dfc4'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
34 changes: 34 additions & 0 deletions alembic/versions/949e5fc5dfc4_增加用户信息描述.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""增加用户信息描述

Revision ID: 949e5fc5dfc4
Revises: a434b17f5caf
Create Date: 2025-05-11 22:31:11.511674

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '949e5fc5dfc4'
down_revision: Union[str, None] = 'a434b17f5caf'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('notes', sa.Column('creator_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'notes', 'users', ['creator_id'], ['id'])
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'notes', type_='foreignkey')
op.drop_column('notes', 'creator_id')
# ### end Alembic commands ###
25 changes: 21 additions & 4 deletions app/api/v1/endpoints/note.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
from sqlalchemy.ext.asyncio import AsyncSession
from app.schemas.note import NoteCreate, NoteUpdate, NoteFind
from app.utils.get_db import get_db
from app.curd.note import create_note_in_db, delete_note_in_db, update_note_in_db, find_notes_in_db, find_notes_title_in_db
from app.curd.note import create_note_in_db, delete_note_in_db, update_note_in_db, find_notes_in_db, find_notes_title_in_db, find_self_notes_count_in_db, find_self_recent_notes_in_db
from typing import Optional

from app.utils.auth import get_current_user
router = APIRouter()

@router.post("/create", response_model=dict)
async def create_note(note: NoteCreate, db: AsyncSession = Depends(get_db)):
new_note = await create_note_in_db(note, db)
async def create_note(note: NoteCreate, db: AsyncSession = Depends(get_db), current_user: dict = Depends(get_current_user)):
user_id = current_user["id"]
new_note = await create_note_in_db(note, db, user_id)
return {"msg": "Note created successfully", "note_id": new_note.id}

@router.delete("/{note_id}", response_model=dict)
Expand Down Expand Up @@ -52,3 +53,19 @@ async def get_notes_title(note_find: NoteFind = Depends(), db: AsyncSession = De
},
"notes": notes
}

@router.get("/count", response_model=dict)
async def get_notes_count(db: AsyncSession = Depends(get_db), current_user: dict = Depends(get_current_user)):
user_id = current_user["id"]
count = await find_self_notes_count_in_db(db, user_id)
return {
"count": count
}

@router.get("/count/recent", response_model=dict)
async def get_recent_notes_count(db: AsyncSession = Depends(get_db), current_user: dict = Depends(get_current_user)):
user_id = current_user["id"]
notes = await find_self_recent_notes_in_db(db, user_id)
return {
"notes": notes
}
50 changes: 47 additions & 3 deletions app/curd/note.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from app.models.model import Note
from app.schemas.note import NoteCreate, NoteUpdate, NoteFind, NoteResponse

async def create_note_in_db(note: NoteCreate, db: AsyncSession):
new_note = Note(content=note.content, article_id=note.article_id, title=note.title)
async def create_note_in_db(note: NoteCreate, db: AsyncSession, user_id: int):
new_note = Note(content=note.content, article_id=note.article_id, title=note.title, creator_id=user_id)
db.add(new_note)
await db.commit()
await db.refresh(new_note)
Expand Down Expand Up @@ -104,4 +104,48 @@ async def find_recent_notes_in_db(db: AsyncSession):
# 格式化结果为字典列表
recent_notes = [{"date": row.date, "count": row.count} for row in data]

return recent_notes
return recent_notes

async def find_self_recent_notes_in_db(db: AsyncSession, user_id: int):
"""
返回近7天内创建的笔记的数目和对应日期
"""
# 获取当前日期和7天前的日期
today = datetime.now().date()
seven_days_ago = today - timedelta(days=6)

# 查询近7天内的笔记数目,按日期分组
stmt = (
select(
cast(Note.create_time, Date).label("date"), # 按日期分组
func.count(Note.id).label("count") # 统计每日期的笔记数
)
.where(
Note.create_time >= seven_days_ago, # 筛选近7天的笔记
Note.create_time <= today, # 包括今天
Note.creator_id == user_id # 筛选特定用户的笔记
)
.group_by(cast(Note.create_time, Date)) # 按日期分组
.order_by(cast(Note.create_time, Date)) # 按日期排序
)

# 执行查询
result = await db.execute(stmt)
data = result.fetchall()

# 格式化结果为字典列表
recent_notes = [{"date": row.date, "count": row.count} for row in data]

return recent_notes

async def find_self_notes_count_in_db(db: AsyncSession, user_id: int):
"""
返回用户的笔记数目
"""
stmt = (
select(func.count(Note.id))
.where(Note.creator_id == user_id)
)
result = await db.execute(stmt)
count = result.scalar_one_or_none()
return count
2 changes: 1 addition & 1 deletion app/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class Note(Base):
article_id = Column(Integer, ForeignKey('articles.id'))
create_time = Column(DateTime, default=func.now(), nullable=False) # 创建时间
update_time = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False) # 更新时间

creator_id = Column(Integer, ForeignKey('users.id')) # 创建者ID
visible = Column(Boolean, default=True, nullable=False) # 是否可见 False表示在回收站中

article = relationship('Article', back_populates='notes')
Expand Down