Skip to content

Commit

Permalink
[#135] Fix default_factory issue for date in chat model
Browse files Browse the repository at this point in the history
  • Loading branch information
wayangalihpratama committed Nov 21, 2024
1 parent 2fa4ad4 commit e031896
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 4 deletions.
17 changes: 15 additions & 2 deletions backend/core/socketio_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ def get_rabbitmq_client():
)

cookie = SimpleCookie()
tz = timezone.utc


USER_CACHE_DICT = {}
Expand Down Expand Up @@ -124,7 +125,7 @@ def save_chat_history(
else:
# If timestamp is not provided,
# it will default to current UTC time in the model
created_at = None # Let the model handle the default
created_at = datetime.now(tz) # Let the model handle the default

conversation_exist = session.exec(
select(Chat_Session)
Expand Down Expand Up @@ -268,7 +269,9 @@ async def handle_incoming_message(session: Session, message: dict):
session.commit()

new_chat_session = Chat_Session(
user_id=user.id, client_id=client.id, platform=platform
user_id=user.id,
client_id=client.id,
platform=platform,
)
session.add(new_chat_session)
session.commit()
Expand All @@ -285,6 +288,7 @@ async def handle_incoming_message(session: Session, message: dict):
chat_session_id=chat_session_id,
message=get_value_or_raise_error(message, "body"),
sender_role=(Sender_Role_Enum[sender_role.upper()]),
created_at=datetime.now(tz),
)
session.add(new_chat)
session.commit()
Expand All @@ -309,6 +313,7 @@ async def handle_incoming_message(session: Session, message: dict):
chat_session_id=chat_session_id,
message=initial_message,
sender_role=Sender_Role_Enum.SYSTEM,
created_at=datetime.now(tz),
)
session.add(new_chat)
session.commit()
Expand Down Expand Up @@ -342,6 +347,14 @@ def handle_read_message(session: Session, chat_session_id: int):
for um in unread_messages:
um.status = Chat_Status_Enum.READ
session.commit()

# update chat_session last_read
chat_session = session.exec(
select(Chat_Session).where(Chat_Session.id == chat_session_id)
).first()
if chat_session:
chat_session.last_read = datetime.now(tz)
session.commit()
session.flush()
return unread_messages
except Exception as e:
Expand Down
3 changes: 1 addition & 2 deletions backend/models/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ class Chat_Session(SQLModel, table=True):
server_default=func.now(),
nullable=False,
),
default_factory=lambda: datetime.now(tz),
)
client: "Client" = Relationship()
user: "User" = Relationship()
Expand Down Expand Up @@ -81,9 +80,9 @@ class Chat(SQLModel, table=True):
created_at: datetime = Field(
sa_column=Column(
DateTime(),
server_default=func.now(),
nullable=False,
),
default_factory=lambda: datetime.now(tz),
)
chat_session: "Chat_Session" = Relationship()
media: list["Chat_Media"] = Relationship(back_populates="chat")
Expand Down
3 changes: 3 additions & 0 deletions backend/routes/chat_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
from pydantic_extra_types.phone_numbers import PhoneNumber
from typing import List
from clients.twilio_client import TwilioClient
from datetime import datetime, timezone

router = APIRouter()
security = HTTPBearer()

twilio_client = TwilioClient()
tz = timezone.utc


class BroadcastRequest(BaseModel):
Expand Down Expand Up @@ -199,6 +201,7 @@ async def send_broadcast(
message=message,
sender_role=Sender_Role_Enum.USER_BROADCAST,
status=Chat_Status_Enum.UNREAD,
created_at=datetime.now(tz),
)
new_chats.append(new_chat)

Expand Down
3 changes: 3 additions & 0 deletions backend/routes/client_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from clients.twilio_client import TwilioClient
from middleware import verify_user
from typing_extensions import Annotated
from datetime import datetime, timezone


router = APIRouter()
Expand All @@ -28,6 +29,7 @@
"Hi {farmer_name}, I'm {officer_name} the extension officer.",
)
twilio_client = TwilioClient()
tz = timezone.utc


@router.post("/client")
Expand Down Expand Up @@ -102,6 +104,7 @@ async def add_client(
message=initial_message,
sender_role=Sender_Role_Enum.SYSTEM,
status=Chat_Status_Enum.READ, # user/officer message mark as READ
created_at=datetime.now(tz),
)
session.add(new_chat)
session.commit()
Expand Down
3 changes: 3 additions & 0 deletions backend/seeder/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
from sqlalchemy.exc import IntegrityError
from core.database import engine
from sqlmodel import Session, select
from datetime import datetime, timezone


faker = Faker()
tz = timezone.utc


def get_last_user(session: Session):
Expand Down Expand Up @@ -71,6 +73,7 @@ def seed_chat_data(session: Session, user_id: int, client_id: int):
chat_session_id=chat_session.id,
message=message,
sender_role=sender_role,
created_at=datetime.now(tz),
)
session.add(chat)

Expand Down
3 changes: 3 additions & 0 deletions backend/seeder/initial_conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
from core.database import engine
from sqlmodel import Session, select
from typing import List
from datetime import datetime, timezone


faker = Faker()
tz = timezone.utc


def get_client_phone_numbers(session: Session):
Expand Down Expand Up @@ -49,6 +51,7 @@ def seed_chat_data(session: Session, user_id: int, client_id: int):
chat_session_id=chat_session.id,
message="Welcome to Agriconnect. This is initial conversation..",
sender_role=Sender_Role_Enum.SYSTEM,
created_at=datetime.now(tz),
)
session.add(chat)
session.commit()
Expand Down
4 changes: 4 additions & 0 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
Platform_Enum,
Chat_Status_Enum,
)
from datetime import datetime, timezone

tz = timezone.utc


def truncate(session: Session, table: str):
Expand Down Expand Up @@ -80,6 +83,7 @@ def init_db(session: Session) -> None:
message=message["message"],
sender_role=message["sender"],
status=message["status"],
created_at=datetime.now(tz),
)
session.add(chat)
session.commit()
Expand Down

0 comments on commit e031896

Please sign in to comment.