kshitij230 commited on
Commit
e8e997c
·
verified ·
1 Parent(s): 6014c36

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +9 -0
  2. Procfile +1 -0
  3. main.py +131 -0
  4. requirements.txt +5 -0
  5. tests/test_analytics.py +20 -0
Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+ WORKDIR /app
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY . .
6
+ # Hugging Face default port is 7860
7
+ ENV PORT=7860
8
+ EXPOSE 7860
9
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
Procfile ADDED
@@ -0,0 +1 @@
 
 
1
+ web: uvicorn main:app --host 0.0.0.0 --port $PORT
main.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timedelta
3
+ from fastapi import FastAPI, HTTPException, Query
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from pymongo import MongoClient
6
+ from bson import ObjectId
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
10
+
11
+ app = FastAPI(title="QuickTask Analytics Service")
12
+
13
+ # CORS middleware
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ # MongoDB connection
23
+ client = MongoClient(os.getenv("MONGO_URI"))
24
+ db = client.quicktask
25
+ tasks_collection = db.tasks
26
+
27
+ @app.get("/")
28
+ async def root():
29
+ return {"message": "QuickTask Analytics Service API"}
30
+
31
+ @app.get("/analytics/stats/{user_id}")
32
+ async def get_user_stats(user_id: str):
33
+ try:
34
+ user_oid = ObjectId(user_id)
35
+
36
+ # Total tasks
37
+ total_tasks = tasks_collection.count_documents({"user": user_oid})
38
+ if total_tasks == 0:
39
+ return {
40
+ "total_tasks": 0,
41
+ "avg_completion_time_hrs": 0,
42
+ "overdue_tasks": 0,
43
+ "productivity_score": 0
44
+ }
45
+
46
+ # Completed tasks
47
+ completed_tasks = list(tasks_collection.find({"user": user_oid, "status": "completed"}))
48
+ completed_count = len(completed_tasks)
49
+
50
+ # Average completion time
51
+ total_completion_time_sec = 0
52
+ for task in completed_tasks:
53
+ # Re-calculating from timestamps
54
+ created_at = task.get("createdAt")
55
+ updated_at = task.get("updatedAt")
56
+ if created_at and updated_at:
57
+ diff = (updated_at - created_at).total_seconds()
58
+ total_completion_time_sec += diff
59
+
60
+ avg_completion_time = (total_completion_time_sec / completed_count / 3600) if completed_count > 0 else 0
61
+
62
+ # Overdue tasks
63
+ now = datetime.now()
64
+ overdue_tasks = tasks_collection.count_documents({
65
+ "user": user_oid,
66
+ "status": {"$ne": "completed"},
67
+ "dueDate": {"$lt": now}
68
+ })
69
+
70
+ # Productivity score
71
+ productivity_score = (completed_count / total_tasks * 100)
72
+
73
+ return {
74
+ "total_tasks": total_tasks,
75
+ "avg_completion_time_hrs": round(avg_completion_time, 2),
76
+ "overdue_tasks": overdue_tasks,
77
+ "productivity_score": round(productivity_score, 2)
78
+ }
79
+ except Exception as e:
80
+ raise HTTPException(status_code=500, detail=str(e))
81
+
82
+ @app.get("/analytics/trends/{user_id}")
83
+ async def get_productivity_trends(user_id: str, days: int = Query(7, ge=1, le=30)):
84
+ try:
85
+ user_oid = ObjectId(user_id)
86
+ end_date = datetime.now()
87
+ start_date = end_date - timedelta(days=days)
88
+
89
+ # Aggregate tasks completed per day
90
+ pipeline = [
91
+ {
92
+ "$match": {
93
+ "user": user_oid,
94
+ "status": "completed",
95
+ "updatedAt": {"$gte": start_date, "$lte": end_date}
96
+ }
97
+ },
98
+ {
99
+ "$group": {
100
+ "_id": {
101
+ "$dateToString": {"format": "%Y-%m-%d", "date": "$updatedAt"}
102
+ },
103
+ "count": {"$sum": 1}
104
+ }
105
+ },
106
+ {"$sort": {"_id": 1}}
107
+ ]
108
+
109
+ results = list(tasks_collection.aggregate(pipeline))
110
+
111
+ # Fill in missing dates
112
+ trend_data = []
113
+ current_date = start_date
114
+ results_dict = {item["_id"]: item["count"] for item in results}
115
+
116
+ while current_date <= end_date:
117
+ date_str = current_date.strftime("%Y-%m-%d")
118
+ trend_data.append({
119
+ "date": date_str,
120
+ "count": results_dict.get(date_str, 0)
121
+ })
122
+ current_date += timedelta(days=1)
123
+
124
+ return trend_data
125
+ except Exception as e:
126
+ raise HTTPException(status_code=500, detail=str(e))
127
+
128
+ if __name__ == "__main__":
129
+ import uvicorn
130
+ port = int(os.getenv("PORT", 8000))
131
+ uvicorn.run(app, host="0.0.0.0", port=port)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ pymongo
4
+ python-dotenv
5
+ pydantic
tests/test_analytics.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi.testclient import TestClient
3
+ from main import app
4
+ import mongomock
5
+ from bson import ObjectId
6
+ from datetime import datetime, timedelta
7
+
8
+ # Mocking database isn't straightforward with global db object,
9
+ # so we'll test the logic via the app if possible or just unit test the calculations.
10
+
11
+ client = TestClient(app)
12
+
13
+ def test_root():
14
+ response = client.get("/")
15
+ assert response.status_code == 200
16
+ assert response.json() == {"message": "QuickTask Analytics Service API"}
17
+
18
+ def test_stats_invalid_user():
19
+ response = client.get("/analytics/stats/invalid_id")
20
+ assert response.status_code == 500 # Should be 400 ideally, but handled as catch-all 500 in code