File size: 15,692 Bytes
48322a4
 
 
 
 
80320be
48322a4
 
 
 
7e03cc0
48322a4
 
 
 
 
 
 
7e03cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48322a4
 
 
 
e4582d3
 
7e03cc0
 
 
80320be
e4582d3
 
 
 
 
 
 
48322a4
 
 
 
 
7e03cc0
48322a4
 
 
 
 
 
 
 
7e03cc0
 
 
48322a4
 
 
 
 
 
 
 
 
7e03cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48322a4
 
7e03cc0
48322a4
 
 
 
 
 
 
80320be
 
f6fd5fc
 
7e03cc0
 
 
48322a4
80320be
 
7e03cc0
 
 
 
 
 
 
 
 
 
f6fd5fc
7e03cc0
 
 
f6fd5fc
7e03cc0
 
f6fd5fc
7e03cc0
f6fd5fc
 
 
 
7e03cc0
 
 
 
 
 
 
 
48322a4
 
 
 
7e03cc0
80320be
7e03cc0
 
 
 
 
 
 
 
 
 
 
 
 
80320be
 
7e03cc0
80320be
7e03cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
80320be
7e03cc0
80320be
 
 
48322a4
 
 
 
 
 
 
 
80320be
 
 
 
 
 
 
 
 
 
 
 
 
 
48322a4
 
 
 
 
80320be
48322a4
 
80320be
7e03cc0
48322a4
 
 
 
80320be
48322a4
 
 
 
80320be
7e03cc0
48322a4
 
 
7e03cc0
48322a4
7e03cc0
48322a4
 
 
 
 
 
 
 
 
 
 
 
80320be
 
 
 
 
48322a4
 
80320be
48322a4
 
7e03cc0
 
 
 
 
 
 
48322a4
 
 
 
 
 
 
 
80320be
48322a4
 
 
80320be
7e03cc0
48322a4
 
 
 
 
 
 
80320be
48322a4
 
80320be
48322a4
80320be
 
 
 
48322a4
 
 
 
80320be
48322a4
 
 
 
 
 
 
 
 
 
 
56d51a5
 
 
 
7e03cc0
 
 
 
 
 
 
48322a4
 
 
 
 
 
7e03cc0
48322a4
 
 
7e03cc0
 
 
48322a4
 
 
 
 
56d51a5
 
80320be
 
48322a4
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import pandas as pd 
import numpy as np 
import sys
import os
import uuid
from bson import ObjectId
from fastapi import UploadFile
from src.logger import logging
from src.exception import CustomException
from src.utils import cleanup_after_download, ensure_artifacts_directory
from src.subject_mapping import SUBJECT_MAP

# Import DB CRUD operations
try:
    from database import crud
except ImportError:
    crud = None

def build_dynamic_subject_map(department_id: str = None) -> dict:
    """

    Merges the hardcoded SUBJECT_MAP with any custom templates 

    created by the department in the database.

    """
    dynamic_map = {}
    
    # 1. Load Hardcoded Subjects
    for code, info in SUBJECT_MAP.items():
        if isinstance(info, dict):
            dynamic_map[code] = {
                "name": info.get("name", code),
                "semester": info.get("semester"),
                "max_marks": float(info.get("max_marks") or 100.0)
            }
        else:
            dynamic_map[code] = {
                "name": info,
                "semester": None,
                "max_marks": 100.0
            }
            
    # 2. Overwrite with Department Custom Subjects
    if department_id and crud:
        try:
            custom_subjects = crud.get_department_subjects(department_id)
            for subj in custom_subjects:
                dynamic_map[subj["code"]] = {
                    "name": subj["name"],
                    "semester": subj.get("semester"),
                    "max_marks": float(subj.get("max_marks") or 100.0)
                }
        except Exception as e:
            logging.error(f"Failed to fetch custom subjects for department {department_id}: {e}")
            
    return dynamic_map

def add_total_score_column(df: pd.DataFrame, subject_map: dict):
    try:
        metadata = ["PRN", "NAME", "Seat No", "Rank"] 
        subj_cols = [col for col in df.columns if col not in metadata]
        
        valid_subj_cols = []
        for col in subj_cols:
            subject_info = subject_map.get(col, {})
            # If we explicitly defined max_marks as None in the map, skip it
            if "max_marks" in subject_info and subject_info.get("max_marks") is None:
                continue 
            valid_subj_cols.append(col)
        
        if valid_subj_cols:
            df['Total Score'] = pd.to_numeric(df[valid_subj_cols].stack(), errors='coerce').unstack().sum(axis=1)
        else:
            df['Total Score'] = 0
            
        return df
    except Exception as e:
        logging.error(f"Failed to add Total score column: {e}")
        raise CustomException(e, sys)
    
def add_percentage_column(df: pd.DataFrame, subject_map: dict):
    try:
        metadata = ["PRN", "NAME", "Seat No", "Rank", "Total Score"] 
        subj_cols = [col for col in df.columns if col not in metadata]

        def calculate_student_max_marks(row):
            total_max = 0
            for col in subj_cols:
                if pd.notna(row.get(col)) and str(row.get(col)).strip() != "":
                    subject_info = subject_map.get(col, {})
                    total_max += subject_info.get("max_marks", 100.0)
            return total_max if total_max > 0 else 100.0 

        df['Total Max Marks'] = df.apply(calculate_student_max_marks, axis=1)
        df['Percentage'] = np.round((df['Total Score'] / df['Total Max Marks']) * 100, 2)
        
        return df
    except Exception as e:
        logging.error(f"Failed to add Percentage column: {e}")
        raise CustomException(e, sys)

def parse_academic_year(year_str: str, offset_years: int):
    """Dynamically shifts an academic year backwards or forwards."""
    try:
        parts = year_str.split("-")
        return f"{int(parts[0]) + offset_years}-{int(parts[1]) + offset_years}"
    except:
        return year_str

def get_class_level_info(class_name: str):
    """Extracts the year level and prefix from a class name."""
    c = str(class_name).upper()
    if "FY" in c or "FIRST" in c: return 1, "FY" if "FY" in c else "FIRST"
    elif "SY" in c or "SECOND" in c: return 2, "SY" if "SY" in c else "SECOND"
    elif "TY" in c or "THIRD" in c: return 3, "TY" if "TY" in c else "THIRD"
    elif "FOURTH" in c: return 4, "FOURTH"
    return None, class_name

def process_and_store_db(df: pd.DataFrame, session_data: dict, subject_map: dict):
    """

    Performs the wide-to-long transformation for the database using bulk operations.

    Includes Smart Time-Travel Routing for backlogs and N+1 query optimization.

    """
    try:
        if not crud:
            logging.error("CRUD module not found. Skipping DB insertion.")
            return

        school_id = session_data.get("school_id")
        teacher_id = session_data.get("id")
        department_id = session_data.get("department_id")
        
        target_class_name = session_data.get("class_name", "General Class")
        academic_year = session_data.get("academic_year", "2024-2025")
        
        target_level, base_prefix = get_class_level_info(target_class_name)

        db = crud.get_db()
        
        class_cache = {} # Map (name, year) -> class_id
        class_year_lookup = {} # Map class_id -> academic_year

        def get_or_create_class(c_name, c_year):
            cache_key = f"{c_name}_{c_year}"
            if cache_key in class_cache:
                return class_cache[cache_key]
                
            query = {"school_id": school_id, "academic_year": c_year, "name": c_name}
            if department_id: query["department_id"] = ObjectId(department_id)
            
            existing = db.classes.find_one(query)
            if existing:
                cid = str(existing["_id"])
            else:
                c_data = {
                    "name": c_name,
                    "semester": 1,
                    "academic_year": c_year,
                    "department_id": department_id,
                    "class_teacher_id": teacher_id,
                    "school_id": school_id
                }
                cid = crud.create_class(c_data)
                
            class_cache[cache_key] = cid
            class_year_lookup[cid] = c_year
            return cid

        # Base target class
        class_id = get_or_create_class(target_class_name, academic_year)

        metadata_cols = ["PRN", "NAME", "Seat No", "Rank", "Total Score", "Total Max Marks", "Percentage"]
        subject_cols = [col for col in df.columns if col not in metadata_cols]

        # --- PRE-FLIGHT CHECK ---
        for subj_code in subject_cols:
            subj_info = subject_map.get(subj_code, {})
            sem = subj_info.get("semester")
            
            subj_level = None
            if sem in [1, 2]: subj_level = 1
            elif sem in [3, 4]: subj_level = 2
            elif sem in [5, 6]: subj_level = 3
            elif sem in [7, 8]: subj_level = 4
            
            if target_level and subj_level and subj_level > target_level:
                raise ValueError(f"Upload Blocked: You selected {target_class_name}, but the ledger contains advanced subjects (Sem {sem}).")

        # --- PHASE 1: DYNAMIC TIME-TRAVEL ROUTING ---
        subject_routing_map = {}
        for subj_code in subject_cols:
            sem = subject_map.get(subj_code, {}).get("semester")
            
            subj_level = None
            subj_prefix = None
            if sem in [1, 2]: subj_level, subj_prefix = 1, "FY"
            elif sem in [3, 4]: subj_level, subj_prefix = 2, "SY"
            elif sem in [5, 6]: subj_level, subj_prefix = 3, "TY"
            elif sem in [7, 8]: subj_level, subj_prefix = 4, "FOURTH"
            
            if target_level and subj_level and subj_level < target_level:
                # Time-travel: calculate exact historical class
                offset = subj_level - target_level
                routed_year = parse_academic_year(academic_year, offset)
                routed_class_name = target_class_name.upper().replace(base_prefix, subj_prefix)
                routed_class_id = get_or_create_class(routed_class_name, routed_year)
                subject_routing_map[subj_code] = routed_class_id
            else:
                # Fallback to current class
                subject_routing_map[subj_code] = class_id

        # --- PHASE 2: PREPARE DATA FOR BULK UPSERT ---
        students_to_upsert = []
        subjects_to_upsert = []
        unique_subject_codes = set()

        for _, row in df.iterrows():
            roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
            student_name = str(row.get("NAME", "Unknown"))
            
            target_class_ids = set()
            for subj_code in subject_cols:
                marks_obtained = row.get(subj_code)
                if pd.notna(marks_obtained) and str(marks_obtained).strip() != "":
                    target_class_ids.add(subject_routing_map[subj_code])
            
            for target_class_id in target_class_ids:
                students_to_upsert.append({
                    "roll_number": roll_number,
                    "name": student_name,
                    "class_id": target_class_id,
                    "school_id": school_id,
                    "department_id": department_id
                })

            for subj_code in subject_cols:
                marks_obtained = row.get(subj_code)
                if pd.isna(marks_obtained): 
                    continue
                
                if subj_code not in unique_subject_codes:
                    unique_subject_codes.add(subj_code)
                    target_class_id = subject_routing_map[subj_code]
                    subj_name = subject_map.get(subj_code, {}).get("name", subj_code)

                    subjects_to_upsert.append({
                        "code": subj_code,
                        "name": subj_name,
                        "class_id": target_class_id,
                        "teacher_id": teacher_id,
                        "school_id": school_id
                    })

        # --- PHASE 3: EXECUTE BULK UPSERTS & GET ID MAPS ---
        logging.info("Executing Master Data Bulk Upserts with Time-Travel Routing...")
        student_id_map = crud.bulk_upsert_students(students_to_upsert)
        subject_id_map = crud.bulk_upsert_subjects(subjects_to_upsert)

        # --- PHASE 4: BUILD FACT TABLE RECORDS (Instant Cache Access) ---
        records_to_insert = []

        for _, row in df.iterrows():
            roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))

            for subj_code in subject_cols:
                marks_obtained = row.get(subj_code)
                if pd.isna(marks_obtained): 
                    continue
                try:
                    marks_obtained = float(marks_obtained)
                except ValueError:
                    continue  

                target_class_id = subject_routing_map[subj_code]
                student_key = f"{school_id}_{str(target_class_id)}_{roll_number}"
                student_id = student_id_map.get(student_key)

                subject_key = f"{school_id}_{str(target_class_id)}_{subj_code}"
                subject_id = subject_id_map.get(subject_key)

                if not student_id or not subject_id:
                    continue

                # Fetch year from fast local dictionary cache
                target_class_year = class_year_lookup.get(target_class_id, academic_year)

                subject_info = subject_map.get(subj_code, {})
                subj_name = subject_info.get("name", subj_code)
                subject_max_marks = subject_info.get("max_marks", 100.0) 
                subject_semester = subject_info.get("semester")

                grade = "Pass" if marks_obtained >= (0.40 * subject_max_marks) else "Fail"

                record = {
                    "school_id": school_id,
                    "student_id": student_id,
                    "teacher_id": teacher_id,
                    "subject_id": subject_id,
                    "class_id": target_class_id,
                    "department_id": department_id,
                    "subject_code": subj_code,
                    "subject_name": subj_name,
                    "academic_year": target_class_year,
                    "semester": subject_semester,
                    "marks_obtained": marks_obtained,
                    "total_marks": subject_max_marks,
                    "grade": grade,
                    "attendance_percentage": 0.0
                }
                records_to_insert.append(record)

        # --- PHASE 5: BULK INSERT/UPDATE ACADEMIC RECORDS ---
        if records_to_insert:
            inserted_count = crud.insert_academic_records_bulk(records_to_insert)
            logging.info(f"Successfully routed and upserted {inserted_count} academic records into DB!")

    except ValueError as ve:
        # Pass validation errors cleanly to the frontend
        logging.warning(f"Validation Blocked Upload: {ve}")
        raise CustomException(str(ve), sys)
    except Exception as e:
        logging.error(f"Error during DB extraction/insertion process: {e}")
        raise CustomException(e, sys)

@cleanup_after_download(delay_seconds=60)  
def generate_rank_list(processed_file: UploadFile, session_data: dict = None):
    try:
        if processed_file:
            logging.info(f"Received processed file for finalization: {processed_file.filename}")
            
        logging.info("Started generating rank list...")

        artifacts_dir = ensure_artifacts_directory()
        csv_path = os.path.join(artifacts_dir, f"ranks_of_student_{uuid.uuid4().hex}.csv")
        
        df = pd.read_csv(processed_file.file)

        if "Rank" in df.columns or "Percentage" in df.columns:
            raise ValueError("you already have the ranked list and precentage you can't use this file.")

        # Build dynamic subject map based on user's department
        department_id = session_data.get("department_id") if session_data else None
        dynamic_subject_map = build_dynamic_subject_map(department_id)

        df = add_total_score_column(df, dynamic_subject_map)
        df = add_percentage_column(df, dynamic_subject_map) 
        
        df = df.sort_values(by='Percentage', ascending=False).reset_index(drop=True)
        df.index += 1
        df.index.name = 'Rank'
        
        if session_data:
            logging.info("Authorized user detected. Initiating database insertion...")
            process_and_store_db(df, session_data, dynamic_subject_map) 
        else:
            logging.info("Public user detected. Skipping database insertion.")
            
        # Map codes to names using the new dynamic map
        rename_map = {code: info["name"] for code, info in dynamic_subject_map.items() if code in df.columns}
        df = df.rename(columns=rename_map)

        df.to_csv(csv_path)
        logging.info(f"Rank list successfully generated with {len(df)} students.")
        return csv_path
        
    except ValueError as ve:
        raise ve
    except CustomException:
        raise
    except Exception as e:
        logging.critical(f"Unexpected error occurred in generate_rank_list(): {e}")
        raise CustomException(e, sys)