Skip to content

Commit 3b6092c

Browse files
Merge pull request #16 from Code4GovTech/dev_vedant
🗃️ Updated files as per the new DB structure
2 parents c6f2da6 + 3250a5e commit 3b6092c

5 files changed

Lines changed: 265 additions & 53 deletions

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
dmp_2/__pycache__/*
22
.env
33
env/*
4-
4+
venv
55
__pycache__/*

app.py

Lines changed: 58 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import re,os,traceback
66
from utils import *
77
from flask_cors import CORS,cross_origin
8-
from functools import wraps
8+
from v2_app import v2
99

1010

1111
app = Flask(__name__)
@@ -45,15 +45,6 @@ def greeting():
4545

4646

4747

48-
# Custom decorator to validate secret key
49-
def require_secret_key(f):
50-
@wraps(f)
51-
def decorated_function(*args, **kwargs):
52-
secret_key = request.headers.get('X-Secret-Key')
53-
if secret_key != SECRET_KEY:
54-
return jsonify({'message': 'Unauthorized access'}), 401
55-
return f(*args, **kwargs)
56-
return decorated_function
5748

5849
@app.route('/get-data', methods=['GET'])
5950
@cross_origin(supports_credentials=True)
@@ -82,7 +73,7 @@ def get_data():
8273
data = response.data
8374
return jsonify(data)
8475
except Exception as e:
85-
return jsonify({'error': str(e)}), 500
76+
return jsonify({'error': str(e)}), 200
8677

8778

8879

@@ -108,7 +99,7 @@ def v1get_issues():
10899

109100
except Exception as e:
110101
error_traceback = traceback.format_exc()
111-
return jsonify({'error': str(e), 'traceback': error_traceback}), 500
102+
return jsonify({'error': str(e), 'traceback': error_traceback}), 200
112103

113104

114105
@app.route('/issues', methods=['GET'])
@@ -136,88 +127,99 @@ def get_issues():
136127
type: string
137128
"""
138129
try:
139-
dmp_issue =SupabaseInterface().get_instance().client.table('dmp_issues').select('*').execute().data
130+
# Fetch all issues with their details
131+
dmp_issues = SupabaseInterface().get_instance().client.table('dmp_issues').select('*').execute().data
140132

141-
updated_issues = []
142-
143-
for i in dmp_issue:
144-
val = SupabaseInterface().get_instance().client.table('dmp_issue_updates').select('*').eq('dmp_issue_url',i['repo_url']).execute().data
145-
if val!=[]:
146-
i['issues'] = val[0] #append first obj ie all are reder same issue
147-
i['org_id'] = val[0]['org_id']
148-
i['org_name'] = val[0]['org_name']
149-
150-
updated_issues.append(i)
151-
152-
# Create a defaultdict of lists
133+
# Create a defaultdict of lists to group issues by 'org_id'
153134
grouped_data = defaultdict(list)
154-
# Group data by 'org_name'
155-
for item in updated_issues:
156-
grouped_data[item['org_name']].append(item)
135+
for issue in dmp_issues:
136+
# Fetch organization details for the issue
137+
org_details = SupabaseInterface().get_instance().client.table('dmp_orgs').select('*').eq('id', issue['org_id']).execute().data
138+
if org_details:
139+
issue['org_name'] = org_details[0]['name']
140+
141+
grouped_data[issue['org_id']].append(issue)
157142

143+
# Prepare response in the required format
158144
response = []
159-
for org_name, items in grouped_data.items():
145+
for org_id, items in grouped_data.items():
160146
issues = [
161147
{
162-
"html_url": item['issues']['html_issue_url'],
163-
"id": item['issues']['comment_id'],
164-
"issue_number": item['issues']['issue_number'],
165-
"name": item['issues']['title']
148+
"id": item['issue_number'],
149+
"name": item['title']
166150
}
167151
for item in items
168152
]
169153

170154
response.append({
171-
"issues": issues,
172-
"org_id": items[0]['org_id'],
173-
"org_name": org_name
155+
"org_id": org_id,
156+
"org_name": items[0]['org_name'], # Assuming all items in the group have the same org_name
157+
"issues": issues
174158
})
175159

176-
return jsonify(response)
160+
return jsonify({"issues": response})
177161

178162
except Exception as e:
179163
error_traceback = traceback.format_exc()
180164
return jsonify({'error': str(e), 'traceback': error_traceback}), 500
181-
165+
182166
@app.route('/issues/<owner>', methods=['GET'])
183167
@cross_origin(supports_credentials=True)
184168
@require_secret_key
185169
def get_issues_by_owner(owner):
186170
"""
187-
Fetch issues by owner.
171+
Fetch organization details by owner's GitHub URL.
188172
---
189173
parameters:
190174
- name: owner
191175
in: path
192176
type: string
193177
required: true
194-
description: The owner of the issues
178+
description: The owner of the GitHub URL (e.g., organization owner)
195179
responses:
196180
200:
197-
description: Issues fetched successfully
181+
description: Organization details fetched successfully
198182
schema:
199-
type: array
200-
items:
201-
type: object
183+
type: object
184+
properties:
185+
name:
186+
type: string
187+
description: Name of the organization
188+
description:
189+
type: string
190+
description: Description of the organization
191+
404:
192+
description: Organization not found
193+
schema:
194+
type: object
195+
properties:
196+
error:
197+
type: string
198+
description: Error message
202199
500:
203-
description: Error fetching issues
200+
description: Error fetching organization details
204201
schema:
205202
type: object
206203
properties:
207204
error:
208205
type: string
206+
description: Error message
209207
"""
210208
try:
211-
response = SupabaseInterface().get_instance().client.table('dmp_issue_updates').select('*').eq('owner', owner).order('comment_updated_at', desc=True).execute()
209+
# Construct the GitHub URL based on the owner parameter
210+
org_link = f"https://github.com/{owner}"
211+
212+
# Fetch organization details from dmp_orgs table
213+
response = SupabaseInterface().get_instance().client.table('dmp_orgs').select('name', 'description').eq('link', org_link).execute()
214+
212215
if not response.data:
213-
return jsonify({'error': "No data found"}), 500
214-
data = response.data[0]
215-
return jsonify({"name": data['org_name'], "description": data['org_description']})
216+
return jsonify({'error': "Organization not found"}), 404
217+
218+
return jsonify(response.data)
216219

217220
except Exception as e:
218221
error_traceback = traceback.format_exc()
219222
return jsonify({'error': str(e), 'traceback': error_traceback}), 500
220-
221223

222224

223225
@app.route('/issues/<owner>/<issue>', methods=['GET'])
@@ -259,7 +261,7 @@ def get_issues_by_owner_id(owner, issue):
259261
SUPABASE_DB = SupabaseInterface().get_instance()
260262
response = SUPABASE_DB.client.table('dmp_issue_updates').select('*').eq('owner', owner).eq('issue_number', issue).execute()
261263
if not response.data:
262-
return jsonify({'error': "No data found"}), 500
264+
return jsonify({'error': "No data found"}), 200
263265
data = response.data
264266

265267
final_data = []
@@ -329,7 +331,7 @@ def get_issues_by_owner_id(owner, issue):
329331

330332
except Exception as e:
331333
error_traceback = traceback.format_exc()
332-
return jsonify({'error': str(e), 'traceback': error_traceback}), 500
334+
return jsonify({'error': str(e), 'traceback': error_traceback}), 200
333335

334336

335337

@@ -344,5 +346,9 @@ def check_secret_key():
344346
break # Stop checking if the current route matches
345347

346348

349+
350+
# Register the v2 Blueprint
351+
app.register_blueprint(v2, url_prefix='/v2')
352+
347353
if __name__ == '__main__':
348354
app.run(debug=True)

utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22
from collections import defaultdict
33
from datetime import datetime, timedelta
44
from dateutil import parser
5+
from flask import jsonify,request
6+
from functools import wraps
57

68

79
GITHUB_TOKEN =os.getenv('GITHUB_TOKEN')
10+
SECRET_KEY =os.getenv('SECRET_KEY')
11+
812

913
headers = {
1014
"Accept": "application/vnd.github+json",
@@ -14,6 +18,17 @@
1418

1519

1620

21+
# Custom decorator to validate secret key
22+
def require_secret_key(f):
23+
@wraps(f)
24+
def decorated_function(*args, **kwargs):
25+
secret_key = request.headers.get('X-Secret-Key')
26+
if secret_key != SECRET_KEY:
27+
return jsonify({'message': 'Unauthorized access'}), 401
28+
return f(*args, **kwargs)
29+
return decorated_function
30+
31+
1732
def find_org_data(url):
1833
try:
1934
url_parts = url.split("/")

v2_app.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import traceback,re
2+
from flask import Blueprint, jsonify, request
3+
import markdown2
4+
from utils import require_secret_key
5+
from db import SupabaseInterface
6+
from utils import determine_week
7+
from v2_utils import calculate_overall_progress, define_link_data, week_data_formatter
8+
9+
v2 = Blueprint('v2', __name__)
10+
11+
12+
@v2.route('/issues/<owner>/<issue>', methods=['GET'])
13+
@require_secret_key
14+
def get_issues_by_owner_id_v2(owner, issue):
15+
try:
16+
SUPABASE_DB = SupabaseInterface().get_instance()
17+
# Fetch issue updates based on owner and issue number
18+
19+
url = f"https://github.com/{owner}"
20+
dmp_issue_id = SUPABASE_DB.client.table('dmp_issues').select('*').like('issue_url', f'%{url}%').eq('issue_number', issue).execute()
21+
if not dmp_issue_id.data:
22+
return jsonify({'error': "No data found"}), 500
23+
24+
dmp_issue_id = dmp_issue_id.data[0]
25+
response = SUPABASE_DB.client.table('dmp_issue_updates').select('*').eq('dmp_id', dmp_issue_id['id']).execute()
26+
27+
if not response.data:
28+
return jsonify({'error': "No data found"}), 500
29+
30+
data = response.data
31+
32+
final_data = []
33+
w_learn_url,w_goal_url,avg,cont_details,plain_text_body,plain_text_wurl = None,None,None,None,None,None
34+
35+
36+
for val in data:
37+
# issue_url = "https://api.github.com/repos/{}/{}/issues/comments".format(val['owner'],val['repo'])
38+
# week_avg ,cont_name,cont_id,w_goal,w_learn,weekby_avgs,org_link = find_week_avg(issue_url)
39+
# mentors_data = find_mentors(val['issue_url']) if val['issue_url'] else {'mentors': [], 'mentor_usernames': []}
40+
41+
if val['body_text']:
42+
if ("Weekly Goals" in val['body_text'] and not w_goal_url) and ("@"+val['created_by'].lower() == dmp_issue_id['mentor_username'].lower()):
43+
w_goal_url = val['body_text']
44+
plain_text_body = markdown2.markdown(val['body_text'])
45+
tasks = re.findall(r'\[(x| )\]', plain_text_body)
46+
total_tasks = len(tasks)
47+
completed_tasks = tasks.count('x')
48+
avg = round((completed_tasks/total_tasks)*100) if total_tasks!=0 else 0
49+
50+
if ("Weekly Learnings" in val['body_text'] and not w_learn_url) and ((val['created_by'] == dmp_issue_id['contributor_username'])):
51+
w_learn_url = val['body_text']
52+
plain_text_wurl = markdown2.markdown(val['body_text'])
53+
54+
55+
# mentors = mentors_data['mentors']
56+
# ment_usernames = mentors_data['mentor_usernames']
57+
if not cont_details:
58+
cont_details = dmp_issue_id['contributor_username']
59+
week_data = week_data_formatter(plain_text_body,"Goals")
60+
61+
res = {
62+
"name": owner,
63+
"description": dmp_issue_id['description'],
64+
"mentor": define_link_data(dmp_issue_id['mentor_username']),
65+
"mentor_id": dmp_issue_id['mentor_username'] ,
66+
"contributor":define_link_data(cont_details),
67+
# "contributor_id": cont_details[0]['contributor_id'],
68+
"org": define_link_data(dmp_issue_id['mentor_username'])[0] if dmp_issue_id['mentor_username'] else [],
69+
"weekly_goals_html": w_goal_url,
70+
"weekly_learnings_html": w_learn_url,
71+
"overall_progress":calculate_overall_progress(week_data,12),
72+
"issue_url":dmp_issue_id['issue_url'],
73+
"pr_details":None,
74+
"weekly_goals":week_data,
75+
"weekly_learnings":week_data_formatter(plain_text_wurl,"Learnings")
76+
}
77+
78+
79+
pr_Data = SUPABASE_DB.client.table('dmp_pr_updates').select('*').eq('dmp_id', dmp_issue_id['id']).like('title', f'%#{issue} - %').execute()
80+
transformed = {"pr_details": []}
81+
if pr_Data.data:
82+
for pr in pr_Data.data:
83+
transformed["pr_details"].append({
84+
"id": pr.get("pr_id", ""),
85+
"name": pr.get("title", ""),
86+
"week": determine_week(pr['created_at']),
87+
"link": pr.get("link", ""),
88+
"status": pr.get("status", ""),
89+
})
90+
91+
res['pr_details'] = transformed['pr_details']
92+
93+
return jsonify(res),200
94+
95+
except Exception as e:
96+
error_traceback = traceback.format_exc()
97+
return jsonify({'error': str(e), 'traceback': error_traceback}), 200

0 commit comments

Comments
 (0)