ABAO77 commited on
Commit
d3cce17
·
verified ·
1 Parent(s): 5570653

Upload 159 files

Browse files
src/apis/__pycache__/create_app.cpython-311.pyc CHANGED
Binary files a/src/apis/__pycache__/create_app.cpython-311.pyc and b/src/apis/__pycache__/create_app.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/post_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/post_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/post_controller.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/scheduling_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/scheduling_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/scheduling_controller.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/user_controller.cpython-311.pyc ADDED
Binary file (5.75 kB). View file
 
src/apis/controllers/post_controller.py CHANGED
@@ -6,6 +6,7 @@ from asyncio import gather
6
  from src.utils.helper import call_external_api, serialize_datetime
7
  from datetime import datetime
8
  from bson import ObjectId
 
9
 
10
 
11
  async def create_a_post_controller(
@@ -56,9 +57,24 @@ async def get_a_post_controller(post_id: str) -> Dict:
56
  return {"status": "error", "message": str(e)}
57
 
58
 
59
- async def list_all_posts_controller(user_id: str):
60
  try:
61
- posts = await PostCRUD.find_all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  user_ids = list({post.get("user_id") for post in posts})
63
  user_infos = await gather(*[UserCRUD.find_by_id(uid) for uid in user_ids])
64
  user_info_map = {
@@ -115,19 +131,53 @@ async def list_all_posts_controller(user_id: str):
115
  }
116
  serialized_posts.append(serialized_post)
117
 
118
- return {"status": "success", "message": serialized_posts}
 
 
 
 
 
 
 
 
 
119
 
120
  except Exception as e:
121
  logger.error(f"Error listing posts: {str(e)}")
122
  return {"status": "error", "message": str(e)}
123
 
124
 
125
- async def list_posts_by_destination_controller(destination_id: str, user_id: str):
 
 
126
  try:
127
- # Filtered posts only for the given destination_id
128
- posts = await PostCRUD.find_many({"destination_id": destination_id})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  if not posts:
130
- return {"status": "success", "message": []}
 
 
 
 
 
 
 
 
 
131
 
132
  # Get unique user_ids
133
  user_ids = list({post.get("user_id") for post in posts})
@@ -186,7 +236,16 @@ async def list_posts_by_destination_controller(destination_id: str, user_id: str
186
  }
187
  serialized_posts.append(serialized_post)
188
 
189
- return {"status": "success", "message": serialized_posts}
 
 
 
 
 
 
 
 
 
190
 
191
  except Exception as e:
192
  logger.error(f"Error listing posts by destination: {str(e)}")
 
6
  from src.utils.helper import call_external_api, serialize_datetime
7
  from datetime import datetime
8
  from bson import ObjectId
9
+ import math
10
 
11
 
12
  async def create_a_post_controller(
 
57
  return {"status": "error", "message": str(e)}
58
 
59
 
60
+ async def list_all_posts_controller(user_id: str, page: int = 1):
61
  try:
62
+ PAGE_SIZE = 1
63
+ # Calculate skip value for pagination
64
+ skip = (page - 1) * PAGE_SIZE
65
+
66
+ # Get total count for pagination metadata
67
+ total_items = await PostCRUD.count({})
68
+ total_pages = math.ceil(total_items / PAGE_SIZE)
69
+
70
+ # Get paginated posts
71
+ posts = await PostCRUD.find_many(
72
+ filter={}, # Empty filter means get all
73
+ skip=skip,
74
+ limit=PAGE_SIZE,
75
+ sort=[("created_at", -1)], # Sort by created_at descending
76
+ )
77
+
78
  user_ids = list({post.get("user_id") for post in posts})
79
  user_infos = await gather(*[UserCRUD.find_by_id(uid) for uid in user_ids])
80
  user_info_map = {
 
131
  }
132
  serialized_posts.append(serialized_post)
133
 
134
+ return {
135
+ "status": "success",
136
+ "message": {
137
+ "data": serialized_posts,
138
+ "page": page,
139
+ "total_pages": total_pages,
140
+ "total_items": total_items,
141
+ "page_size": PAGE_SIZE,
142
+ },
143
+ }
144
 
145
  except Exception as e:
146
  logger.error(f"Error listing posts: {str(e)}")
147
  return {"status": "error", "message": str(e)}
148
 
149
 
150
+ async def list_posts_by_destination_controller(
151
+ destination_id: str, user_id: str, page: int = 1
152
+ ):
153
  try:
154
+ PAGE_SIZE = 1 # Changed from 1 to 5 posts per page
155
+ # Calculate skip value for pagination
156
+ skip = (page - 1) * PAGE_SIZE
157
+
158
+ # Get total count for pagination metadata
159
+ total_items = await PostCRUD.count({"destination_id": destination_id})
160
+ total_pages = math.ceil(total_items / PAGE_SIZE)
161
+
162
+ # Get paginated posts
163
+ posts = await PostCRUD.find_many(
164
+ filter={"destination_id": destination_id},
165
+ skip=skip,
166
+ limit=PAGE_SIZE,
167
+ sort=[("created_at", -1)], # Sort by created_at descending
168
+ )
169
+
170
  if not posts:
171
+ return {
172
+ "status": "success",
173
+ "message": {
174
+ "data": [],
175
+ "page": page,
176
+ "total_pages": total_pages,
177
+ "total_items": total_items,
178
+ "page_size": PAGE_SIZE,
179
+ },
180
+ }
181
 
182
  # Get unique user_ids
183
  user_ids = list({post.get("user_id") for post in posts})
 
236
  }
237
  serialized_posts.append(serialized_post)
238
 
239
+ return {
240
+ "status": "success",
241
+ "message": {
242
+ "data": serialized_posts,
243
+ "page": page,
244
+ "total_pages": total_pages,
245
+ "total_items": total_items,
246
+ "page_size": PAGE_SIZE,
247
+ },
248
+ }
249
 
250
  except Exception as e:
251
  logger.error(f"Error listing posts by destination: {str(e)}")
src/apis/controllers/scheduling_controller.py CHANGED
@@ -2,10 +2,6 @@ from typing import Optional, Dict, Union
2
  from datetime import datetime
3
  from src.utils.mongo import ScheduleCRUD
4
  from src.utils.logger import logger
5
- from datetime import datetime
6
- from bson import ObjectId
7
- from typing import Optional, Dict
8
- from datetime import datetime
9
  from bson import ObjectId
10
 
11
 
 
2
  from datetime import datetime
3
  from src.utils.mongo import ScheduleCRUD
4
  from src.utils.logger import logger
 
 
 
 
5
  from bson import ObjectId
6
 
7
 
src/apis/controllers/user_controller.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from src.utils.mongo import UserCRUD
3
+ from src.utils.logger import logger
4
+ from bson import ObjectId
5
+ from fastapi.responses import JSONResponse
6
+ from typing import Dict
7
+
8
+
9
+ async def list_users_controller():
10
+ try:
11
+ users = await UserCRUD.find_all()
12
+ # Convert datetime fields to ISO format
13
+ for user in users:
14
+ if "created_at" in user and isinstance(user["created_at"], datetime):
15
+ user["created_at"] = user["created_at"].isoformat()
16
+ if "updated_at" in user and isinstance(user["updated_at"], datetime):
17
+ user["updated_at"] = user["updated_at"].isoformat()
18
+ if "expire_at" in user and isinstance(user["expire_at"], datetime):
19
+ user["expire_at"] = user["expire_at"].isoformat()
20
+ return JSONResponse(
21
+ content={
22
+ "status": "success",
23
+ "data": users,
24
+ },
25
+ status_code=200,
26
+ )
27
+ except Exception as e:
28
+ logger.error(f"Error listing users: {e}")
29
+ return JSONResponse(
30
+ content={
31
+ "status": "error",
32
+ "message": str(e),
33
+ },
34
+ status_code=500,
35
+ )
36
+
37
+
38
+ async def update_user_controller(user_id: str, user_data: dict):
39
+ try:
40
+ user = await UserCRUD.update({"_id": ObjectId(user_id)}, user_data)
41
+
42
+ # Convert datetime fields to ISO format
43
+ if user:
44
+ if "created_at" in user and isinstance(user["created_at"], datetime):
45
+ user["created_at"] = user["created_at"].isoformat()
46
+ if "updated_at" in user and isinstance(user["updated_at"], datetime):
47
+ user["updated_at"] = user["updated_at"].isoformat()
48
+ if "expire_at" in user and isinstance(user["expire_at"], datetime):
49
+ user["expire_at"] = user["expire_at"].isoformat()
50
+
51
+ return JSONResponse(
52
+ content={
53
+ "status": "success",
54
+ "data": user,
55
+ },
56
+ status_code=200,
57
+ )
58
+ else:
59
+ return JSONResponse(
60
+ content={
61
+ "status": "error",
62
+ "message": "User not found",
63
+ },
64
+ status_code=404,
65
+ )
66
+ except Exception as e:
67
+ logger.error(f"Error updating user: {e}")
68
+ return JSONResponse(
69
+ content={
70
+ "status": "error",
71
+ "message": str(e),
72
+ },
73
+ status_code=500,
74
+ )
75
+
76
+
77
+ async def delete_user_controller(user_id: str):
78
+ try:
79
+ user = await UserCRUD.delete_one({"_id": ObjectId(user_id)})
80
+ return JSONResponse(
81
+ content={
82
+ "status": "success",
83
+ "data": user,
84
+ },
85
+ status_code=200,
86
+ )
87
+ except Exception as e:
88
+ logger.error(f"Error deleting user: {e}")
89
+ return JSONResponse(
90
+ content={
91
+ "status": "error",
92
+ "message": str(e),
93
+ },
94
+ status_code=500,
95
+ )
96
+
97
+
98
+ async def get_user_by_id_controller(user_id: str):
99
+ try:
100
+ user = await UserCRUD.find_by_id(user_id)
101
+ if not user:
102
+ return JSONResponse(
103
+ content={
104
+ "status": "error",
105
+ "message": "User not found",
106
+ },
107
+ status_code=404,
108
+ )
109
+ # Convert datetime fields to ISO format
110
+ if "created_at" in user and isinstance(user["created_at"], datetime):
111
+ user["created_at"] = user["created_at"].isoformat()
112
+ if "updated_at" in user and isinstance(user["updated_at"], datetime):
113
+ user["updated_at"] = user["updated_at"].isoformat()
114
+ if "expire_at" in user and isinstance(user["expire_at"], datetime):
115
+ user["expire_at"] = user["expire_at"].isoformat()
116
+ return JSONResponse(
117
+ content={
118
+ "status": "success",
119
+ "data": user,
120
+ },
121
+ status_code=200,
122
+ )
123
+ except Exception as e:
124
+ logger.error(f"Error getting user by id: {e}")
125
+ return JSONResponse(
126
+ content={
127
+ "status": "error",
128
+ "message": str(e),
129
+ },
130
+ status_code=500,
131
+ )
src/apis/create_app.py CHANGED
@@ -10,6 +10,7 @@ from src.apis.routes.planner_route import router as router_planner
10
  from src.apis.routes.post_router import router as router_post
11
  from src.apis.routes.comment_route import router as router_comment
12
  from src.apis.routes.reaction_route import router as router_reaction
 
13
  api_router = APIRouter()
14
  api_router.include_router(router_chat)
15
  api_router.include_router(router_auth)
 
10
  from src.apis.routes.post_router import router as router_post
11
  from src.apis.routes.comment_route import router as router_comment
12
  from src.apis.routes.reaction_route import router as router_reaction
13
+
14
  api_router = APIRouter()
15
  api_router.include_router(router_chat)
16
  api_router.include_router(router_auth)
src/apis/models/__pycache__/user_models.cpython-311.pyc CHANGED
Binary files a/src/apis/models/__pycache__/user_models.cpython-311.pyc and b/src/apis/models/__pycache__/user_models.cpython-311.pyc differ
 
src/apis/models/user_models.py CHANGED
@@ -18,6 +18,7 @@ def list_serial(users) -> list:
18
 
19
 
20
  class User(BaseDocument):
 
21
  name: str = Field("", description="User's name")
22
  email: EmailStr = Field("", description="User's email")
23
  picture: str = Field("", title="User Picture")
 
18
 
19
 
20
  class User(BaseDocument):
21
+ id: str = Field("", description="User's id")
22
  name: str = Field("", description="User's name")
23
  email: EmailStr = Field("", description="User's email")
24
  picture: str = Field("", title="User Picture")
src/apis/routes/__pycache__/auth_route.cpython-311.pyc CHANGED
Binary files a/src/apis/routes/__pycache__/auth_route.cpython-311.pyc and b/src/apis/routes/__pycache__/auth_route.cpython-311.pyc differ
 
src/apis/routes/__pycache__/post_router.cpython-311.pyc CHANGED
Binary files a/src/apis/routes/__pycache__/post_router.cpython-311.pyc and b/src/apis/routes/__pycache__/post_router.cpython-311.pyc differ
 
src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc CHANGED
Binary files a/src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc and b/src/apis/routes/__pycache__/travel_dest_route.cpython-311.pyc differ
 
src/apis/routes/auth_route.py CHANGED
@@ -3,6 +3,12 @@ from fastapi.responses import JSONResponse
3
  from typing import Annotated
4
  from src.apis.models.user_models import User
5
  from src.apis.controllers.auth_controller import login_control
 
 
 
 
 
 
6
  from src.apis.interfaces.auth_interface import _LoginResponseInterface
7
  from src.apis.interfaces.auth_interface import Credential
8
  from src.apis.middlewares.auth_middleware import get_current_user
@@ -36,11 +42,22 @@ async def get_user_info(user: user_dependency):
36
  return JSONResponse(content={"message": "User not found"}, status_code=401)
37
  return JSONResponse(content={"user": user}, status_code=200)
38
 
39
- import time
40
- import asyncio
41
- @router.get("/test", status_code=status.HTTP_200_OK)
42
- async def test():
43
- print("da vao")
44
- await asyncio.sleep(5) # Use asyncio.sleep for non-blocking sleep
45
- print("alo")
46
- return "test"
 
 
 
 
 
 
 
 
 
 
 
 
3
  from typing import Annotated
4
  from src.apis.models.user_models import User
5
  from src.apis.controllers.auth_controller import login_control
6
+ from src.apis.controllers.user_controller import (
7
+ list_users_controller,
8
+ update_user_controller,
9
+ delete_user_controller,
10
+ get_user_by_id_controller,
11
+ )
12
  from src.apis.interfaces.auth_interface import _LoginResponseInterface
13
  from src.apis.interfaces.auth_interface import Credential
14
  from src.apis.middlewares.auth_middleware import get_current_user
 
42
  return JSONResponse(content={"message": "User not found"}, status_code=401)
43
  return JSONResponse(content={"user": user}, status_code=200)
44
 
45
+
46
+ @router.get("/users", status_code=status.HTTP_200_OK)
47
+ async def get_users():
48
+ return await list_users_controller()
49
+
50
+
51
+ @router.put("/users/{user_id}", status_code=status.HTTP_200_OK)
52
+ async def update_user(user_id: str, user_data: dict):
53
+ return await update_user_controller(user_id, user_data)
54
+
55
+
56
+ @router.delete("/users/{user_id}", status_code=status.HTTP_200_OK)
57
+ async def delete_user(user_id: str):
58
+ return await delete_user_controller(user_id)
59
+
60
+
61
+ @router.get("/users/{user_id}", status_code=status.HTTP_200_OK)
62
+ async def get_user_by_id(user_id: str):
63
+ return await get_user_by_id_controller(user_id)
src/apis/routes/post_router.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import APIRouter, status, Depends, BackgroundTasks
2
  from typing import Annotated, Optional
3
  from fastapi.responses import JSONResponse
4
  from pydantic import Field
@@ -66,12 +66,13 @@ async def get_post(post_id: str):
66
 
67
 
68
  @router.get("/list", status_code=status.HTTP_200_OK)
69
- async def list_all_posts(user_id: Optional[str] = None):
70
  # result = await get_key_redis("all_posts")
71
  result = None
72
  # result = eval(result) if result else None
73
  if not result:
74
- result = await list_all_posts_controller(user_id)
 
75
  # background_tasks.add_task(set_key_redis, "all_posts", str(result), 20)
76
  if result["status"] == "error":
77
  return JSONResponse(content=result, status_code=404)
@@ -83,12 +84,13 @@ async def list_all_posts(user_id: Optional[str] = None):
83
  async def list_all_posts_destination(
84
  destination_id: str,
85
  user_id: Optional[str] = None,
 
86
  ):
87
  # result = await get_key_redis("all_posts")
88
  result = None
89
  result = eval(result) if result else None
90
  if not result:
91
- result = await list_posts_by_destination_controller(destination_id, user_id)
92
  # background_tasks.add_task(set_key_redis, "all_posts", str(result),20)
93
  if result["status"] == "error":
94
  return JSONResponse(content=result, status_code=404)
 
1
+ from fastapi import APIRouter, status, Depends, BackgroundTasks, Query
2
  from typing import Annotated, Optional
3
  from fastapi.responses import JSONResponse
4
  from pydantic import Field
 
66
 
67
 
68
  @router.get("/list", status_code=status.HTTP_200_OK)
69
+ async def list_all_posts(user_id: Optional[str] = None, page: int = Query(default=1, ge=1)):
70
  # result = await get_key_redis("all_posts")
71
  result = None
72
  # result = eval(result) if result else None
73
  if not result:
74
+ result = await list_all_posts_controller(user_id, page)
75
+ print("result", result)
76
  # background_tasks.add_task(set_key_redis, "all_posts", str(result), 20)
77
  if result["status"] == "error":
78
  return JSONResponse(content=result, status_code=404)
 
84
  async def list_all_posts_destination(
85
  destination_id: str,
86
  user_id: Optional[str] = None,
87
+ page: int = Query(default=1, ge=1),
88
  ):
89
  # result = await get_key_redis("all_posts")
90
  result = None
91
  result = eval(result) if result else None
92
  if not result:
93
+ result = await list_posts_by_destination_controller(destination_id, user_id, page)
94
  # background_tasks.add_task(set_key_redis, "all_posts", str(result),20)
95
  if result["status"] == "error":
96
  return JSONResponse(content=result, status_code=404)
src/apis/routes/travel_dest_route.py CHANGED
@@ -63,7 +63,7 @@ async def get_destinations(destination_id: str = Query(min_length=1, max_length=
63
  destination_data.pop("expire_at")
64
  destination_data["id"] = str(destination_data["_id"])
65
  destination_data.pop("_id")
66
-
67
  return JSONResponse(content=destination_data, status_code=200)
68
 
69
  except Exception as e:
 
63
  destination_data.pop("expire_at")
64
  destination_data["id"] = str(destination_data["_id"])
65
  destination_data.pop("_id")
66
+ print("destination_data", destination_data)
67
  return JSONResponse(content=destination_data, status_code=200)
68
 
69
  except Exception as e: