Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Articles #62

Draft
wants to merge 7 commits into
base: develop
Choose a base branch
from
Draft
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
51 changes: 51 additions & 0 deletions backend/alembic/versions/3c54be1b70e2_add_article.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Add article

Revision ID: 3c54be1b70e2
Revises: 9ef2bf852502
Create Date: 2024-12-29 16:58:40.321861

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '3c54be1b70e2'
down_revision: Union[str, None] = '9ef2bf852502'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('articles',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('title', sa.String(length=255), nullable=False),
sa.Column('slug', sa.String(length=255), nullable=False),
sa.Column('content', sa.Text(), nullable=False),
sa.Column('event_id', sa.UUID(), nullable=False),
sa.Column('created_by_id', sa.UUID(), nullable=False),
sa.Column('published_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
op.create_index(op.f('ix_articles_slug'), 'articles', ['slug'], unique=False)
op.create_index(op.f('ix_articles_title'), 'articles', ['title'], unique=False)
op.create_unique_constraint(None, 'event_interests', ['id'])
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'event_interests', type_='unique')
op.drop_index(op.f('ix_articles_title'), table_name='articles')
op.drop_index(op.f('ix_articles_slug'), table_name='articles')
op.drop_table('articles')
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion backend/app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from app.models import base, event, event_interest, organisation, user # noqa: F401
from app.models import article, base, event, event_interest, organisation, user # noqa: F401
24 changes: 24 additions & 0 deletions backend/app/models/article.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from sqlalchemy import UUID, Column, DateTime, ForeignKey, String, Text
from sqlalchemy.orm import declarative_base, relationship

from app.models.base import BaseModel

Base = declarative_base()


class Article(BaseModel):
"""Article model for events."""

__tablename__ = 'articles'

title = Column(String(255), nullable=False, index=True)
slug = Column(String(255), nullable=False, index=True)
content = Column(Text, nullable=False)

event_id = Column(UUID(as_uuid=True), ForeignKey('events.id'), nullable=False)
event = relationship('Event', back_populates='articles')

created_by_id = Column(UUID(as_uuid=True), ForeignKey('users.id'), nullable=False)
created_by = relationship('User', back_populates='articles')

published_at = Column(DateTime, nullable=True)
1 change: 1 addition & 0 deletions backend/app/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,4 @@ class Event(BaseModel):
created_by = relationship('User', back_populates='events')

interests = relationship('EventInterest', back_populates='event')
articles = relationship('Article', back_populates='event')
1 change: 1 addition & 0 deletions backend/app/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class User(BaseModel):
organisations = relationship('Organisation', back_populates='created_by')
events = relationship('Event', back_populates='created_by')
event_interests = relationship('EventInterest', back_populates='user')
articles = relationship('Article', back_populates='created_by')

__table_args__ = (UniqueConstraint('phone_code', 'phone_number', name='_phone_code_phone_number_uc'),)

Expand Down
2 changes: 2 additions & 0 deletions backend/app/v3/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from fastapi import APIRouter
from fastapi_pagination import add_pagination

from app.v3.articles import endpoints as articles_endpoints
from app.v3.auth import endpoints as auth_endpoints
from app.v3.event_interests import endpoints as event_interests_endpoints
from app.v3.events import endpoints as events_endpoints
Expand All @@ -18,4 +19,5 @@
router.include_router(organisations_endpoints.router, tags=['organisations'], prefix='/organisations')
router.include_router(events_endpoints.router, tags=['events'], prefix='/events')
router.include_router(event_interests_endpoints.router, tags=['event interests'])
router.include_router(articles_endpoints.router, tags=['event articles'])
router.include_router(system_endpoints.router, tags=['system'], prefix='/system') # Should be last
Empty file.
83 changes: 83 additions & 0 deletions backend/app/v3/articles/endpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from typing import List
from uuid import UUID

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session

from app.dependencies import get_db
from app.models.user import User
from app.v3.articles.schemas import ArticleCreate, ArticleResponse, ArticleUpdate
from app.v3.articles.service import (
create_article,
delete_article,
get_article,
get_articles,
update_article,
)
from app.v3.auth.utils import get_current_user

router = APIRouter()


@router.post(
'/events/{event_id}/articles',
name='EA-1',
response_model=ArticleResponse,
)
async def post_create_article(
event_id: UUID, article_data: ArticleCreate, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)
) -> JSONResponse:
"""Create a new article"""
return create_article(db=db, event_id=event_id, current_user=current_user, article_data=article_data)


@router.get(
'/events/{event_id}/articles',
name='EA-2',
response_model=List[ArticleResponse],
)
async def get_articles_list(event_id: UUID, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)) -> JSONResponse:
"""Get published articles for an event"""
return get_articles(db=db, event_id=event_id, skip=skip, limit=limit)


@router.get(
'/events/{event_id}/articles/{article_id}',
name='EA-3',
response_model=ArticleResponse,
)
async def get_article_by_id(event_id: UUID, article_id: UUID, db: Session = Depends(get_db)) -> JSONResponse:
"""Get article by ID"""
return get_article(db=db, event_id=event_id, article_id=article_id)


@router.put(
'/events/{event_id}/articles/{article_id}',
name='EA-4',
response_model=ArticleResponse,
)
async def put_update_article(
event_id: UUID, article_id: UUID, article_data: ArticleUpdate, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)
) -> JSONResponse:
"""Update article"""
return update_article(db=db, event_id=event_id, article_id=article_id, current_user=current_user, article_data=article_data)


@router.delete(
'/events/{event_id}/articles/{article_id}',
name='EA-5',
)
async def delete_article_by_id(event_id: UUID, article_id: UUID, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> JSONResponse:
"""Delete article"""
return delete_article(db=db, event_id=event_id, article_id=article_id, current_user=current_user)


@router.get(
'/events/{event_id}/articles/all',
name='EA-6',
response_model=List[ArticleResponse],
)
async def get_all_articles(event_id: UUID, db: Session = Depends(get_db)) -> JSONResponse:
"""Get all articles for an event"""
return get_all_articles(db=db, event_id=event_id)
53 changes: 53 additions & 0 deletions backend/app/v3/articles/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from datetime import datetime
from typing import Optional
from uuid import UUID

from pydantic import BaseModel

from app.v3.auth.schemas import UserResponse


class ArticleBase(BaseModel):
"""Base article model"""

title: str
slug: Optional[str]
content: str
published_at: Optional[datetime]


class ArticleCreate(ArticleBase):
"""Create article input model"""

pass


class ArticleUpdate(ArticleBase):
"""Update article input model"""

pass


class ArticleResponse(ArticleBase):
"""Article response model"""

id: UUID
event_id: UUID
created_by: UserResponse
created_at: datetime
updated_at: datetime
deleted_at: Optional[datetime]

class Config:
"""Pydantic config"""

orm_mode = True


class ArticleListResponse(BaseModel):
"""Article list response model"""

articles: list[ArticleResponse]
total: int
skip: int
limit: int
126 changes: 126 additions & 0 deletions backend/app/v3/articles/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import logging

from pydantic import TypeAdapter
from pydantic.v1 import UUID4
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from tunsberg.responses import (
response_bad_request,
response_conflict,
response_created,
response_no_content,
response_not_found,
response_success,
)

from app.models.article import Article
from app.models.event import Event
from app.models.user import User
from app.v3.articles.schemas import ArticleCreate, ArticleResponse, ArticleUpdate


def create_article(db: Session, event_id: UUID4, current_user: User, article_data: ArticleCreate):
"""Create a new article"""
# Check if event exists
event = db.query(Event).filter(Event.id == event_id).first()
if not event:
return response_bad_request(message='Event not found')

try:
article = Article(**article_data.model_dump(), created_by_id=current_user.id, event_id=event_id)
db.add(article)
db.commit()
db.refresh(article)

adapter = TypeAdapter(ArticleResponse)
return response_created(message='Article created', data=adapter.dump_json(article))
except IntegrityError as e:
db.rollback()
logging.error(f'Error creating article: {e}')
return response_conflict(message='Error creating article')


def get_articles(db: Session, event_id: UUID4, skip: int = 0, limit: int = 100):
"""Get published articles for an event"""
# Check if event exists
event = db.query(Event).filter(Event.id == event_id).first()
if not event:
return response_bad_request(message='Event not found')

articles = (
db.query(Article)
.filter(Article.event_id == event_id, Article.deleted_at.is_(None), Article.published_at.isnot(None))
.order_by(Article.published_at.desc())
.offset(skip)
.limit(limit)
.all()
)

adapter = TypeAdapter(list[ArticleResponse])
data = adapter.dump_json(articles)
return response_success(message='Articles retrieved', data=data)


def get_article(db: Session, event_id: UUID4, article_id: UUID4):
"""Get article by ID"""
# Check if event exists
event = db.query(Event).filter(Event.id == event_id).first()
if not event:
return response_bad_request(message='Event not found')

article = db.query(Article).filter(Article.id == article_id, Article.event_id == event_id, Article.deleted_at.is_(None)).first()
if not article:
return response_not_found(message='Article not found')

adapter = TypeAdapter(ArticleResponse)
return response_success(message='Article retrieved', data=adapter.dump_json(article))


def update_article(db: Session, event_id: UUID4, article_id: UUID4, current_user: User, article_data: ArticleUpdate):
"""Update article"""
# Check if event exists
event = db.query(Event).filter(Event.id == event_id).first()
if not event:
return response_bad_request(message='Event not found')

article = db.query(Article).filter(Article.id == article_id, Article.deleted_at.is_(None)).first()
if not article:
return response_not_found(message='Article not found')

try:
for field, value in article_data.model_dump(exclude_unset=True).items():
setattr(article, field, value)

db.commit()
db.refresh(article)

adapter = TypeAdapter(ArticleResponse)
return response_success(message='Article updated', data=adapter.dump_json(article))
except IntegrityError as e:
db.rollback()
logging.error(f'Error updating article: {e}')
return response_conflict(message='Error updating article')


def delete_article(db: Session, event_id: UUID4, article_id: UUID4, current_user: User):
"""Delete article"""
article = db.query(Article).filter(Article.id == article_id, Article.event_id == event_id, Article.deleted_at.is_(None)).first()
if not article:
return response_not_found(message='Article not found')

try:
db.delete(article)
db.commit()
return response_no_content()
except Exception as e:
db.rollback()
logging.error(f'Error deleting article: {e}')
return response_bad_request(message='Could not delete article')


def get_all_articles(db: Session, event_id: UUID4):
"""Get all articles for an event"""
articles = db.query(Article).filter(Article.event_id == event_id, Article.deleted_at.is_(None)).all()
adapter = TypeAdapter(list[ArticleResponse])
data = adapter.dump_json(articles)
return response_success(message='Articles retrieved', data=data)
Loading
Loading