From 07e68efca8996999953e764506fa421882435723 Mon Sep 17 00:00:00 2001 From: harshabonu Date: Mon, 22 Apr 2024 10:51:33 +0530 Subject: [PATCH 1/5] with courses and curriculim from academic information --- FusionIIIT/Fusion/settings/common.py | 11 +- FusionIIIT/Fusion/settings/development.py | 12 +- .../academic_information/admin.py | 1 + .../academic_information/api/serializers.py | 1 + .../migrations/0001_initial.py | 8 +- .../academic_information/models.py | 26 +- .../academic_information/views.py | 62 +- .../academic_procedures/api/serializers.py | 44 +- .../academic_procedures/api/urls.py | 41 +- .../academic_procedures/api/views.py | 1076 +----- .../migrations/0001_initial.py | 16 +- .../migrations/0002_auto_20240420_1925.py | 38 + .../academic_procedures/models.py | 25 +- .../applications/academic_procedures/tests.py | 1 - .../applications/academic_procedures/urls.py | 26 +- .../applications/academic_procedures/views.py | 752 +--- FusionIIIT/applications/central_mess/admin.py | 73 +- .../central_mess/api/serializers.py | 91 - .../applications/central_mess/api/urls.py | 27 - .../applications/central_mess/api/views.py | 487 --- FusionIIIT/applications/central_mess/forms.py | 34 +- .../applications/central_mess/handlers.py | 513 +-- .../central_mess/migrations/0001_initial.py | 94 +- .../applications/central_mess/models.py | 111 +- FusionIIIT/applications/central_mess/tasks.py | 151 - FusionIIIT/applications/central_mess/urls.py | 28 +- FusionIIIT/applications/central_mess/utils.py | 2 +- FusionIIIT/applications/central_mess/views.py | 1014 ++---- .../applications/complaint_system/admin.py | 3 +- .../complaint_system/api/views.py | 6 +- .../migrations/0001_initial.py | 24 +- .../applications/complaint_system/models.py | 21 +- .../static/complaint_system/js/rating.js | 182 - .../applications/complaint_system/urls.py | 22 +- .../applications/complaint_system/views.py | 1665 +++------ .../migrations/0001_initial.py | 4 +- .../department/migrations/0001_initial.py | 2 +- FusionIIIT/applications/department/models.py | 1 + FusionIIIT/applications/department/views.py | 2 +- .../eis/migrations/0001_initial.py | 44 +- .../eis/migrations/0002_auto_20240420_1925.py | 53 + FusionIIIT/applications/eis/models.py | 26 +- FusionIIIT/applications/eis/views.py | 6 +- .../establishment/migrations/0001_initial.py | 2 +- .../estate_module/migrations/0001_initial.py | 2 +- .../static/estate_module/sidebar.js | 2 +- .../examination/migrations/0001_initial.py | 29 +- .../examination/migrations/__init__.py} | 0 .../feeds/migrations/0001_initial.py | 2 +- FusionIIIT/applications/feeds/views.py | 1 - FusionIIIT/applications/filetracking/admin.py | 24 +- .../filetracking/api/serializers.py | 24 - .../applications/filetracking/api/urls.py | 24 - .../applications/filetracking/api/views.py | 247 -- .../applications/filetracking/decorators.py | 51 - .../filetracking/migrations/0001_initial.py | 6 +- .../applications/filetracking/models.py | 18 +- .../applications/filetracking/sdk/methods.py | 429 --- FusionIIIT/applications/filetracking/urls.py | 44 +- FusionIIIT/applications/filetracking/views.py | 795 ++--- .../migrations/0001_initial.py | 2 +- .../globals/migrations/0001_initial.py | 6 +- FusionIIIT/applications/globals/models.py | 2 + FusionIIIT/applications/globals/views.py | 21 +- .../gymkhana/migrations/0001_initial.py | 4 +- .../applications/health_center/admin.py | 10 +- .../health_center/api/serializers.py | 24 +- .../applications/health_center/api/urls.py | 5 +- .../applications/health_center/api/views.py | 19 +- .../health_center/migrations/0001_initial.py | 114 +- .../applications/health_center/models.py | 87 +- FusionIIIT/applications/health_center/urls.py | 8 +- .../applications/health_center/utils.py | 237 +- .../applications/health_center/views.py | 342 +- .../applications/hostel_management/admin.py | 14 +- .../applications/hostel_management/forms.py | 28 +- .../management/commands/copy_data.py | 36 - .../migrations/0001_initial.py | 4 +- .../applications/hostel_management/models.py | 184 +- .../applications/hostel_management/urls.py | 87 - .../applications/hostel_management/utils.py | 77 +- .../applications/hostel_management/views.py | 1900 +--------- .../hr2/migrations/0001_initial.py | 2 +- .../migrations/0001_initial.py | 2 +- .../iwdModuleV2/migrations/0001_initial.py | 2 +- FusionIIIT/applications/iwdModuleV2/models.py | 50 +- FusionIIIT/applications/iwdModuleV2/urls.py | 43 +- FusionIIIT/applications/iwdModuleV2/views.py | 1056 +----- .../leave/migrations/0001_initial.py | 2 +- .../api/serializers.py | 6 - .../notifications_extension/api/urls.py | 53 - .../notifications_extension/api/views.py | 371 -- .../notifications_extension/urls.py | 4 - .../notifications_extension/views.py | 21 +- .../office_module/migrations/0001_initial.py | 6 +- .../online_cms/migrations/0001_initial.py | 4 +- .../migrations/0002_student_grades.py | 28 + FusionIIIT/applications/online_cms/models.py | 2 +- .../applications/placement_cell/forms.py | 86 +- .../placement_cell/migrations/0001_initial.py | 2 +- .../applications/placement_cell/models.py | 3 +- .../applications/placement_cell/urls.py | 1 - .../applications/placement_cell/views.py | 3132 +---------------- .../programme_curriculum/admin.py | 12 +- .../programme_curriculum/filters.py | 10 +- .../programme_curriculum/forms.py | 108 +- .../migrations/0001_initial.py | 84 +- .../migrations/0002_auto_20240420_1925.py | 23 + .../programme_curriculum/models.py | 241 +- .../applications/programme_curriculum/urls.py | 19 +- .../programme_curriculum/views.py | 746 +--- FusionIIIT/applications/ps1/__init__.py | 0 FusionIIIT/applications/ps1/admin.py | 6 +- .../applications/ps1/api/serializers.py | 45 - FusionIIIT/applications/ps1/api/urls.py | 53 - FusionIIIT/applications/ps1/api/views.py | 619 ---- .../ps1/migrations/0001_initial.py | 4 +- FusionIIIT/applications/ps1/models.py | 88 +- FusionIIIT/applications/ps1/urls.py | 54 +- FusionIIIT/applications/ps1/views.py | 992 ++---- .../recruitment/migrations/0001_initial.py | 2 +- .../migrations/0001_initial.py | 2 +- .../applications/scholarships/helpers.py | 14 - .../scholarships/migrations/0001_initial.py | 6 +- .../migrations/0002_auto_20240420_1925.py | 18 + FusionIIIT/applications/scholarships/urls.py | 1 - FusionIIIT/applications/scholarships/views.py | 133 +- .../applications/visitor_hostel/forms.py | 48 +- .../visitor_hostel/migrations/0001_initial.py | 14 +- .../applications/visitor_hostel/models.py | 19 +- .../static/visitor_hostel/visitor-hostel.js | 210 +- .../applications/visitor_hostel/urls.py | 7 +- .../applications/visitor_hostel/views.py | 447 ++- .../academic_information/sheet.xlsx | Bin 8786 -> 0 bytes FusionIIIT/notification/views.py | 115 +- .../academic_procedures/academic.html | 21 +- .../academic_procedures/academicfac.html | 66 +- .../academic_procedures/addCourse.html | 2 +- .../academic_procedures/allot_courses.html | 2 +- .../auto_finalregister.html | 251 -- .../auto_pre_registration.html | 437 --- .../academic_procedures/backlog.html | 76 - .../academic_procedures/dropCourse.html | 4 +- .../academic_procedures/finalregister.html | 4 + .../academic_procedures/register.html | 2 + .../academic_procedures/replace.html | 182 - .../academic_procedures/studentCourses.html | 23 +- .../academic_procedures/studentSwayam.html | 322 -- .../academic_procedures/student_table.html | 9 +- .../academic_procedures/studentlist.html | 2 +- .../academic_procedures/swayam_list.html | 57 - FusionIIIT/templates/ais/ais.html | 133 +- .../ais/config_courseslot_courses.html | 140 - FusionIIIT/templates/ais/generateSheet.html | 6 +- .../ais/pre_registration_courses.html | 254 -- FusionIIIT/templates/ais/profile.html | 2 +- .../templates/ais/student_dashboard.html | 2 +- .../complaintModule/add_workers.html | 34 +- .../complaintModule/assignworker.html | 160 +- .../complaintModule/carefeedback.html | 133 - .../complaintModule/complaint_caretaker.html | 59 +- .../complaint_caretaker_detail.html | 167 + .../complaint_secincharge.html | 161 - .../complaint_supervisor_detail.html | 4 +- .../complaintModule/complaint_user.html | 6 +- .../complaint_user_detail.html | 7 +- .../complainthistory_care_final.html | 335 -- ...e.html => complainthistory_caretaker.html} | 14 +- .../complainthistory_super_final.html | 369 -- .../complainthistory_user.html | 608 +++- .../complainthistory_user_final.html | 379 +- .../templates/complaintModule/feedback.html | 18 +- .../lodgecomplaint_caretaker.html | 160 - .../complaintModule/lodgecomplaint_super.html | 160 - .../complaintModule/lodgecomplaint_user.html | 2 +- .../complaintModule/overdue_complaint1.html | 4 +- .../complaintModule/overdue_super.html | 32 +- .../complaintModule/overduecomplaint.html | 58 +- .../complaintModule/reassignworker.html | 82 +- .../complaintModule/resolve_caretaker.html | 162 - .../complaintModule/resolve_pending.html | 15 +- ...vecomplaint.html => resolvecomplaint.html} | 78 +- .../resolvecomplaint_caretaker.html | 128 - .../resolvecomplaint_secincharge.html | 134 - .../complaintModule/resolved_super.html | 6 +- .../complaintModule/supervisor1.html | 57 +- .../complaintModule/unresolved_super.html | 184 +- .../complaintModule/worker_id_know_more.html | 2 +- FusionIIIT/templates/dashboard/alerts.html | 7 +- FusionIIIT/templates/dashboard/alerts1.html | 8 +- FusionIIIT/templates/dashboard/dashboard.html | 2 +- .../dashboard/director_dashboard.html | 2 +- FusionIIIT/templates/dashboard/modules.html | 389 +- FusionIIIT/templates/dashboard/navbar.html | 1 - .../templates/dashboard/sidenavbar.html | 5 +- .../templates/filetracking/archive.html | 54 +- .../filetracking/archive_design.html | 2 +- .../filetracking/archive_finish.html | 57 +- .../templates/filetracking/composefile.html | 58 +- .../templates/filetracking/confirmdelete.html | 4 +- .../templates/filetracking/draft_design.html | 30 - FusionIIIT/templates/filetracking/drafts.html | 58 +- .../templates/filetracking/editdraft.html | 197 -- .../filetracking/fileTrackingNotAllowed.html | 41 - .../templates/filetracking/filetracking.html | 15 +- .../fileview.html} | 14 +- .../templates/filetracking/fileview1.html | 49 + .../templates/filetracking/fileview2.html | 57 + .../templates/filetracking/forward.html | 70 +- FusionIIIT/templates/filetracking/inbox.html | 54 - .../filetracking/invalid_designation.html | 44 - FusionIIIT/templates/filetracking/inward.html | 2 +- .../filetracking/notif_sidepanel.html | 28 - FusionIIIT/templates/filetracking/outbox.html | 48 - .../templates/filetracking/outward.html | 2 +- .../templates/filetracking/viewfile.html | 144 - FusionIIIT/templates/globals/base.html | 2 +- FusionIIIT/templates/globals/usercard.html | 4 - .../hostelmanagement/add_hostel.html | 45 - .../hostelmanagement/add_student.html | 10 +- .../hostelmanagement/admin_hostel_list.html | 63 - .../hostelmanagement/all_leave_data.html | 115 - .../hostelmanagement/alloted_rooms_main.html | 174 - .../hostelmanagement/assign_batch.html | 66 - .../hostelmanagement/assign_caretaker.html | 83 - .../hostelmanagement/assign_warden.html | 81 - .../hostelmanagement/book_guest_room.html | 227 -- .../book_guest_room_status.html | 60 - .../hostelmanagement/create_leave.html | 88 - .../hostelmanagement/edit_student.html | 179 - .../templates/hostelmanagement/hall_list.html | 16 - .../templates/hostelmanagement/hostel.html | 555 +-- .../hostelmanagement/hostel_complaint.html | 25 - .../hostelmanagement/hostel_fine_list.html | 127 - .../hostelmanagement/hostel_history.html | 33 - .../hostelmanagement/hostel_history_data.html | 38 - .../hostelmanagement/hostel_transactions.html | 30 - .../hostelmanagement/impose_fine.html | 76 - .../hostelmanagement/impose_fine_edit.html | 129 - .../hostelmanagement/inventory_form.html | 59 - .../hostelmanagement/inventory_list.html | 129 - .../inventory_update_form.html | 72 - .../templates/hostelmanagement/my_leaves.html | 48 - .../templates/hostelmanagement/notice.html | 2 +- .../hostelmanagement/post_complaint_form.html | 39 - .../hostelmanagement/request_list.html | 99 - .../hostelmanagement/student_details.html | 100 - .../student_fine_details.html | 34 - .../hostelmanagement/update_guest_room.html | 28 - .../hostelmanagement/user_complaints.html | 118 - FusionIIIT/templates/iwdModuleV2/Page1.html | 5 +- FusionIIIT/templates/iwdModuleV2/Page2.html | 31 +- FusionIIIT/templates/iwdModuleV2/Page3.html | 8 +- .../templates/iwdModuleV2/addBudget.html | 111 - .../templates/iwdModuleV2/addItemsView.html | 120 - .../iwdModuleV2/auditDocumentView.html | 121 - .../templates/iwdModuleV2/billsView.html | 147 - FusionIIIT/templates/iwdModuleV2/budget.html | 111 - .../templates/iwdModuleV2/createWork.html | 13 +- .../iwdModuleV2/createdRequests.html | 128 - .../templates/iwdModuleV2/dashboard.html | 201 +- .../iwdModuleV2/deanProcessedRequests.html | 110 - .../templates/iwdModuleV2/editBudget.html | 120 - .../templates/iwdModuleV2/editInventory.html | 124 - .../engineerProcessedRequests.html | 128 - .../generatedBillsRequestsView.html | 127 - .../templates/iwdModuleV2/inventory.html | 111 - .../templates/iwdModuleV2/issueWorkOrder.html | 120 - .../templates/iwdModuleV2/page1_create.html | 2 +- .../iwdModuleV2/page1_support_1_aes.html | 3 +- .../page2_support_1_corrigendum.html | 206 +- .../iwdModuleV2/rejectedRequests.html | 118 - .../iwdModuleV2/requestFromInventory.html | 139 - .../iwdModuleV2/requestsInProgress.html | 140 - .../templates/iwdModuleV2/requestsStatus.html | 114 - .../templates/iwdModuleV2/requestsView.html | 135 - .../iwdModuleV2/settleBillsView.html | 113 - .../templates/iwdModuleV2/updateRequests.html | 146 - .../templates/iwdModuleV2/viewBudget.html | 106 - .../templates/iwdModuleV2/viewWork.html | 3 +- .../templates/iwdModuleV2/workOrder.html | 175 - FusionIIIT/templates/leaveModule.zip | Bin 0 -> 12720 bytes .../templates/libraryModule/issuedItems.html | 2 +- .../libraryModule/libraryModule.html | 2 +- .../templates/messModule/add_remove.html | 243 -- FusionIIIT/templates/messModule/alerts.html | 89 - .../templates/messModule/applications.html | 50 +- .../templates/messModule/billpdfexport.html | 20 +- .../templates/messModule/changemenu.html | 367 +- .../messModule/de-registraionsrequests.html | 277 -- .../templates/messModule/de-registration.html | 113 - .../messModule/meeting_information.html | 6 +- .../templates/messModule/menu_card.html | 125 +- .../messModule/menudownloadable1.html | 106 +- .../messModule/menudownloadable2.html | 75 +- FusionIIIT/templates/messModule/mess.html | 125 +- .../templates/messModule/messInfoForm.html | 32 +- .../templates/messModule/messactivities.html | 473 ++- .../templates/messModule/nonvegfood.html | 20 +- .../templates/messModule/nonvegorder.html | 4 +- FusionIIIT/templates/messModule/reg_list.html | 354 -- .../messModule/registered_student.html | 328 -- .../templates/messModule/registration.html | 85 - .../templates/messModule/respondmenu.html | 12 +- .../messModule/respondtorequests.html | 798 ++--- FusionIIIT/templates/messModule/splreq.html | 4 +- .../templates/messModule/updateSemdates.html | 73 - .../templates/messModule/updatemenu.html | 519 --- .../templates/messModule/view_feedback.html | 115 +- .../messModule/view_payments_bills.html | 319 -- FusionIIIT/templates/messModule/viewmenu.html | 170 +- FusionIIIT/templates/messModule/views.html | 333 +- .../academic_procedures_sidepanel.html | 26 - .../account_admin_medical_relief.html | 210 -- .../templates/phcModule/appointment.html | 485 ++- .../{patientlog.html => comapproval.html} | 106 +- .../phcModule/comp_prescription.html | 54 +- .../phcModule/compounder_medical_relief.html | 109 - FusionIIIT/templates/phcModule/doctors.html | 231 +- FusionIIIT/templates/phcModule/history.html | 34 +- .../phcModule/make_announce_comp.html | 163 - .../templates/phcModule/medical_relief.html | 195 - FusionIIIT/templates/phcModule/phc.html | 6 +- .../templates/phcModule/phc_compounder.html | 47 +- .../templates/phcModule/phc_student.html | 59 +- FusionIIIT/templates/phcModule/publish.html | 134 - FusionIIIT/templates/phcModule/schedule.html | 412 +-- .../templates/phcModule/schedule_student.html | 294 +- .../templates/placementModule/activity.html | 12 +- .../placementModule/add_placement_visits.html | 4 +- .../placementModule/managerecords.html | 12 +- .../templates/placementModule/placement.html | 51 +- .../placementModule/placementstatistics.html | 169 +- .../placementModule/studentrecords.html | 16 +- ..._course_form.html => add_course_form.html} | 21 +- .../acad_admin/add_curriculum_form.html | 7 - .../acad_admin/admin_view_a_course.html | 6 +- .../acad_admin/admin_view_all_courses.html | 2 - .../admin_view_all_working_curriculums.html | 2 +- .../acad_admin/course_form.html | 244 -- .../programme_curriculum/faculty/common.html | 78 - .../faculty/course_proposal_form.html | 259 -- .../faculty/dean_view_a_course_proposal.html | 249 -- .../faculty/faculty_view_a_course.html | 181 - .../faculty/faculty_view_all_courses.html | 105 - .../faculty/filetracking.html | 126 - .../programme_curriculum/faculty/forward.html | 144 - .../faculty/inward_course_forms.html | 107 - .../faculty/outward_course_forms.html | 105 - .../faculty/update_course_proposal_form.html | 261 -- .../faculty/view_a_course.html | 162 - .../faculty/view_a_course_proposal.html | 192 - .../faculty/view_a_courseslot.html | 119 - .../view_a_semester_of_a_curriculum.html | 143 - .../faculty/view_all_batches.html | 134 - .../faculty/view_all_courses.html | 92 - .../faculty/view_all_disciplines.html | 75 - .../faculty/view_all_programmes.html | 154 - .../faculty/view_all_working_curriculums.html | 97 - .../faculty/view_course_proposal_forms.html | 185 - .../view_curriculums_of_a_programme.html | 155 - .../faculty/view_file.html | 369 -- .../view_semesters_of_a_curriculum.html | 166 - .../programme_curriculum/view_a_course.html | 2 +- .../view_all_courses.html | 2 - .../templates/ps1/ComposeIndentMultiple.html | 537 --- FusionIIIT/templates/ps1/StockEntry.html | 314 +- FusionIIIT/templates/ps1/addNewItem.html | 136 - FusionIIIT/templates/ps1/composeIndent.html | 69 +- .../templates/ps1/composed_indents.html | 2 +- FusionIIIT/templates/ps1/createdindent.html | 50 +- .../templates/ps1/current_stock_view.html | 104 - .../ps1/current_stock_view_filter.html | 135 - FusionIIIT/templates/ps1/drafts.html | 2 +- FusionIIIT/templates/ps1/drafts1.html | 26 - FusionIIIT/templates/ps1/draftview.html | 2 +- FusionIIIT/templates/ps1/entry.html | 37 +- FusionIIIT/templates/ps1/forwardindent.html | 142 +- FusionIIIT/templates/ps1/indentview.html | 2 +- FusionIIIT/templates/ps1/indentview2.html | 24 +- FusionIIIT/templates/ps1/inwardIndent.html | 48 +- .../templates/ps1/perform_transfer1.html | 162 - FusionIIIT/templates/ps1/ps1.html | 12 - FusionIIIT/templates/ps1/ps2.html | 34 +- FusionIIIT/templates/ps1/report.html | 246 -- FusionIIIT/templates/ps1/stock_edit.html | 89 +- .../templates/ps1/stock_entry_item_view.html | 105 - .../templates/ps1/stock_entry_view.html | 304 -- FusionIIIT/templates/ps1/stock_item_view.html | 116 - FusionIIIT/templates/ps1/stock_transfer.html | 139 - .../{generate_report.html => stock_view.html} | 26 +- FusionIIIT/templates/ps1/view_transfer.html | 88 - .../scholarshipsModule/aboutspacs.html | 4 +- .../scholarshipsModule/applyNew.html | 16 +- .../templates/scholarshipsModule/invite.html | 35 +- FusionIIIT/templates/vhModule/accounts.html | 11 +- .../templates/vhModule/add-item-modal.html | 31 +- FusionIIIT/templates/vhModule/bookaroom.html | 2 +- .../templates/vhModule/booking-details.html | 4 +- .../booking-request-action-modal.html | 9 +- FusionIIIT/templates/vhModule/bookings.html | 12 +- .../templates/vhModule/check-out-modal.html | 8 +- .../templates/vhModule/generate_records.html | 2 +- .../templates/vhModule/record-meal.html | 45 +- .../templates/vhModule/request-booking.html | 47 +- .../templates/vhModule/room-availability.html | 228 +- .../vhModule/room-availability1.html | 3 + .../templates/vhModule/view-inventory.html | 49 +- .../templates/vhModule/visitorhostel.html | 10 +- 409 files changed, 7832 insertions(+), 41747 deletions(-) create mode 100644 FusionIIIT/applications/academic_procedures/migrations/0002_auto_20240420_1925.py delete mode 100644 FusionIIIT/applications/central_mess/api/serializers.py delete mode 100644 FusionIIIT/applications/central_mess/api/urls.py delete mode 100644 FusionIIIT/applications/central_mess/api/views.py create mode 100644 FusionIIIT/applications/eis/migrations/0002_auto_20240420_1925.py rename FusionIIIT/{templates/complaintModule/complaint_secincharge_detail.html => applications/examination/migrations/__init__.py} (100%) delete mode 100644 FusionIIIT/applications/filetracking/api/serializers.py delete mode 100644 FusionIIIT/applications/filetracking/api/urls.py delete mode 100644 FusionIIIT/applications/filetracking/api/views.py delete mode 100644 FusionIIIT/applications/filetracking/decorators.py delete mode 100644 FusionIIIT/applications/filetracking/sdk/methods.py delete mode 100644 FusionIIIT/applications/hostel_management/management/commands/copy_data.py delete mode 100644 FusionIIIT/applications/notifications_extension/api/serializers.py delete mode 100644 FusionIIIT/applications/notifications_extension/api/urls.py delete mode 100644 FusionIIIT/applications/notifications_extension/api/views.py create mode 100644 FusionIIIT/applications/online_cms/migrations/0002_student_grades.py create mode 100644 FusionIIIT/applications/programme_curriculum/migrations/0002_auto_20240420_1925.py create mode 100644 FusionIIIT/applications/ps1/__init__.py delete mode 100644 FusionIIIT/applications/ps1/api/serializers.py delete mode 100644 FusionIIIT/applications/ps1/api/urls.py delete mode 100644 FusionIIIT/applications/ps1/api/views.py delete mode 100644 FusionIIIT/applications/scholarships/helpers.py create mode 100644 FusionIIIT/applications/scholarships/migrations/0002_auto_20240420_1925.py delete mode 100644 FusionIIIT/media/Administrator/academic_information/sheet.xlsx delete mode 100644 FusionIIIT/templates/academic_procedures/auto_finalregister.html delete mode 100644 FusionIIIT/templates/academic_procedures/auto_pre_registration.html delete mode 100644 FusionIIIT/templates/academic_procedures/backlog.html delete mode 100644 FusionIIIT/templates/academic_procedures/replace.html delete mode 100644 FusionIIIT/templates/academic_procedures/studentSwayam.html delete mode 100644 FusionIIIT/templates/academic_procedures/swayam_list.html delete mode 100644 FusionIIIT/templates/ais/config_courseslot_courses.html delete mode 100644 FusionIIIT/templates/ais/pre_registration_courses.html delete mode 100644 FusionIIIT/templates/complaintModule/carefeedback.html create mode 100644 FusionIIIT/templates/complaintModule/complaint_caretaker_detail.html delete mode 100644 FusionIIIT/templates/complaintModule/complaint_secincharge.html delete mode 100644 FusionIIIT/templates/complaintModule/complainthistory_care_final.html rename FusionIIIT/templates/complaintModule/{complainthistory_secincharge.html => complainthistory_caretaker.html} (96%) delete mode 100644 FusionIIIT/templates/complaintModule/complainthistory_super_final.html delete mode 100644 FusionIIIT/templates/complaintModule/lodgecomplaint_caretaker.html delete mode 100644 FusionIIIT/templates/complaintModule/lodgecomplaint_super.html delete mode 100644 FusionIIIT/templates/complaintModule/resolve_caretaker.html rename FusionIIIT/templates/complaintModule/{unresolvecomplaint.html => resolvecomplaint.html} (79%) delete mode 100644 FusionIIIT/templates/complaintModule/resolvecomplaint_caretaker.html delete mode 100644 FusionIIIT/templates/complaintModule/resolvecomplaint_secincharge.html delete mode 100644 FusionIIIT/templates/filetracking/draft_design.html delete mode 100644 FusionIIIT/templates/filetracking/editdraft.html delete mode 100644 FusionIIIT/templates/filetracking/fileTrackingNotAllowed.html rename FusionIIIT/templates/{ps1/draftview1.html => filetracking/fileview.html} (70%) create mode 100644 FusionIIIT/templates/filetracking/fileview1.html create mode 100644 FusionIIIT/templates/filetracking/fileview2.html delete mode 100644 FusionIIIT/templates/filetracking/inbox.html delete mode 100644 FusionIIIT/templates/filetracking/invalid_designation.html delete mode 100644 FusionIIIT/templates/filetracking/notif_sidepanel.html delete mode 100644 FusionIIIT/templates/filetracking/outbox.html delete mode 100644 FusionIIIT/templates/filetracking/viewfile.html delete mode 100644 FusionIIIT/templates/hostelmanagement/add_hostel.html delete mode 100644 FusionIIIT/templates/hostelmanagement/admin_hostel_list.html delete mode 100644 FusionIIIT/templates/hostelmanagement/all_leave_data.html delete mode 100644 FusionIIIT/templates/hostelmanagement/alloted_rooms_main.html delete mode 100644 FusionIIIT/templates/hostelmanagement/assign_batch.html delete mode 100644 FusionIIIT/templates/hostelmanagement/assign_caretaker.html delete mode 100644 FusionIIIT/templates/hostelmanagement/assign_warden.html delete mode 100644 FusionIIIT/templates/hostelmanagement/book_guest_room.html delete mode 100644 FusionIIIT/templates/hostelmanagement/book_guest_room_status.html delete mode 100644 FusionIIIT/templates/hostelmanagement/create_leave.html delete mode 100644 FusionIIIT/templates/hostelmanagement/edit_student.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hall_list.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hostel_complaint.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hostel_fine_list.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hostel_history.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hostel_history_data.html delete mode 100644 FusionIIIT/templates/hostelmanagement/hostel_transactions.html delete mode 100644 FusionIIIT/templates/hostelmanagement/impose_fine.html delete mode 100644 FusionIIIT/templates/hostelmanagement/impose_fine_edit.html delete mode 100644 FusionIIIT/templates/hostelmanagement/inventory_form.html delete mode 100644 FusionIIIT/templates/hostelmanagement/inventory_list.html delete mode 100644 FusionIIIT/templates/hostelmanagement/inventory_update_form.html delete mode 100644 FusionIIIT/templates/hostelmanagement/my_leaves.html delete mode 100644 FusionIIIT/templates/hostelmanagement/post_complaint_form.html delete mode 100644 FusionIIIT/templates/hostelmanagement/request_list.html delete mode 100644 FusionIIIT/templates/hostelmanagement/student_details.html delete mode 100644 FusionIIIT/templates/hostelmanagement/student_fine_details.html delete mode 100644 FusionIIIT/templates/hostelmanagement/update_guest_room.html delete mode 100644 FusionIIIT/templates/hostelmanagement/user_complaints.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/addBudget.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/addItemsView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/auditDocumentView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/billsView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/budget.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/createdRequests.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/deanProcessedRequests.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/editBudget.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/editInventory.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/engineerProcessedRequests.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/generatedBillsRequestsView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/inventory.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/issueWorkOrder.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/rejectedRequests.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/requestFromInventory.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/requestsInProgress.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/requestsStatus.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/requestsView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/settleBillsView.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/updateRequests.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/viewBudget.html delete mode 100644 FusionIIIT/templates/iwdModuleV2/workOrder.html create mode 100644 FusionIIIT/templates/leaveModule.zip delete mode 100644 FusionIIIT/templates/messModule/add_remove.html delete mode 100644 FusionIIIT/templates/messModule/alerts.html delete mode 100644 FusionIIIT/templates/messModule/de-registraionsrequests.html delete mode 100644 FusionIIIT/templates/messModule/de-registration.html delete mode 100644 FusionIIIT/templates/messModule/reg_list.html delete mode 100644 FusionIIIT/templates/messModule/registered_student.html delete mode 100644 FusionIIIT/templates/messModule/registration.html delete mode 100644 FusionIIIT/templates/messModule/updateSemdates.html delete mode 100644 FusionIIIT/templates/messModule/updatemenu.html delete mode 100644 FusionIIIT/templates/messModule/view_payments_bills.html delete mode 100644 FusionIIIT/templates/notifications/academic_procedures_sidepanel.html delete mode 100644 FusionIIIT/templates/phcModule/account_admin_medical_relief.html rename FusionIIIT/templates/phcModule/{patientlog.html => comapproval.html} (86%) delete mode 100644 FusionIIIT/templates/phcModule/compounder_medical_relief.html delete mode 100644 FusionIIIT/templates/phcModule/make_announce_comp.html delete mode 100644 FusionIIIT/templates/phcModule/medical_relief.html delete mode 100644 FusionIIIT/templates/phcModule/publish.html rename FusionIIIT/templates/programme_curriculum/acad_admin/{update_course_form.html => add_course_form.html} (94%) delete mode 100644 FusionIIIT/templates/programme_curriculum/acad_admin/course_form.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/common.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/course_proposal_form.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/dean_view_a_course_proposal.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/faculty_view_a_course.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/faculty_view_all_courses.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/filetracking.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/forward.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/inward_course_forms.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/outward_course_forms.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/update_course_proposal_form.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_a_course.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_a_course_proposal.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_a_courseslot.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_a_semester_of_a_curriculum.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_all_batches.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_all_courses.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_all_disciplines.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_all_programmes.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_all_working_curriculums.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_course_proposal_forms.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_curriculums_of_a_programme.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_file.html delete mode 100644 FusionIIIT/templates/programme_curriculum/faculty/view_semesters_of_a_curriculum.html delete mode 100644 FusionIIIT/templates/ps1/ComposeIndentMultiple.html delete mode 100644 FusionIIIT/templates/ps1/addNewItem.html delete mode 100644 FusionIIIT/templates/ps1/current_stock_view.html delete mode 100644 FusionIIIT/templates/ps1/current_stock_view_filter.html delete mode 100644 FusionIIIT/templates/ps1/drafts1.html delete mode 100644 FusionIIIT/templates/ps1/perform_transfer1.html delete mode 100644 FusionIIIT/templates/ps1/report.html delete mode 100644 FusionIIIT/templates/ps1/stock_entry_item_view.html delete mode 100644 FusionIIIT/templates/ps1/stock_entry_view.html delete mode 100644 FusionIIIT/templates/ps1/stock_item_view.html delete mode 100644 FusionIIIT/templates/ps1/stock_transfer.html rename FusionIIIT/templates/ps1/{generate_report.html => stock_view.html} (90%) delete mode 100644 FusionIIIT/templates/ps1/view_transfer.html diff --git a/FusionIIIT/Fusion/settings/common.py b/FusionIIIT/Fusion/settings/common.py index f697dbd30..1b0160f37 100644 --- a/FusionIIIT/Fusion/settings/common.py +++ b/FusionIIIT/Fusion/settings/common.py @@ -104,7 +104,7 @@ 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', - 'django_crontab', + 'corsheaders', 'applications.eis', @@ -172,7 +172,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, '..', 'templates'),], + 'DIRS': [os.path.join(BASE_DIR, '..', 'templates/'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -257,9 +257,9 @@ # os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' -STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static') +STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static/') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' -MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media') +MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media/') MEDIA_URL = '/media/' ACCOUNT_USERNAME_REQUIRED = False @@ -280,6 +280,5 @@ YOUTUBE_DATA_API_KEY = 'api_key' - CORS_ORIGIN_ALLOW_ALL = True -ALLOW_PASS_RESET = True \ No newline at end of file +ALLOW_PASS_RESET = True diff --git a/FusionIIIT/Fusion/settings/development.py b/FusionIIIT/Fusion/settings/development.py index 3f95a478c..6acc214c1 100644 --- a/FusionIIIT/Fusion/settings/development.py +++ b/FusionIIIT/Fusion/settings/development.py @@ -1,7 +1,7 @@ from Fusion.settings.common import * DEBUG = True -TEMPLATE_DEBUG = True + SECRET_KEY = '=&w9due426k@l^ju1=s1)fj1rnpf0ok8xvjwx+62_nc-f12-8(' ALLOWED_HOSTS = ['*'] @@ -16,11 +16,9 @@ } } - REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', - 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', @@ -55,11 +53,3 @@ DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } - -CRONJOBS = [ - # the below job will update the bill at every minute can be used for testing - # ('* * * * *', 'applications.central_mess.tasks.generate_bill'), - - #the below job which we need to add in production server, to update the mess bill of student everyday at 10 pm in night - ('0 22 * * *', 'applications.central_mess.tasks.generate_bill'), -] diff --git a/FusionIIIT/applications/academic_information/admin.py b/FusionIIIT/applications/academic_information/admin.py index 522815707..94f60274d 100755 --- a/FusionIIIT/applications/academic_information/admin.py +++ b/FusionIIIT/applications/academic_information/admin.py @@ -32,3 +32,4 @@ class Curriculum_InstructorAdmin(admin.ModelAdmin): admin.site.register(Holiday) admin.site.register(Curriculum,CurriculumAdmin) +#Hello! diff --git a/FusionIIIT/applications/academic_information/api/serializers.py b/FusionIIIT/applications/academic_information/api/serializers.py index fd4fb59b7..06d6154c5 100644 --- a/FusionIIIT/applications/academic_information/api/serializers.py +++ b/FusionIIIT/applications/academic_information/api/serializers.py @@ -18,6 +18,7 @@ class Meta: class CurriculumSerializer(serializers.ModelSerializer): course_id = CourseSerializer() + class Meta: model = Curriculum fields = ('curriculum_id','course_code','course_id','credits','course_type', diff --git a/FusionIIIT/applications/academic_information/migrations/0001_initial.py b/FusionIIIT/applications/academic_information/migrations/0001_initial.py index 4b0f359c3..f75d3119c 100644 --- a/FusionIIIT/applications/academic_information/migrations/0001_initial.py +++ b/FusionIIIT/applications/academic_information/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion @@ -9,8 +9,8 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('globals', '0001_initial'), ('programme_curriculum', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ @@ -117,8 +117,8 @@ class Migration(migrations.Migration): ('batch', models.IntegerField(default=2016)), ('cpi', models.FloatField(default=0)), ('category', models.CharField(choices=[('GEN', 'General'), ('SC', 'Scheduled Castes'), ('ST', 'Scheduled Tribes'), ('OBC', 'Other Backward Classes')], max_length=10)), - ('father_name', models.CharField(default='', max_length=40, null=True)), - ('mother_name', models.CharField(default='', max_length=40, null=True)), + ('father_name', models.CharField(default='', max_length=40)), + ('mother_name', models.CharField(default='', max_length=40)), ('hall_no', models.IntegerField(default=0)), ('room_no', models.CharField(blank=True, max_length=10, null=True)), ('specialization', models.CharField(choices=[('Power and Control', 'Power and Control'), ('Microwave and Communication Engineering', 'Microwave and Communication Engineering'), ('Micro-nano Electronics', 'Micro-nano Electronics'), ('CAD/CAM', 'CAD/CAM'), ('Design', 'Design'), ('Manufacturing', 'Manufacturing'), ('CSE', 'CSE'), ('Mechatronics', 'Mechatronics'), ('MDes', 'MDes'), ('None', 'None')], default='', max_length=40, null=True)), diff --git a/FusionIIIT/applications/academic_information/models.py b/FusionIIIT/applications/academic_information/models.py index 280e84b32..8f2609870 100755 --- a/FusionIIIT/applications/academic_information/models.py +++ b/FusionIIIT/applications/academic_information/models.py @@ -66,35 +66,15 @@ class Constants: class Student(models.Model): - ''' - Current Purpose : To store information pertinent to a user who is also a student - - - - ATTRIBUTES : - - id(globals.ExtraInfo) - one to one unique reference to the nominal details of the student[not nullable] - program(char) - to store the programme (eg: Btech Mtech) - batch(Integer) - to store the batch year(eg 2019) - batch_id(programme_curriculum.Batch) - reference to the Batch collective details(foreign key, can be null) - cpi(Float) - to store the current CPI of the student - category - to store the details about category of a sutdent (General/OBC etc)[not nullable] - father_name(char) - father's name - mother_name(char) - mother's name - hall_no(integer) - the hostel number in which the student has been alloted a room - room_no(char) - the room.no of the student - specialization - to dentote the specialization for MTECH students[null is allowed] - cur_sem_no(integer) - the current semester of the student - - ''' + id = models.OneToOneField(ExtraInfo, on_delete=models.CASCADE, primary_key=True) programme = models.CharField(max_length=10, choices=Constants.PROGRAMME) batch = models.IntegerField(default=2016) batch_id = models.ForeignKey(Batch, null=True, blank=True, on_delete=models.CASCADE) cpi = models.FloatField(default=0) category = models.CharField(max_length=10, choices=Constants.CATEGORY, null=False) - father_name = models.CharField(max_length=40, default='',null=True) - mother_name = models.CharField(max_length=40, default='',null=True) + father_name = models.CharField(max_length=40, default='') + mother_name = models.CharField(max_length=40, default='') hall_no = models.IntegerField(default=0) room_no = models.CharField(max_length=10, blank=True, null=True) specialization = models.CharField(max_length=40,choices=Constants.MTechSpecialization, null=True, default='') diff --git a/FusionIIIT/applications/academic_information/views.py b/FusionIIIT/applications/academic_information/views.py index b3702b3ef..22210a52e 100755 --- a/FusionIIIT/applications/academic_information/views.py +++ b/FusionIIIT/applications/academic_information/views.py @@ -28,7 +28,7 @@ -from applications.academic_procedures.views import acad_proced_global_context , get_sem_courses +from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @@ -107,8 +107,9 @@ def get_context(request): # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() + procedures_context = acad_proced_global_context() - notifs = request.user.notifications.all() + try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() @@ -175,8 +176,7 @@ def get_context(request): 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, - 'account_flag' : account_flag, - 'notifications': notifs, + 'account_flag' : account_flag } return context @@ -842,16 +842,12 @@ def generatexlsheet(request): """ if user_check(request): return HttpResponseRedirect('/academic-procedures/') - # print(request.POST) + try: - batch = request.POST['batch']#batch hai year wala (2020 , 21) - course_id = int(request.POST['course']) # id of course in integer - course = course = Courses.objects.get(id=course_id) - - # print(course.name) + batch = request.POST['batch'] + course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e: - print(str(e)) batch="" course="" curr_key="" @@ -1033,14 +1029,9 @@ def generate_preregistration_report(request): max_width = max(max_width,len(choices_of_current_student)) for choice in range(1,len(choices_of_current_student)+1): - try: - current_choice = InitialRegistration.objects.get(student_id=student, semester_id__semester_no=sem, course_slot_id=slot, priority=choice) - z.append(str(current_choice.course_id.code) + "-" + str(current_choice.course_id.name)) - except : - z.append("No registration found") - # current_choice = InitialRegistration.objects.get(student_id=student, semester_id__semester_no=sem,course_slot_id = slot,priority = choice) - # # #print("current choice is ",current_choice) - # z.append(str(current_choice.course_id.code)+"-"+str(current_choice.course_id.name)) + current_choice = InitialRegistration.objects.get(student_id=student, semester_id__semester_no=sem,course_slot_id = slot,priority = choice) + # #print("current choice is ",current_choice) + z.append(str(current_choice.course_id.code)+"-"+str(current_choice.course_id.name)) data.append(z) m+=1 @@ -1178,9 +1169,9 @@ def add_new_profile (request): } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] - excel = xlrd.open_workbook(profiles.name,file_contents=profiles.read()) + excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) - for i in range(1,sheet.nrows): + for i in range(sheet.nrows): roll_no=sheet.cell(i,0).value first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) @@ -1200,7 +1191,7 @@ def add_new_profile (request): category="" phone_no=0 address="" - dept=str(sheet.cell(i,11).value) + dept=str(sheet.cell(i,12).value) specialization=str(sheet.cell(i,12).value) hall_no=None @@ -1218,6 +1209,7 @@ def add_new_profile (request): batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() + user = User.objects.create_user( username=roll_no, password='hello123', @@ -1225,7 +1217,6 @@ def add_new_profile (request): last_name=last_name, email=email, ) - einfo = ExtraInfo.objects.create( id=roll_no, @@ -1262,11 +1253,6 @@ def add_new_profile (request): working=user, designation=desig, ) - - user.save() - einfo.save() - stud_data.save() - hold_des.save() sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) @@ -2077,15 +2063,14 @@ def view_all_student_data(request): "specailization": student.specialization, "gender" : student.id.sex, "category": student.category, - # "pwd_status": student.pwd_status, - "pwd_status": False, + "pwd_status": student.pwd_status, "Mobile": student.id.phone_no, "dob" : student.id.date_of_birth, "emailid" : student.id.user.email, "father_name": student.father_name, - # "father_mobile_no": student.father_mobile_no, + "father_mobile_no": student.father_mobile_no, "mother_name": student.mother_name, - # "mother_mobile_no": student.mother_mobile_no, + "mother_mobile_no": student.mother_mobile_no, "address": student.id.address } data.append(obj) @@ -2155,9 +2140,9 @@ def generatestudentxlsheet(request): data = None else: if(request_rollno != ""): - students = Student.objects.select_related('batch_id', 'id__user', 'batch_id__discipline', 'id').filter(id = request_rollno).only('batch', 'id__id', 'id__user', 'programme', 'batch_id__discipline__acronym', 'specialization', 'id__sex', 'category', 'id__phone_no', 'id__date_of_birth', 'id__user__first_name', 'id__user__last_name', 'id__user__email', 'father_name', 'mother_name', 'id__address') + students = Student.objects.select_related('batch_id', 'id__user', 'batch_id__discipline', 'id').filter(id = request_rollno).only('batch', 'id__id', 'id__user', 'programme','pwd_status', 'father_mobile_no', 'mother_mobile_no', 'batch_id__discipline__acronym', 'specialization', 'id__sex', 'category', 'id__phone_no', 'id__date_of_birth', 'id__user__first_name', 'id__user__last_name', 'id__user__email', 'father_name', 'mother_name', 'id__address') else: - students = Student.objects.select_related('batch_id', 'id__user', 'batch_id__discipline', 'id').filter(**filter_names).order_by('id').all().only('batch', 'id__id', 'id__user', 'programme', 'batch_id__discipline__acronym', 'specialization', 'id__sex', 'category', 'id__phone_no', 'id__date_of_birth', 'id__user__first_name', 'id__user__last_name', 'id__user__email', 'father_name', 'mother_name', 'id__address') + students = Student.objects.select_related('batch_id', 'id__user', 'batch_id__discipline', 'id').filter(**filter_names).order_by('id').all().only('batch', 'id__id', 'id__user', 'programme','pwd_status', 'father_mobile_no', 'mother_mobile_no', 'batch_id__discipline__acronym', 'specialization', 'id__sex', 'category', 'id__phone_no', 'id__date_of_birth', 'id__user__first_name', 'id__user__last_name', 'id__user__email', 'father_name', 'mother_name', 'id__address') for i in students: obj = [] obj.append(i.batch) @@ -2168,17 +2153,14 @@ def generatestudentxlsheet(request): obj.append(i.specialization) obj.append(i.id.sex) obj.append(i.category) - #obj.append(i.pwd_status) - obj.append(None) + obj.append(i.pwd_status) obj.append(i.id.phone_no) obj.append(i.id.date_of_birth) obj.append(i.id.user.email) obj.append(i.father_name) - #obj.append(i.father_mobile_no) - obj.append(None) + obj.append(i.father_mobile_no) obj.append(i.mother_name) - # obj.append(i.mother_mobile_no) - obj.append(None) + obj.append(i.mother_mobile_no) obj.append(i.id.address) data.append(obj) data.sort() diff --git a/FusionIIIT/applications/academic_procedures/api/serializers.py b/FusionIIIT/applications/academic_procedures/api/serializers.py index bf66ef870..e8020d0e0 100644 --- a/FusionIIIT/applications/academic_procedures/api/serializers.py +++ b/FusionIIIT/applications/academic_procedures/api/serializers.py @@ -1,13 +1,13 @@ from rest_framework.authtoken.models import Token from rest_framework import serializers -from applications.academic_procedures.models import (ThesisTopicProcess, InitialRegistrations,InitialRegistration, - FinalRegistration, FinalRegistrations, SemesterMarks, - BranchChange , StudentRegistrationChecks, Semester, backlog_course , CourseSlot , FeePayments , course_registration) +from applications.academic_procedures.models import (ThesisTopicProcess, InitialRegistrations, + FinalRegistrations, SemesterMarks, + BranchChange) from applications.academic_information.api.serializers import (CurriculumInstructorSerializer, - CurriculumSerializer , CourseSerializer , StudentSerializers ) -from applications.globals.api.serializers import (UserSerializer, HoldsDesignationSerializer , ExtraInfoSerializer) + CurriculumSerializer) +from applications.globals.api.serializers import (UserSerializer, HoldsDesignationSerializer) class ThesisTopicProcessSerializer(serializers.ModelSerializer): @@ -27,24 +27,6 @@ class Meta: model = FinalRegistrations fields = ('__all__') -class InitialRegistrationSerializer(serializers.ModelSerializer): - - class Meta: - model = InitialRegistration - fields = ('__all__') - -class FinalRegistrationSerializer(serializers.ModelSerializer): - - class Meta: - model = FinalRegistration - fields = ('__all__') - -class StudentRegistrationChecksSerializer(serializers.ModelSerializer): - class Meta: - model = StudentRegistrationChecks - fields = '__all__' - - class SemesterMarksSerializer(serializers.ModelSerializer): class Meta: @@ -56,19 +38,3 @@ class BranchChangeSerializer(serializers.ModelSerializer): class Meta: model = BranchChange fields = ('__all__') - -class SemesterSerializer(serializers.ModelSerializer): - - class Meta: - model = Semester - fields = ('__all__') - -class CourseRegistrationSerializer(serializers.ModelSerializer): - class Meta: - model = course_registration - fields = ('__all__') - -class CourseSlotSerializer(serializers.ModelSerializer): - class Meta: - model = CourseSlot - fields = ('__all__') \ No newline at end of file diff --git a/FusionIIIT/applications/academic_procedures/api/urls.py b/FusionIIIT/applications/academic_procedures/api/urls.py index 1bf63b660..3abeace02 100644 --- a/FusionIIIT/applications/academic_procedures/api/urls.py +++ b/FusionIIIT/applications/academic_procedures/api/urls.py @@ -1,41 +1,12 @@ from django.conf.urls import url -from . import views +from . import views urlpatterns = [ - url(r'^stu/details', views.academic_procedures_student, name='student_procedures'), - url(r'^stu/pre_registration' , views.student_pre_registration , name = 'pre_registration'), - url(r'^stu/final_registration' , views.student_final_registration , name = 'final_registration'), - url(r'^stu/view_registration' , views.student_view_registration , name = 'view_registration'), - url(r'^stu/view_offered_courses' , views.view_offered_courses , name = 'student_view_offered_courses'), - url(r'^stu/backlog_courses', views.student_backlog_courses , name = 'student_backlog_courses'), - url(r'^stu/add_course' , views.add_course , name ='add_course') , - url(r'^stu/drop_course' , views.drop_course , name = 'drop_course'), - # url(r'^stu/replaceCourse' , views.replaceCourse , name = 'replaceCourse') - - - - url(r'^acad/view_registrations' , views.acad_view_reigstrations , name='acad_view_registrations'), - url(r'^acad/get_course_list' , views.get_course_list , name = 'get_course_list' ), - url(r'^acad/configure_pre_registration' , views.configure_pre_registration_date , name = 'configure_pre_registration'), - url(r'^acad/configure_final_registration' , views.configure_final_registration_date , name = 'configure_final_registration'), - url(r'^acad/add_course_to_slot' , views.add_course_to_slot , name = 'add_course_to_slot'), - url(r'^acad/remove_course_from_slot' , views.remove_course_from_slot , name = 'remove_course_from_slot'), - url(r'^get_next_sem_courses' , views.get_next_sem_courses , name= 'get_next_sem_courses'), - - - url(r'^fac/view_assigned_courses' , views.faculty_assigned_courses , name = 'faculty_assigned_courses'), - # url(r'^fac/get_roll_list' , views.fetch_roll_list , name = 'fetch_roll_list'), - - - - url(r'^get_user_info' , views.get_user_info , name = 'get_user_info'), - - # these urls were designed previously and are not working any more - # url(r'^fac/', views.academic_procedures_faculty, name='faculty_procedures'), - # url(r'^stu', views.academic_procedures_student, name='student_procedures'), - # url(r'^addThesis/', views.add_thesis, name='add_thesis'), - # url(r'^approve_thesis/(?P[0-9]+)/', views.approve_thesis, name='approve_thesis') + url(r'^fac/', views.academic_procedures_faculty, name='faculty_procedures'), + url(r'^stu/', views.academic_procedures_student, name='student_procedures'), + url(r'^addThesis/', views.add_thesis, name='add_thesis'), + url(r'^approve_thesis/(?P[0-9]+)/', views.approve_thesis, name='approve_thesis'), -] \ No newline at end of file +] diff --git a/FusionIIIT/applications/academic_procedures/api/views.py b/FusionIIIT/applications/academic_procedures/api/views.py index 99a807cd4..aab6deaa7 100644 --- a/FusionIIIT/applications/academic_procedures/api/views.py +++ b/FusionIIIT/applications/academic_procedures/api/views.py @@ -2,9 +2,7 @@ from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404, redirect -from django.db import transaction -from django.http import JsonResponse from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework import status @@ -12,16 +10,12 @@ from rest_framework.permissions import AllowAny from rest_framework.response import Response +from applications.academic_information.models import Curriculum +from applications.academic_procedures.models import ThesisTopicProcess from applications.globals.models import HoldsDesignation, Designation, ExtraInfo -from applications.programme_curriculum.models import ( CourseSlot, Course as Courses, Batch, Semester) +from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester) -from applications.academic_procedures.models import (Course, Student, Curriculum , ThesisTopicProcess, InitialRegistrations, - FinalRegistrations, SemesterMarks,backlog_course, - BranchChange , StudentRegistrationChecks, Semester , FeePayments , course_registration) - -from applications.academic_information.models import (Curriculum_Instructor , Calendar) - from applications.academic_procedures.views import (get_user_semester, get_acad_year, get_currently_registered_courses, get_current_credits, get_branch_courses, @@ -29,9 +23,7 @@ get_registration_courses, get_add_course_options, get_pre_registration_eligibility, get_final_registration_eligibility, - get_add_or_drop_course_date_eligibility, - get_detailed_sem_courses, - InitialRegistration) + get_add_or_drop_course_date_eligibility) from . import serializers @@ -39,12 +31,46 @@ date_time = datetime.datetime.now() +@api_view(['GET']) +def academic_procedures_faculty(request): + current_user = request.user + user_details = current_user.extrainfo + des = current_user.holds_designations.all().first() + if str(des.designation) == 'student': + return Response({'error':'Not a faculty'}, status=status.HTTP_400_BAD_REQUEST) + elif str(current_user) == 'acadadmin': + return Response({'error':'User is acadadmin'}, status=status.HTTP_400_BAD_REQUEST) + + elif str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor": + faculty_object = user_details.faculty + month = int(date_time.month) + sem = [] + if month>=7 and month<=12: + sem = [1,3,5,7] + else: + sem = [2,4,6,8] + student_flag = False + fac_flag = True -#--------------------------------------- APIs of student---------------------------------------------------------- + thesis_supervision_request_list = faculty_object.thesistopicprocess_supervisor.all() + thesis_supervision_request_list_data = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list, many=True).data + approved_thesis_request_list = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list.filter(approval_supervisor = True), many=True).data + pending_thesis_request_list = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list.filter(pending_supervisor = True), many=True).data + courses_list = serializers.CurriculumInstructorSerializer(user_details.curriculum_instructor_set.all(), many=True).data + fac_details = serializers.UserSerializer(current_user).data + resp = { + 'student_flag' : student_flag, + 'fac_flag' : fac_flag, + 'thesis_supervision_request_list' : thesis_supervision_request_list_data, + 'pending_thesis_request_list' : pending_thesis_request_list, + 'approved_thesis_request_list' : approved_thesis_request_list, + 'courses_list': courses_list, + 'faculty': fac_details + } + return Response(data=resp, status=status.HTTP_200_OK) -# with this student can get all his details in one api call @api_view(['GET']) def academic_procedures_student(request): current_user = request.user @@ -119,7 +145,6 @@ def academic_procedures_student(request): 'cpi' : cpi, 'spi' : cur_spi } - currently_registered_courses = get_currently_registered_courses(user_details.id, user_sem) currently_registered_courses_data = serializers.CurriculumSerializer(currently_registered_courses, many=True).data try: @@ -138,11 +163,8 @@ def academic_procedures_student(request): final_registered_courses_data = serializers.FinalRegistrationsSerializer(final_registered_courses, many=True).data current_credits = get_current_credits(currently_registered_courses) - print(current_user, user_sem+1, user_branch) - try: - next_sem_branch_courses = get_branch_courses(current_user, user_sem+1, user_branch) - except Exception as e: - return Response(data = str(e)) + + next_sem_branch_courses = get_branch_courses(current_user, user_sem+1, user_branch) next_sem_branch_courses_data = serializers.CurriculumSerializer(next_sem_branch_courses, many=True).data fee_payment_mode_list = dict(Constants.PaymentMode) @@ -151,8 +173,7 @@ def academic_procedures_student(request): next_sem_branch_registration_courses_data = [] for choices in next_sem_branch_registration_courses: next_sem_branch_registration_courses_data.append(serializers.CurriculumSerializer(choices, many=True).data) - # print(next_sem_branch_registration_courses_data) - # next_sem_branch_registration_courses_data = serializers.CurriculumSerializer(next_sem_branch_registration_courses_data, many=True).data + # next_sem_branch_registration_courses_data = serializers.CurriculumSerializer(next_sem_branch_registration_courses, many=True).data final_registration_choices = get_registration_courses(get_branch_courses(request.user, user_sem, user_branch)) final_registration_choices_data = [] @@ -175,7 +196,7 @@ def academic_procedures_student(request): current_sem_branch_courses = get_branch_courses(current_user, user_sem, user_branch) - pre_registration_date_flag = get_pre_registration_eligibility(current_date , user_sem , acad_year) + pre_registration_date_flag = get_pre_registration_eligibility(current_date) final_registration_date_flag = get_final_registration_eligibility(current_date) add_or_drop_course_date_flag = get_add_or_drop_course_date_eligibility(current_date) @@ -194,6 +215,18 @@ def academic_procedures_student(request): teaching_credit_registration_course = Curriculum.objects.all().filter(batch = 2016, sem =6) teaching_credit_registration_course_data = serializers.CurriculumSerializer(teaching_credit_registration_course, many=True).data + if student_flag: + try: + due = obj.dues_set.get() + lib_d = due.library_due + pc_d = due.placement_cell_due + hos_d = due.hostel_due + mess_d = due.mess_due + acad_d = due.academic_due + except: + lib_d, pc_d, hos_d, mess_d, acad_d = 0, 0, 0, 0, 0 + + tot_d = lib_d + acad_d + pc_d + hos_d + mess_d registers = obj.register_set.all() course_list = [] @@ -221,7 +254,7 @@ def academic_procedures_student(request): if user_sem == 2: branchchange_flag=True - faculty_list = serializers.HoldsDesignationSerializer(get_faculty_list(), many=True).data + # faculty_list = serializers.HoldsDesignationSerializer(get_faculty_list(), many=True).data resp = { 'details': details, @@ -234,15 +267,15 @@ def academic_procedures_student(request): 'fee_payment_mode_list' : fee_payment_mode_list, 'next_sem_branch_registration_courses' : next_sem_branch_registration_courses_data, 'final_registration_choices' : final_registration_choices_data, - - + 'performance_list' : performance_list_data, + 'thesis_request_list' : thesis_request_list, 'student_flag' : student_flag, 'ug_flag' : ug_flag, 'masters_flag' : masters_flag, 'phd_flag' : phd_flag, 'fac_flag' : fac_flag, 'des_flag' : des_flag, - + 'thesis_flag' : pre_existing_thesis_flag, 'drop_courses_options' : currently_registered_courses_data, 'pre_registration_date_flag': pre_registration_date_flag, 'final_registration_date_flag': final_registration_date_flag, @@ -250,897 +283,116 @@ def academic_procedures_student(request): 'pre_registration_flag' : pre_registration_flag, 'final_registration_flag': final_registration_flag, 'teaching_credit_registration_course' : teaching_credit_registration_course_data, - + 'lib_d':lib_d, + 'acad_d':acad_d, + 'mess_d':mess_d, + 'pc_d':pc_d, + 'hos_d':hos_d, + 'tot_d':tot_d, 'attendance': attendance_data, 'Branch_Change_Flag':branchchange_flag + # 'faculty_list' : faculty_list } - return Response(data=resp, status=status.HTTP_200_OK) - + return Response(data=resp, status=status.HTTP_200_OK) -# api for student for adding courses @api_view(['POST']) -def add_course(request): - try: - current_user = request.user - current_user = ExtraInfo.objects.all().filter(user=current_user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - - sem_id_instance = Semester.objects.get(id = request.data['semester']) - - count = request.data['ct'] - count = int(count) - reg_curr = [] - - for i in range(1, count+1): - choice = "choice["+str(i)+"]" - slot = "slot["+str(i)+"]" - try: - course_id_instance = Courses.objects.get(id = request.data[choice]) - courseslot_id_instance = CourseSlot.objects.get(id = request.data[slot]) - - print(courseslot_id_instance.max_registration_limit) - if course_registration.objects.filter(working_year = current_user.batch_id.year, course_id = course_id_instance).count() < courseslot_id_instance.max_registration_limit and (course_registration.objects.filter(course_id=course_id_instance, student_id=current_user).count() == 0): - p = course_registration( - course_id=course_id_instance, - student_id=current_user, - course_slot_id=courseslot_id_instance, - semester_id=sem_id_instance - ) - print(serializers.course_registration(p)) - if p not in reg_curr: - reg_curr.append(p) - else: - print("already exist") - except Exception as e: - error_message = str(e) - resp = {'message': 'Course addition failed', 'error': error_message} - return Response(resp, status=status.HTTP_400_BAD_REQUEST) - print(reg_curr) - course_registration_data = course_registration.objects.bulk_create(reg_curr) - course_registration_data = serializers.CourseRegistrationSerializer(course_registration_data , many = True).data - res = {'message' : 'Courses successfully added' , "courses_added" : course_registration_data } - return Response(data = res , status = status.HTTP_200_OK) - except Exception as e: - return Response(data = str(e) , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - -@api_view(['POST']) -def drop_course(request): +def add_thesis(request): current_user = request.user - current_user = ExtraInfo.objects.all().filter(user=current_user).first() - current_user = Student.objects.all().filter(id = current_user.id).first() - - courses = request.data['courses'] - - for course in courses: - try: - course_id = Courses.objects.all().filter(id=course).first() - course_registration.objects.filter(course_id = course_id, student_id = current_user).delete() - except Exception as e: - resp = {"message" : "Course drop failed", "error" : str(e)} - return Response(data = resp, status = status.HTTP_400_BAD_REQUEST) - - resp = {"message" : "Course successfully dropped"} - return Response(data = resp , status = status.HTTP_200_OK) - + profile = current_user.extrainfo + if profile.user_type == 'student': + if not 'thesis_topic' in request.data: + return Response({'error':'Thesis topic is required'}, status=status.HTTP_400_BAD_REQUEST) + if not 'research_area' in request.data: + return Response({'error':'Research area is required'}, status=status.HTTP_400_BAD_REQUEST) + if 'supervisor_id' in request.data: + try: + supervisor_faculty = User.objects.get(username=request.data['supervisor_id']) + supervisor_faculty = supervisor_faculty.extrainfo + request.data['supervisor_id'] = supervisor_faculty + except: + return Response({'error':'Wrong supervisor id. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) + else: + return Response({'error':'supervisor id is required'}, status=status.HTTP_400_BAD_REQUEST) + if 'co_supervisor_id' in request.data: + try: + co_supervisor_faculty = User.objects.get(username=request.data['co_supervisor_id']) + co_supervisor_faculty = co_supervisor_faculty.extrainfo + request.data['co_supervisor_id'] = co_supervisor_faculty + except: + return Response({'error':'Wrong co_supervisor id. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) + else: + co_supervisor_faculty = None + if 'curr_id' in request.data: + curr_id = None + student = profile.student + request.data['student_id'] = profile + request.data['submission_by_student'] = True + serializer = serializers.ThesisTopicProcessSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + else: + return Response({'error':'Cannot add thesis'}, status=status.HTTP_400_BAD_REQUEST) -# simple api for getting to know the details of user who have logined in the system -@api_view(['GET']) -def get_user_info(request): +@api_view(['PUT']) +def approve_thesis(request, id): current_user = request.user - details1 = serializers.UserSerializer(current_user).data - details2 = serializers.ExtraInfoSerializer(current_user.extrainfo).data - details = { - "user_serializer_Data" : details1, - "ExtraInfoSerializer_Data" : details2 - } - return Response(data = details , status= status.HTTP_200_OK) - - -# with this api student can see the list of courses offered to him in upcoming semester -@api_view(['GET']) -def view_offered_courses(request): - try : - obj = Curriculum.objects.filter( - programme = request.data['programme'], - branch = request.data['branch'], - batch = request.data["batch"], - sem = request.data["semester"] - ) - serializer = serializers.CurriculumSerializer(obj, many=True).data - return Response(serializer, status=status.HTTP_200_OK) - except Exception as e: - return Response(data = str(e) , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - # try: - # ug_flag = True - # masters_flag = False - # phd_flag = False - # current_semester = get_user_semester(request.user, ug_flag, masters_flag, phd_flag) - # current_year = date_time.date().year - - # return Response(data= { } , status=status.HTTP_200_OK) - # except Exception as e: - # return Response(data = {"error" : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this student can know status of pre registration and final registration -@api_view(['GET']) -def student_view_registration(request): - try: - # getting the registration status of current user for the given semester - current_user = request.user - student_id = current_user.extrainfo.id - - sem_id = Semester.objects.get(id = request.data.get('semester')) - sem_id = serializers.SemesterSerializer(sem_id).data["id"] - - # filter based on the semester id and student id - obj = StudentRegistrationChecks.objects.filter(semester_id_id = sem_id, student_id = student_id) - - # serialize the data for displaying - serializer = serializers.StudentRegistrationChecksSerializer(obj, many=True).data - - return Response(serializer, status=status.HTTP_200_OK) - except Exception as e: - return Response(data = str(e) , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this student can do his pre registration for the upcoming semester -@api_view(['POST']) -@transaction.atomic -def student_pre_registration(request): - try: - current_user = request.user - current_user_id = serializers.UserSerializer(current_user).data["id"] - s_id = current_user.extrainfo.id - - current_user = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user_id).first() - current_user = serializers.ExtraInfoSerializer(current_user).data - - current_user_instance = Student.objects.all().filter(id=current_user["id"]).first() - current_user = serializers.StudentSerializers(current_user_instance).data - - sem_id_instance = Semester.objects.get(id = request.data.get('semester')) - sem_id = serializers.SemesterSerializer(sem_id_instance).data["id"] - - # filter based on the semester id and student id - obj = StudentRegistrationChecks.objects.filter(semester_id_id = sem_id, student_id = s_id) - # serialize the data for displaying - student_registration_check = serializers.StudentRegistrationChecksSerializer(obj, many=True).data - - try: - # check if user have already done pre registration - if(student_registration_check and student_registration_check[0]["pre_registration_flag"] ): - return Response(data = {"message" : "You have already registered for this semester" }, status=status.HTTP_400_BAD_REQUEST) - except Exception as e: - return Response(data = str(e) , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - course_slots=request.data.get("course_slot") - reg_curr = [] - - - for course_slot in course_slots : - course_priorities = request.data.get("course_priority-"+course_slot) - if(course_priorities[0] == 'NULL'): - print("NULL FOUND") - continue - course_slot_id_for_model = CourseSlot.objects.get(id = int(course_slot)) - - # return Response(data = course_slots , status=status.HTTP_200_OK) - for course_priority in course_priorities: - priority_of_current_course,course_id = map(int,course_priority.split("-")) - # get course id for the model - course_id_for_model = Courses.objects.get(id = course_id) - print("check") - p = InitialRegistration( - course_id = course_id_for_model, - semester_id = sem_id_instance, - student_id = current_user_instance, - course_slot_id = course_slot_id_for_model, - priority = priority_of_current_course - ) - p.save() - reg_curr.append(p) - - - try: - serialized_reg_curr = serializers.InitialRegistrationSerializer(reg_curr, many=True).data - - registration_check = StudentRegistrationChecks( - student_id = current_user_instance, - pre_registration_flag = True, - final_registration_flag = False, - semester_id = sem_id_instance - ) - registration_check.save() - return Response(data={"message": "Successfully Registered for the courses.", "registrations": serialized_reg_curr}, status=status.HTTP_200_OK) - except Exception as e: - return Response(data = {"message" : "Error in Registration." , "error" : str(e)} , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - return Response(data = {"message" : "Error in Registration." , "error" : str(e)} , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this student can do his final registration for the upcoming semester -@api_view(['POST']) -@transaction.atomic -def student_final_registration(request): - try: - current_user = request.user - current_user_id = serializers.UserSerializer(current_user).data["id"] - s_id = current_user.extrainfo.id - - current_user = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - current_user = serializers.ExtraInfoSerializer(current_user).data - - current_user_instance = Student.objects.all().filter(id=current_user["id"]).first() - current_user = serializers.StudentSerializers(current_user_instance).data - - # these details we need from the body of the request fot doing final registration - sem_id_instance = Semester.objects.get(id = request.data.get('semester')) - sem_id = serializers.SemesterSerializer(sem_id_instance).data["id"] - registration_status = StudentRegistrationChecks.objects.filter(student_id = current_user["id"], semester_id = sem_id) - registration_status = serializers.StudentRegistrationChecksSerializer(registration_status , many = True ).data - - if(registration_status[0] and registration_status[0]["pre_registration_flag"] == False): - return Response(data = {"message" : "Student haven't done pre registration yet."} , status= status.HTTP_400_BAD_REQUEST ) - - mode = str(request.data.get('mode')) - transaction_id = str(request.data.get('transaction_id')) - deposit_date = request.data.get('deposit_date') - utr_number = str(request.data.get('utr_number')) - fee_paid = request.data.get('fee_paid') - actual_fee = request.data.get('actual_fee') - reason = str(request.data.get('reason')) - if reason=="": - reason=None - fee_receipt = request.FILES['fee_receipt'] - - print(fee_receipt) - obj = FeePayments( - student_id = current_user_instance, - semester_id = sem_id_instance, - mode = mode, - transaction_id = transaction_id, - fee_receipt = fee_receipt, - deposit_date = deposit_date, - utr_number = utr_number, - fee_paid = fee_paid, - actual_fee = actual_fee, - reason = reason - ) - obj.save() - try: - registration_status = StudentRegistrationChecks.objects.filter(student_id = current_user["id"], semester_id = sem_id).update(final_registration_flag = True) - return Response(data = {"message" : "Final Registration Successfull" } , status= status.HTTP_200_OK) - except Exception as e: - return Response(data = {"message" : "Final Registration Failed " , "error" : str(e)} , status = status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - return Response(data = {"message" : "Final Registration Failed " , "error" : str(e)} , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this api student can get his backlog courses list -@api_view(['GET']) -def student_backlog_courses(request): - try : - stu_id = Student.objects.select_related('id','id__user','id__department').get(id=request.user.username) - backlogCourseList = [] - backlogCourses = backlog_course.objects.select_related('course_id' , 'student_id' , 'semester_id' ).filter(student_id=stu_id) - for i in backlogCourses: - obj = { - "course_id" : i.course_id.id, - "course_name" : i.course_id.course_name, - "faculty" : i.course_id.course_details, - "semester" : i.semester_id.semester_no, - "is_summer_course" : i.is_summer_course - } - backlogCourseList.append(obj) - - return Response(backlogCourseList, status=status.HTTP_200_OK) - except Exception as e: - return Response(data = str(e) , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - - -#--------------------------------------- APIs of acad person---------------------------------------------------------- - - -# with this acad admin can fetch the list of courses for any batch , semester and brach -@api_view(['GET']) -def get_course_list(request): - - programme = request.data['programme'] - branch = request.data['branch'] - batch = request.data['batch'] - - try : - print(programme , branch , batch) - obj = Curriculum.objects.filter( - programme = request.data['programme'], - branch = request.data['branch'], - batch = request.data["batch"] - ) - serializer = serializers.CurriculumSerializer(obj, many=True).data - return Response(serializer, status=status.HTTP_200_OK) - except Exception as e: - return Response(data = str(e) , status=status.HTTP_500_INTERNAL_SERVER_ERROR) - # obj = Curriculum.objects.filter(curriculum_id_=curriculum_id, course_type_ = course_type, programme_ = programme, batch_ = batch, branch_ = branch, sem_ = sem, optional_ = optional) - - -# with this api acad person can see the list of students who have completed their pre and final registrations for any semester -@api_view(['GET']) -def acad_view_reigstrations(request): - try: - semester = request.data["semester"] - sem_id_instance = Semester.objects.get(id = request.data.get('semester')) - sem_id = serializers.SemesterSerializer(sem_id_instance).data["id"] - obj = StudentRegistrationChecks.objects.filter(semester_id_id = sem_id, final_registration_flag =True) - student_registration_check = serializers.StudentRegistrationChecksSerializer(obj, many=True).data - - return Response(data= student_registration_check , status=status.HTTP_200_OK) - except Exception as e: - return Response(data = {"error" : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this api acad person set the date of pre registration date for any semester -@api_view(['POST']) -def configure_pre_registration_date(request): - try: + profile = current_user.extrainfo + if profile.user_type == 'faculty': try: - from_date = request.data.get('from_date') - to_date = request.data.get('to_date') - semester = request.data.get('semester') - current_year = date_time.date().year - desc = "Pre Registration " + str(semester) +" " + str(current_year) - print(from_date , to_date , desc) - from_date = from_date.split('-') - from_date = [int(i) for i in from_date] - from_date = datetime.datetime(*from_date).date() - to_date = to_date.split('-') - to_date = [int(i) for i in to_date] - to_date = datetime.datetime(*to_date).date() - except Exception as e: - from_date="" - to_date="" - desc="" - pass - c = Calendar( - from_date=from_date, - to_date=to_date, - description=desc) - c.save() - return Response(data = {"message" : "Pre registration for semester " + str(semester) + " will be opened from " + str(from_date) + " to " + str(to_date) + ". " , } , status= status.HTTP_200_OK) - except Exception as e: - return Response(data = {"error " : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - -# with this api request acad person can set the date of final registration -@api_view(['POST']) -def configure_final_registration_date(request): - try: - try: - from_date = request.data.get('from_date') - to_date = request.data.get('to_date') - semester = request.data.get('semester') - current_year = date_time.date().year - desc = "Physical Reporting at the Institute" - print(from_date , to_date , desc) - from_date = from_date.split('-') - from_date = [int(i) for i in from_date] - from_date = datetime.datetime(*from_date).date() - to_date = to_date.split('-') - to_date = [int(i) for i in to_date] - to_date = datetime.datetime(*to_date).date() - except Exception as e: - from_date="" - to_date="" - desc="" - pass - c = Calendar( - from_date=from_date, - to_date=to_date, - description=desc) - c.save() - return Response(data = {"message" : "Physical Reporting at the Institute will be opened from " + str(from_date) + " to " + str(to_date) + ". " , } , status= status.HTTP_200_OK) - except Exception as e: - return Response(data = {"error " : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - -# with this api request acad person can add any courses in a specific slot -@api_view(['POST']) -def add_course_to_slot(request): - course_code = request.data.get('course_code') - course_slot_name = request.data.get('course_slot_name') - try: - course_slot = CourseSlot.objects.get(name=course_slot_name) - course = Courses.objects.get(code=course_code) - course_slot.courses.add(course) - - return JsonResponse({'message': f'Course {course_code} added to slot {course_slot_name} successfully.'}, status=200) - except CourseSlot.DoesNotExist: - return JsonResponse({'error': 'Course slot does not exist.'}, status=400) - except Course.DoesNotExist: - return JsonResponse({'error': 'Course does not exist.'}, status=400) - -# with this api request acad person can remove any course from a specific slot -@api_view(['POST']) -def remove_course_from_slot(request): - course_code = request.data.get('course_code') - course_slot_name = request.data.get('course_slot_name') - try: - course_slot = CourseSlot.objects.get(name=course_slot_name) - course = Courses.objects.get(code=course_code) - course_slot.courses.remove(course) - return JsonResponse({'message': f'Course {course_code} removed from slot {course_slot_name} successfully.'}, status=200) - except CourseSlot.DoesNotExist: - return JsonResponse({'error': 'Course slot does not exist.'}, status=400) - except Course.DoesNotExist: - return JsonResponse({'error': 'Course does not exist.'}, status=400) - - - -#--------------------------------------- APIs of faculty---------------------------------------------------------- - -# with this api faculty can know what are the courses assigned to him -@api_view(['GET']) -def faculty_assigned_courses(request): - try: - current_user = request.user - curriculum_ids = Curriculum_Instructor.objects.filter(instructor_id=current_user.id).values_list('curriculum_id', flat=True) - course_infos = [] - print(current_user.id) - for curriculum_id in curriculum_ids: - course_info = Curriculum.objects.filter(curriculum_id=curriculum_id).values_list('course_code','course_type','programme','branch','sem','course_id_id').first() - course_infos.append(course_info) - - return Response(data= course_infos , status=status.HTTP_200_OK) - except Exception as e: - return Response(data = {"error" : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - -@api_view(['POST']) -def get_next_sem_courses(request): - try: - next_sem = request.data.get('next_sem') - branch = request.data.get('branch') - programme = request.data.get('programme') - batch = request.data.get('batch') - - # we go to student table and apply filters and get batch_id of the students with these filter - batch_id = Student.objects.filter(programme = programme , batch = batch , specialization = branch)[0].batch_id - - curr_id = batch_id.curriculum - next_sem_id = Semester.objects.get(curriculum = curr_id, semester_no = next_sem) - - if next_sem_id: - next_sem_registration_courses = get_detailed_sem_courses(next_sem_id ) - return JsonResponse(next_sem_registration_courses, safe=False) - except Exception as e: - return Response(data = {"error" : str(e)} , status= status.HTTP_500_INTERNAL_SERVER_ERROR) - - - - - - - - - - - -# These apis were implemented before but now don't use them they have some errors - - -# @api_view(['GET']) -# def academic_procedures_faculty(request): -# current_user = request.user -# user_details = current_user.extrainfo -# des = current_user.holds_designations.all().first() - -# if str(des.designation) == 'student': -# return Response({'error':'Not a faculty'}, status=status.HTTP_400_BAD_REQUEST) -# elif str(current_user) == 'acadadmin': -# return Response({'error':'User is acadadmin'}, status=status.HTTP_400_BAD_REQUEST) - -# elif str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor": -# faculty_object = user_details.faculty -# month = int(date_time.month) -# sem = [] -# if month>=7 and month<=12: -# sem = [1,3,5,7] -# else: -# sem = [2,4,6,8] -# student_flag = False -# fac_flag = True - -# thesis_supervision_request_list = faculty_object.thesistopicprocess_supervisor.all() -# thesis_supervision_request_list_data = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list, many=True).data -# approved_thesis_request_list = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list.filter(approval_supervisor = True), many=True).data -# pending_thesis_request_list = serializers.ThesisTopicProcessSerializer(thesis_supervision_request_list.filter(pending_supervisor = True), many=True).data -# courses_list = serializers.CurriculumInstructorSerializer(user_details.curriculum_instructor_set.all(), many=True).data -# fac_details = serializers.UserSerializer(current_user).data - -# resp = { -# 'student_flag' : student_flag, -# 'fac_flag' : fac_flag, -# 'thesis_supervision_request_list' : thesis_supervision_request_list_data, -# 'pending_thesis_request_list' : pending_thesis_request_list, -# 'approved_thesis_request_list' : approved_thesis_request_list, -# 'courses_list': courses_list, -# 'faculty': fac_details -# } -# return Response(data=resp, status=status.HTTP_200_OK) - - - - - - -# @api_view(['GET']) -# def academic_procedures_student(request): -# current_user = request.user -# current_user_data = { -# 'first_name': current_user.first_name, -# 'last_name': current_user.last_name, -# 'username': current_user.username, -# 'email': current_user.email -# } -# user_details = current_user.extrainfo -# des = current_user.holds_designations.all().first() -# if str(des.designation) == 'student': -# obj = user_details.student - -# if obj.programme.upper() == "PH.D": -# student_flag = True -# ug_flag = False -# masters_flag = False -# phd_flag = True -# fac_flag = False -# des_flag = False - -# elif obj.programme.upper() == "M.DES": -# student_flag = True -# ug_flag = False -# masters_flag = True -# phd_flag = False -# fac_flag = False -# des_flag = True - -# elif obj.programme.upper() == "B.DES": -# student_flag = True -# ug_flag = True -# masters_flag = False -# phd_flag = False -# fac_flag = False -# des_flag = True - -# elif obj.programme.upper() == "M.TECH": -# student_flag = True -# ug_flag = False -# masters_flag = True -# phd_flag = False -# fac_flag = False -# des_flag = False - -# elif obj.programme.upper() == "B.TECH": -# student_flag = True -# ug_flag = True -# masters_flag = False -# phd_flag = False -# fac_flag = False -# des_flag = False - -# else: -# return Response({'message':'Student has no record'}, status=status.HTTP_400_BAD_REQUEST) - -# current_date = date_time.date() -# current_year = date_time.year -# batch = obj.batch_id -# user_sem = get_user_semester(request.user, ug_flag, masters_flag, phd_flag) -# acad_year = get_acad_year(user_sem, current_year) -# user_branch = user_details.department.name -# cpi = obj.cpi -# cur_spi='Sem results not available' # To be fetched from db if result uploaded - -# details = { -# 'current_user': current_user_data, -# 'year': acad_year, -# 'user_sem': user_sem, -# 'user_branch' : str(user_branch), -# 'cpi' : cpi, -# 'spi' : cur_spi -# } - -# currently_registered_courses = get_currently_registered_courses(user_details.id, user_sem) -# currently_registered_courses_data = serializers.CurriculumSerializer(currently_registered_courses, many=True).data -# try: -# pre_registered_courses = obj.initialregistrations_set.all().filter(semester = user_sem) -# pre_registered_courses_show = obj.initialregistrations_set.all().filter(semester = user_sem+1) -# except: -# pre_registered_courses = None -# pre_registered_courses_show=None -# try: -# final_registered_courses = obj.finalregistrations_set.all().filter(semester = user_sem) -# except: -# final_registered_courses = None - -# pre_registered_courses_data = serializers.InitialRegistrationsSerializer(pre_registered_courses, many=True).data -# pre_registered_courses_show_data = serializers.InitialRegistrationsSerializer(pre_registered_courses_show, many=True).data -# final_registered_courses_data = serializers.FinalRegistrationsSerializer(final_registered_courses, many=True).data - -# current_credits = get_current_credits(currently_registered_courses) -# print(current_user, user_sem+1, user_branch) -# try: -# next_sem_branch_courses = get_branch_courses(current_user, user_sem+1, user_branch) -# except Exception as e: -# return Response(data = str(e)) -# next_sem_branch_courses_data = serializers.CurriculumSerializer(next_sem_branch_courses, many=True).data - -# fee_payment_mode_list = dict(Constants.PaymentMode) - -# next_sem_branch_registration_courses = get_registration_courses(next_sem_branch_courses) -# next_sem_branch_registration_courses_data = [] -# for choices in next_sem_branch_registration_courses: -# next_sem_branch_registration_courses_data.append(serializers.CurriculumSerializer(choices, many=True).data) -# # next_sem_branch_registration_courses_data = serializers.CurriculumSerializer(next_sem_branch_registration_courses, many=True).data - -# final_registration_choices = get_registration_courses(get_branch_courses(request.user, user_sem, user_branch)) -# final_registration_choices_data = [] -# for choices in final_registration_choices: -# final_registration_choices_data.append(serializers.CurriculumSerializer(choices, many=True).data) - -# performance_list = [] -# result_announced = False -# for i in currently_registered_courses: -# try: -# performance_obj = obj.semestermarks_set.all().filter(curr_id = i).first() -# except: -# performance_obj = None -# performance_list.append(performance_obj) -# performance_list_data = serializers.SemesterMarksSerializer(performance_list, many=True).data - -# thesis_request_list = serializers.ThesisTopicProcessSerializer(obj.thesistopicprocess_set.all(), many=True).data - -# pre_existing_thesis_flag = True if obj.thesistopicprocess_set.all() else False - -# current_sem_branch_courses = get_branch_courses(current_user, user_sem, user_branch) - -# # pre_registration_date_flag = get_pre_registration_eligibility(current_date) -# final_registration_date_flag = get_final_registration_eligibility(current_date) - -# add_or_drop_course_date_flag = get_add_or_drop_course_date_eligibility(current_date) - -# student_registration_check_pre = obj.studentregistrationcheck_set.all().filter(semester=user_sem+1) -# student_registration_check_final = obj.studentregistrationcheck_set.all().filter(semester=user_sem) -# pre_registration_flag = False -# final_registration_flag = False -# if(student_registration_check_pre): -# pre_registration_flag = student_registration_check_pre.pre_registration_flag -# if(student_registration_check_final): -# final_registration_flag = student_registration_check_final.final_registration_flag - -# teaching_credit_registration_course = None -# if phd_flag: -# teaching_credit_registration_course = Curriculum.objects.all().filter(batch = 2016, sem =6) -# teaching_credit_registration_course_data = serializers.CurriculumSerializer(teaching_credit_registration_course, many=True).data - -# if student_flag: -# try: -# due = obj.dues_set.get() -# lib_d = due.library_due -# pc_d = due.placement_cell_due -# hos_d = due.hostel_due -# mess_d = due.mess_due -# acad_d = due.academic_due -# except: -# lib_d, pc_d, hos_d, mess_d, acad_d = 0, 0, 0, 0, 0 - -# tot_d = lib_d + acad_d + pc_d + hos_d + mess_d - -# registers = obj.register_set.all() -# course_list = [] -# for i in registers: -# course_list.append(i.curr_id) -# attendence = [] -# for i in course_list: -# instructors = i.curriculum_instructor_set.all() -# pr,ab=0,0 -# for j in list(instructors): - -# presents = obj.student_attendance_set.all().filter(instructor_id=j, present=True) -# absents = obj.student_attendance_set.all().filter(instructor_id=j, present=False) -# pr += len(presents) -# ab += len(absents) -# attendence.append((i,pr,pr+ab)) -# attendance_data = {} -# for course in attendence: -# attendance_data[course[0].course_id.course_name] = { -# 'present' : course[1], -# 'total' : course[2] -# } - -# branchchange_flag = False -# if user_sem == 2: -# branchchange_flag=True - -# faculty_list = serializers.HoldsDesignationSerializer(get_faculty_list(), many=True).data - -# resp = { -# 'details': details, -# 'currently_registered': currently_registered_courses_data, -# # 'pre_registered_courses' : pre_registered_courses_data, -# # 'pre_registered_courses_show' : pre_registered_courses_show_data, -# 'final_registered_courses' : final_registered_courses_data, -# 'current_credits' : current_credits, -# 'courses_list': next_sem_branch_courses_data, -# 'fee_payment_mode_list' : fee_payment_mode_list, -# 'next_sem_branch_registration_courses' : next_sem_branch_registration_courses_data, -# 'final_registration_choices' : final_registration_choices_data, -# 'performance_list' : performance_list_data, -# 'thesis_request_list' : thesis_request_list, -# 'student_flag' : student_flag, -# 'ug_flag' : ug_flag, -# 'masters_flag' : masters_flag, -# 'phd_flag' : phd_flag, -# 'fac_flag' : fac_flag, -# 'des_flag' : des_flag, -# 'thesis_flag' : pre_existing_thesis_flag, -# 'drop_courses_options' : currently_registered_courses_data, -# # 'pre_registration_date_flag': pre_registration_date_flag, -# 'final_registration_date_flag': final_registration_date_flag, -# 'add_or_drop_course_date_flag': add_or_drop_course_date_flag, -# # 'pre_registration_flag' : pre_registration_flag, -# 'final_registration_flag': final_registration_flag, -# 'teaching_credit_registration_course' : teaching_credit_registration_course_data, -# 'lib_d':lib_d, -# 'acad_d':acad_d, -# 'mess_d':mess_d, -# 'pc_d':pc_d, -# 'hos_d':hos_d, -# 'tot_d':tot_d, -# 'attendance': attendance_data, -# 'Branch_Change_Flag':branchchange_flag -# # 'faculty_list' : faculty_list -# } -# return Response(data=resp, status=status.HTTP_200_OK) - - - - - - - - - - - - - - - - - - - - - - -# These apis are not needed in this module - - - -# @api_view(['POST']) -# def add_thesis(request): -# current_user = request.user -# profile = current_user.extrainfo -# if profile.user_type == 'student': -# if not 'thesis_topic' in request.data: -# return Response({'error':'Thesis topic is required'}, status=status.HTTP_400_BAD_REQUEST) -# if not 'research_area' in request.data: -# return Response({'error':'Research area is required'}, status=status.HTTP_400_BAD_REQUEST) -# if 'supervisor_id' in request.data: -# try: -# supervisor_faculty = User.objects.get(username=request.data['supervisor_id']) -# supervisor_faculty = supervisor_faculty.extrainfo -# request.data['supervisor_id'] = supervisor_faculty -# except: -# return Response({'error':'Wrong supervisor id. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) -# else: -# return Response({'error':'supervisor id is required'}, status=status.HTTP_400_BAD_REQUEST) -# if 'co_supervisor_id' in request.data: -# try: -# co_supervisor_faculty = User.objects.get(username=request.data['co_supervisor_id']) -# co_supervisor_faculty = co_supervisor_faculty.extrainfo -# request.data['co_supervisor_id'] = co_supervisor_faculty -# except: -# return Response({'error':'Wrong co_supervisor id. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) -# else: -# co_supervisor_faculty = None -# if 'curr_id' in request.data: -# curr_id = None -# student = profile.student -# request.data['student_id'] = profile -# request.data['submission_by_student'] = True -# serializer = serializers.ThesisTopicProcessSerializer(data=request.data) -# if serializer.is_valid(): -# serializer.save() -# return Response(serializer.data, status=status.HTTP_200_OK) -# else: -# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -# else: -# return Response({'error':'Cannot add thesis'}, status=status.HTTP_400_BAD_REQUEST) - - - - - - - - - - - - - - - - - -# @api_view(['PUT']) -# def approve_thesis(request, id): -# current_user = request.user -# profile = current_user.extrainfo -# if profile.user_type == 'faculty': -# try: -# thesis = ThesisTopicProcess.objects.get(id=id) -# except: -# return Response({'error':'This thesis does not exist'}, status=status.HTTP_400_BAD_REQUEST) -# if 'member1' in request.data: -# try: -# user1 = User.objects.get(username=request.data['member1']) -# member1 = user1.extrainfo -# request.data['member1'] = member1 -# except: -# return Response({'error':'Wrong username of member 1. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) -# else: -# return Response({'error':'Member 1 is required'}, status=status.HTTP_400_BAD_REQUEST) -# if 'member2' in request.data: -# try: -# user2 = User.objects.get(username=request.data['member2']) -# member2 = user2.extrainfo -# request.data['member2'] = member2 -# except: -# return Response({'error':'Wrong username of member 2. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) -# else: -# return Response({'error':'Member 2 is required'}, status=status.HTTP_400_BAD_REQUEST) -# if 'member3' in request.data: -# try: -# user3 = User.objects.get(username=request.data['member3']) -# member3 = user3.extrainfo -# request.data['member3'] = member3 -# except: -# return Response({'error':'Wrong username of member 3. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) -# else: -# member3 = None -# if not 'approval' in request.data: -# return Response({'error':'Approval value is required.'}, status=status.HTTP_400_BAD_REQUEST) -# elif request.data['approval'] != 'yes' and request.data['approval'] != 'no': -# return Response({'error':'Wrong approval value provided. Approval value should be yes or no'}, status=status.HTTP_400_BAD_REQUEST) -# if request.data['approval'] == 'yes': -# request.data.pop('approval', None) -# request.data['pending_supervisor'] = False -# request.data['approval_supervisor'] = True -# request.data['forwarded_to_hod'] = True -# request.data['pending_hod'] = True -# else: -# request.data.pop('approval', None) -# request.data['pending_supervisor'] = False -# request.data['approval_supervisor'] = False -# request.data['forwarded_to_hod'] = False -# request.data['pending_hod'] = False -# serializer = serializers.ThesisTopicProcessSerializer(thesis, data=request.data, partial=True) -# if serializer.is_valid(): -# serializer.save() -# return Response(serializer.data, status=status.HTTP_200_OK) -# else: -# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -# else: -# return Response({'error':'Cannot approve thesis'}, status=status.HTTP_400_BAD_REQUEST) \ No newline at end of file + thesis = ThesisTopicProcess.objects.get(id=id) + except: + return Response({'error':'This thesis does not exist'}, status=status.HTTP_400_BAD_REQUEST) + if 'member1' in request.data: + try: + user1 = User.objects.get(username=request.data['member1']) + member1 = user1.extrainfo + request.data['member1'] = member1 + except: + return Response({'error':'Wrong username of member 1. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) + else: + return Response({'error':'Member 1 is required'}, status=status.HTTP_400_BAD_REQUEST) + if 'member2' in request.data: + try: + user2 = User.objects.get(username=request.data['member2']) + member2 = user2.extrainfo + request.data['member2'] = member2 + except: + return Response({'error':'Wrong username of member 2. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) + else: + return Response({'error':'Member 2 is required'}, status=status.HTTP_400_BAD_REQUEST) + if 'member3' in request.data: + try: + user3 = User.objects.get(username=request.data['member3']) + member3 = user3.extrainfo + request.data['member3'] = member3 + except: + return Response({'error':'Wrong username of member 3. User does not exist.'}, status=status.HTTP_400_BAD_REQUEST) + else: + member3 = None + if not 'approval' in request.data: + return Response({'error':'Approval value is required.'}, status=status.HTTP_400_BAD_REQUEST) + elif request.data['approval'] != 'yes' and request.data['approval'] != 'no': + return Response({'error':'Wrong approval value provided. Approval value should be yes or no'}, status=status.HTTP_400_BAD_REQUEST) + if request.data['approval'] == 'yes': + request.data.pop('approval', None) + request.data['pending_supervisor'] = False + request.data['approval_supervisor'] = True + request.data['forwarded_to_hod'] = True + request.data['pending_hod'] = True + else: + request.data.pop('approval', None) + request.data['pending_supervisor'] = False + request.data['approval_supervisor'] = False + request.data['forwarded_to_hod'] = False + request.data['pending_hod'] = False + serializer = serializers.ThesisTopicProcessSerializer(thesis, data=request.data, partial=True) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + else: + return Response({'error':'Cannot approve thesis'}, status=status.HTTP_400_BAD_REQUEST) diff --git a/FusionIIIT/applications/academic_procedures/migrations/0001_initial.py b/FusionIIIT/applications/academic_procedures/migrations/0001_initial.py index 42142593d..b873390df 100644 --- a/FusionIIIT/applications/academic_procedures/migrations/0001_initial.py +++ b/FusionIIIT/applications/academic_procedures/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models @@ -11,9 +11,9 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('globals', '0001_initial'), ('academic_information', '0001_initial'), ('programme_curriculum', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ @@ -188,7 +188,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('month', models.CharField(choices=[('Jan', 'January'), ('Feb', 'Febuary'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')], max_length=10)), - ('year', models.IntegerField(choices=[(2024, 2024), (2023, 2023)])), + ('year', models.IntegerField(choices=[(2023, 2023), (2022, 2022)])), ('description', models.CharField(choices=[('Stu_paid', 'Paid'), ('Stu_due', 'Due')], max_length=15)), ('amount', models.IntegerField()), ('remaining_amount', models.IntegerField()), @@ -243,7 +243,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('semester', models.IntegerField()), - ('batch', models.IntegerField(default=2024)), + ('batch', models.IntegerField(default=2023)), ('verified', models.BooleanField(default=False)), ('curr_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.curriculum')), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), @@ -334,7 +334,7 @@ class Migration(migrations.Migration): name='course_registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('working_year', models.IntegerField(blank=True, choices=[(2024, 2024), (2023, 2023)], null=True)), + ('working_year', models.IntegerField(blank=True, choices=[(2023, 2023), (2022, 2022)], null=True)), ('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='programme_curriculum.course')), ('course_slot_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='programme_curriculum.courseslot')), ('semester_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='programme_curriculum.semester')), @@ -374,7 +374,7 @@ class Migration(migrations.Migration): ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(auto_now_add=True)), ('month', models.CharField(choices=[('Jan', 'January'), ('Feb', 'Febuary'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')], max_length=10)), - ('year', models.IntegerField(choices=[(2024, 2024), (2023, 2023)])), + ('year', models.IntegerField(choices=[(2023, 2023), (2022, 2022)])), ('bank_account', models.CharField(max_length=11)), ('applicability', models.CharField(choices=[('GATE', 'GATE'), ('NET', 'NET'), ('CEED', 'CEED')], max_length=5)), ('ta_supervisor_remark', models.BooleanField(default=False)), @@ -392,7 +392,7 @@ class Migration(migrations.Migration): name='Register', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('year', models.IntegerField(default=2024)), + ('year', models.IntegerField(default=2023)), ('semester', models.IntegerField()), ('curr_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.curriculum')), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), @@ -402,4 +402,4 @@ class Migration(migrations.Migration): 'unique_together': {('curr_id', 'student_id')}, }, ), - ] \ No newline at end of file + ] diff --git a/FusionIIIT/applications/academic_procedures/migrations/0002_auto_20240420_1925.py b/FusionIIIT/applications/academic_procedures/migrations/0002_auto_20240420_1925.py new file mode 100644 index 000000000..83f511d5f --- /dev/null +++ b/FusionIIIT/applications/academic_procedures/migrations/0002_auto_20240420_1925.py @@ -0,0 +1,38 @@ +# Generated by Django 3.1.5 on 2024-04-20 19:25 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('academic_procedures', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='assistantshipclaim', + name='year', + field=models.IntegerField(choices=[(2024, 2024), (2023, 2023)]), + ), + migrations.AlterField( + model_name='course_registration', + name='working_year', + field=models.IntegerField(blank=True, choices=[(2024, 2024), (2023, 2023)], null=True), + ), + migrations.AlterField( + model_name='finalregistrations', + name='batch', + field=models.IntegerField(default=2024), + ), + migrations.AlterField( + model_name='messdue', + name='year', + field=models.IntegerField(choices=[(2024, 2024), (2023, 2023)]), + ), + migrations.AlterField( + model_name='register', + name='year', + field=models.IntegerField(default=2024), + ), + ] diff --git a/FusionIIIT/applications/academic_procedures/models.py b/FusionIIIT/applications/academic_procedures/models.py index 6a3d5dcc7..ffb18cda0 100644 --- a/FusionIIIT/applications/academic_procedures/models.py +++ b/FusionIIIT/applications/academic_procedures/models.py @@ -568,6 +568,8 @@ class StudentRegistrationChecks(models.Model): final_registration_flag(boolean) - to denote whether the final registration is complete semester_id(programme_curriculum.Semester) - reference to the semester for which the registration will be considered + + ''' @@ -619,6 +621,9 @@ class FinalRegistration(models.Model): verified(Boolean) - denotes whether the registration is verified by academic department and complete course_slot_id(programme_curriculum.CourseSlot) - details about under which course slot the course is offered(Optional/Core other details) + + + ''' @@ -669,12 +674,16 @@ class course_registration(models.Model): ''' Current Purpose : stores information regarding the process of registration of a student for a course + ATTRIBUTES course_id(programme_curriculum.Course) - reference to the course details for which the registration is being done semester_id(programme_curriculum.Semester) - reference to the semester for which the course registration is done student_id(academic_information.Student) - reference to the student course_slot_id(programme_curriculum.CourseSlot) - details about under which course slot the course is offered(Optional/Core other details) + + + ''' @@ -689,19 +698,3 @@ def __str__(self): return self.semester_id class Meta: db_table = 'course_registration' - - -class backlog_course(models.Model): - ''' - Current Purpose : stores information regarding the backlog courses of a student (purpose is unclear and is open to interpretations) - - ATTRIBUTES - course_id(programme_curriculum.Course) - reference to the course details for which the registration is being done - semester_id(programme_curriculum.Semester) - reference to the semester for which the course registration is done - student_id(academic_information.Student) - reference to the student - is_summer_course(Boolean) - details about whether this course is available as summer_course or not - ''' - student_id = models.ForeignKey(Student, on_delete=models.CASCADE) - semester_id = models.ForeignKey(Semester, on_delete=models.CASCADE) - course_id = models.ForeignKey(Course, on_delete=models.CASCADE) - is_summer_course = models.BooleanField(default= False) \ No newline at end of file diff --git a/FusionIIIT/applications/academic_procedures/tests.py b/FusionIIIT/applications/academic_procedures/tests.py index 2c9e754ad..e9137c85e 100644 --- a/FusionIIIT/applications/academic_procedures/tests.py +++ b/FusionIIIT/applications/academic_procedures/tests.py @@ -1,4 +1,3 @@ # from django.test import TestCase # Create your tests here. - diff --git a/FusionIIIT/applications/academic_procedures/urls.py b/FusionIIIT/applications/academic_procedures/urls.py index e11bdcd7d..21d546e00 100644 --- a/FusionIIIT/applications/academic_procedures/urls.py +++ b/FusionIIIT/applications/academic_procedures/urls.py @@ -1,4 +1,5 @@ from django.conf.urls import url, include + from . import views appname = 'procedures' urlpatterns = [ @@ -6,23 +7,19 @@ url(r'^main/', views.academic_procedures, name='procedures'), url(r'^register/', views.register, name='register'), url(r'^pre_registration/', views.pre_registration, name='pre_register'), - url(r'^auto_pre_registration/', views.auto_pre_registration, name='automatic_pre_register'), - url(r'^final_registration/', views.final_registration, name='final_register'), url(r'^addCourse/', views.add_courses, name='addCourse'), - url(r'^add_one_course/' , views.add_one_course , name = 'add_one_course'), url(r'^drop_course/', views.drop_course, name='drop_course'), - url(r'^replaceCourse/', views.replace_courses, name='replace_courses'), - url(r'^replace_one_course/', views.replace_one_course, name='replace_one_course'), url(r'^branch-change/', views.approve_branch_change, name='branch_change'), url(r'^brach-change-request/', views.branch_change_request, name='branch_change_request'), - url(r'^acad_person/verifyCourse/drop/$',views.dropcourseadmin, name='dropcourseadmin'), url(r'^acad_person/verifyCourse/', views.verify_course, name='verifyCourse'), url(r'^acad_person/addCourse/', views.acad_add_course, name="acad_add_course"), url(r'^acad_person/student_list$', views.student_list, name='studentlist'), url(r'^acad_person/course_list$', views.course_list, name='courseList'), url(r'^acad_person/$', views.acad_person, name='acad_person'), + url(r'^acad_person/verifyCourse/drop/$', + views.dropcourseadmin, name='dropcourseadmin'), url(r'^branch-validate', views.approve_branch_change, name='branch_validate'), url(r'^acad_person/branch_change/$', views.acad_branch_change, name='acad_branch_change'), @@ -31,7 +28,6 @@ url(r'^account/$', views.account), url(r'^addThesis/$', views.add_thesis, name='add_thesis'), url(r'^process_verification_request/$', views.process_verification_request), - url(r'^auto_process_verification_request/$', views.auto_process_verification_request), url(r'^teaching_credit/$', views.teaching_credit_register), url(r'^course_marks_data/$', views.course_marks_data), # -- url(r'^submit_marks/$', views.submit_marks), # -- @@ -45,10 +41,7 @@ url(r'^test/$', views.test), url(r'^bonafide_pdf/$', views.Bonafide_form), url(r'^test_ret/$', views.test_ret), - url(r'^api/', include('applications.academic_procedures.api.urls')), - - url(r'^faculty_data/$', views.facultyData, name='faculty_data'), url(r'^ACF/$', views.ACF, name='ACF'), url(r'^MTSGF/$', views.MTSGF), @@ -58,19 +51,12 @@ url(r'^update_phdform/$', views.update_phdform), url(r'^update_dues/$', views.update_dues), url(r'^dues_pdf/$', views.dues_pdf), - url(r'^acad_person/gen_course_list$', views.gen_course_list, name='gen_course_list'), + url(r'^acad_person/gen_course_list$', + views.gen_course_list, name='gen_course_list'), url(r'^update_acad_assistantship/$', views.update_acad_assis), url(r'^update_account_assistantship/$', views.update_account_assistantship), url(r'^update_hod_assistantship/$', views.update_hod_assistantship), url(r'^mdue/$', views.mdue), url(r'^assis_stat/$', views.assis_stat), - url(r'^acad_person/allot_courses/' , views.allot_courses, name='allot_courses'), - - url(r'^acad_person/get_next_sem_courses/' , views.get_next_sem_courses , name = 'get_next_sem_courses'), - - url(r'^acad_person/remove_course_from_slot/' , views.remove_course_from_slot , name = 'remove_course_from_slot'), - url(r'^acad_person/add_course_to_slot/' , views.add_course_to_slot , name = 'add_course_to_slot'), - url(r'^acad_person/replaceSwayam/', views.replaceSwayam, name='replaceSwayam'), - url(r'^acad_person/swayam_replace/', views.swayam_replace, name='swayam_replace'), - url(r'^register_backlog_course/' , views.register_backlog_course , name = 'register_backlog_course') + url(r'^acad_person/allot_courses/' , views.allot_courses, name='allot_courses') ] diff --git a/FusionIIIT/applications/academic_procedures/views.py b/FusionIIIT/applications/academic_procedures/views.py index 416992134..7e55e3e45 100644 --- a/FusionIIIT/applications/academic_procedures/views.py +++ b/FusionIIIT/applications/academic_procedures/views.py @@ -11,7 +11,6 @@ import logging from django.db import transaction from django.contrib import messages -from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.db.models import Max,Value,IntegerField,CharField,F,Sum @@ -30,21 +29,16 @@ from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester , CourseInstructor) from applications.globals.models import (DepartmentInfo, Designation, ExtraInfo, Faculty, HoldsDesignation) -from applications.programme_curriculum.models import Course as Courses + from .models import (BranchChange, CoursesMtech, InitialRegistration, StudentRegistrationChecks, Register, Thesis, FinalRegistration, ThesisTopicProcess, Constants, FeePayments, TeachingCreditRegistration, SemesterMarks, MarkSubmissionCheck, Dues,AssistantshipClaim, MTechGraduateSeminarReport, - PhDProgressExamination,CourseRequested, course_registration, MessDue, Assistantship_status , backlog_course) + PhDProgressExamination,CourseRequested, course_registration, MessDue, Assistantship_status) from notification.views import academics_module_notif from .forms import BranchChangeForm from django.db.models.functions import Concat,ExtractYear,ExtractMonth,ExtractDay,Cast -from .api import serializers -from django.core.serializers import serialize - -"""every newfuncitons that have been created with name auto_ in start of their original name is to implement new logic of registraion .. -unlike the previous registration logic that was done with priority """ demo_date = timezone.now() @@ -59,7 +53,12 @@ available_ece_seats = 100 available_me_seats = 100 +# assistantship_status = Assistantship_status.objects.all() +# for obj in assistantship_status: +# student_status = obj.student_status +# hod_status = obj.hod_status +# account_status = obj.account_status @login_required(login_url='/accounts/login') @@ -76,17 +75,17 @@ def main(request): def academic_procedures(request): current_user = get_object_or_404(User, username=request.user.username) - + #extra info details , user id used as main id user_details = ExtraInfo.objects.select_related('user','department').get(user = request.user) - # des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() + des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session.get('currentDesignationSelected') == "student": + if str(des.designation) == "student": obj = Student.objects.select_related('id','id__user','id__department').get(id = user_details.id) return HttpResponseRedirect('/academic-procedures/stu/') # return HttpResponseRedirect('/logout/') - elif request.session.get('currentDesignationSelected') == "faculty" or request.session.get('currentDesignationSelected') == "Associate Professor" or request.session.get('currentDesignationSelected') == "Professor" or request.session.get('currentDesignationSelected') == "Assistant Professor" : + elif str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/academic-procedures/fac/') # return HttpResponseRedirect('/logout/') @@ -107,7 +106,7 @@ def academic_procedures(request): }) else: - return HttpResponseRedirect('/dashboard/') + return HttpResponse('person not found') # # # @@ -118,20 +117,19 @@ def academic_procedures(request): def academic_procedures_faculty(request): current_user = get_object_or_404(User, username=request.user.username) - if request.user.extrainfo.user_type != 'faculty': - return HttpResponseRedirect('/dashboard/') + #extra info details , user id used as main id user_details = ExtraInfo.objects.select_related('user','department').get(user = request.user) des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() fac_id = user_details fac_name = user_details.user.first_name + " " + user_details.user.last_name - # if str(des.designation) == "student": - # return HttpResponseRedirect('/academic-procedures/main/') + if str(des.designation) == "student": + return HttpResponseRedirect('/academic-procedures/main/') - # elif str(request.user) == "acadadmin": - # return HttpResponseRedirect('/academic-procedures/main/') - notifs = request.user.notifications.all() - if request.session.get('currentDesignationSelected') == "faculty" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor": + elif str(request.user) == "acadadmin": + return HttpResponseRedirect('/academic-procedures/main/') + + elif str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor": object_faculty = Faculty.objects.select_related('id','id__user','id__department').get(id = user_details.pk) @@ -160,15 +158,6 @@ def academic_procedures_faculty(request): mtechseminar_request_list = MTechGraduateSeminarReport.objects.all().filter(Overall_grade = '') phdprogress_request_list = PhDProgressExamination.objects.all().filter(Overall_grade = '') courses_list = list(CourseInstructor.objects.select_related('course_id', 'batch_id', 'batch_id__discipline').filter(instructor_id__id=fac_id.id).only('course_id__code', 'course_id__name', 'batch_id')) - - assigned_courses = CourseInstructor.objects.select_related('course_id', 'batch_id', 'batch_id__discipline').filter( - instructor_id__id=fac_id.id, # Filter by faculty ID - batch_id__running_batch=True, # Filter by currently running batches - course_id__working_course=True # Filter by currently active courses - ).only('course_id__code', 'course_id__name', 'batch_id') - assigned_courses = list(assigned_courses) - - # print('------------------------------------------------------------------------------------------------------------------' , list(assigned_courses)) r = range(4) return render( request, @@ -192,8 +181,6 @@ def academic_procedures_faculty(request): 'mtechseminar_request_list' : mtechseminar_request_list, 'phdprogress_request_list' : phdprogress_request_list, 'r' : r, - 'assigned_courses' : assigned_courses, - 'notifications': notifs, }) else: HttpResponse("user not found") @@ -218,13 +205,11 @@ def account(request): def academic_procedures_student(request): current_user = get_object_or_404(User, username=request.user.username) - # if global_var != "student": - # return HttpResponse("Student has no record") + user_details = ExtraInfo.objects.select_related('user','department').get(id = request.user) des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() if str(des.designation) == "student": - notifs = request.user.notifications.all() obj = Student.objects.select_related('id','id__user','id__department').get(id = user_details.id) if obj.programme.upper() == "PHD" : @@ -356,23 +341,17 @@ def academic_procedures_student(request): currently_registered_course = get_currently_registered_course(obj,obj.curr_semester_no) current_credits = get_current_credits(currently_registered_course) - + cur_cpi=0.0 details = { 'current_user': current_user, 'year': acad_year, - 'user_sem': user_sem - 1, + 'user_sem': user_sem, 'user_branch' : str(user_branch), 'cpi' : cpi, } cur_cpi=details['cpi'] - swayam_courses_count = 0 - next_sem_student = user_sem + 1 - if(next_sem_student > 2): - swayam_courses_count = 2 - if(next_sem_student == 6 or next_sem_student == 7 or next_sem_student == 8): - swayam_courses_count = 3 try: pre_registered_courses = InitialRegistration.objects.all().filter(student_id = user_details.id,semester_id = next_sem_id) @@ -395,14 +374,13 @@ def academic_procedures_student(request): for final_registered_course in final_registered_courses: final_registered_course_show.append({"course_code":final_registered_course.course_id.code,"course_name":final_registered_course.course_id.name,"course_credit":final_registered_course.course_id.credit}) add_courses_options = get_add_course_options(current_sem_branch_course, currently_registered_course, batch.year) - drop_courses_options = get_drop_course_options(currently_registered_course) - replace_courses_options = get_replace_course_options(currently_registered_course, batch.year) + #drop_courses_options = get_drop_course_options(currently_registered_course) + except Exception as e: final_registered_courses = None final_registered_course_show = None - # drop_courses_options = None + #drop_courses_options = None add_courses_options = None - replace_courses_options = None fee_payment_mode_list = dict(Constants.PaymentMode) @@ -477,24 +455,10 @@ def academic_procedures_student(request): attendence.append((i,pr,pr+ab)) cur_spi='Sem results not available' # To be fetched from db if result uploaded - backlogCourseList = [] - auto_backlog_courses = list(SemesterMarks.objects.filter(student_id = obj , grade = 'F')) - auto_backlog_courses_list = [] - for i in auto_backlog_courses: - if not i.curr_id.courseslots.filter(type__contains="Optional").exists(): - auto_backlog_courses_list.append([i.curr_id.name, i.curr_id.code, i.curr_id.version, i.curr_id.credit , i.grade]) - - backlogCourses = backlog_course.objects.select_related('course_id' , 'student_id' , 'semester_id' ).filter(student_id=obj) - for i in backlogCourses: - summer_course = "Yes" if i.is_summer_course else "No" - course_details = i.course_id.course_details if i.course_id.course_details else "N/A" - - backlogCourseList.append([i.course_id.course_name, course_details , i.semester_id.semester_no , summer_course]) - # Mess_bill = Monthly_bill.objects.filter(student_id = obj) - # Mess_pay = Payments.objects.filter(student_id = obj) - Mess_bill = [] - Mess_pay = [] + Mess_bill = Monthly_bill.objects.filter(student_id = obj) + Mess_pay = Payments.objects.filter(student_id = obj) + # Branch Change Form save if request.method=='POST': if True: @@ -506,7 +470,7 @@ def academic_procedures_student(request): return render( request, '../templates/academic_procedures/academic.html', {'details': details, - # 'calendar': calendar, + # 'calendar': calendar, 'currently_registered': currently_registered_course, 'pre_registered_course' : pre_registered_courses, 'pre_registered_course_show' : pre_registered_course_show, @@ -539,8 +503,7 @@ def academic_procedures_student(request): # 'change_branch': change_branch, # 'add_course': add_course, 'add_courses_options': add_courses_options, - 'drop_courses_options' : drop_courses_options, - 'replace_courses_options' : replace_courses_options, + #'drop_courses_options' : drop_courses_options, # 'pre_register': pre_register, 'pre_registration_timestamp': pre_registration_timestamp, 'prd': pre_registration_date_flag, @@ -549,7 +512,6 @@ def academic_procedures_student(request): 'adc_date_flag': add_or_drop_course_date_flag, 'pre_registration_flag' : pre_registration_flag, 'final_registration_flag': final_registration_flag, - 'swayam_courses_count':swayam_courses_count, # 'final_r': final_register_1, 'teaching_credit_registration_course' : teaching_credit_registration_course, @@ -565,12 +527,9 @@ def academic_procedures_student(request): 'hos_d':hos_d, 'tot_d':tot_d, 'attendence':attendence, - 'backlogCourseList' : backlogCourseList, - 'auto_backlog_courses_list' : auto_backlog_courses_list, 'BranchChangeForm': BranchChangeForm(), 'BranchFlag':branchchange_flag, 'assistantship_flag' : student_status, - 'notifications': notifs, } ) @@ -893,16 +852,12 @@ def dropcourseadmin(request): ''' data = request.GET.get('id') data = data.split(" - ") - student_id = data[0] course_code = data[1] - course = Courses.objects.get(code=course_code , version = 1.0) # need to add batch and programme - # curriculum_object = Curriculum.objects.all().filter(course_code = course_code) + curriculum_object = Curriculum.objects.all().filter(course_code = course_code) try: - # Register.objects.filter(curr_id = curriculum_object.first(),student_id=int(data[0])).delete() - course_registration.objects.filter(student_id = student_id , course_id = course.id).delete() - except Exception as e: - print(str(e)) + Register.objects.filter(curr_id = curriculum_object.first(),student_id=int(data[0])).delete() + except: pass # print("hello ") response_data = {} @@ -977,12 +932,9 @@ def verify_course(request): 'firstname': firstname, 'lastname': lastname} obj2 = Student.objects.all().select_related( 'id', 'id__user', 'id__department').filter(id=roll_no).first() - # obj = Register.objects.all().select_related('curr_id', 'student_id', 'curr_id__course_id', - # 'student_id__id', 'student_id__id__user', 'student_id__id__department').filter(student_id=obj2) - batch = obj2.batch_id - curr_id = batch.curriculum - curr_sem_id = Semester.objects.get(curriculum = curr_id, semester_no = obj2.curr_semester_no) - # curr_sem_id = obj2.curr_semester_no + obj = Register.objects.all().select_related('curr_id', 'student_id', 'curr_id__course_id', + 'student_id__id', 'student_id__id__user', 'student_id__id__department').filter(student_id=obj2) + curr_sem_id = obj2.curr_semester_no details = [] current_sem_courses = get_currently_registered_course( @@ -991,10 +943,7 @@ def verify_course(request): idd = obj2 for z in current_sem_courses: z = z[1] - print(z) - course_code = z.code - course_name = z.name - # course_code, course_name = str(z).split(" - ") + course_code, course_name = str(z).split(" - ") k = {} # reg_ig has course registration id appended with the the roll number # so that when we have removed the registration we can be redirected to this view @@ -1006,7 +955,7 @@ def verify_course(request): for p in courseobj2: k['course_id'] = course_code k['course_name'] = course_name - k['sem'] = curr_sem_id.semester_no + k['sem'] = curr_sem_id k['credits'] = p.credit details.append(k) @@ -1022,9 +971,6 @@ def verify_course(request): date = {'year': yearr, 'semflag': semflag} course_list = Courses.objects.all() semester_list = Semester.objects.all() - semester_no_list=[] - for i in semester_list: - semester_no_list.append(int(i.semester_no)) html = render_to_string('academic_procedures/studentCourses.html', {'details': details, 'dict2': dict2, @@ -1422,77 +1368,7 @@ def pre_registration(request): else: return HttpResponseRedirect('/academic-procedures/main') -@login_required(login_url='/accounts/login') -@transaction.atomic -def auto_pre_registration(request): - if request.method == 'POST': - try: - current_user = get_object_or_404(User, username=request.POST.get('user')) - current_user = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - sem_id = Semester.objects.get(id = request.POST.get('semester')) - course_slots=request.POST.getlist("course_slot") - try: - student_registeration_check=get_student_registrtion_check(current_user,sem_id) - if(student_registeration_check and student_registeration_check.pre_registration_flag==True): - messages.error(request,"You have already registered for next semester") - return HttpResponseRedirect('/academic-procedures/main') - except Exception as e: - print(e) - - reg_curr = [] - final_reg_curr = [] - existing_entries = set() - for course_slot in course_slots : - course_priorities = request.POST.getlist("course_priority-"+course_slot) - if(course_priorities[0] == 'NULL'): - continue - course_slot_id_for_model = CourseSlot.objects.get(id = int(course_slot)) - print("=----> course_priorities ----- ",course_priorities) - print("------------>course slot id ",course_slot_id_for_model) - for course_priority in course_priorities: - if(course_priority == 'NULL'): - continue - priority_of_current_course,course_id = map(int,course_priority.split("-")) - - course_id_for_model = Courses.objects.get(id = course_id) - current_combination = (course_slot_id_for_model.id, course_id_for_model.id) - if current_combination not in existing_entries: - p = InitialRegistration( - course_id = course_id_for_model, - semester_id = sem_id, - student_id = current_user, - course_slot_id = course_slot_id_for_model, - priority = priority_of_current_course - ) - f =FinalRegistration(student_id=current_user ,course_slot_id=course_slot_id_for_model , course_id=course_id_for_model ,semester_id=sem_id) - final_reg_curr.append(f) - reg_curr.append(p) - existing_entries.add(current_combination) - try: - - InitialRegistration.objects.bulk_create(reg_curr) - FinalRegistration.objects.bulk_create(final_reg_curr) - registration_check = StudentRegistrationChecks( - student_id = current_user, - pre_registration_flag = True, - final_registration_flag = False, - semester_id = sem_id - ) - registration_check.save() - messages.info(request, 'Successfully Registered.') - messages.success(request, "Successfully Registered.") - return HttpResponseRedirect('/academic-procedures/stu') - except Exception as e: - messages.error(request, "Error in Registration.") - return HttpResponseRedirect('/academic-procedures/stu') - except Exception as e: - messages.error(request, "Error in Registration.") - return HttpResponseRedirect('/academic-procedures/main') - else: - return HttpResponseRedirect('/academic-procedures/main') - def get_student_registrtion_check(obj, sem): return StudentRegistrationChecks.objects.all().filter(student_id = obj, semester_id = sem).first() @@ -1552,31 +1428,24 @@ def allot_courses(request): profiles=request.FILES['allotedCourses'] batch_id=request.POST['batch'] sem_no=int(request.POST['semester']) - + batch=Batch.objects.get(id=batch_id) sem_id=Semester.objects.get(curriculum=batch.curriculum,semester_no=sem_no) - print(batch , sem_id) - # format of excel sheet being uploaded should be xls only , otherwise error + excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) final_registrations=[] - # print('>>>>>>>>>>>>>>>>>>>' , sheet.nrows) for i in range(1,sheet.nrows): roll_no = str(sheet.cell(i,0).value).split(".")[0] - # print("Roll No from Excel:", roll_no) course_slot_name = sheet.cell_value(i,1) course_code = sheet.cell_value(i,2) course_name = sheet.cell_value(i,3) - try: - user=User.objects.get(username=roll_no) - user_info = ExtraInfo.objects.get(user=user) - student = Student.objects.get(id=user_info) - course_slot=CourseSlot.objects.get(name=course_slot_name.strip(),semester=sem_id) - print(course_code.strip() , course_name.strip()) - course = Courses.objects.get(code=course_code.strip(),name=course_name.strip()) - # print(">>>>>",roll_no,course_slot_name,course_code,course_name) - except Exception as e: - print('----------------------' , e) + user=User.objects.get(username=roll_no) + user_info = ExtraInfo.objects.get(user=user) + student = Student.objects.get(id=user_info) + course_slot=CourseSlot.objects.get(name=course_slot_name.strip(),semester=sem_id) + course = Courses.objects.get(code=course_code.strip(),name=course_name.strip()) + #print(">>>>>",roll_no,course_slot_name,course_code,course_name) final_registration=FinalRegistration(student_id=student,course_slot_id=course_slot, course_id=course,semester_id=sem_id) final_registrations.append(final_registration) @@ -1758,52 +1627,6 @@ def drop_course(request): else: return HttpResponseRedirect('/academic-procedures/main') -def replace_courses(request): - """ - This function is used to replace elective courses which have been registered - @param: - request - contains metadata about the requested page - @variables: - current_user - contains current logged in user - sem_id - contains current semester id - count - no of courses to be replaced - course_id - contains course id for a particular course - course_slot_id - contains course slot id for a particular course - choice - contains choice of a particular course - slot - contains slot of a particular course - """ - - if request.method == 'POST' : - try: - current_user = get_object_or_404(User, username=request.POST.get('user')) - current_user = ExtraInfo.objects.all().filter(user=current_user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - - # sem_id = Semester.objects.get(id = request.POST.get('semester')) - count = request.POST.get('ct') - count = int(count) - - for i in range(1, count+1): - choice = "choice["+str(i)+"]" - slot = "slot["+str(i)+"]" - try : - - course_id = Courses.objects.get(id = request.POST.get(choice)) - courseslot_id = CourseSlot.objects.get(id = request.POST.get(slot)) - - registered_course = course_registration.objects.filter(student_id=current_user, course_slot_id = courseslot_id).first() - - if registered_course: - registered_course.course_id = course_id - registered_course.save() - except Exception as e: - continue - return HttpResponseRedirect('/academic-procedures/main') - except Exception as e: - return HttpResponseRedirect('/academic-procedures/main') - else : - return HttpResponseRedirect('/academic-procedures/main') - @@ -1903,7 +1726,7 @@ def get_final_registration_choices(branch_courses,batch): max_limit = courseslot.max_registration_limit lis = [] for course in courseslot.courses.all(): - if FinalRegistration.objects.filter(student_id__batch_id__year = batch, course_id = course).count() < max_limit: + if FinalRegistration .objects.filter(student_id__batch_id__year = batch, course_id = course).count() < max_limit: lis.append(course) else: unavailable_courses.append(course) @@ -1918,8 +1741,6 @@ def get_add_course_options(branch_courses, current_register, batch): for c in current_register: slots.append(c[0]) for courseslot in branch_courses: - if courseslot.type == "Swayam": - continue max_limit = courseslot.max_registration_limit if courseslot not in slots: lis = [] @@ -1936,24 +1757,7 @@ def get_drop_course_options(current_register): courses.append(item[1]) return courses -def get_replace_course_options( current_register, batch): - replace_options = [] - - for registered_course in current_register: - courseslot_id = registered_course[0] - course_id = registered_course[1] - courseslot = courseslot_id - coursename = course_id.name - lis = [] - - if 'Elective' in courseslot.type: - for course in courseslot.courses.all(): - if course != course_id: - lis.append(course) - replace_options.append((courseslot, coursename, lis)) - - return replace_options @@ -1985,11 +1789,7 @@ def get_user_semester(roll_no, ug_flag, masters_flag, phd_flag): def get_branch_courses(roll_no, user_sem, branch): roll = str(roll_no) - try: - year = int(roll[:4]) - except: - year = int(roll[:2]) - year = 2000 + year + year = int(roll[:4]) courses = Curriculum.objects.all().select_related().filter(batch=(year)) courses = courses.filter(sem = user_sem) courses = courses.filter(floated = True) @@ -2423,13 +2223,12 @@ def student_list(request): batch_id = Batch.objects.get(id = batch) student_obj = FeePayments.objects.all().select_related('student_id').filter(student_id__batch_id = batch_id) if (student_obj): - reg_table = student_obj.prefetch_related('student_id__studentregistrationchecks').filter(semester_id = student_obj[0].semester_id, student_id__studentregistrationchecks__final_registration_flag = True , student_id__finalregistration__verified=False , student_id__finalregistration__semester_id= student_obj[0].semester_id ).select_related( + reg_table = student_obj.prefetch_related('student_id__studentregistrationchecks').filter(semester_id = student_obj[0].semester_id, student_id__studentregistrationchecks__final_registration_flag = True).select_related( 'student_id','student_id__id','student_id__id__user','student_id__id__department').values( 'student_id__id','student_id__id__user__first_name','student_id__id__user__last_name','student_id__batch','student_id__id__department__name', 'student_id__programme','student_id__curr_semester_no','student_id__id__sex','student_id__id__phone_no','student_id__category', 'student_id__specialization','mode','transaction_id','deposit_date','fee_paid','utr_number','reason','fee_receipt','actual_fee', - 'student_id__id__user__username').order_by('student_id__id__user').distinct() - # print('------------------------------------------------------------------------------------------------------------------------------------------',reg_table) + 'student_id__id__user__username').order_by('student_id__id__user') else : reg_table = [] @@ -2489,7 +2288,7 @@ def student_list(request): 'specialization','gender','category', 'pwd_status','phone_no','actual_fee', 'fee_paid','reason','date_deposited', - 'mode','utr_number','fee_receipt')).distinct() + 'mode','utr_number','fee_receipt')) excel_response = BytesIO() @@ -2527,12 +2326,6 @@ def process_verification_request(request): return verify_registration(request) return JsonResponse({'status': 'Failed'}, status=400) - -def auto_process_verification_request(request): - if request.is_ajax(): - return auto_verify_registration(request) - return JsonResponse({'status': 'Failed'}, status=400) - @transaction.atomic def verify_registration(request): @@ -2542,17 +2335,12 @@ def verify_registration(request): batch = student.batch_id curr_id = batch.curriculum - - if(student.curr_semester_no+1 >= 9): - sem_no = 4 - else: - sem_no = student.curr_semester_no+1 - - sem_id = Semester.objects.get(curriculum = curr_id, semester_no = sem_no) + sem_id = Semester.objects.get(curriculum = curr_id, semester_no = student.curr_semester_no+1) final_register_list = FinalRegistration.objects.all().filter(student_id = student, verified = False, semester_id = sem_id) - + sem_no = student.curr_semester_no + 1 + with transaction.atomic(): ver_reg = [] for obj in final_register_list: @@ -2565,7 +2353,6 @@ def verify_registration(request): ver_reg.append(p) o = FinalRegistration.objects.filter(id= obj.id).update(verified = True) course_registration.objects.bulk_create(ver_reg) - # StudentRegistrationChecks.objects.filter(student_id = student_id, semester_id = sem_id).update(final_registration_flag = True) academics_module_notif(request.user, student.id.user, 'registration_approved') Student.objects.filter(id = student_id).update(curr_semester_no = sem_no) return JsonResponse({'status': 'success', 'message': 'Successfully Accepted'}) @@ -2576,11 +2363,8 @@ def verify_registration(request): batch = student_id.batch_id curr_id = batch.curriculum - if(student.curr_semester_no+1 >= 9): - sem_no = 4 - else: - sem_no = student.curr_semester_no+1 - sem_id = Semester.objects.get(curriculum = curr_id, semester_no = sem_no) + sem_id = Semester.objects.get(curriculum = curr_id, semester_no = student_id.curr_semester_no + 1) + with transaction.atomic(): academicadmin = get_object_or_404(User, username = "acadadmin") FinalRegistration.objects.filter(student_id = student_id, verified = False, semester_id = sem_id).delete() @@ -2589,53 +2373,8 @@ def verify_registration(request): academics_module_notif(academicadmin, student_id.id.user, 'Registration Declined - '+reject_reason) return JsonResponse({'status': 'success', 'message': 'Successfully Rejected'}) -@transaction.atomic -def auto_verify_registration(request): - if request.POST.get('status_req') == "accept" : - student_id = request.POST.get('student_id') - student = Student.objects.get(id = student_id) - batch = student.batch_id - curr_id = batch.curriculum - - if(student.curr_semester_no+1 >= 9): - # print('----------------------------------------------------------------' , student.curr_semester_no) - sem_no = 8 - else: - # print('----------------------------------------------------------------' , student.curr_semester_no) - sem_no = student.curr_semester_no+1 - sem_id = Semester.objects.get(curriculum = curr_id, semester_no = sem_no) - # print('----------------------------------------------------------------' , student.curr_semester_no) - - final_register_list = FinalRegistration.objects.all().filter(student_id = student, verified = False, semester_id = sem_id) - - # final_register_list = FinalRegistration.objects.all().filter(student_id = student, verified = False) - - with transaction.atomic(): - for obj in final_register_list: - o = FinalRegistration.objects.filter(id= obj.id).update(verified = True) - academics_module_notif(request.user, student.id.user, 'registration_approved') - - Student.objects.filter(id = student_id).update(curr_semester_no = sem_no) - return JsonResponse({'status': 'success', 'message': 'Successfully Accepted'}) - - elif request.POST.get('status_req') == "reject" : - reject_reason = request.POST.get('reason') - student_id = request.POST.get('student_id') - student_id = Student.objects.get(id = student_id) - batch = student_id.batch_id - curr_id = batch.curriculum - if(student_id.curr_semester_no+1 >= 9): - sem_no = 8 - else: - sem_no = student_id.curr_semester_no+1 - sem_id = Semester.objects.get(curriculum = curr_id, semester_no = sem_no) - with transaction.atomic(): - academicadmin = get_object_or_404(User, username = "acadadmin") - # FinalRegistration.objects.filter(student_id = student_id, verified = False, semester_id = sem_id).delete() - StudentRegistrationChecks.objects.filter(student_id = student_id, semester_id = sem_id).update(final_registration_flag = False) - FeePayments.objects.filter(student_id = student_id, semester_id = sem_id).delete() - academics_module_notif(academicadmin, student_id.id.user, 'Registration Declined - '+reject_reason) - return JsonResponse({'status': 'success', 'message': 'Successfully Rejected'}) + + def get_registration_courses(courses): x = [[]] @@ -2700,8 +2439,8 @@ def course_marks_data(request): try: course_id = request.POST.get('course_id') course = Courses.objects.select_related().get(id = course_id) - # print(course) - # print(course_id) + print(course) + print(course_id) student_list = course_registration.objects.filter(course_id__id=course_id).select_related( 'student_id__id__user','student_id__id__department').only('student_id__batch', 'student_id__id__user__first_name', 'student_id__id__user__last_name', @@ -3723,378 +3462,7 @@ def mdue(request): content = json.dumps("success") return HttpResponse(content) - - - -def get_detailed_sem_courses(sem_id): - course_slots = CourseSlot.objects.filter(semester_id=sem_id) - # Serialize queryset of course slots into JSON - course_slots_json = serialize('json', course_slots) - # Convert JSON string into Python object - course_slots_data = json.loads(course_slots_json) - - # Iterate over each course slot data and include associated course data - for slot_data in course_slots_data: - # Retrieve associated courses for the current course slot - slot = CourseSlot.objects.get(id=slot_data['pk']) - courses = list(slot.courses.all().values()) - # Add courses data to the course slot data - slot_data['courses'] = courses - - return course_slots_data - - -def get_next_sem_courses(request): - if request.method == 'POST': - data = json.loads(request.body) - next_sem = data.get('next_sem') - branch = data.get('branch') - programme = data.get('programme') - batch = data.get('batch') - # we go to student table and apply filters and get batch_id of the students with these filter - batch_id = Student.objects.filter(programme = programme , batch = batch , specialization = branch)[0].batch_id - - curr_id = batch_id.curriculum - # print('-----------------------------------------------------------------------------------------', curr_id) - # curr_id = 1 - next_sem_id = Semester.objects.get(curriculum = curr_id, semester_no = next_sem) - - if next_sem_id: - next_sem_registration_courses = get_detailed_sem_courses(next_sem_id ) - # print(next_sem_registration_courses) - return JsonResponse(next_sem_registration_courses, safe=False) - return JsonResponse({'error': 'Invalid request'}) - - -def add_course_to_slot(request): - if request.method == 'POST': - data = json.loads(request.body) - course_slot_name = data.get('course_slot_name') - course_code = data.get('course_name') - # print('-----------------------------------------------------------------------------------------' , course_slot_name , course_code) - try: - course_slot = CourseSlot.objects.get(name=course_slot_name) - course = Courses.objects.get(code=course_code) - course_slot.courses.add(course) - - return JsonResponse({'message': f'Course {course_code} added to slot {course_slot_name} successfully.'}, status=200) - except CourseSlot.DoesNotExist: - return JsonResponse({'error': 'Course slot does not exist.'}, status=400) - except Course.DoesNotExist: - return JsonResponse({'error': 'Course does not exist.'}, status=400) - - return JsonResponse({'error': 'Invalid request method.'}, status=405) - - -def remove_course_from_slot(request): - if request.method == 'POST': - data = json.loads(request.body) - course_slot_name = data.get('course_slot_name') - course_code = data.get('course_name') - # print('-----------------------------------------------------------------------------------------' , course_slot_name , course_code) - try: - course_slot = CourseSlot.objects.get(name=course_slot_name) - course = Courses.objects.get(code=course_code) - course_slot.courses.remove(course) - return JsonResponse({'message': f'Course {course_code} removed from slot {course_slot_name} successfully.'}, status=200) - except CourseSlot.DoesNotExist: - return JsonResponse({'error': 'Course slot does not exist.'}, status=400) - except Course.DoesNotExist: - return JsonResponse({'error': 'Course does not exist.'}, status=400) - - return JsonResponse({'error': 'Invalid request method.'}, status=405) - - -def add_one_course(request): - if request.method == 'POST': - try: - # print(request.POST) - current_user = get_object_or_404(User, username=request.POST.get('user')) - current_user = ExtraInfo.objects.all().filter(user=current_user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - - sem_id = Semester.objects.get(id=request.POST.get('semester')) - choice = request.POST.get('choice') - slot = request.POST.get('slot') - - try: - course_id = Courses.objects.get(id=choice) - courseslot_id = CourseSlot.objects.get(id=slot) - print(courseslot_id) - print(courseslot_id.type) - if course_registration.objects.filter(course_slot_id_id=courseslot_id, student_id=current_user).count() == 1 and courseslot_id.type != "Swayam": - already_registered_course_id = course_registration.objects.filter(course_slot_id_id=courseslot_id, student_id=current_user)[0].course_id - # print(already_registered_course_id) - msg = 'Already Registered in the course : ' +already_registered_course_id.code + '-'+ already_registered_course_id.name - return JsonResponse({'message' : msg}) - if((course_registration.objects.filter(course_id=course_id, student_id=current_user).count() >= 1)): - return JsonResponse({'message': 'Already registered in this course!'}, status=200) - # Check if maximum course registration limit has not been reached - if course_registration.objects.filter(student_id__batch_id__year=current_user.batch_id.year, course_id=course_id).count() < courseslot_id.max_registration_limit and \ - (course_registration.objects.filter(course_id=course_id, student_id=current_user).count() == 0): - p = course_registration( - course_id=course_id, - student_id=current_user, - course_slot_id=courseslot_id, - semester_id=sem_id - ) - p.save() - return JsonResponse({'message': 'Course added successfully'}) - else: - return JsonResponse({'message': 'Course not added because seats are full!'}, status=200) - except Exception as e: - return JsonResponse({'message': 'Error adding course'}, status=500) - except Exception as e: - return JsonResponse({'message': 'Error adding course'}, status=500) - else: - return JsonResponse({'message': 'Invalid request method'}, status=405) - -def replace_one_course(request): - if request.method == 'POST' : - try: - current_user = get_object_or_404(User, username=request.POST.get('user')) - current_user = ExtraInfo.objects.all().filter(user=current_user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - - - course_id = Courses.objects.get(id = request.POST.get('choice')) - courseslot_id = CourseSlot.objects.get(id = request.POST.get('slot')) - if course_registration.objects.filter(student_id__batch_id__year=current_user.batch_id.year, course_id=course_id).count() < courseslot_id.max_registration_limit and \ - (course_registration.objects.filter(course_id=course_id, student_id=current_user).count() == 0): - # print('---------------------------------------------------------------------------------' , course_registration.objects.filter(student_id__batch_id__year=current_user.batch_id.year, course_id=course_id).count() , courseslot_id.max_registration_limit ) - registered_course = course_registration.objects.filter(student_id=current_user, course_slot_id = courseslot_id).first() - - if registered_course: - registered_course.course_id = course_id - registered_course.save() - else: - return JsonResponse({'message': 'Cannot Replace to this course seats are full!'}, status=200) - - return JsonResponse({'message': 'Course Replaced Successfully'}, status=200) - except Exception as e: - return JsonResponse({'message': 'Error Replacing course'}, status=500) - else : - return JsonResponse({'message': 'Invalid request method'}, status=405) - -def get_sem_swayam(sem_id, batch): - courses = [] - course_slots = CourseSlot.objects.all().filter(type='Swayam') - - for slot in course_slots: - courses.append(slot) - - return courses - -def replaceSwayam(request): - if(request.POST): - # print(f"++++++++++++++++++++++++++++++++++++++++++++++++{request.POST}") - - current_user = get_object_or_404(User, username=request.user.username) - user_details = ExtraInfo.objects.all().select_related( - 'user', 'department').filter(user=current_user).first() - desig_id = Designation.objects.all().filter(name='adminstrator').first() - temp = HoldsDesignation.objects.all().select_related().filter( - designation=desig_id).first() - acadadmin = temp.working - k = str(user_details).split() - final_user = k[2] - - if (str(acadadmin) != str(final_user)): - return HttpResponseRedirect('/academic-procedures/') - roll_no = request.POST["rollNo"] - obj = ExtraInfo.objects.all().select_related( - 'user', 'department').filter(id=roll_no).first() - firstname = obj.user.first_name - lastname = obj.user.last_name - dict2 = {'roll_no': roll_no, - 'firstname': firstname, 'lastname': lastname} - - details = [] - obj2 = Student.objects.all().select_related( - 'id', 'id__user', 'id__department').filter(id=roll_no).first() - # obj = Register.objects.all().select_related('curr_id', 'student_id', 'curr_id__course_id', - # 'student_id__id', 'student_id__id__user', 'student_id__id__department').filter(student_id=obj2) - batch = obj2.batch_id - curr_id = batch.curriculum - curr_sem_id = Semester.objects.get(curriculum = curr_id, semester_no = obj2.curr_semester_no) - current_sem_courses = get_currently_registered_elective( - roll_no, curr_sem_id) - current_sem_swayam = get_sem_swayam(curr_sem_id,2025) - idd = obj2 - for z in current_sem_courses: - eletive_id=z[2] - z = z[1] - - course_code = z.code - course_name = z.name - - k = {} - # reg_ig has course registration id appended with the the roll number - # so that when we have removed the registration we can be redirected to this view - k['reg_id'] = roll_no+" - "+course_code - k['rid'] = roll_no+" - "+course_code - # Name ID Confusion here , be carefull - courseobj2 = Courses.objects.all().filter(code=course_code) - # if(str(z.student_id) == str(idd)): - for p in courseobj2: - k['course_id'] = course_code - k['course_name'] = course_name - k['sem'] = curr_sem_id.semester_no - k['credits'] = p.credit - k['eletive_id'] = eletive_id - details.append(k) - - year = demo_date.year - month = demo_date.month - yearr = str(year) + "-" + str(year+1) - semflag = 0 - if(month >= 7): - semflag = 1 - else: - semflag = 2 - # TO DO Bdes - date = {'year': yearr, 'semflag': semflag} - course_list = Courses.objects.all() - semester_list = Semester.objects.all() - html = render_to_string('academic_procedures/studentSwayam.html', - {'details': details, - 'dict2': dict2, - 'course_list': course_list, - 'current_sem_swayam':current_sem_swayam, - 'roll_no':roll_no, - 'semester_list': semester_list, - # 'csrf_token' : csrf_token, - 'date': date}, request) - - maindict = {'html': html} - obj = json.dumps(maindict) - return HttpResponse(obj, content_type='application/json') - -def get_currently_registered_elective(student_id, semester_id): - registrations = course_registration.objects.filter(student_id=student_id, semester_id=semester_id) - courses = [] - for registration in registrations: - if registration.course_slot_id.type == "Optional Elective": - courses.append((registration.course_slot_id, registration.course_id, registration.id)) - return courses - - - -def swayam_replace(request): - if request.method == 'POST': - csrf_token = request.POST.get('csrfmiddlewaretoken', None) - - # print(f"---------------------------------{csrf_token}") - try: - - # print(f"djfhajjfsjfhajfhjdsfsdfj{request.POST}") - csrf_token = request.POST.get('csrfmiddlewaretoken', None) - - # print(f"---------------------------------{csrf_token}") - # Accessing individual values by key - user_value = request.POST['user'] - course_id_value = request.POST['course_id'] - - # print(user_value) 20BCS074 - # print(course_id_value) 8955 - - elective_to_delete = course_registration.objects.get(id=course_id_value) - sem = elective_to_delete.semester_id - # print(elective_to_delete) - # print(sem) cse ug curri v1 - - - swayam_course_id_value = request.POST['swayam_course_id'] - swayam_course_id_value_array = [int(id_str) for id_str in swayam_course_id_value.split(',')[:-1]] - # print(swayam_course_id_value_array) - # print(swayam_course_id_value) - - - - swayam_course_slot_id_value = request.POST['swayam_course_slot_id'] - swayam_course_slot_id_value_array = [int(slot_str) for slot_str in swayam_course_slot_id_value.split(',')[:-1]] - # print(swayam_course_slot_id_value_array) - # print(swayam_course_slot_id_value) - - - swayam_semester_id_value = request.POST['swayam_semester_id'] - swayam_semester_id_value_array = [int(semester_str) for semester_str in swayam_semester_id_value.split(',')[:-1]] - - - - - n = len(swayam_course_id_value_array) - # print(n) - # new_row_data = [] - for i in range(n): - course_id_model = Courses.objects.get(id=swayam_course_id_value_array[i]) - # print(course_id_model) - semester_id_model = Semester.objects.get(id=swayam_semester_id_value_array[i]) - student_id_model = Student.objects.get(id=user_value) - course_slot_id_model = CourseSlot.objects.get(id=swayam_course_slot_id_value_array[i]) - obj = course_registration( - course_id = course_id_model, - semester_id = semester_id_model, - student_id = student_id_model, - course_slot_id = course_slot_id_model, - working_year = 1 - ) - obj.save() - - # for j in range(n): - # SwayamCourses.objects.filter(course_id = swayam_course_id_value_array[j], student_id=user_value).update(course_used = True) - - elective_to_delete.delete() - - - messages.success(request, "Your Courses have been replaced.") - return HttpResponseRedirect('/academic-procedures/main') - - - - - except Exception as e: - error_message = str(e) - print("Error:", error_message) - messages.error(request, f"Error in Registration: {error_message}") - return HttpResponseRedirect('/academic-procedures/main') - else: - return HttpResponseRedirect('/academic-procedures/main') - -def register_backlog_course(request): - if request.method == 'POST': - try: - current_user = request.user - current_user = ExtraInfo.objects.all().filter(user=request.user).first() - current_user = Student.objects.all().filter(id=current_user.id).first() - sem_id = Semester.objects.filter(id = request.POST.get('semester')).first() - course_id = Courses.objects.get(code = request.POST.get('courseCode') , version = request.POST.get('Version')) - course_slots = course_id.courseslots.all() - course_slot_id = '' - if course_slots: - course_slot_id = CourseSlot.objects.filter(id = course_slots[0].id).first() - if (sem_id.semester_no - course_slot_id.semester.semester_no)%2 != 0 : - return JsonResponse({'message':'Wait for Next Semester !'}, status=200) - # print('_____________________________________________________________________________________________' , course_id ,current_user , course_slot_id , sem_id) - try: - if course_registration.objects.filter(course_id=course_id, student_id=current_user , semester_id = sem_id).count() == 0: - p = course_registration( - course_id=course_id, - student_id=current_user, - course_slot_id=course_slot_id, - semester_id=sem_id - ) - p.save() - return JsonResponse({'message': 'Successfully Registered Backlog course' }, status=200) - else: - return JsonResponse({'message': 'Already Registered Backlog course' }, status=200) - except Exception as e: - print(str(e)) - return JsonResponse({'message': 'Error Registering course ' + str(e)}, status=500) - except Exception as e: - print(str(e)) - return JsonResponse({'message': 'Adding Backlog Failed ' +str(e)}, status=500) \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/admin.py b/FusionIIIT/applications/central_mess/admin.py index cbeb94d1c..cbb2fcb6c 100755 --- a/FusionIIIT/applications/central_mess/admin.py +++ b/FusionIIIT/applications/central_mess/admin.py @@ -2,8 +2,8 @@ from .models import (Feedback, Menu, Menu_change_request, Mess_meeting, Mess_minutes, Mess_reg, Messinfo, Monthly_bill, - Payments, Rebate, - Special_request, Vacation_food,MessBillBase, Registration_Request, Reg_records, Reg_main) + Nonveg_data, Nonveg_menu, Payments, Rebate, + Special_request, Vacation_food,MessBillBase) # Register your models here. @@ -45,7 +45,7 @@ class Mess_regAdmin(admin.ModelAdmin): ('start_reg', {'fields': ['start_reg']}), ('end_reg', {'fields': ['end_reg']}), ] - list_display = ('sem','start_reg', 'end_reg') + list_display = ('start_reg', 'end_reg') @@ -56,14 +56,14 @@ class Monthly_billAdmin(admin.ModelAdmin): ('month', {'fields': ['month']}), ('year', {'fields': ['year']}), ('amount', {'fields': ['amount']}), - # ('nonveg_total_bill', {'fields': ['nonveg_total_bill']}), + ('nonveg_total_bill', {'fields': ['nonveg_total_bill']}), ('rebate_count', {'fields': ['rebate_count']}), ('rebate_amount', {'fields': ['rebate_amount']}), ('total_bill', {'fields': ['total_bill']}), ] list_display = ('student_id', 'month', 'year', 'amount', - 'rebate_count', 'rebate_amount', 'total_bill') + 'nonveg_total_bill', 'rebate_count', 'rebate_amount', 'total_bill') @@ -71,9 +71,11 @@ class PaymentsAdmin(admin.ModelAdmin): model = Payments fieldsets = [ ('student_id', {'fields': ['student_id']}), + ('sem', {'fields': ['sem']}), + ('year', {'fields': ['year']}), ('amount_paid', {'fields': ['amount_paid']}), ] - list_display = ('student_id', 'amount_paid') + list_display = ('student_id', 'sem', 'year', 'amount_paid') class RebateAdmin(admin.ModelAdmin): @@ -104,26 +106,26 @@ class Vacation_foodAdmin(admin.ModelAdmin): -# class Nonveg_menuAdmin(admin.ModelAdmin): -# model = Nonveg_menu -# fieldsets = [ -# ('dish', {'fields': ['dish']}), -# ('price', {'fields': ['price']}), -# ('order_interval', {'fields': ['order_interval']}), -# ] -# list_display = ('dish', 'price', 'order_interval') +class Nonveg_menuAdmin(admin.ModelAdmin): + model = Nonveg_menu + fieldsets = [ + ('dish', {'fields': ['dish']}), + ('price', {'fields': ['price']}), + ('order_interval', {'fields': ['order_interval']}), + ] + list_display = ('dish', 'price', 'order_interval') -# class Nonveg_dataAdmin(admin.ModelAdmin): -# model = Nonveg_data -# fieldsets = [ -# ('student_id', {'fields': ['student_id']}), -# ('order_date', {'fields': ['order_date']}), -# ('dish', {'fields': ['dish']}), -# ('order_interval', {'fields': ['order_interval']}), -# ] -# list_display = ('student_id', 'order_date', 'dish', 'order_interval') +class Nonveg_dataAdmin(admin.ModelAdmin): + model = Nonveg_data + fieldsets = [ + ('student_id', {'fields': ['student_id']}), + ('order_date', {'fields': ['order_date']}), + ('dish', {'fields': ['dish']}), + ('order_interval', {'fields': ['order_interval']}), + ] + list_display = ('student_id', 'order_date', 'dish', 'order_interval') @@ -170,10 +172,9 @@ class FeedbackAdmin(admin.ModelAdmin): ('student_id', {'fields': ['student_id']}), ('fdate', {'fields': ['fdate']}), ('description', {'fields': ['description']}), - ('feedback_type', {'fields': ['feedback_type']}), - ('feedback_remark', {'fields':['feedback_remark']}) + ('feedback_type', {'fields': ['feedback_type']}) ] - list_display = ('student_id', 'fdate', 'description', 'feedback_type', 'feedback_remark') + list_display = ('student_id', 'fdate', 'description', 'feedback_type') class MessBillBaseAdmin(admin.ModelAdmin): @@ -183,19 +184,6 @@ class MessBillBaseAdmin(admin.ModelAdmin): ] list_display = ('bill_amount', 'timestamp') -class Reg_mainAdmin(admin.ModelAdmin): - model = Reg_main - list_display = ('student_id','program','current_mess_status','balance','mess_option') - -class Reg_recordsAdmin(admin.ModelAdmin): - model=Reg_records - list_display = ('student_id','start_date','end_date') - - -class Registration_RequestAdmin(admin.ModelAdmin): - model=Registration_Request - list_display = ('student_id','Txn_no','img','amount','status','registration_remark') - admin.site.register(Mess_minutes, Mess_minutesAdmin), admin.site.register(Messinfo, MessinfoAdmin), @@ -206,12 +194,9 @@ class Registration_RequestAdmin(admin.ModelAdmin): admin.site.register(Rebate, RebateAdmin), admin.site.register(Vacation_food, Vacation_foodAdmin), admin.site.register(Special_request, Special_requestAdmin), -# admin.site.register(Nonveg_menu, Nonveg_menuAdmin), -# admin.site.register(Nonveg_data, Nonveg_dataAdmin), +admin.site.register(Nonveg_menu, Nonveg_menuAdmin), +admin.site.register(Nonveg_data, Nonveg_dataAdmin), admin.site.register(Mess_meeting, Mess_meetingAdmin), admin.site.register(Feedback, FeedbackAdmin), admin.site.register(MessBillBase,MessBillBaseAdmin), admin.site.register(Menu_change_request, Menu_change_requestAdmin) -admin.site.register(Reg_main,Reg_mainAdmin) -admin.site.register(Reg_records,Reg_recordsAdmin) -admin.site.register(Registration_Request,Registration_RequestAdmin) diff --git a/FusionIIIT/applications/central_mess/api/serializers.py b/FusionIIIT/applications/central_mess/api/serializers.py deleted file mode 100644 index b30ad2686..000000000 --- a/FusionIIIT/applications/central_mess/api/serializers.py +++ /dev/null @@ -1,91 +0,0 @@ -from rest_framework import serializers -from applications.central_mess.models import * - -class MessinfoSerializer(serializers.ModelSerializer): - - class Meta: - model=Messinfo - fields=('__all__') - -class Mess_regSerializer(serializers.ModelSerializer): - class Meta: - model = Mess_reg - fields=('__all__') - -class MessBillBaseSerializer(serializers.ModelSerializer): - class Meta: - model = MessBillBase - fields=('__all__') - -class Monthly_billSerializer(serializers.ModelSerializer): - class Meta: - model=Monthly_bill - fields=('__all__') - -class PaymentsSerializer(serializers.ModelSerializer): - class Meta: - model=Payments - fields=('__all__') - -class MenuSerializer(serializers.ModelSerializer): - class Meta: - model=Menu - fields=('__all__') - -class RebateSerializer(serializers.ModelSerializer): - - class Meta: - model=Rebate - fields=('__all__') - -class Vacation_foodSerializer(serializers.ModelSerializer): - class Meta: - model = Vacation_food - fields=('__all__') - -# class Nonveg_menuSerializer(serializers.ModelSerializer): -# class Meta: -# model = Nonveg_menu -# fields=('__all__') - -# class Nonveg_dataSerializer(serializers.ModelSerializer): -# class Meta: -# model=Nonveg_data -# fields=('__all__') - -class Special_requestSerializer(serializers.ModelSerializer): - class Meta: - model=Special_request - fields=('__all__') - -class Mess_meetingSerializer(serializers.ModelSerializer): - class Meta: - model=Mess_meeting - fields=('__all__') - -class Mess_minutesSerializer(serializers.ModelSerializer): - class Meta: - model = Mess_minutes - fields=('__all__') - -class Menu_change_requestSerializer(serializers.ModelSerializer): - class Meta: - model = Menu_change_request - fields=('__all__') - -class FeedbackSerializer(serializers.ModelSerializer): - class Meta: - model=Feedback - fields=('__all__') - -class GetFilteredSerialzer(serializers.ModelSerializer): - first_name = serializers.CharField(source='student_id.id.user.first_name') - last_name = serializers.CharField(source='student_id.id.user.last_name') - class Meta: - model=Reg_main - fields=('__all__') - -class reg_recordSerialzer(serializers.ModelSerializer): - class Meta: - model = Reg_records - fields=('__all__') \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/api/urls.py b/FusionIIIT/applications/central_mess/api/urls.py deleted file mode 100644 index 2bd15c746..000000000 --- a/FusionIIIT/applications/central_mess/api/urls.py +++ /dev/null @@ -1,27 +0,0 @@ -from django.conf.urls import url -from . import views -from .views import * - -urlpatterns = [ - url("feedbackApi", views.FeedbackApi.as_view(), name="feedbackApi"), - url("menuChangeRequestApi", views.Menu_change_requestApi.as_view(), name="menuChangeRequestApi"), - url("messMinutesApi", views.Mess_minutesApi.as_view(), name="messMinutesApi"), - # url("nonvegDataApi", views.Nonveg_dataApi.as_view(), name="nonvegDataApi"), - url("specialRequestApi", views.Special_requestApi.as_view(), name="specialRequestApi"), - url("messMeetingApi", views.Mess_meetingApi.as_view(), name="messMeetingApi"), - # url("nonvegMenuApi", views.Nonveg_menuApi.as_view(), name="nonvegMenuApi"), - url("vacationFoodApi", views.Vacation_foodApi.as_view(), name="vacationFoodApi"), - url("messInfoApi", views.MessinfoApi.as_view(), name="messInfoApi"), - url("rebateApi", views.RebateApi.as_view(), name="rebateApi"), - url("menuApi", views.MenuApi.as_view(), name="menuApi"), - url("paymentsApi", views.PaymentsApi.as_view(), name="paymentsApi"), - url("monthlyBillApi", views.Monthly_billApi.as_view(), name="monthlyBillApi"), - url("messBillBaseApi", views.MessBillBaseApi.as_view(), name="messBillBaseApi"), - url("messRegApi", views.Mess_regApi.as_view(), name="messRegApi"), - url("get_mess_students", views.Get_Filtered_Students.as_view(), name="get_mess_students"), - url("get_reg_records",views.Get_Reg_Records.as_view(),name="reg_record_API"), - # url("billDashboard", views.Bill_dashboard.as_view(), name="billDashboard"), - url("get_student_bill",views.Get_Student_bill.as_view(),name="student_bill_API"), - url("get_student_payment",views.Get_Student_Payments.as_view(),name="student_payment_API"), - url("get_student_all_details",views.Get_Student_Details.as_view(),name="get_student_details_API") -] \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/api/views.py b/FusionIIIT/applications/central_mess/api/views.py deleted file mode 100644 index 6d1b7d4ae..000000000 --- a/FusionIIIT/applications/central_mess/api/views.py +++ /dev/null @@ -1,487 +0,0 @@ - #APIs -from rest_framework.views import APIView -from rest_framework.response import Response -from .serializers import * -from django.shortcuts import get_object_or_404 -from applications.central_mess.models import * -from django.contrib.auth.models import User -from applications.globals.models import ExtraInfo, HoldsDesignation, Designation -from django.http import JsonResponse - -class FeedbackApi(APIView): - - def get(self, request): - feedback_obj = Feedback.objects.all(); - serialized_obj = FeedbackSerializer(feedback_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - mess = data['mess'] - _type = data['type'] - desc = data['desc'] - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - obj = Feedback( - student_id = student, - mess =mess, - feedback_type=_type, - description=desc - ) - obj.save() - return Response({'status':200}) - - -class MessinfoApi(APIView): - def get(self, request): - messinfo_obj = Messinfo.objects.all(); - serialized_obj = MessinfoSerializer(messinfo_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - mess_option = data['mess_option'] - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - obj = Messinfo( - student_id = student, - mess_option =mess_option, - ) - obj.save() - return Response({'status':200}) - -class Mess_regApi(APIView): - def get(self, request): - mess_reg_obj = Mess_reg.objects.all(); - serialized_obj = Mess_regSerializer(mess_reg_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - sem = data['sem'] - start_reg = data['start_reg'] - end_reg= data['end_reg'] - - obj = Mess_reg( - sem = sem, - start_reg = start_reg, - end_reg = end_reg - ) - obj.save() - return Response({'status':200}) - -class MessBillBaseApi(APIView): - def get(self, request): - messBillBase_obj = MessBillBase.objects.all(); - serialized_obj = MessBillBaseSerializer(messBillBase_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - bill_amount = data['bill_amount'] - # timestamp = data['timestamp'] - - obj = MessBillBase( - bill_amount = bill_amount, - # timestamp = timestamp, - ) - obj.save() - return Response({'status':200}) - -class Monthly_billApi(APIView): - def get(self, request): - monthly_bill_obj = Monthly_bill.objects.all(); - serialized_obj = Monthly_billSerializer(monthly_bill_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - month = data['month'] - year = data['year'] - amount = data['amount'] - rebate_count = data['rebate_count'] - rebate_amount = data['rebate_amount'] - #nonveg_total_bill = data['nonveg_total_bill'] - paid = data['paid'] - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - - obj = Monthly_bill( - student_id = student, - month = month, - year = year, - amount = amount, - rebate_count = rebate_count, - rebate_amount = rebate_amount, - # nonveg_total_bill = nonveg_total_bill, - paid = paid - ) - obj.save() - return Response({'status':200}) - -class PaymentsApi(APIView): - def get(self, request): - payments_obj = Payments.objects.all(); - serialized_obj = PaymentsSerializer(payments_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - # sem = data['sem'] - # year = data['year'] - amount_paid = data['amount_paid'] - - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - - obj = Payments( - student_id = student, - # sem = sem, - # year = year, - amount_paid = amount_paid, - ) - obj.save() - return Response({'status':200}) -class MenuApi(APIView): - def get(self, request): - menu_obj = Menu.objects.all(); - serialized_obj = MenuSerializer(menu_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - mess_option = data['mess_option'] - meal_time = data['meal_time'] - dish = data['dish'] - - - obj = Menu( - mess_option = mess_option, - meal_time = meal_time, - dish = dish, - ) - obj.save() - return Response({'status':200}) -class RebateApi(APIView): - def get(self, request): - rebate_obj = Rebate.objects.all(); - serialized_obj = RebateSerializer(rebate_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - # student_id = data['mess_option'] - start_date = data['start_date'] - end_date = data['end_date'] - purpose = data['purpose'] - status = data['status'] - app_date = data['app_date'] - leave_type = data['leave_type'] - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - - obj = Rebate( - student_id = student, - leave_type = leave_type, - app_date = app_date, - status = status, - purpose = purpose, - end_date= end_date, - start_date = start_date - ) - obj.save() - return Response({'status':200}) -class Vacation_foodApi(APIView): - def get(self, request): - vacation_food_obj = Vacation_food.objects.all(); - serialized_obj = Vacation_foodSerializer(vacation_food_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - start_date = data['start_date'] - end_date = data['end_date'] - purpose = data['purpose'] - status = data['status'] - app_date = data['app_date'] - - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - - obj = Vacation_food( - student_id = student, - app_date = app_date, - status = status, - purpose = purpose, - end_date= end_date, - start_date = start_date - ) - obj.save() - return Response({'status':200}) - -class Nonveg_menuApi(APIView): - def get(self, request): - nonveg_menu_obj = Nonveg_menu.objects.all(); - serialized_obj = Nonveg_menuSerializer(nonveg_menu_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - dish= data['dish'] - price = data['price'] - order_interval = data['order_interval'] - - - obj = Nonveg_menu( - dish = dish, - price = price, - order_interval = order_interval, - ) - obj.save() - return Response({'status':200}) - -class Nonveg_dataApi(APIView): - def get(self, request): - nonveg_data_obj = Nonveg_data.objects.all(); - serialized_obj = Nonveg_dataSerializer(nonveg_data_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - dish= data['dish'] - order_date = data['order_date'] - app_date = data['app_date'] - order_interval = data['order_interval'] - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - dish_obj = Nonveg_menu.objects.get(dish=dish) - - obj = Nonveg_data( - student_id = student, - order_date = order_date, - app_date = app_date, - dish = dish_obj, - order_interval = order_interval, - ) - obj.save() - return Response({'status':200}) - -class Special_requestApi(APIView): - def get(self, request): - special_request_obj = Special_request.objects.all(); - serialized_obj = Special_requestSerializer(special_request_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - - def post(self, request): - data = request.data - - - start_date = data['start_date'] - end_date = data['end_date'] - status = data['status'] - app_date = data['app_date'] - request_= data['request'] - item1 = data['item1'] - item2 = data['item2'] - - - - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - obj = Special_request( - student_id = student, - app_date = app_date, - status = status, - item1 = item1, - item2 = item2, - end_date= end_date, - start_date = start_date, - request = request_ - ) - obj.save() - return Response({'status':200}) - -class Mess_meetingApi(APIView): - def get(self, request): - mess_meeting_obj = Mess_meeting.objects.all(); - serialized_obj = Mess_meetingSerializer(mess_meeting_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - meet_date = data['meet_date'] - agenda = data['agenda'] - venue = data['venue'] - meeting_time = data['meeting_time'] - - obj = Mess_meeting( - meet_date = meet_date, - meeting_time = meeting_time, - agenda = agenda, - venue = venue, - ) - obj.save() - return Response({'status':200}) - -class Mess_minutesApi(APIView): - def get(self, request): - mess_minutes_obj = Mess_minutes.objects.all(); - serialized_obj = Mess_minutesSerializer(mess_minutes_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - - # meeting_date = data['meeting_date'] - mess_minutes = data['mess_minutes'] - meeting_date_obj = Mess_meeting.objects.get(meet_date=meeting_date) - - obj = Mess_minutes( - # meeting_date = meeting_date_obj, - mess_minutes = mess_minutes, - ) - obj.save() - return Response({'status':200}) - -class Menu_change_requestApi(APIView): - def get(self, request): - menu_change_request_obj = Menu_change_request.objects.all(); - serialized_obj = Menu_change_requestSerializer(menu_change_request_obj, many=True) - return Response({'status':200, 'payload':serialized_obj.data}) - - def post(self, request): - data = request.data - dish = data['dish'] - reason = data['reason'] - status = data['status'] - app_date = data['app_date'] - request_ = data['request'] - - - dish_obj = Menu.objects.get(dish=dish) - username = get_object_or_404(User,username=request.user.username) - idd = ExtraInfo.objects.get(user=username) - student = Student.objects.get(id=idd.id) - - obj = Menu_change_request( - student_id = student, - app_date = app_date, - status = status, - reason = reason, - request = request_, - dish = dish_obj - ) - obj.save() - return Response({'status':200}) - -class Get_Filtered_Students(APIView): - - def post(self,request): - type = request.data['type'] - if(type=='filter'): - reg_main = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all() - status=request.data['status'] - program=request.data['program'] - mess_option=request.data['mess_option'] - - if(status!='all'): - - reg_main=reg_main.filter(current_mess_status=status) - - if(program!='all'): - reg_main=reg_main.filter(program=program) - - if(mess_option!='all'): - - reg_main=reg_main.filter(mess_option=mess_option) - - serialized_obj = GetFilteredSerialzer(reg_main,many=True) - return Response({'payload':serialized_obj.data}) - - elif(type=='search'): - student = request.data['student_id'] - student = str(student).upper() - try: - reg_main = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) - serialized_obj = GetFilteredSerialzer(reg_main) - return Response({'payload':serialized_obj.data}) - except: - response = JsonResponse({"error": "student does not exist"}) - response.status_code = 404 - return response - -class Get_Reg_Records(APIView): - - def post(self,request): - student = request.data['student_id'] - reg_record = Reg_records.objects.filter(student_id=student) - - serialized_obj = reg_recordSerialzer(reg_record,many=True) - return Response({'payload':serialized_obj.data}) - - -class Get_Student_bill(APIView): - - def post(self,request): - student = request.data['student_id'] - bill_details = Monthly_bill.objects.filter(student_id=student) - - serialized_obj = Monthly_billSerializer(bill_details,many=True) - return Response({'payload':serialized_obj.data}) - - -class Get_Student_Payments(APIView): - - def post(self,request): - student = request.data['student_id'] - payment_details = Payments.objects.filter(student_id=student) - - serialized_obj = PaymentsSerializer(payment_details,many=True) - return Response({'payload':serialized_obj.data}) - -class Get_Student_Details(APIView): - - def post(self,request): - student = request.data['student_id'] - bill_details = Monthly_bill.objects.filter(student_id=student) - payment_details = Payments.objects.filter(student_id=student) - reg_record = Reg_records.objects.filter(student_id=student) - payment_serialized_obj = PaymentsSerializer(payment_details,many=True) - bill_serialized_obj = Monthly_billSerializer(bill_details,many=True) - reg_record_serialized_obj = reg_recordSerialzer(reg_record,many=True) - reg_main = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) - serialized_obj = GetFilteredSerialzer(reg_main) - data={'payment':payment_serialized_obj.data,'bill':bill_serialized_obj.data,'reg_records':reg_record_serialized_obj.data,'student_details':serialized_obj.data} - return Response({'payload':data}) \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/forms.py b/FusionIIIT/applications/central_mess/forms.py index ceecf4400..ac52d5d3a 100644 --- a/FusionIIIT/applications/central_mess/forms.py +++ b/FusionIIIT/applications/central_mess/forms.py @@ -1,8 +1,6 @@ from django import forms from .models import Mess_minutes -from .models import Registration_Request -from .models import Semdates class MinuteForm(forms.ModelForm): @@ -15,34 +13,4 @@ class MessInfoForm(forms.Form, ): ('mess1', 'Veg Mess'), ('mess2', 'Non Veg Mess'), ] - mess_option = forms.CharField(label='Mess Option', widget=forms.Select( - choices=MESS_CHOICES, attrs={'style': 'border-radius:1rem;padding:7px;'})) - - - -class RegistrationRequest(forms.ModelForm): - - class Meta: - model = Registration_Request - fields = ('Txn_no','amount','img','start_date','payment_date') - - widgets={ - 'Txn_no':forms.TextInput(attrs={'class':'ui big input','style':'border-radius:4px', 'initial':'590'}), - 'amount':forms.TextInput(attrs={'class':'ui big input'}), - 'img':forms.FileInput(attrs={'class':'ui big input'}), - 'start_date':forms.widgets.DateInput(attrs={'type':'date'}), - 'payment_date':forms.widgets.DateInput(attrs={'type':'date'}), - } - - -class UpdateBalanceRequest(forms.ModelForm): - - class Meta: - model = Registration_Request - fields = ('Txn_no','amount','img') - - widgets={ - 'Txn_no':forms.TextInput(attrs={'class':'ui big input','style':'border-radius:4px'}), - 'amount':forms.TextInput(attrs={'class':'ui big input'}), - 'img':forms.FileInput(attrs={'class':'ui big input'}), - } \ No newline at end of file + mess_option = forms.CharField(label='Mess Option', widget=forms.Select(choices=MESS_CHOICES)) \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/handlers.py b/FusionIIIT/applications/central_mess/handlers.py index 47e840810..e469e1286 100644 --- a/FusionIIIT/applications/central_mess/handlers.py +++ b/FusionIIIT/applications/central_mess/handlers.py @@ -16,7 +16,8 @@ from applications.globals.models import ExtraInfo, HoldsDesignation, Designation from .models import (Feedback, Menu, Menu_change_request, Mess_meeting, Mess_minutes, Mess_reg, Messinfo, Monthly_bill, - Payments, Rebate,Special_request, Vacation_food, MessBillBase,Registration_Request, Reg_main, Reg_records ,Deregistration_Request, Semdates) + Nonveg_data, Nonveg_menu, Payments, Rebate, + Special_request, Vacation_food, MessBillBase) from notification.views import central_mess_notif @@ -24,49 +25,40 @@ year_g = today_g.year tomorrow_g = today_g + timedelta(days=1) first_day_of_this_month = date.today().replace(day=1) -this_month = first_day_of_this_month.strftime('%B') -this_year = first_day_of_this_month.year last_day_prev_month = first_day_of_this_month - timedelta(days=1) previous_month = last_day_prev_month.strftime('%B') previous_month_year = last_day_prev_month.year first_day_of_next_month = (date.today().replace(day=28) + timedelta(days=4)).replace(day=1) last_day_of_this_month = first_day_of_next_month - timedelta(days=1) next_month = first_day_of_next_month.month -first_day_prev_month = last_day_prev_month.replace(day=1) - -def current_month(): - return date.today().strftime("%B") - - -def current_year(): - return date.today().strftime("%Y") - -# def add_nonveg_order(request, student): -# """ -# This function is to place non veg orders -# :param request: -# user: Current user -# order_interval: Time of the day for which order is placed eg breakfast/lunch/dinner -# :param student: student placing the order -# :variables: -# extra_info: Extra information about the current user. From model ExtraInfo -# student: Student information about the current user -# student_mess: Mess choices of the student -# dish_request: Predefined dish available -# nonveg_object: Object of Nonveg_data -# :return: -# """ -# try: -# dish_request = Nonveg_menu.objects.get(dish=request.POST.get("dish")) -# order_interval = request.POST.get("interval") -# order_date = tomorrow_g -# nonveg_object = Nonveg_data(student_id=student, order_date=order_date, -# order_interval=order_interval, dish=dish_request) -# nonveg_object.save() -# # messages.success(request, 'Your request is forwarded !!', extra_tags='successmsg') - -# except ObjectDoesNotExist: -# return HttpResponse("Seems like object does not exist") + + +def add_nonveg_order(request, student): + """ + This function is to place non veg orders + :param request: + user: Current user + order_interval: Time of the day for which order is placed eg breakfast/lunch/dinner + :param student: student placing the order + :variables: + extra_info: Extra information about the current user. From model ExtraInfo + student: Student information about the current user + student_mess: Mess choices of the student + dish_request: Predefined dish available + nonveg_object: Object of Nonveg_data + :return: + """ + try: + dish_request = Nonveg_menu.objects.get(dish=request.POST.get("dish")) + order_interval = request.POST.get("interval") + order_date = tomorrow_g + nonveg_object = Nonveg_data(student_id=student, order_date=order_date, + order_interval=order_interval, dish=dish_request) + nonveg_object.save() + # messages.success(request, 'Your request is forwarded !!', extra_tags='successmsg') + + except ObjectDoesNotExist: + return HttpResponse("Seems like object does not exist") def add_mess_feedback(request, student): @@ -84,7 +76,7 @@ def add_mess_feedback(request, student): data: to record success or any errors """ date_today = datetime.now().date() - mess_optn = Reg_main.objects.get(student_id=student) + mess_optn = Messinfo.objects.get(student_id=student) description = request.POST.get('description') feedback_type = request.POST.get('feedback_type') feedback_object = Feedback(student_id=student, fdate=date_today, @@ -125,7 +117,7 @@ def add_vacation_food_request(request, student): } return data - vacation_check = Vacation_food.objects.filter(student_id=student).prefetch_related('student_id','student_id__id','student_id__id__user','student_id__id__department') + vacation_check = Vacation_food.objects.filter(student_id =student) date_format = "%Y-%m-%d" b = datetime.strptime(str(start_date), date_format) @@ -163,10 +155,11 @@ def add_menu_change_request(request, student): :return: """ try: - - dishID =request.POST['dish']; - dish=Menu.objects.get(id=dishID) + print("inside add_menu") + dish = Menu.objects.get(dish=request.POST.get("dish")) + print(dish, "-------------------------------------------------------------------") new_dish = request.POST.get("newdish") + print(new_dish) reason = request.POST.get("reason") # menu_object = Menu_change_request(dish=dish, request=new_dish, reason=reason) menu_object = Menu_change_request(dish=dish, student_id=student, request=new_dish, reason=reason) @@ -179,6 +172,7 @@ def add_menu_change_request(request, student): data = { 'status': 0 } + print(e) return data @@ -198,15 +192,16 @@ def handle_menu_change_response(request): ap_id = request.POST.get('idm') user = request.user stat = request.POST['status'] - application = Menu_change_request.objects.get(id=ap_id) + application = Menu_change_request.objects.get(pk=ap_id) # student = application.student_id # receiver = User.objects.get(username=student) if stat == '2': application.status = 2 - obj = Menu.objects.get(Q(meal_time=application.dish.meal_time) & Q(mess_option=application.dish.mess_option)) + meal = application.dish + obj = Menu.objects.get(dish=meal.dish) obj.dish = application.request obj.save() - data = { + data = { 'status': '2', } # central_mess_notif(user, receiver, 'menu_change_accepted') @@ -339,9 +334,9 @@ def add_leave_request(request, student): } return data - rebate_check = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student, status__in=['1', '2']) - - + rebates = Rebate.objects.filter(student_id=student) + rebate_check = rebates.filter(Q(status='1') | Q(status='2')) + for r in rebate_check: a = datetime.strptime(str(r.start_date), date_format) c = datetime.strptime(str(r.end_date), date_format) @@ -378,8 +373,8 @@ def add_mess_meeting_invitation(request): venue = request.POST['venue'] agenda = request.POST['agenda'] time = request.POST['time'] - members_mess = HoldsDesignation.objects.select_related().filter(Q(designation__name__contains='mess_convener') - | Q(designation__name__contains='mess_committee')|Q(designation__name='mess_manager') + members_mess = HoldsDesignation.objects.filter(Q(designation__name__contains='mess_convener') + | Q(designation__name__contains='mess_committee')|Q(designation__name='mess_manager') | Q(designation__name='mess_warden')) date_today = str(today_g.date()) if date <= date_today: @@ -403,49 +398,7 @@ def add_mess_meeting_invitation(request): } return data -def rebateCountFn(start_date, end_date, student_id): - ''' - This function is used to store the rebate_count in generte bill table and in what month that rebate has been issued. - ''' - start_date_month = start_date.strftime('%B') - start_date_year = start_date.year - end_date_month = end_date.strftime('%B') - date_format = "%Y-%m-%d" - begin_day = datetime.strptime(str(start_date), date_format) - end_day = datetime.strptime(str(end_date), date_format) - rebate_count_days = 0 - rebate_count_days_next_month = 0 - if start_date_month != end_date_month: - last_day_day = int(last_day_of_this_month.day) - begin_day_day = int(begin_day.day) - end_day_day = int(end_day.day) - first_day_day = int(first_day_of_next_month.day) - rebate_count_days = abs(last_day_day-begin_day_day) + 1 - rebate_count_days_next_month = abs(end_day_day-first_day_day)+1 - else: - rebate_count_days = abs((end_day - begin_day).days) + 1 - - #### Storing the rebate count days into the monthly bill table so it can be used while bill generation. - - try: - existing_student = Monthly_bill.objects.get(student_id=student_id, month=start_date_month, year=start_date_year) - new_rebate_count = existing_student.rebate_count + rebate_count_days - existing_student.rebate_count = new_rebate_count - existing_student.save() - if(rebate_count_days_next_month != 0): - new_student = Monthly_bill.objects.create(student_id=student_id, month=end_date_month, year=start_date_year, rebate_count=rebate_count_days_next_month) - new_student.save() - except: - new_student = Monthly_bill.objects.create(student_id=student_id, month=start_date_month, year=start_date_year, rebate_count=rebate_count_days) - new_student.save() - if(rebate_count_days_next_month != 0): - new_student = Monthly_bill.objects.create(student_id=student_id, month=end_date_month, year=start_date_year, rebate_count=rebate_count_days_next_month) - new_student.save() - - - - - + def handle_rebate_response(request): """ This function is to respond to rebate requests @@ -466,12 +419,9 @@ def handle_rebate_response(request): rebate_count = abs((d - b).days) + 1 receiver = leaves.student_id.id.user action = request.POST["status"] - remark = request.POST["remark"] - leaves.rebate_remark = remark leaves.status = action leaves.save() if action == '2': - rebateCountFn(leaves.start_date, leaves.end_date, leaves.student_id) message = 'Your leave request has been accepted between dates ' + str(b.date()) + ' and ' + str(d.date()) else: message = 'Your leave request has been rejected between dates ' + str(b.date()) + ' and ' + str(d.date()) @@ -520,8 +470,8 @@ def add_special_food_request(request, student): return data spfood_obj = Special_request(student_id=student, start_date=fr, end_date=to, item1=food1, item2=food2, request=purpose) - s_check = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student,status__in=['1', '2']).order_by('-app_date') - + requests_food = Special_request.objects.filter(student_id=student) + s_check = requests_food.filter(Q(status='1') | Q(status='2')) for r in s_check: a = datetime.strptime(str(r.start_date), date_format) @@ -586,302 +536,95 @@ def add_bill_base_amount(request): return data -def add_sem_dates(request): - """ - This function is to update the semester start and end date - :param request: - :return: - """ - start_date = request.POST.get("semstart_date") - end_date = request.POST.get("semend_date") - - if (end_date <= start_date): - data = { - 'status': 3, - 'message': "Please check the dates" - } - return data - - data = { - 'status': 1, - 'message': "Successfully updated" - } - semdate_object = Semdates(start_date=start_date, end_date=end_date) - semdate_object.save() - return data def add_mess_committee(request, roll_number): - studentHere = Student.objects.get(id=roll_number) - try: - mess = Messinfo.objects.get(student_id_id=studentHere) - if mess.mess_option == 'mess1': - designation = Designation.objects.get(name='mess_committee') - else: - designation = Designation.objects.get(name='mess_committee_mess2') - check_obj=HoldsDesignation.objects.select_related().filter(Q(user__username=studentHere) & + print("\n\n\\n\n\n\n\n") + print(roll_number) + mess = Messinfo.objects.get(student_id__id=roll_number) + print(mess) + if mess.mess_option == 'mess1': + designation = Designation.objects.get(name='mess_committee_mess1') + else: + designation = Designation.objects.get(name='mess_committee_mess2') + # designation = Designation.objects.get(name='mess_committee') + # add_obj = HoldsDesignation.objects.filter(Q(user__username=roll_number) & Q(designation=designation)) + check_obj = HoldsDesignation.objects.filter(Q(user__username=roll_number) & (Q(designation__name__contains='mess_committee') | Q(designation__name__contains='mess_convener'))) - if check_obj: - data = { - 'status': 2, - 'message': roll_number + " is already a part of mess committee" - } - return data - else: - add_user = User.objects.get(username=roll_number) - designation_object = HoldsDesignation(user=add_user, working=add_user, designation=designation) - designation_object.save() - central_mess_notif(request.user, add_user, 'added_committee', '') - data = { - 'status': 1, - 'message': roll_number + " is added to Mess Committee" - } + if check_obj: + data = { + 'status': 2, + 'message': roll_number + " is already a part of mess committee" + } return data - except: + else: + add_user = User.objects.get(username=roll_number) + designation_object = HoldsDesignation(user=add_user, working=add_user, designation=designation) + designation_object.save() + central_mess_notif(request.user, add_user, 'added_committee', '') data = { - 'status': 0, - 'message': roll_number + " is not registered for any Mess." + 'status': 1, + 'message': roll_number + " is added to Mess Committee" } + return data -def Calculate_rebate(id, month_previous, amount_per_day): - students = Rebate.objects.filter(student_id_id=id) - print(students) - no_of_days = 0 - for student in students: - start_date_month = student.start_date.month - end_date_month = student.end_date.month - if(start_date_month == month_previous): - if(end_date_month == month_previous): - no_of_days = no_of_days + abs((student.end_date - student.start_date).days) + 1 - elif(end_date_month == today_g.month): - no_of_days = no_of_days + abs((last_day_prev_month - student.start_date).days) + 1 - else: - if(end_date_month == month_previous): - no_of_days = no_of_days + abs((student.end_date - student.start_date).days) + 1 - elif(end_date_month == today_g.month): - no_of_days = no_of_days + abs((last_day_prev_month - first_day_prev_month).days) + 1 - print(no_of_days) - rebate_amount = no_of_days*amount_per_day - return rebate_amount - - def generate_bill(): - - per_day_cost_obj = MessBillBase.objects.latest('timestamp') - per_day_cost = per_day_cost_obj.bill_amount - print(per_day_cost) - amount = int(last_day_prev_month.day) * int(per_day_cost) - print(amount) - student_all = Reg_main.objects.filter(current_mess_status = "Registered") - print(student_all) + student_all = Student.objects.all() + month_t = datetime.now().month - 1 + month_g = last_day_prev_month.month + first_day_prev_month = last_day_prev_month.replace(day=1) + # previous_month = month_t.strftime("%B") + amount_c = MessBillBase.objects.latest('timestamp') for student in student_all: - student_id = student.student_id - rem_balance = student.balance - try: - monthly_bill_obj = Monthly_bill.objects.get(student_id=student_id, month=previous_month, year=previous_month_year) - rebate_count_count = monthly_bill_obj.rebate_count - rebate_amount = int(rebate_count_count)*int(per_day_cost) - monthly_bill_obj.rebate_amount = rebate_amount - total_bill = amount - rebate_amount - monthly_bill_obj.total_bill = total_bill - rem_balance = rem_balance - total_bill - student.balance = rem_balance - monthly_bill_obj.amount = amount - monthly_bill_obj.save() - except: - new_monthly_bill_obj = Monthly_bill(student_id=student_id, month=previous_month, year=previous_month_year, amount=amount, total_bill=amount) - rem_balance = rem_balance - amount - student.balance = rem_balance - new_monthly_bill_obj.save() - if(student.balance <= 0): - student.current_mess_status = 'Deregistered' - student.save() - - - - -def handle_reg_response(request): - """ - This function is to respond to registeration requests - @variables: - id: id of the registeration request - reg_req: Object corresponding to the id of the reg request - @return: - data: returns the status of the application - """ - - id = request.POST['id_reg'] - status = request.POST['status'] - remark = request.POST['remark'] - reg_req = Registration_Request.objects.get(pk=id) - start_date = reg_req.start_date - payment_date = reg_req.payment_date - student = reg_req.student_id - reg_req.status = status - reg_req.registration_remark=remark - try: - sem_end_date = Semdates.objects.latest('start_date').end_date - except: - sem_end_date= None - reg_req.save() - message='' - if(status=='accept'): - amount = reg_req.amount - mess = request.POST['mess_no'] - try : - reg_main = Reg_main.objects.get(student_id=student) - if(start_date == date.today()): - reg_main.current_mess_status="Registered" - else: - reg_main.current_mess_status = "Deregistered" - reg_main.mess_option=mess - reg_main.balance=reg_main.balance+amount - reg_main.save() - except: - program = student.programme - if(start_date == date.today()): - mess_status = "Registered" - else: - mess_status = "Deregistered" - new_reg = Reg_main(student_id=student,program=program,current_mess_status=mess_status,balance=amount,mess_option=mess) - new_reg.save() - new_reg_record = Reg_records(student_id=student, start_date=start_date, end_date=sem_end_date) - new_reg_record.save() - - new_payment_record = Payments(student_id = student, amount_paid = amount, payment_date=payment_date, payment_month=current_month(), payment_year=current_year()) - new_payment_record.save() - message="Your registeration request has been accepted" - else: - message="Your registeration request has been rejected" - - - - - receiver = reg_req.student_id.id.user - central_mess_notif(request.user, receiver, 'leave_request', message) - data = { - 'message': 'success' - } - return data - - -def handle_dreg_response(request): - """ - This function is to respond to de registeration requests - @variables: - id: id of the registeration request - dreg_req: Object corresponding to the id of the de reg request - @return: - data: returns the status of the application - """ - - id = request.POST['id_reg'] - status = request.POST['status'] - remark = request.POST['remark'] - dreg_req = Deregistration_Request.objects.get(pk=id) - end_date = dreg_req.end_date - student = dreg_req.student_id - dreg_req.status = status - dreg_req.deregistration_remark=remark - dreg_req.save() - message='' - if(status=='accept'): - try : - reg_main = Reg_main.objects.get(student_id=student) - if(end_date == date.today()): - reg_main.current_mess_status="Deregistered" - reg_record_obj = Reg_records.objects.filter(student_id = student).latest('start_date') - reg_record_obj.end_date = end_date - reg_record_obj.save() - reg_main.save() - except: - data = {'message': 'Student does not exist in database'} - return data - - message="Your De-registeration request has been accepted" - else: - message="Your De-registeration request has been rejected" - - receiver = dreg_req.student_id.id.user - central_mess_notif(request.user, receiver, 'leave_request', message) - data = { - 'message': 'success' - } - return data + nonveg_total_bill=0 + rebate_count = 0 + total = 0 + nonveg_data = Nonveg_data.objects.filter(student_id=student) + rebates = Rebate.objects.filter(student_id=student) + for order in nonveg_data: + if order.order_date.strftime("%B") == previous_month: + nonveg_total_bill = nonveg_total_bill + order.dish.price + for r in rebates: + if r.status == '2': + if r.start_date.month == month_g: + if r.end_date.month == today_g: + rebate_count = rebate_count + abs((last_day_prev_month - r.start_date).days) + 1 + else: + rebate_count = rebate_count + abs((r.end_date - r.start_date).days) + 1 + elif r.end_date.month == month_g: + rebate_count = rebate_count + abs((r.end_date - first_day_prev_month).days) + 1 + else: + rebate_count = 0 + rebate_amount = rebate_count*amount_c.bill_amount/30 + total = amount_c.bill_amount + nonveg_total_bill - rebate_amount + bill_object = Monthly_bill(student_id=student, + month=previous_month, + year = previous_month_year, + amount=amount_c.bill_amount, + rebate_count=rebate_count, + rebate_amount=rebate_amount, + nonveg_total_bill=nonveg_total_bill, + total_bill=total) + if Monthly_bill.objects.filter(student_id=student, + month=previous_month, + year = previous_month_year, + total_bill=total): + print("exists") + elif Monthly_bill.objects.filter(student_id=student, + month=previous_month, + year = previous_month_year): + Monthly_bill.objects.filter(student_id=student, + month=previous_month, + year=previous_month_year).update(student_id=student, + month=previous_month, + amount=amount_c.bill_amount, + rebate_count=rebate_count, + rebate_amount=rebate_amount, + nonveg_total_bill=nonveg_total_bill, + total_bill=total) + # bill_object.update() + else: + bill_object.save() -def update_month_bill(request): - """ - This function is used to update the monthly bill of student by caretaker if any discrepancy arises. - """ - student = str(request.POST.get("rollNo")).upper() - studentHere = Student.objects.get(id = student) - rebate_count = int(request.POST.get("RebateCount")) - print(rebate_count) - rebate_amount = int(request.POST.get("RebateAmount")) - print(rebate_amount) - new_amount = int(request.POST.get("new_amount")) - month = request.POST.get("Month") - year = int(request.POST.get("Year")) - bill_base_amount = int(MessBillBase.objects.latest('timestamp').bill_amount) - fixed_amount_per_month = int(bill_base_amount)*int(30) - - reg_main_obj = Reg_main.objects.get(student_id=student) - curr_balance = reg_main_obj.balance - try: - existing_monthly_bill_object = Monthly_bill.objects.get(student_id = studentHere, month=month, year=year) - previous_total_bill = existing_monthly_bill_object.total_bill - curr_balance = curr_balance + previous_total_bill - existing_monthly_bill_object.total_bill = new_amount - curr_balance = curr_balance - int(new_amount) - reg_main_obj.balance = curr_balance - reg_main_obj.save() - existing_monthly_bill_object.save() - except: - new_monthly_bill_obj = Monthly_bill(student_id = studentHere, rebate_amount=rebate_amount, rebate_count=rebate_count, month=month, year= year, total_bill = new_amount, amount=fixed_amount_per_month) - curr_balance = curr_balance - new_amount - reg_main_obj.balance = curr_balance - reg_main_obj.save() - new_monthly_bill_obj.save() - data = { - 'message': 'success' - } - return data -def handle_add_reg(request): - start_date = request.POST['start_date'] - amount = int(request.POST['amount']) - studentID = str(request.POST['input_roll']).upper() - student = Student.objects.select_related('id','id__user','id__department').get(id=studentID) - payment_date = request.POST['payment_date'] - try: - latest=Semdates.objects.latest('start_date') - latest_end_date = latest.end_date - except: - latest_end_date= None - - mess=request.POST['mess_option_form'] - try : - reg_main = Reg_main.objects.get(student_id=studentID) - if(start_date==str(date.today())): - reg_main.current_mess_status='Registered' - reg_main.mess_option=mess - reg_main.balance=reg_main.balance+amount - reg_main.save() - except: - program = student.programme - if(start_date==str(date.today())): - mess_status = "Registered" - else: - mess_status = "Deregistered" - new_reg = Reg_main(student_id=student,program=program,current_mess_status=mess_status,balance=amount,mess_option=mess) - new_reg.save() - - new_reg_record = Reg_records(student_id=student, start_date=start_date,end_date = latest_end_date) - new_reg_record.save() - - new_payment_record = Payments(student_id = student, amount_paid = amount, payment_date=payment_date, payment_month=current_month(), payment_year=current_year()) - new_payment_record.save() - message="Your registeration request has been accepted" - - diff --git a/FusionIIIT/applications/central_mess/migrations/0001_initial.py b/FusionIIIT/applications/central_mess/migrations/0001_initial.py index c197e0231..2a5bce41c 100644 --- a/FusionIIIT/applications/central_mess/migrations/0001_initial.py +++ b/FusionIIIT/applications/central_mess/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import applications.central_mess.models import datetime @@ -19,7 +19,7 @@ class Migration(migrations.Migration): name='Menu', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('mess_option', models.CharField(choices=[('mess1', 'Mess1'), ('mess2', 'Mess2')], default='mess2', max_length=20)), + ('mess_option', models.CharField(choices=[('mess1', 'Veg_mess'), ('mess2', 'Non_veg_mess')], default='mess2', max_length=20)), ('meal_time', models.CharField(choices=[('MB', 'Monday Breakfast'), ('ML', 'Monday Lunch'), ('MD', 'Monday Dinner'), ('TB', 'Tuesday Breakfast'), ('TL', 'Tuesday Lunch'), ('TD', 'Tuesday Dinner'), ('WB', 'Wednesday Breakfast'), ('WL', 'Wednesday Lunch'), ('WD', 'Wednesday Dinner'), ('THB', 'Thursday Breakfast'), ('THL', 'Thursday Lunch'), ('THD', 'Thursday Dinner'), ('FB', 'Friday Breakfast'), ('FL', 'Friday Lunch'), ('FD', 'Friday Dinner'), ('SB', 'Saturday Breakfast'), ('SL', 'Saturday Lunch'), ('SD', 'Saturday Dinner'), ('SUB', 'Sunday Breakfast'), ('SUL', 'Sunday Lunch'), ('SUD', 'Sunday Dinner')], max_length=20)), ('dish', models.CharField(max_length=200)), ], @@ -51,6 +51,15 @@ class Migration(migrations.Migration): ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), + migrations.CreateModel( + name='Nonveg_menu', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('dish', models.CharField(max_length=20)), + ('price', models.IntegerField()), + ('order_interval', models.CharField(choices=[('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner')], default='Breakfast', max_length=20)), + ], + ), migrations.CreateModel( name='Vacation_food', fields=[ @@ -71,68 +80,33 @@ class Migration(migrations.Migration): ('end_date', models.DateField(default=datetime.date.today)), ('request', models.TextField()), ('status', models.CharField(choices=[('0', 'rejected'), ('1', 'pending'), ('2', 'accepted')], default='1', max_length=20)), - ('item1', models.CharField(choices=[('dal_chawal', 'Dal Chawal'), ('khicdi', 'Khicdi'), ('tomato_soup', 'Tomato Soup')], default='dal_chawal', max_length=50)), - ('item2', models.CharField(choices=[('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('dinner', 'Dinner')], default='breakfast', max_length=50)), + ('item1', models.CharField(max_length=50)), + ('item2', models.CharField(max_length=50)), ('app_date', models.DateField(default=datetime.date.today)), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], ), migrations.CreateModel( - name='Semdates', + name='Rebate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start_date', models.DateField(default=datetime.date.today)), ('end_date', models.DateField(default=datetime.date.today)), - ], - options={ - 'unique_together': {('start_date', 'end_date')}, - }, - ), - migrations.CreateModel( - name='Registration_Request', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('Txn_no', models.CharField(max_length=20)), - ('img', models.ImageField(default=None, upload_to='images/')), - ('amount', models.IntegerField(default=0)), - ('status', models.CharField(default='pending', max_length=10)), - ('registration_remark', models.CharField(default='NA', max_length=50)), - ('start_date', models.DateField(default=None, null=True)), - ('payment_date', models.DateField(default=None, null=True)), - ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Reg_records', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('start_date', models.DateField(default=datetime.date.today)), - ('end_date', models.DateField(default=None, null=True)), - ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Reg_main', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('program', models.CharField(max_length=10)), - ('current_mess_status', models.CharField(default='Deregistered', max_length=20)), - ('balance', models.IntegerField(default=0)), - ('mess_option', models.CharField(default='mess2', max_length=20)), + ('purpose', models.TextField()), + ('status', models.CharField(choices=[('0', 'rejected'), ('1', 'pending'), ('2', 'accepted')], default='1', max_length=20)), + ('app_date', models.DateField(default=datetime.date.today)), + ('leave_type', models.CharField(choices=[('casual', 'Casual'), ('vacation', 'Vacation')], default='casual', max_length=20)), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], ), migrations.CreateModel( - name='Rebate', + name='Nonveg_data', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('start_date', models.DateField(default=datetime.date.today)), - ('end_date', models.DateField(default=datetime.date.today)), - ('purpose', models.TextField()), - ('status', models.CharField(choices=[('0', 'rejected'), ('1', 'pending'), ('2', 'accepted')], default='1', max_length=20)), + ('order_date', models.DateField(default=datetime.date.today)), + ('order_interval', models.CharField(choices=[('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner')], default='Breakfast', max_length=20)), ('app_date', models.DateField(default=datetime.date.today)), - ('leave_type', models.CharField(choices=[('casual', 'Casual'), ('vacation', 'Vacation')], default='casual', max_length=20)), - ('rebate_remark', models.CharField(default='NA', max_length=50)), + ('dish', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='central_mess.nonveg_menu')), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], ), @@ -160,22 +134,11 @@ class Migration(migrations.Migration): name='Feedback', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('mess', models.CharField(choices=[('mess1', 'Mess1'), ('mess2', 'Mess2')], default='mess1', max_length=10)), + ('mess', models.CharField(choices=[('mess1', 'Veg_mess'), ('mess2', 'Non_veg_mess')], default='mess1', max_length=10)), ('mess_rating', models.PositiveSmallIntegerField(default='5')), ('fdate', models.DateField(default=datetime.date.today)), ('description', models.TextField()), ('feedback_type', models.CharField(choices=[('maintenance', 'Maintenance'), ('food', 'Food'), ('cleanliness', 'Cleanliness & Hygiene'), ('others', 'Others')], max_length=20)), - ('feedback_remark', models.CharField(default='NA', max_length=50)), - ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Deregistration_Request', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('status', models.CharField(default='pending', max_length=10)), - ('deregistration_remark', models.CharField(default='NA', max_length=50)), - ('end_date', models.DateField(default=None, null=True)), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], ), @@ -183,14 +146,13 @@ class Migration(migrations.Migration): name='Payments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('sem', models.IntegerField()), + ('year', models.IntegerField(default=applications.central_mess.models.current_year)), ('amount_paid', models.IntegerField(default=0)), - ('payment_month', models.CharField(default=applications.central_mess.models.current_month, max_length=20)), - ('payment_year', models.IntegerField(default=applications.central_mess.models.current_year)), - ('payment_date', models.DateField(default=datetime.date(2024, 4, 15))), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], options={ - 'unique_together': {('student_id', 'payment_date')}, + 'unique_together': {('student_id', 'sem', 'year')}, }, ), migrations.CreateModel( @@ -202,8 +164,8 @@ class Migration(migrations.Migration): ('amount', models.IntegerField(default=0)), ('rebate_count', models.IntegerField(default=0)), ('rebate_amount', models.IntegerField(default=0)), + ('nonveg_total_bill', models.IntegerField(default=0)), ('total_bill', models.IntegerField(default=0)), - ('paid', models.BooleanField(default=False)), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], options={ @@ -214,7 +176,7 @@ class Migration(migrations.Migration): name='Messinfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('mess_option', models.CharField(choices=[('mess1', 'Mess1'), ('mess2', 'Mess2')], default='mess2', max_length=20)), + ('mess_option', models.CharField(choices=[('mess1', 'Veg_mess'), ('mess2', 'Non_veg_mess')], default='mess2', max_length=20)), ('student_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], options={ diff --git a/FusionIIIT/applications/central_mess/models.py b/FusionIIIT/applications/central_mess/models.py index cd5427736..cdd4de8a3 100644 --- a/FusionIIIT/applications/central_mess/models.py +++ b/FusionIIIT/applications/central_mess/models.py @@ -8,18 +8,6 @@ ('vacation', 'Vacation') ) -SPECIAL_FOOD = ( - ('dal_chawal', 'Dal Chawal'), - ('khicdi', 'Khicdi'), - ('tomato_soup','Tomato Soup') -) - -MEAL_TIME = ( - ('breakfast', 'Breakfast'), - ('lunch', 'Lunch'), - ('dinner','Dinner') -) - MEAL = ( ('MB', 'Monday Breakfast'), ('ML', 'Monday Lunch'), @@ -95,8 +83,8 @@ ) MESS_OPTION = ( - ('mess1', 'Mess1'), - ('mess2', 'Mess2') + ('mess1', 'Veg_mess'), + ('mess2', 'Non_veg_mess') ) @@ -138,9 +126,8 @@ class Monthly_bill(models.Model): amount = models.IntegerField(default=0) rebate_count = models.IntegerField(default=0) rebate_amount = models.IntegerField(default=0) - # nonveg_total_bill = models.IntegerField(default=0) + nonveg_total_bill = models.IntegerField(default=0) total_bill = models.IntegerField(default=0) - paid = models.BooleanField(default=False) class Meta: unique_together = (('student_id', 'month', 'year'),) @@ -151,16 +138,15 @@ def __str__(self): class Payments(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) + sem = models.IntegerField() + year = models.IntegerField(default=current_year) amount_paid = models.IntegerField(default=0) - payment_month = models.CharField(max_length=20, default=current_month) - payment_year = models.IntegerField(default = current_year) - payment_date = models.DateField(default= datetime.date.today()) class Meta: - unique_together = (('student_id', 'payment_date')) + unique_together = (('student_id', 'sem', 'year'),) def __str__(self): - return '{}'.format(self.student_id.id) + return '{} - {}'.format(self.student_id.id, self.sem) class Menu(models.Model): @@ -181,10 +167,9 @@ class Rebate(models.Model): purpose = models.TextField() status = models.CharField(max_length=20, choices=STATUS, default='1') app_date = models.DateField(default=datetime.date.today) - # TODO = remove leave type leave_type = models.CharField(choices=LEAVE_TYPE, max_length=20, default="casual") # leave_document = models.FileField(upload_to='central_mess/') - rebate_remark = models.CharField(max_length=50,default='NA') + def __str__(self): return str(self.student_id.id) @@ -201,26 +186,26 @@ def __str__(self): return str(self.student_id.id) -# class Nonveg_menu(models.Model): -# dish = models.CharField(max_length=20) -# price = models.IntegerField() -# order_interval = models.CharField(max_length=20, choices=INTERVAL, -# default='Breakfast') +class Nonveg_menu(models.Model): + dish = models.CharField(max_length=20) + price = models.IntegerField() + order_interval = models.CharField(max_length=20, choices=INTERVAL, + default='Breakfast') -# def __str__(self): -# return '{} - {}'.format(self.dish, self.price) + def __str__(self): + return '{} - {}'.format(self.dish, self.price) -# class Nonveg_data(models.Model): -# student_id = models.ForeignKey(Student, on_delete=models.CASCADE) -# order_date = models.DateField(default=datetime.date.today) -# order_interval = models.CharField(max_length=20, choices=INTERVAL, -# default='Breakfast') -# dish = models.ForeignKey(Nonveg_menu, on_delete=models.CASCADE) -# app_date = models.DateField(default=datetime.date.today) +class Nonveg_data(models.Model): + student_id = models.ForeignKey(Student, on_delete=models.CASCADE) + order_date = models.DateField(default=datetime.date.today) + order_interval = models.CharField(max_length=20, choices=INTERVAL, + default='Breakfast') + dish = models.ForeignKey(Nonveg_menu, on_delete=models.CASCADE) + app_date = models.DateField(default=datetime.date.today) -# def __str__(self): -# return str(self.student_id.id) + def __str__(self): + return str(self.student_id.id) class Special_request(models.Model): @@ -229,10 +214,9 @@ class Special_request(models.Model): end_date = models.DateField(default=datetime.date.today) request = models.TextField() status = models.CharField(max_length=20, choices=STATUS, default='1') - item1 = models.CharField(choices = SPECIAL_FOOD, max_length=50, default ='dal_chawal') - item2 = models.CharField(choices = MEAL_TIME, max_length=50, default ='breakfast') + item1 = models.CharField(max_length=50) + item2 = models.CharField(max_length=50) app_date = models.DateField(default=datetime.date.today) - # special_food = models.CharField(choices = SPECIAL_FOOD, max_length = 50) def __str__(self): return str(self.student_id.id) @@ -275,49 +259,6 @@ class Feedback(models.Model): fdate = models.DateField(default=datetime.date.today) description = models.TextField() feedback_type = models.CharField(max_length=20, choices=FEEDBACK_TYPE) - feedback_remark = models.CharField(max_length=50, default ="NA") - def __str__(self): - return str(self.student_id.id) - -class Registration_Request(models.Model): - student_id = models.ForeignKey(Student, on_delete=models.CASCADE) - Txn_no =models.CharField(max_length=20) - img = models.ImageField(upload_to='images/',default=None) - amount=models.IntegerField(default=0) - status=models.CharField(max_length=10,default='pending') - registration_remark=models.CharField(max_length=50,default='NA') - start_date=models.DateField(default=None, null=True) - # end_date=models.DateField(default=None, null=True) - payment_date= models.DateField(default=None, null=True) - def __str__(self): - return str(self.student_id.id) - -class Reg_main(models.Model): - student_id = models.ForeignKey(Student, on_delete=models.CASCADE) - program = models.CharField(max_length=10) - current_mess_status = models.CharField(max_length=20,default='Deregistered') - balance = models.IntegerField(default=0) - mess_option = models.CharField(max_length=20,default='mess2') def __str__(self): return str(self.student_id.id) -class Reg_records(models.Model): - student_id = models.ForeignKey(Student, on_delete=models.CASCADE) - start_date = models.DateField(default=datetime.date.today) - end_date = models.DateField(default=None, null=True) - def __str__(self): - return str(self.student_id.id) - -class Deregistration_Request(models.Model): - student_id = models.ForeignKey(Student, on_delete=models.CASCADE) - status=models.CharField(max_length=10,default='pending') - deregistration_remark=models.CharField(max_length=50,default='NA') - end_date = models.DateField(default=None, null=True) - def __str__(self): - return str(self.student_id.id) - -class Semdates(models.Model): - start_date = models.DateField(blank=False,default=datetime.date.today) - end_date = models.DateField(blank=False,default=datetime.date.today) - class Meta: - unique_together = (('start_date', 'end_date'),) diff --git a/FusionIIIT/applications/central_mess/tasks.py b/FusionIIIT/applications/central_mess/tasks.py index e27254b36..36ce85d45 100644 --- a/FusionIIIT/applications/central_mess/tasks.py +++ b/FusionIIIT/applications/central_mess/tasks.py @@ -18,154 +18,3 @@ # @periodic_task(run_every=(crontab(minute='*/1')), name="some_task", ignore_result=True) # def some_task(): # print("5") - -from datetime import date, datetime, timedelta -from django.db import transaction -from threading import Thread -from .models import * -from notification.views import central_mess_notif - -today_g = date.today() -year_g = today_g.year -tomorrow_g = today_g + timedelta(days=1) -first_day_of_this_month = date.today().replace(day=1) -this_month = first_day_of_this_month.strftime('%B') -this_year = first_day_of_this_month.year -last_day_prev_month = first_day_of_this_month - timedelta(days=1) -previous_month = last_day_prev_month.strftime('%B') -previous_month_year = last_day_prev_month.year -first_day_of_next_month = (date.today().replace(day=28) + timedelta(days=4)).replace(day=1) -last_day_of_this_month = first_day_of_next_month - timedelta(days=1) -next_month = first_day_of_next_month.month -first_day_prev_month = last_day_prev_month.replace(day=1) - - -def generate_bill(): - print(today_g) - print(this_month) - print(previous_month) - - t1 = Thread(target=generate_per_day_bill(), args=()) - t1.setDaemon(True) - t1.start() - - - - -def check_registration(student): - try: - reg_date = Reg_records.objects.filter(student_id = student).latest('start_date') - if(reg_date.start_date == today_g): - try: - reg_object = Reg_main.objects.get(student_id = student) - reg_object.current_mess_status = "Registered" - except: - pass - except: - pass - - - - -def check_deregistration(student): - try: - reg_end_date = Reg_records.objects.filter(student_id = student).latest('start_date') - if(reg_end_date.end_date == today_g): - try: - reg_object = Reg_main.objects.get(student_id = student) - reg_object.current_mess_status = "Deregistered" - reg_object.save() - except: - pass - except: - pass - - - -def check_next_month_status(per_day_cost, current_balance, amount): - rem_days = abs(int(last_day_of_this_month.day) -25) - amount_for_remain_days = int(rem_days)*int(per_day_cost) - if(current_balance - amount_for_remain_days < amount): - # TODO send notification to student for paying the fees - central_mess_notif() - - -def check_daily(student, per_day_cost): - two_day_amount = int(2)*int(per_day_cost) - reg_main_obj = Reg_main.objects.get(student_id=student) - balance = reg_main_obj.balance - if(balance <= two_day_amount): - #TODO add the notification for the student - central_mess_notif() - - reg_end_date_obj = Reg_records.objects.filter(student_id = student).latest('start_date') - reg_end_date = tomorrow_g + timedelta(days=1) - reg_end_date_obj.end_date = reg_end_date - reg_end_date_obj.save() - - -def generate_per_day_bill(): - per_day_cost_obj = MessBillBase.objects.latest('timestamp') - per_day_cost = per_day_cost_obj.bill_amount - amount = int(30) * int(per_day_cost) - # print(per_day_cost) - deregistered_students = Reg_main.objects.filter(current_mess_status = "Deregistered") - for student in deregistered_students: - student_id = student.student_id - check_registration(student_id) - - registered_students = Reg_main.objects.filter(current_mess_status = "Registered") - for student in registered_students: - student_id = student.student_id - check_deregistration(student_id) - - registered_students = Reg_main.objects.filter(current_mess_status = "Registered") - for student in registered_students: - student_id = student.student_id - current_balance = student.balance - check_daily(student_id, per_day_cost) - if(int(today_g.day) == 25): - check_next_month_status(per_day_cost, current_balance, amount) - try: - rebate_obj = Rebate.objects.get(student_id = student_id, start_date__lte = today_g, end_date__gte= today_g, status = 2) # TODO check for the correct value of accepting status - try: - monthly_bill_object = Monthly_bill.objects.get(student_id=student_id, month= this_month, year=this_year) - monthly_bill_object.rebate_count = monthly_bill_object.rebate_count + 1 - monthly_bill_object.rebate_amount = monthly_bill_object.rebate_amount + per_day_cost - monthly_bill_object.save() - except: - new_monthly_bill_object = Monthly_bill(student_id=student_id, month = this_month, year=this_year, amount= amount, total_bill = 0, rebate_count = 1, rebate_amount= per_day_cost) - new_monthly_bill_object.save() - except: - try: - monthly_bill_object = Monthly_bill.objects.get(student_id=student_id, month= this_month, year=this_year) - print(monthly_bill_object.total_bill) - monthly_bill_object.total_bill = monthly_bill_object.total_bill + per_day_cost - print(monthly_bill_object.total_bill) - - current_balance = current_balance - per_day_cost - student.balance = current_balance - monthly_bill_object.save() - except: - new_monthly_bill_object = Monthly_bill(student_id=student_id, month = this_month, year=this_year, amount= amount, total_bill = per_day_cost, rebate_count = 0, rebate_amount= 0) - current_balance = current_balance - per_day_cost - student.balance = current_balance - new_monthly_bill_object.save() - if(today_g == last_day_of_this_month and current_balance < amount): - student.current_mess_status = "Deregistered" - try: - reg_record_end_date = Reg_records.objects.filter(student_id = student_id).order_by('start_date')[0] - reg_record_end_date.end_date = first_day_of_next_month - print(reg_record_end_date) - reg_record_end_date.save() - except: - pass - student.save() - - - - - -# def my_scheduled_task(): - # Your task code goes here - # Monthly_bill.objects.all().delete() \ No newline at end of file diff --git a/FusionIIIT/applications/central_mess/urls.py b/FusionIIIT/applications/central_mess/urls.py index 031626819..f98b83047 100644 --- a/FusionIIIT/applications/central_mess/urls.py +++ b/FusionIIIT/applications/central_mess/urls.py @@ -1,6 +1,4 @@ -from django.conf.urls import url , include -from django.conf import settings -from django.conf.urls.static import static +from django.conf.urls import url from . import views @@ -10,16 +8,15 @@ url(r'^$', views.mess, name='mess'), url(r'^menurequest/', views.menu_change_request, name='menu_change_request'), - # url(r'^placeorder/', views.place_order, name='placeorder'), + url(r'^placeorder/', views.place_order, name='placeorder'), url(r'^addleavet/', views.add_leave_manager, name='addleavet'), url(r'^submitmessfeedback/', views.submit_mess_feedback, name='submitmessfeedback'), url(r'^messvacationsubmit/', views.mess_vacation_submit, name='messvacationsubmit'), url(r'^messmenusubmit/', views.submit_mess_menu, name='messmenusubmit'), url(r'^regsubmit/', views.regsubmit, name='regsubmit'), url(r'^startmessregistration/', views.start_mess_registration, name='startmessregistration'), - url(r'^closemessregistration/', views.closeRegistration, name='closemessregistration'), url(r'^menudownload/', views.MenuPDF.as_view(), name='MenuPDF'), - url(r'^menudownload1/', views.MenuPDF1.as_view(), name='MenuPDF1'), + url(r'^menudownload1/', views.MenuPDF.as_view(), name='MenuPDF1'), # url(r'^(?P[0-9]+)/response/', views.response, name='response'), url(r'^response', views.menu_change_response, name='response'), url(r'^(?P[0-9]+)/responsevacationfood/', views.response_vacation_food, name='responsevacationfood'), @@ -32,25 +29,12 @@ url(r'^rebateresponse', views.rebate_response, name='rebateresponse'), url(r'^specialrequestresponse', views.special_request_response, name='specialrequestresponse'), url(r'^updatecost', views.update_cost, name='updatecost'), - # url(r'^getnonvegorder', views.get_nonveg_order, name='getnonvegorder'), + url(r'^getnonvegorder', views.get_nonveg_order, name='getnonvegorder'), url(r'^getleave', views.get_leave_data, name='getleave'), url(r'^generatemessbill', views.generate_mess_bill, name='generatemessbill'), url(r'^acceptleave', views.accept_vacation_leaves, name='acceptleave'), url(r'^selectmessconvener', views.select_mess_convener, name='selectmessconvener'), - url(r'^billdownload', views.BillPDFStudent.as_view(), name='BillPDFStudent'), + url(r'^billdownload', views.download_bill_mess, name='billdownload'), url("info-form", views.mess_info, name="info"), - url(r'^updatemenuu', views.update_menu1, name='update_menu1'), - url(r'^updatemenu', views.update_menu2, name='update_menu2'), - url(r'^api', include('applications.central_mess.api.urls')), - - url(r'^registeredstudent', views.searchAddOrRemoveStudent, name='registeredstudent'), - url(r'^registrationRequest', views.reg_request, name='reg_request'), - # url(r'^uploadpayment', views.uploadPaymentDue, name='uploadpayment') - url(r'^respond_to_reg_req',views.respond_to_reg, name='reg_response'), - url(r'^deregistrationRequest', views.de_reg_request, name='deregistrationRequest'), - url(r'^updatesemdates', views.update_semdates, name='updatesemdates'), - url(r'^updateBill', views.update_bill, name='updateBill'), - url(r'^updatemonthlybill',views.update_bill_excel,name="update_bill"), - -]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ No newline at end of file +] diff --git a/FusionIIIT/applications/central_mess/utils.py b/FusionIIIT/applications/central_mess/utils.py index 480ef91a3..17ea7826e 100644 --- a/FusionIIIT/applications/central_mess/utils.py +++ b/FusionIIIT/applications/central_mess/utils.py @@ -10,7 +10,7 @@ def render_to_pdf(template_src, context_dict={}): html = template.render(context_dict) result = BytesIO() print(result.read) - pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) + pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None diff --git a/FusionIIIT/applications/central_mess/views.py b/FusionIIIT/applications/central_mess/views.py index 4bc7238bd..bb1498d55 100644 --- a/FusionIIIT/applications/central_mess/views.py +++ b/FusionIIIT/applications/central_mess/views.py @@ -14,30 +14,25 @@ from .utils import render_to_pdf from applications.academic_information.models import Student from applications.globals.models import ExtraInfo, HoldsDesignation, Designation -from .forms import MinuteForm, MessInfoForm,RegistrationRequest -from .tasks import * +from .forms import MinuteForm, MessInfoForm from .models import (Feedback, Menu, Menu_change_request, Mess_meeting, Mess_minutes, Mess_reg, Messinfo, Monthly_bill, - Payments, Rebate, - Special_request, Vacation_food, MessBillBase,Registration_Request, Reg_records ,Reg_main,Deregistration_Request,Semdates) -from .handlers import (add_mess_feedback, add_sem_dates, add_vacation_food_request, + Nonveg_data, Nonveg_menu, Payments, Rebate, + Special_request, Vacation_food, MessBillBase) +from .handlers import (add_nonveg_order, add_mess_feedback, add_vacation_food_request, add_menu_change_request, handle_menu_change_response, handle_vacation_food_request, add_mess_registration_time, add_leave_request, add_mess_meeting_invitation, handle_rebate_response, add_special_food_request, - handle_special_request, add_bill_base_amount, add_mess_committee, handle_reg_response, handle_dreg_response, update_month_bill,handle_add_reg) - + handle_special_request, add_bill_base_amount, add_mess_committee, generate_bill) from notification.views import central_mess_notif -import csv -import openpyxl - -today_g = datetime.datetime.now() +today_g = datetime.today() month_g = today_g.month month_g_l = today_g.strftime('%B') year_g = today_g.year tomorrow_g = today_g + timedelta(days=1) -first_day_of_this_month = date.today().replace(day=1) +first_day_of_this_month = date.today().replace(day=1) first_day_of_next_month = (date.today().replace(day=28) + timedelta(days=4)).replace(day=1) last_day_of_this_month = first_day_of_next_month - timedelta(days=1) next_month = first_day_of_next_month.month @@ -46,14 +41,13 @@ year_last_g = last_day_prev_month.year previous_month = last_day_prev_month.strftime('%B') -@login_required + def mess(request): """ This view get the access to the central mess dashboard. View all details and apply for any changes. It also shows the previous feedback submitted by the user. """ user = request.user - notifs=request.user.notifications.all() extrainfo = ExtraInfo.objects.select_related().get(user=user) current_date = date.today() holds_designations = HoldsDesignation.objects.select_related().filter(user=user) @@ -68,162 +62,140 @@ def mess(request): count6 = 0 count7 = 0 count8 = 0 - reg_form = RegistrationRequest() + if extrainfo.user_type == 'student': - # def deleteEntries(): - # Registration_Request.objects.all().delete() - # deleteEntries() student = Student.objects.select_related('id','id__user','id__department').get(id=extrainfo) vaca_obj = Vacation_food.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student) feedback_obj = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student).order_by('-fdate') + data = Nonveg_data.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').filter(student_id=student).order_by('-app_date') monthly_bill = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student) payments = Payments.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student) rebates = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student).order_by('-app_date') splrequest = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student).order_by('-app_date') - - reg_form = RegistrationRequest() - - reg_request = Registration_Request.objects.filter(student_id=student) - - de_reg_request = Deregistration_Request.objects.filter(student_id=student) - menu_data = Menu.objects.all() - try: - mess_optn = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) - y = Menu.objects.filter(mess_option=mess_optn.mess_option) - current_rem_balance = mess_optn.balance - current_mess_status = mess_optn.current_mess_status + mess_optn = Messinfo.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) except: - mess_optn={} - mess_optn={'mess_option':'no-mess'} - y = Menu.objects.filter(mess_option="mess1") - current_rem_balance = 0 - current_mess_status = 'Deregistered' - - - - reg_record = Reg_records.objects.filter(student_id=student) - monthly_bill=monthly_bill[::-1] - - # tot_am=0 - # if len(payments)>0: - # tot_am=payments[0].amount_paid - # else: - # tot_am=0 - # for x in monthly_bill: - # tot_am=tot_am+x.total_bill - # Payments.objects.create(student_id=student,amount_paid=(-tot_am)) - # payments = Payments.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student) - - - - - # for i in range(0,len(monthly_bill)): - # if(monthly_bill[i].paid): - # monthly_bill[i].due_amount=0; - # elif monthly_bill[i].total_bill+tot_am<0: - # monthly_bill[i].due_amount=(monthly_bill[i].total_bill) - # else: - # monthly_bill[i].due_amount=(-tot_am) - # tot_am+=monthly_bill[i].total_bill - # amount_due=-payments[0].amount_paid - amount_due = 0 - ## adding the batch of student if btech or bdes then value of programme is 1 or else 0, holds value of phd and mtech. + return HttpResponseRedirect("/mess/info-form") if student.programme == 'B.Tech' or student.programme == 'B.Des': programme = 1 else: programme = 0 - meeting = Mess_meeting.objects.all() - minutes = Mess_minutes.objects.all() + # newmenu = Menu_change_request.objects.all() + # meeting = Mess_meeting.objects.all() + # minutes = Mess_minutes.objects.all() + # feed = Feedback.objects.all() + # sprequest = Special_request.objects.filter(status='1') count = 0 + #variable y stores the menu items - # try: - # mess_optn = Messinfo.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) - # y = Menu.objects.filter(mess_option=mess_optn.mess_option) + y = Menu.objects.filter(mess_option=mess_optn.mess_option) + x = Nonveg_menu.objects.all() - - # bill = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(Q(student_id=student) & Q(month=month_g_l) & Q(year=year_g)) - # amount_c = MessBillBase.objects.latest('timestamp') - # rebate_count = 0 - - # for r in rebates: - # if r.status == '2': - # if r.start_date.month == month_g: - # if r.end_date.month == next_month: - # rebate_count = rebate_count + abs((last_day_of_this_month - r.start_date).days) + 1 - # else: - # rebate_count = rebate_count + abs((r.end_date - r.start_date).days) + 1 - # elif r.end_date.month == month_g: - # rebate_count = rebate_count + abs((r.end_date - first_day_of_this_month).days) + 1 - # else: - # rebate_count = 0 - # rebate_amount = rebate_count * amount_c.bill_amount / 30 - # total_bill = amount_c.bill_amount - rebate_amount - # if bill: - # bill.update(student_id = student, - # month = month_g_l, - # year = year_g, - # amount = amount_c.bill_amount, - # rebate_count = rebate_count, - # rebate_amount = rebate_amount, - # total_bill = total_bill) - - # else: - # bill_object = Monthly_bill(student_id=student, - # amount=amount_c.bill_amount, - # rebate_count=rebate_count, - # rebate_amount=rebate_amount, - # total_bill=total_bill, - # month=month_g_l, - # year=year_g) - # bill_object.save() - # except: - # mess_optn={'mess_option':'no-mess'} - # y = Menu.objects.filter(mess_option="mess1") + # for item in rebates: + # d1 = item.start_date + # d2 = item.end_date + # item.duration = abs((d2 - d1).days)+1 + # item.save() + + # for items in rebates: + # if items.leave_type == 'casual' and (items.status == '1' or items.status == '2'): + # count += item.duration + + bill = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(Q(student_id=student) & Q(month=month_g_l) & Q(year=year_g)) + amount_c = MessBillBase.objects.latest('timestamp') + rebate_count = 0 + nonveg_total_bill = 0 + for z in data: + if z.order_date.month == month_g: + nonveg_total_bill = nonveg_total_bill + z.dish.price + + else: + bill.nonveg_total_bill = 0 + + for r in rebates: + if r.status == '2': + if r.start_date.month == month_g: + if r.end_date.month == next_month: + rebate_count = rebate_count + abs((last_day_of_this_month - r.start_date).days) + 1 + else: + rebate_count = rebate_count + abs((r.end_date - r.start_date).days) + 1 + elif r.end_date.month == month_g: + rebate_count = rebate_count + abs((r.end_date - first_day_of_this_month).days) + 1 + else: + rebate_count = 0 + rebate_amount = rebate_count * amount_c.bill_amount / 30 + total_bill = amount_c.bill_amount - rebate_amount + nonveg_total_bill + if bill: + bill.update(student_id = student, + month = month_g_l, + year = year_g, + amount = amount_c.bill_amount, + rebate_count = rebate_count, + rebate_amount = rebate_amount, + nonveg_total_bill=nonveg_total_bill, + total_bill = total_bill) + + else: + bill_object = Monthly_bill(student_id=student, + amount=amount_c.bill_amount, + rebate_count=rebate_count, + rebate_amount=rebate_amount, + nonveg_total_bill=nonveg_total_bill, + total_bill=total_bill, + month=month_g_l, + year=year_g) + bill_object.save() for d in desig: - if d.designation.name == 'mess_committee' or d.designation.name == 'mess_convener': + if d.designation.name == 'mess_committee_mess1' or d.designation.name == 'mess_convener_mess1': newmenu = Menu_change_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').filter(dish__mess_option='mess1').order_by('-app_date') + # newmenu = Menu_change_request.objects.all() meeting = Mess_meeting.objects.all() minutes = Mess_minutes.objects.select_related().all() feed = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess1').order_by('-fdate') feed2 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess2').order_by('-fdate') sprequest = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='1').order_by('-app_date') sprequest_past = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='2').order_by('-app_date') - menuchangerequest= Menu_change_request.objects.select_related('student_id').filter().order_by('-app_date') - # menu_data = Menu.objects.all() + # count1 = feed.filter(Q(feedback_type='Maintenance') & Q(mess='mess1')).count() for f in feed: - if f.feedback_type == 'Maintenance' : + if f.feedback_type == 'Maintenance' and mess_optn.mess_option == 'mess1': count1 += 1 - elif f.feedback_type == 'Food' : + elif f.feedback_type == 'Food' and mess_optn.mess_option == 'mess1': count2 += 1 - elif f.feedback_type == 'Cleanliness' : + elif f.feedback_type == 'Cleanliness' and mess_optn.mess_option == 'mess1': count3 += 1 - elif f.feedback_type == 'Others' : + elif f.feedback_type == 'Others' and mess_optn.mess_option == 'mess1': count4 += 1 - count5=0 - count6=0 - count7=0 - count8=0 + for f in feed2: + if f.feedback_type == 'Maintenance' and mess_optn.mess_option == 'mess2': + count5 += 1 + + elif f.feedback_type == 'Food' and mess_optn.mess_option == 'mess2': + count6 += 1 + + elif f.feedback_type == 'Cleanliness' and mess_optn.mess_option == 'mess2': + count7 += 1 + + elif f.feedback_type == 'Others' and mess_optn.mess_option == 'mess2': + count8 += 1 context = { - 'menu': menu_data, - 'reg_menu': y, + 'menu': y, 'messinfo': mess_optn, 'newmenu': newmenu, 'monthly_bill': monthly_bill, - 'total_due': amount_due, - + 'payments': payments, + 'nonveg': x, 'vaca': vaca_obj, 'info': extrainfo, 'feedback': feedback_obj, - 'feed1': feed, - 'feed2':'', + 'feed': feed, 'student': student, + 'data': data, 'mess_reg': mess_reg, 'current_date': current_date, 'count': count, @@ -233,7 +205,6 @@ def mess(request): 'sprequest': sprequest, 'splrequest': splrequest, 'sprequest_past': sprequest_past, - 'menuchangerequest':menuchangerequest, 'programme':programme, 'count1': count1, 'count2': count2, @@ -244,17 +215,12 @@ def mess(request): 'count7': count7, 'count8': count8, 'form': form, - 'desig': desig, - 'reg_form':reg_form, - 'reg_request':reg_request, - 'reg_main':mess_optn, - 'reg_record':reg_record, - 'de_reg_request':de_reg_request, - + 'desig': desig } return render(request, "messModule/mess.html", context) if d.designation.name == 'mess_committee_mess2' or d.designation.name == 'mess_convener_mess2': + # newmenu = Menu_change_request.objects.all() newmenu = Menu_change_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').filter(dish__mess_option='mess2').order_by('-app_date') meeting = Mess_meeting.objects.all() minutes = Mess_minutes.objects.select_related().all() @@ -262,39 +228,45 @@ def mess(request): feed2 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess1').order_by('-fdate') sprequest = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='1').order_by('-app_date') sprequest_past = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='2').order_by('-app_date') - menuchangerequest= Menu_change_request.objects.select_related('student_id').filter().order_by('-app_date') - # menu_data = Menu.objects.all().order_by() - count5=0 - count6=0 - count7=0 - count8=0 - for f in feed: - if f.feedback_type == 'Maintenance' : + # count5 = feed.filter(Q(feedback_type='Maintenance') & Q(mess='mess2')).count() + for f in feed2: + if f.feedback_type == 'Maintenance' and mess_optn.mess_option == 'mess1': count1 += 1 - elif f.feedback_type == 'Food' : + elif f.feedback_type == 'Food' and mess_optn.mess_option == 'mess1': count2 += 1 - elif f.feedback_type == 'Cleanliness' : + elif f.feedback_type == 'Cleanliness' and mess_optn.mess_option == 'mess1': count3 += 1 - elif f.feedback_type == 'Others' : + elif f.feedback_type == 'Others' and mess_optn.mess_option == 'mess1': count4 += 1 + for f in feed: + if f.feedback_type == 'Maintenance' and mess_optn.mess_option == 'mess2': + count5 += 1 + + elif f.feedback_type == 'Food' and mess_optn.mess_option == 'mess2': + count6 += 1 + + elif f.feedback_type == 'Cleanliness' and mess_optn.mess_option == 'mess2': + count7 += 1 + + elif f.feedback_type == 'Others' and mess_optn.mess_option == 'mess2': + count8 += 1 context = { - 'menu': menu_data, - 'reg_menu': y, + 'menu': y, 'messinfo': mess_optn, 'newmenu': newmenu, 'monthly_bill': monthly_bill, - 'total_due': amount_due, + 'payments': payments, + 'nonveg': x, 'vaca': vaca_obj, 'info': extrainfo, 'feedback': feedback_obj, - 'feed2': feed, - 'feed1':'', + 'feed': feed, 'student': student, - # 'data': data, + 'data': data, 'mess_reg': mess_reg, 'current_date': current_date, 'count': count, @@ -302,10 +274,9 @@ def mess(request): 'programme': programme, 'meeting': meeting, 'minutes': minutes, - 'splrequest': splrequest, 'sprequest': sprequest, + 'splrequest': splrequest, 'sprequest_past': sprequest_past, - 'menuchangerequest':menuchangerequest, 'count1': count1, 'count2': count2, 'count3': count3, @@ -315,25 +286,21 @@ def mess(request): 'count7': count7, 'count8': count8, 'form': form, - 'desig': desig, - 'reg_form':reg_form, - 'reg_request':reg_request, - 'reg_main':mess_optn, - 'reg_record':reg_record, - 'de_reg_request':de_reg_request, + 'desig': desig } return render(request, "messModule/mess.html", context) context = { - 'menu': menu_data, - 'reg_menu': y, + 'menu': y, 'messinfo': mess_optn, 'monthly_bill': monthly_bill, - 'total_due': amount_due, + 'payments': payments, + 'nonveg': x, 'vaca': vaca_obj, 'info': extrainfo, 'feedback': feedback_obj, 'student': student, + 'data': data, 'mess_reg': mess_reg, 'current_date': current_date, 'count': count, @@ -341,153 +308,92 @@ def mess(request): 'splrequest': splrequest, 'form': form, 'programme': programme, - 'desig': desig, - 'minutes': minutes, - 'meeting': meeting, - 'reg_form':reg_form, - 'reg_main_stud':mess_optn, - 'reg_request':reg_request, - 'reg_record':reg_record, - 'de_reg_request':de_reg_request, - 'payments': payments, - 'curr_balance': current_rem_balance, - 'curr_status':current_mess_status, - 'notifications':notifs - } + 'desig': desig + } return render(request, "messModule/mess.html", context) - - - elif extrainfo.user_type == 'staff': - for d in desig: - if(d.designation.name == 'mess_manager'): - current_bill = MessBillBase.objects.latest('timestamp') - newmenu = Menu_change_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').all().order_by('-app_date') - vaca_all = Vacation_food.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all().order_by('-app_date') - members_mess = HoldsDesignation.objects.select_related().filter(Q(designation__name__contains='mess_convener') - | Q(designation__name__contains='mess_committee')) - y = Menu.objects.all() - leave = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='1').order_by('-app_date') - leave_past = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='2').order_by('-app_date') - meeting = Mess_meeting.objects.all() - minutes = Mess_minutes.objects.all() - feed1 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess1').order_by('-fdate') - feed2 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess2').order_by('-fdate') - - for f in feed1: - if f.feedback_type == 'Maintenance' : - count1 += 1 - - elif f.feedback_type == 'Food' : - count2 += 1 - - elif f.feedback_type == 'Cleanliness' : - count3 += 1 - - elif f.feedback_type == 'Others' : - count4 += 1 - - for f in feed2: - if f.feedback_type == 'Maintenance': - count5 += 1 - - elif f.feedback_type == 'Food': - count6 += 1 - - elif f.feedback_type == 'Cleanliness': - count7 += 1 + current_bill = MessBillBase.objects.latest('timestamp') + nonveg_orders_today = Nonveg_data.objects.filter(order_date=today_g)\ + .values('dish__dish','order_interval').annotate(total=Count('dish')) + nonveg_orders_tomorrow = Nonveg_data.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').filter(order_date=tomorrow_g)\ + .values('dish__dish','order_interval').annotate(total=Count('dish')) + # make info with diff name and then pass context + newmenu = Menu_change_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').all().order_by('-app_date') + vaca_all = Vacation_food.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all().order_by('-app_date') + # members_mess = HoldsDesignation.objects.filter(designation__name='mess_convener') + members_mess = HoldsDesignation.objects.select_related().filter(Q(designation__name__contains='mess_convener') + | Q(designation__name__contains='mess_committee')) + y = Menu.objects.all() + x = Nonveg_menu.objects.all() + leave = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='1').order_by('-app_date') + leave_past = Rebate.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='2').order_by('-app_date') - elif f.feedback_type == 'Others': - count8 += 1 - - sprequest = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='1').order_by('-app_date') - sprequest_past = Special_request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(status='2').order_by('-app_date') + context = { + 'bill_base': current_bill, + 'today': today_g.date(), + 'tomorrow': tomorrow_g.date(), + 'nonveg_orders_t':nonveg_orders_tomorrow, + 'nonveg_orders': nonveg_orders_today, + 'members': members_mess, + 'menu': y, + 'newmenu': newmenu, + 'vaca_all': vaca_all, + 'info': extrainfo, + 'leave': leave, + 'leave_past': leave_past, + 'current_date': current_date, + 'mess_reg': mess_reg, + 'desig': desig, + } - reg_request = Registration_Request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all().filter(status='pending') - de_reg_request = Deregistration_Request.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all().filter(status='pending') - reg_main = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(current_mess_status='Registered') - reg_record = Reg_records.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all() - bills = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all() - # bills = Monthly_bill.objects.all() - context = { - 'bill_base': current_bill, - 'today': today_g.date(), - 'tomorrow': tomorrow_g.date(), - 'members': members_mess, - 'menu': y, - 'newmenu': newmenu, - 'vaca_all': vaca_all, - 'info': extrainfo, - 'leave': leave, - 'leave_past': leave_past, - 'current_date': current_date, - 'mess_reg': mess_reg, - 'desig': desig, - 'meeting': meeting, - 'minutes': minutes, - 'sprequest': sprequest, - 'sprequest_past': sprequest_past, - 'count1': count1, - 'count2': count2, 'count3': count3, 'feed1': feed1,'feed2':feed2, - 'count4': count4, 'form': form, 'count5': count5, - 'count6': count6, 'count7': count7, 'count8': count8, 'desig': desig, - 'reg_request':reg_request,'reg_record':reg_record,'reg_main':reg_main, - 'de_reg_request':de_reg_request, - 'bill': bills, - 'reg_form':reg_form - } - return render(request, "messModule/mess.html", context) + return render(request, "messModule/mess.html", context) elif extrainfo.user_type == 'faculty': - for d in desig: - if(d.designation.name == 'mess_warden'): - - feed1 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess1').order_by('-fdate') - feed2 = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(mess='mess2').order_by('-fdate') - y = Menu.objects.all() + meeting = Mess_meeting.objects.all() + minutes = Mess_minutes.objects.select_related().all() + feed = Feedback.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all().order_by('-fdate') + y = Menu.objects.all() - reg_main = Reg_main.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(current_mess_status='Registered') - reg_record = Reg_records.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all() - bills = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').all() + for f in feed: + mess_opt = Messinfo.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=f.student_id) + if f.feedback_type == 'Maintenance' and mess_opt.mess_option == 'mess1': + count1 += 1 - for f in feed1: - if f.feedback_type == 'Maintenance' : - count1 += 1 + elif f.feedback_type == 'Food' and mess_opt.mess_option == 'mess1': + count2 += 1 - elif f.feedback_type == 'Food' : - count2 += 1 + elif f.feedback_type == 'Cleanliness' and mess_opt.mess_option == 'mess1': + count3 += 1 - elif f.feedback_type == 'Cleanliness' : - count3 += 1 + elif f.feedback_type == 'Others' and mess_opt.mess_option == 'mess1': + count4 += 1 - elif f.feedback_type == 'Others' : - count4 += 1 + for f in feed: + mess_opt = Messinfo.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=f.student_id) + if f.feedback_type == 'Maintenance' and mess_opt.mess_option == 'mess2': + count5 += 1 - for f in feed2: - if f.feedback_type == 'Maintenance': - count5 += 1 + elif f.feedback_type == 'Food' and mess_opt.mess_option == 'mess2': + count6 += 1 - elif f.feedback_type == 'Food': - count6 += 1 - - elif f.feedback_type == 'Cleanliness': - count7 += 1 + elif f.feedback_type == 'Cleanliness' and mess_opt.mess_option == 'mess2': + count7 += 1 - elif f.feedback_type == 'Others': - count8 += 1 - context = { - 'info': extrainfo, - 'desig': desig, - 'menu': y, - 'count1': count1, - 'count2': count2, 'count3': count3, 'feed1': feed1,'feed2':feed2, - 'count4': count4, 'form': form, 'count5': count5, - 'count6': count6, 'count7': count7, 'count8': count8, 'desig': desig, - 'reg_record':reg_record,'reg_main':reg_main,'bill': bills, - } - return render(request, 'messModule/mess.html', context) + elif f.feedback_type == 'Others' and mess_opt.mess_option == 'mess2': + count8 += 1 + context = { + 'info': extrainfo, + 'menu': y, + 'meeting': meeting, + 'minutes': minutes, + 'count1': count1, + 'count2': count2, 'count3': count3, 'feed': feed, + 'count4': count4, 'form': form, 'count5': count5, + 'count6': count6, 'count7': count7, 'count8': count8, 'desig': desig + } + return render(request, 'messModule/mess.html', context) @login_required @transaction.atomic @@ -511,19 +417,38 @@ def mess_info(request): mess_option = form.cleaned_data['mess_option'] Messinfo.objects.create(student_id=student_id, mess_option=mess_option) return HttpResponseRedirect("/mess") - user_id = request.user - student_id = Student.objects.select_related( - 'id').only('id__id').get(id__id=user_id) - if Messinfo.objects.filter(student_id=student_id).exists(): - return HttpResponseRedirect("/mess") + form = MessInfoForm() context = { "form": form } return render(request, "messModule/messInfoForm.html", context) +@login_required +@transaction.atomic +@csrf_exempt +def place_order(request): + """ + This function is to place non-veg food orders - + @param: + request: contains metadata about the requested page + + @variables: + user: Current user + order_interval: Time of the day for which order is placed eg breakfast/lunch/dinner + extra_info: Extra information about the current user. From model ExtraInfo + student: Student information about the current user + student_mess: Mess choices of the student + dish_request: Predefined dish available + """ + user = request.user + extra_info = ExtraInfo.objects.select_related().get(user=user) + if extra_info.user_type == 'student': + student = Student.objects.select_related('id','id__user','id__department').get(id=extra_info) + student_mess = Messinfo.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id=student) + add_nonveg_order(request, student) + return HttpResponseRedirect('/mess') @csrf_exempt @@ -600,9 +525,9 @@ def submit_mess_menu(request): extrainfo = ExtraInfo.objects.select_related().get(user=user) designation = holds_designations student = Student.objects.select_related('id','id__user','id__department').get(id=extrainfo) - + # globallyChange() context = {} - + # A user may hold multiple designations data = add_menu_change_request(request,student) if data['status'] == 1: @@ -644,7 +569,7 @@ def response_vacation_food(request, ap_id): holds_designations: designation of current user """ user = request.user - + # extra_info = ExtraInfo.objects.get(user=user) holds_designations = HoldsDesignation.objects.select_related().filter(user=user) designation = holds_designations @@ -734,12 +659,6 @@ def start_mess_registration(request): data = add_mess_registration_time(request) return JsonResponse(data) -@csrf_exempt -def closeRegistration(request): - mess_reg = Mess_reg.objects.last() - yesterday = date.today() - timedelta(days=1) - Mess_reg.objects.filter(id=mess_reg.id).update(end_reg=yesterday) - return HttpResponseRedirect('/mess') @transaction.atomic @csrf_exempt @@ -824,8 +743,6 @@ def rebate_response(request): for d in designation: if d.designation.name == 'mess_manager': data = handle_rebate_response(request) - print(data) - print(request) return JsonResponse(data) @@ -881,29 +798,10 @@ def update_cost(request): user - contains user details """ user = request.user + # extrainfo = ExtraInfo.objects.get(user=user) data = add_bill_base_amount(request) return JsonResponse(data) -@login_required -def update_semdates(request): - """ - This function is to update the semester start and end date - - @param: - request - contains metadata about the requested page - - @variables: - user - contains user details - """ - user = request.user - data = add_sem_dates(request) - return HttpResponseRedirect('/mess') -@csrf_exempt -@login_required -def update_bill(request): - # user = request.user - update_month_bill(request) - return HttpResponseRedirect('/mess') def generate_mess_bill(request): """ @@ -924,10 +822,10 @@ def generate_mess_bill(request): """ # todo generate proper logic for generate_mess_bill user = request.user - # t1 = Thread(target=generate_bill, args=()) - # t1.setDaemon(True) - # t1.start() - generate_bill() + t1 = Thread(target=generate_bill, args=()) + t1.setDaemon(True) + t1.start() + # int = generate_bill() data ={ 'status': 1 } @@ -982,24 +880,6 @@ def post(self, request, *args, **kwargs): 'mess_option': 'mess1' } return render_to_pdf('messModule/menudownloadable1.html', context) - -class BillPDFStudent(View): - def post(self, request, *args, **kwargs): - user = request.user - extra_info = ExtraInfo.objects.select_related().get(user=user) - student = Student.objects.select_related('id','id__user','id__department').get(id=extra_info) - # reg_student = Reg_records.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').get(student_id_id=student) - try: - monthly_bill = Monthly_bill.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department').filter(student_id=student) - if monthly_bill.exists(): - context = { - 'student_bill': monthly_bill - } - return render_to_pdf('messModule/billpdfexport.html', context) - else : - return HttpResponseRedirect('/mess') - except: - return HttpResponseRedirect('/mess') def menu_change_request(request): @@ -1019,7 +899,6 @@ def menu_change_request(request): return JsonResponse(data) -@csrf_exempt def submit_mess_committee(request): """ This function is to add the new mess committee @@ -1031,9 +910,10 @@ def submit_mess_committee(request): current_user - get user from request user_details - extract details and designation of the user from the database """ - roll_number = str(request.POST.get('roll_number')).upper() + roll_number = request.POST['rollnumber'] + data = add_mess_committee(request, roll_number) - return HttpResponseRedirect("/mess") + return JsonResponse(data) def remove_mess_committee(request): @@ -1051,10 +931,10 @@ def remove_mess_committee(request): member_id = request.POST['member_id'] data_m = member_id.split("-") roll_number = data_m[1] - if data_m[0] == 'mess_committee': - designation = Designation.objects.get(name='mess_committee') - elif data_m[0] == 'mess_convener': - designation = Designation.objects.get(name='mess_convener') + if data_m[0] == 'mess_committee_mess1': + designation = Designation.objects.get(name='mess_committee_mess1') + elif data_m[0] == 'mess_convener_mess1': + designation = Designation.objects.get(name='mess_convener_mess1') elif data_m[0] == 'mess_committee_mess2': designation = Designation.objects.get(name='mess_committee_mess2') else: @@ -1135,9 +1015,9 @@ def select_mess_convener(request): data_m = member_id.split("-") roll_number = data_m[1] - if data_m[0] == 'mess_committee': - designation = Designation.objects.get(name='mess_committee') - new_designation = Designation.objects.get(name='mess_convener') + if data_m[0] == 'mess_committee_mess1': + designation = Designation.objects.get(name='mess_committee_mess1') + new_designation = Designation.objects.get(name='mess_convener_mess1') # One mess can have only one mess convener existing_check = HoldsDesignation.objects.select_related().filter(designation=new_designation) if existing_check.count(): @@ -1201,6 +1081,27 @@ def download_bill_mess(request): } return render_to_pdf('messModule/billpdfexport.html', context) + +def get_nonveg_order(request): + """ + This function is to apply for non-veg order + + @param: + request - contains metadata about the requested page + + @variables: + current_user - get user from request + user_details - extract details of the user from the database + """ + date_o = request.POST['order_date'] + nonveg_orders_tomorrow = Nonveg_data.objects.select_related('student_id','student_id__id','student_id__id__user','student_id__id__department','dish').filter(order_date=date_o) \ + .values('dish__dish', 'order_interval').annotate(total=Count('dish')) + data = { + 'status': 1, + } + return JsonResponse(data) + + def add_leave_manager(request): """ This function is to apply for leave @@ -1261,392 +1162,3 @@ def add_leave_manager(request): central_mess_notif(request.user, student.id.user, 'leave_request', message) add_obj.save() return HttpResponseRedirect('/mess') - -def update_menu2(request): - if (request.method == "POST"): - mb = request.POST['MB2'] - ml = request.POST['ML2'] - md = request.POST['MD2'] - sud = request.POST['SUD2'] - sul = request.POST['SUL2'] - sub = request.POST['SUB2'] - sd = request.POST['SD2'] - sl = request.POST['SL2'] - sb = request.POST['SB2'] - fd = request.POST['FD2'] - fl = request.POST['FL2'] - fb = request.POST['FB2'] - thd = request.POST['THD2'] - thl = request.POST['THL2'] - thb = request.POST['THB2'] - wd = request.POST['WD2'] - wl = request.POST['WL2'] - wb = request.POST['WB2'] - td = request.POST['TD2'] - tl = request.POST['TL2'] - tb = request.POST['TB2'] - - print("mb", mb) - Menu.objects.filter(mess_option = 'mess2',meal_time='MB').update(dish = mb) - Menu.objects.filter(mess_option = 'mess2',meal_time='ML').update(dish = ml) - Menu.objects.filter(mess_option = 'mess2',meal_time='MD').update(dish = md) - Menu.objects.filter(mess_option = 'mess2',meal_time='TB').update(dish = tb) - Menu.objects.filter(mess_option = 'mess2',meal_time='TL').update(dish = tl) - Menu.objects.filter(mess_option = 'mess2',meal_time='TD').update(dish = td) - Menu.objects.filter(mess_option = 'mess2',meal_time='WB').update(dish = wb) - Menu.objects.filter(mess_option = 'mess2',meal_time='WL').update(dish = wl) - Menu.objects.filter(mess_option = 'mess2',meal_time='WD').update(dish = wd) - Menu.objects.filter(mess_option = 'mess2',meal_time='THB').update(dish = thb) - Menu.objects.filter(mess_option = 'mess2',meal_time='THL').update(dish = thl) - Menu.objects.filter(mess_option = 'mess2',meal_time='THD').update(dish = thd) - Menu.objects.filter(mess_option = 'mess2',meal_time='FB').update(dish = fb) - Menu.objects.filter(mess_option = 'mess2',meal_time='FL').update(dish = fl) - Menu.objects.filter(mess_option = 'mess2',meal_time='FD').update(dish = fd) - Menu.objects.filter(mess_option = 'mess2',meal_time='SB').update(dish = sb) - Menu.objects.filter(mess_option = 'mess2',meal_time='SL').update(dish = sl) - Menu.objects.filter(mess_option = 'mess2',meal_time='SD').update(dish = sd) - Menu.objects.filter(mess_option = 'mess2',meal_time='SUB').update(dish = sub) - Menu.objects.filter(mess_option = 'mess2',meal_time='SUL').update(dish = sul) - Menu.objects.filter(mess_option = 'mess2',meal_time='SUD').update(dish = sud) - - - return redirect('/mess') -def update_menu1(request): - if (request.method == "POST"): - mb1 = request.POST['MB1'] - ml1 = request.POST['ML1'] - md1 = request.POST['MD1'] - sud1 = request.POST['SUD1'] - sul1 = request.POST['SUL1'] - sub1 = request.POST['SUB1'] - sd1 = request.POST['SD1'] - sl1 = request.POST['SL1'] - sb1 = request.POST['SB1'] - fd1 = request.POST['FD1'] - fl1 = request.POST['FL1'] - fb1 = request.POST['FB1'] - thd1 = request.POST['THD1'] - thl1 = request.POST['THL1'] - thb1 = request.POST['THB1'] - wd1 = request.POST['WD1'] - wl1 = request.POST['WL1'] - wb1 = request.POST['WB1'] - td1 = request.POST['TD1'] - tl1 = request.POST['TL1'] - tb1 = request.POST['TB1'] - - print("mb", mb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='MB').update(dish = mb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='ML').update(dish = ml1) - Menu.objects.filter(mess_option = 'mess1',meal_time='MD').update(dish = md1) - Menu.objects.filter(mess_option = 'mess1',meal_time='TB').update(dish = tb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='TL').update(dish = tl1) - Menu.objects.filter(mess_option = 'mess1',meal_time='TD').update(dish = td1) - Menu.objects.filter(mess_option = 'mess1',meal_time='WB').update(dish = wb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='WL').update(dish = wl1) - Menu.objects.filter(mess_option = 'mess1',meal_time='WD').update(dish = wd1) - Menu.objects.filter(mess_option = 'mess1',meal_time='THB').update(dish = thb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='THL').update(dish = thl1) - Menu.objects.filter(mess_option = 'mess1',meal_time='THD').update(dish = thd1) - Menu.objects.filter(mess_option = 'mess1',meal_time='FB').update(dish = fb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='FL').update(dish = fl1) - Menu.objects.filter(mess_option = 'mess1',meal_time='FD').update(dish = fd1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SB').update(dish = sb1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SL').update(dish = sl1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SD').update(dish = sd1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SUB').update(dish = sub1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SUL').update(dish = sul1) - Menu.objects.filter(mess_option = 'mess1',meal_time='SUD').update(dish = sud1) - - return redirect('/mess') - -@csrf_exempt -def searchAddOrRemoveStudent(request): - if request.method=='GET': - submitType=request.GET.get('type') - msg="" - if submitType=='searchStudent': - studentId=str((request.GET.get('roll_number'))).upper() - try: - reg_main = Reg_main.objects.values('current_mess_status','mess_option').get(student_id=studentId) - if(reg_main['current_mess_status']=="Registered"): - msg= str(studentId)+" is registered for "+str(reg_main['mess_option']) - else: - msg=str(studentId)+" is not registered for Mess" - except: - msg="unable to find this student in database." - - # try: - # mess_optn = Messinfo.objects.select_related().values('mess_option').get(student_id=studentId) - # msg= str(studentId)+" is registered for "+str(mess_optn['mess_option']) - # except: - # msg=str(studentId)+" is not registered for Mess" - - elif submitType=='addStudent': - messNo=request.GET.get('messNo') - studentId = str((request.GET.get('roll_number'))).upper() - try: - reg_main = Reg_main.objects.get(student_id=studentId) - - if(reg_main.current_mess_status=="Registered"): - msg=str(studentId)+" is already registered for "+str(reg_main.mess_option) - else: - reg_main.current_mess_status="Registered" - reg_main.mess_option=str(messNo) - reg_main.save() - msg="success" - except: - msg="unable to find this student in database." - - # try: - # mess_optn = Messinfo.objects.select_related().values('mess_option').get(student_id=studentId) - # msg=str(studentId)+" is already registered for "+str(mess_optn['mess_option']) - # except: - # try: - # studentHere = Student.objects.select_related('id','id__user','id__department').get(id=studentId) - # newData=Messinfo(student_id=studentHere,mess_option=str(messNo)) - # newData.save() - # msg=str(studentId)+" is successfully registered for Mess." - # except: - # msg="unable to find this student in database." - - elif submitType=='removeStudent': - studentId = str((request.GET.get('roll_number'))).upper() - try: - reg_main = Reg_main.objects.get(student_id=studentId,current_mess_status="Registered") - reg_main.current_mess_status="Deregistered" - reg_main.save() - msg=str(studentId)+" is successfully removed from mess." - except: - msg=str(studentId)+" is not registered for mess." - - # try: - # studentHere = Student.objects.select_related('id','id__user','id__department').get(id=studentId) - # data=Messinfo.objects.get(student_id=studentId) - # data.delete() - # Messinfo.objects.all() - # msg=str(studentId)+" is successfully removed from mess." - # except: - # msg=str(studentId)+" is not registered for mess." - elif (submitType=='removeAllStudent1' or submitType=='removeAllStudent2'): - messNo=request.GET.get('mess') - - try: - reg_main = Reg_main.objects.filter(mess_option=str(messNo),current_mess_status="Registered") - for reg in reg_main: - reg.current_mess_status="Deregistered" - reg.save() - msg="All students removed successfully from "+str(messNo) - except: - msg="can't remove students." - - return JsonResponse({'message':msg}) - else: - if(request.FILES): - # if 'excelUpload1' in request.POST: - # messNo='mess1' - # excel_file = request.FILES['excel_file1'] - # else: - # messNo='mess2' - # excel_file = request.FILES['excel_file2'] - try: - latest = Semdates.objects.latest('end_date') - latest_end_date=latest.end_date - print(latest_end_date) - except: - latest_end_date=None - excel_file = request.FILES['excel_file1'] - wb = openpyxl.load_workbook(excel_file) - flag = False - for row in wb.active: - if(flag==False): - flag=True - continue - studentId=(str(row[0].value)).upper() - studentHere = Student.objects.select_related('id','id__user','id__department').get(id=studentId) - balance=row[1].value - messNo = row[2].value - try: - reg_main = Reg_main.objects.get(student_id=studentId) - reg_main.current_mess_status="Registered" - reg_main.mess_option=str(messNo) - reg_main.balance=reg_main.balance+balance - reg_main.save() - # if Messinfo.objects.filter(student_id=studentId).exists(): - # Messinfo.objects.filter(student_id=studentId).update(mess_option=str(messNo)) - # else: - # newData=Messinfo(student_id=studentHere,mess_option=str(messNo)) - # newData.save() - except: - reg_main = Reg_main(student_id=reg_main.student_id,program=studentHere.programme,current_mess_status="Registered",mess_option=str(messNo),balance=balance) - reg_main.save() - - new_reg_record = Reg_records(student_id=reg_main.student_id,start_date=today_g,end_date=latest_end_date) - new_reg_record.save() - # messages.success(request,"Done.") - return HttpResponseRedirect("/mess") - -@csrf_exempt -def uploadPaymentDue(request): - if(request.FILES): - - excel_file = request.FILES['excel_file'] - wb = openpyxl.load_workbook(excel_file) - - for row in wb.active: - studentId=(str(row[0].value)).upper() - amount=(row[1].value) - try: - studentHere = Student.objects.get(id=studentId) - monthly_bill = Monthly_bill.objects.select_related('student_id').filter(student_id=studentHere) - try: - Payments.objects.filter(student_id=studentHere).delete() - except: - 1 - Payments.objects.create(student_id=studentHere,amount_paid=(-1*(amount))) - if amount<=0: - for x in monthly_bill: - Monthly_bill.objects.filter(student_id=studentHere).filter(month=x.month).filter(year=x.year).update(paid=True) - else: - monthly_bill=monthly_bill[::-1] - curr_amount=amount - for x in monthly_bill: - if(curr_amount<=0): - Monthly_bill.objects.filter(student_id=studentHere).filter(month=x.month).filter(year=x.year).update(paid=True) - else: - Monthly_bill.objects.filter(student_id=studentHere).filter(month=x.month).filter(year=x.year).update(paid=False) - curr_amount-=x.total_bill; - print(x) - except: - 1 - messages.success(request,"Done.") - return HttpResponseRedirect("/mess") - - -@csrf_exempt -@login_required -def respond_to_reg(request): - """ - This function is used to respond to registeration requests - - @param request: - request - contains metadata about the requested page - - @variables: - user: Current user details - designation : designation of the user - - @return: - data: returns the status of the application - """ - data = { - 'status': 1 - } - user = request.user - designation = HoldsDesignation.objects.select_related().filter(user=user) - type = request.POST['type'] - for d in designation: - if d.designation.name == 'mess_manager': - if(type=='reg'): - data = handle_reg_response(request) - elif(type=='dreg'): - data = handle_dreg_response(request) - return JsonResponse(data) - - -def reg_request(request): - - user = request.user - extra_info = ExtraInfo.objects.select_related().get(user=user) - try: - if request.POST['input_roll']: - # print(request.POST) - studentID = str(request.POST['input_roll']).upper() - handle_add_reg(request) - form = RegistrationRequest(request.POST, request.FILES) - student = Student.objects.select_related('id','id__user','id__department').get(id=studentID) - if form.is_valid(): - temp=form.save(commit=False) - temp.student_id=student - temp.status='accept' - temp.save() - return HttpResponseRedirect("/mess") - except: - student = Student.objects.select_related('id','id__user','id__department').get(id=extra_info) - if request.method == 'POST': - form = RegistrationRequest(request.POST, request.FILES) - - if form.is_valid(): - temp=form.save(commit=False) - temp.student_id=student - temp.save() - return HttpResponseRedirect("/mess") - - - -@csrf_exempt -def update_bill_excel(request): - if(request.FILES): - excel_file = request.FILES['excel_file_bill'] - wb = openpyxl.load_workbook(excel_file) - flag = False - for row in wb.active: - if(flag==False): - flag=True - continue - studentId=(str(row[0].value)).upper() - studentHere = Student.objects.select_related('id','id__user','id__department').get(id=studentId) - month=str(row[1].value) - year = row[2].value - amt = row[3].value - rebate_cnt = row[4].value - rebate_amt = row[5].value - total_amt = row[6].value - try: - bill = Monthly_bill.objects.get(student_id=studentId,month=month,year=year) - reg_main = Reg_main.objects.get(student_id=studentId) - reg_main.balance=reg_main.balance+bill.total_bill - bill.amount=amt - bill.rebate_count=rebate_cnt - bill.rebate_amount=rebate_amt - bill.total_bill=total_amt - reg_main.balance=reg_main.balance-total_amt - bill.save() - reg_main.save() - except: - bill = Monthly_bill(student_id=studentHere,month=month,year=year,amount=amt,rebate_count=rebate_cnt,rebate_amount=rebate_amt,total_bill=total_amt) - bill.save() - # messages.success(request,"Done.") - return HttpResponseRedirect("/mess") - -def de_reg_request(request): - try: - if request.POST['input_roll']: - # print(request.POST) - studentID = str(request.POST['input_roll']).upper() - end_date = request.POST.get("end_date") - try: - reg_main = Reg_main.objects.get(student_id=studentID) - - if(end_date == str(date.today())): - reg_main.current_mess_status = 'Deregistered' - reg_main.save() - reg_record = Reg_records.objects.filter(student_id=studentID).latest('start_date') - reg_record.end_date=end_date - reg_record.save() - except: - pass - return HttpResponseRedirect('/mess') - except: - data={ - 'message':'request submitted successfully' - } - user = request.user - end_date = request.POST.get("end_date") - print(end_date) - extra_info = ExtraInfo.objects.select_related().get(user=user) - student = Student.objects.select_related('id','id__user','id__department').get(id=extra_info) - new_req=Deregistration_Request(student_id=student, end_date=end_date) - new_req.save() - return HttpResponseRedirect('/mess') - diff --git a/FusionIIIT/applications/complaint_system/admin.py b/FusionIIIT/applications/complaint_system/admin.py index 8bf43cab7..84314fcd9 100644 --- a/FusionIIIT/applications/complaint_system/admin.py +++ b/FusionIIIT/applications/complaint_system/admin.py @@ -1,9 +1,8 @@ from django.contrib import admin -from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge +from .models import Caretaker, StudentComplain, Supervisor, Workers admin.site.register(Caretaker) admin.site.register(Workers) admin.site.register(StudentComplain) admin.site.register(Supervisor) -admin.site.register(SectionIncharge) diff --git a/FusionIIIT/applications/complaint_system/api/views.py b/FusionIIIT/applications/complaint_system/api/views.py index 304697017..612c6573c 100644 --- a/FusionIIIT/applications/complaint_system/api/views.py +++ b/FusionIIIT/applications/complaint_system/api/views.py @@ -23,7 +23,7 @@ def complaint_details_api(request,detailcomp_id1): if complaint_detail.worker_id is None: worker_detail_serialized = {} else : - worker_detail = Workers.objects.get(id=complaint_detail.worker_id.id) + worker_detail = worker_detail.objects.get(id=complaint_detail.worker_id) worker_detail_serialized = serializers.WorkersSerializers(instance=worker_detail).data complainer = User.objects.get(username=complaint_detail.complainer.user.username) complainer_serialized = serializers.UserSerializers(instance=complainer).data @@ -154,7 +154,7 @@ def caretaker_api(request): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(sup_id=user) + supervisor = Supervisor.objects.get(staff_id=user) except Supervisor.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) serializer = serializers.CaretakerSerializers(data=request.data) @@ -170,7 +170,7 @@ def edit_caretaker_api(request,c_id): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(sup_id=user) + supervisor = Supervisor.objects.get(staff_id=user) except Supervisor.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) try: diff --git a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py index 44df90d3c..db74dd14d 100644 --- a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py +++ b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion @@ -15,10 +15,12 @@ class Migration(migrations.Migration): operations = [ migrations.CreateModel( - name='SectionIncharge', + name='Caretaker', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('work_type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=20)), + ('area', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('CC1', 'CC1'), ('CC2', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], default='hall-3', max_length=20)), + ('rating', models.IntegerField(default=0)), + ('myfeedback', models.CharField(default='this is my feedback', max_length=400)), ('staff_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], ), @@ -30,14 +32,14 @@ class Migration(migrations.Migration): ('age', models.CharField(max_length=10)), ('phone', models.BigIntegerField(blank=True)), ('worker_type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='internet', max_length=20)), - ('secincharge_id', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='complaint_system.sectionincharge')), + ('caretaker_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='complaint_system.caretaker')), ], ), migrations.CreateModel( name='Supervisor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=30)), + ('area', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('CC1', 'CC1'), ('CC2', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], max_length=20)), ('sup_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], ), @@ -48,7 +50,7 @@ class Migration(migrations.Migration): ('complaint_date', models.DateTimeField(default=django.utils.timezone.now)), ('complaint_finish', models.DateField(blank=True, null=True)), ('complaint_type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='internet', max_length=20)), - ('location', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('library', 'CC1'), ('computer center', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('NR3', 'NR3'), ('Admin building', 'Admin building'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], max_length=20)), + ('location', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('CC1', 'CC1'), ('CC2', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], max_length=20)), ('specific_location', models.CharField(blank=True, max_length=50)), ('details', models.CharField(max_length=100)), ('status', models.IntegerField(default='0')), @@ -62,14 +64,4 @@ class Migration(migrations.Migration): ('worker_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='complaint_system.workers')), ], ), - migrations.CreateModel( - name='Caretaker', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('area', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('library', 'CC1'), ('computer center', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('NR3', 'NR3'), ('Admin building', 'Admin building'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], default='hall-3', max_length=20)), - ('rating', models.IntegerField(default=0)), - ('myfeedback', models.CharField(default='this is my feedback', max_length=400)), - ('staff_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), - ], - ), ] diff --git a/FusionIIIT/applications/complaint_system/models.py b/FusionIIIT/applications/complaint_system/models.py index 47145fad3..9f8849e69 100644 --- a/FusionIIIT/applications/complaint_system/models.py +++ b/FusionIIIT/applications/complaint_system/models.py @@ -12,13 +12,11 @@ class Constants: ('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), - ('library', 'CC1'), - ('computer center', 'CC2'), + ('CC1', 'CC1'), + ('CC2', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), - ('NR3', 'NR3'), - ('Admin building', 'Admin building'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), @@ -44,18 +42,11 @@ class Caretaker(models.Model): # no_of_comps = models.CharField(max_length=1000) def __str__(self): - return str(self.id) + '-' + str(self.area) + return str(self.id) + '-' + self.area -class SectionIncharge(models.Model): - staff_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) - work_type = models.CharField(choices=Constants.COMPLAINT_TYPE, - max_length=20, default='Electricity') - - def __str__(self): - return str(self.id) + '-' + self.work_type class Workers(models.Model): - secincharge_id = models.ForeignKey(SectionIncharge, on_delete=models.CASCADE, null=True) + caretaker_id = models.ForeignKey(Caretaker, on_delete=models.CASCADE) name = models.CharField(max_length=50) age = models.CharField(max_length=10) phone = models.BigIntegerField(blank=True) @@ -91,7 +82,7 @@ def __str__(self): class Supervisor(models.Model): sup_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) - type = models.CharField(choices=Constants.COMPLAINT_TYPE, max_length=30,default='Electricity') + area = models.CharField(choices=Constants.AREA, max_length=20) def __str__(self): - return str(self.sup_id) + '-' + str(self.type) + return str(self.sup_id.user.username) diff --git a/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js b/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js index 825fe759d..3884f885b 100644 --- a/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js +++ b/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js @@ -58,93 +58,6 @@ $(document).ready(function(){ } }; - function sub2(event) - { - var specific_location= $('input[name="specific_location"]').val(); - var Location = $('input[name="Location"]').val(); - var complaint_type = $('input[name="complaint_type"]').val() ; - var details =$('input[name="details"]').val() ; - var myfile = $('input[name="myfile"]').val(); - if(specific_location=="" || Location=="" || details=="" || complaint_type=="") - { - alert("Please fill all the details!"); - return; - } - else - { - event.preventDefault(); - $.ajax({ - type : 'POST', - url : '.', - data : { - 'specific_location' : specific_location, - 'Location' : Location, - 'complaint_type' : complaint_type, - 'details' : details, - 'myfile' : myfile, - - }, - success : function (data){ - - // alert("Complaint successfully lodged"); - setTimeout(function() { - window.location.replace('http://localhost:8000/complaint/caretaker'); - }, 1500); - - - }, - error : function (data,err){ - alert('Complaint successfully lodged ... '); - - } - }); - } - }; - function sub3(event) - { - var specific_location= $('input[name="specific_location"]').val(); - var Location = $('input[name="Location"]').val(); - var complaint_type = $('input[name="complaint_type"]').val() ; - var details =$('input[name="details"]').val() ; - var myfile = $('input[name="myfile"]').val(); - if(specific_location=="" || Location=="" || details=="" || complaint_type=="") - { - alert("Please fill all the details!"); - return; - } - else - { - event.preventDefault(); - $.ajax({ - type : 'POST', - url : '.', - data : { - 'specific_location' : specific_location, - 'Location' : Location, - 'complaint_type' : complaint_type, - 'details' : details, - 'myfile' : myfile, - - }, - success : function (data){ - - // alert("Complaint successfully lodged"); - setTimeout(function() { - window.location.replace('http://localhost:8000/complaint/supervisor'); - }, 1500); - - - }, - error : function (data,err){ - alert('Complaint successfully lodged ... '); - - } - }); - } - }; - - - @@ -854,98 +767,3 @@ $.fn.rating.settings = { }; })( jQuery, window, document ); - - -function paginate(tableId, rowsPerPage, paginationDiv) { - var currentPage = 1; - var tableRows = document.querySelectorAll('#' + tableId + ' tbody tr'); - var totalPages = Math.ceil(tableRows.length / rowsPerPage); - - function displayRows() { - var startIndex = (currentPage - 1) * rowsPerPage; - var endIndex = startIndex + rowsPerPage; - tableRows.forEach(function (row, index) { - if (index >= startIndex && index < endIndex) { - row.style.display = ''; - } else { - row.style.display = 'none'; - } - }); - } - - function generatePagination() { - var pagination = document.getElementById(paginationDiv); - pagination.innerHTML = ''; - - var maxPagesToShow = 5; - - // Calculate the range of pages to display - var startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2)); - var endPage = Math.min(totalPages, startPage + maxPagesToShow - 1); - - // Adjust startPage and endPage if needed - if (endPage - startPage < maxPagesToShow - 1) { - startPage = Math.max(1, endPage - maxPagesToShow + 1); - } - - // Create the backward scroll button - if (currentPage > 1) { - pagination.appendChild(createScrollButton('<')); - } - - // Create the page links - for (var i = startPage; i <= endPage; i++) { - pagination.appendChild(createPageLink(i)); - } - - // Create the forward scroll button - if (currentPage < totalPages) { - pagination.appendChild(createScrollButton('>')); - } -} - -function createScrollButton(label) { - var button = document.createElement('button'); - button.textContent = label; - button.addEventListener('click', function () { - if (label === '<') { - currentPage = Math.max(1, currentPage - 1); - } else { - currentPage = Math.min(totalPages, currentPage + 1); - } - displayRows(); - generatePagination(); - }); - return button; -} - - - function createPageLink(pageNumber) { - var link = document.createElement('a'); - link.href = '#'; - link.textContent = pageNumber; - link.style.display = 'inline-block'; - link.style.padding = '5px 10px'; - link.style.marginRight = '5px'; - link.style.color = '#333'; - link.style.textDecoration = 'none'; - link.style.border = '1px solid #ccc'; - link.style.borderRadius = '3px'; - - if (pageNumber === currentPage) { - link.style.backgroundColor = '#007bff'; - link.style.color = '#fff'; - } - - link.addEventListener('click', function () { - currentPage = parseInt(this.textContent); - displayRows(); - generatePagination(); - }); - - return link; - } - - displayRows(); - generatePagination(); -} \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/urls.py b/FusionIIIT/applications/complaint_system/urls.py index 2bd0c87e0..b95605ade 100644 --- a/FusionIIIT/applications/complaint_system/urls.py +++ b/FusionIIIT/applications/complaint_system/urls.py @@ -9,30 +9,33 @@ url(r'^$', views.check, name='complaint'), # url(r'^login/$', views.login1, name='complaint'), url(r'^user/$', views.user), + url(r'^user/caretakerfb/$' , views.caretaker_feedback), + url(r'^user/(?P[0-9]+)/$', views.submitfeedback), url(r'^user/detail/(?P[0-9]+)/$', views.detail,name='detail'), - # url(r'^user/check_complaint/$', views.save_comp), + # url(r'^user/check_complaint/$', views.save_comp), + # caretaker - url(r'^caretaker/lodge/$', views.caretakerlodge), url(r'^caretaker/$', views.caretaker, name='caretaker'), url(r'^caretaker/feedback/(?P[0-9]+)/$', views.feedback_care), + url(r'^caretaker/worker_id_know_more/(?P[0-9]+)/complaint_reassign/(?P[0-9]+)/discharge_worker/$', views.discharge_worker,name='discharge_worker'), + url(r'^caretaker/worker_id_know_more/(?P[0-9]+)/$', views.worker_id_know_more, name='come_back_to_this'), + url(r'^caretaker/worker_id_know_more/(?P[0-9]+)/complaint_reassign/(?P[0-9]+)/$', views.complaint_reassign), + #url(r'^caretaker/list_caretakers_area/$', views.caretaker, name='caretaker'), url(r'^caretaker/pending/(?P[0-9]+)/$', views.resolvepending), - url(r'^caretaker/detail2/(?P[0-9]+)/$', views.detail), + url(r'^caretaker/detail2/(?P[0-9]+)/$', views.detail2,name='detail2'), url(r'^caretaker/search_complaint$', views.search_complaint), - url(r'^caretaker/(?P[0-9]+)/feedback/$', views.submitfeedbackcaretaker), # supervisor - url(r'^supervisor/lodge/$', views.supervisorlodge), url(r'^supervisor/$', views.supervisor), url(r'^supervisor/feedback/(?P[0-9]+)/$', views.feedback_super), url(r'^supervisor/caretaker_id_know_more/(?P[0-9]+)/$', views.caretaker_id_know_more), - # url(r'^supervisor/caretaker_id_know_more/(?P[0-9]+)/complaint_reassign_super/(?P[0-9]+)/$', views.complaint_reassign_super, name = 'complaint_reassign_super'), - url(r'^supervisor/detail/(?P[0-9]+)/$', views.detail3, name = 'detail3'), - url(r'^supervisor/pending/(?P[0-9]+)/$', views.resolvependingsuper), - url(r'^supervisor/(?P[0-9]+)/$', views.submitfeedbacksuper), + url(r'^supervisor/caretaker_id_know_more/(?P[0-9]+)/complaint_reassign_super/(?P[0-9]+)/$', views.complaint_reassign_super, name = 'complaint_reassign_super'), + url(r'^supervisor/detail3/(?P[0-9]+)/$', views.detail3, name = 'detail3'), + @@ -42,7 +45,6 @@ url(r'^caretaker/deletecomplaint/(?P[0-9]+)/$', views.deletecomplaint), # url(r'^caretaker/(?P[0-9]+)/$', views.assign_worker), url(r'^caretaker/(?P[0-9]+)/(?P[0-9]+)/$', views.changestatus), - url(r'^supervisor/(?P[0-9]+)/(?P[0-9]+)/$', views.changestatussuper), url(r'^api/',include('applications.complaint_system.api.urls')) diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index 9d3dd7316..b566856aa 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -10,85 +10,96 @@ from applications.globals.models import User , ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge +from .models import Caretaker, StudentComplain, Supervisor, Workers from notification.views import complaint_system_notif - - -from applications.filetracking.sdk.methods import * -from applications.filetracking.models import * -from operator import attrgetter - #function for reassign to another worker -# @login_required -# def complaint_reassign(request,wid,iid): - # current_user = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - # if request.method == 'POST': - # type = request.POST.get('submit', '') - # a = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - # comp_id = y.id - # if type == 'assign': - - # complaint_finish = request.POST.get('complaint_finish', '') - # worker_id = request.POST.get('assign_worker', '') - # w = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) - # StudentComplain.objects.select_for_update().filter(id=iid).\ - # update(worker_id=w, status=1) - # url = '/complaint/secincharge/worker_id_know_more/'+wid; - # complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=iid) - # student=0 - # message = "Your complaint has been re-assigned" - # complaint_system_notif(request.user, complainer_details.complainer.user ,'reassign_worker_alert',complainer_details.id,student,message) - # return HttpResponseRedirect(url) +@login_required +def complaint_reassign(request,wid,iid): + current_user = get_object_or_404(User, username=request.user.username) + y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() + if request.method == 'POST': + type = request.POST.get('submit', '') + a = get_object_or_404(User, username=request.user.username) + y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() + comp_id = y.id + if type == 'assign': + + complaint_finish = request.POST.get('complaint_finish', '') + worker_id = request.POST.get('assign_worker', '') + w = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=worker_id) + StudentComplain.objects.select_for_update().filter(id=iid).\ + update(worker_id=w, status=1) + url = '/complaint/caretaker/worker_id_know_more/'+wid; + complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=iid) + student=0 + message = "Your complaint has been re-assigned" + complaint_system_notif(request.user, complainer_details.complainer.user ,'reassign_worker_alert',complainer_details.id,student,message) + return HttpResponseRedirect(url) + elif type == 'redirect': + assign_caretaker = request.POST.get('assign_caretaker', '') + c = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id=assign_caretaker) + c1 = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id=iid) + remark = 'Redirect complaint from ' + c1.area + StudentComplain.objects.select_for_update().filter(id=iid).\ + update(location=c.area, remarks=remark) + url = '/complaint/caretaker/worker_id_know_more/'+wid; + complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=iid) + student=0 + message = "Your complaint has been redirected to another caretaker" + complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_redirect_alert',complainer_details.id,student,message) + return HttpResponseRedirect(url) - # else: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - # b = a.work_type - # comp_id = y.id - # try: - # detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=iid).first() - # total_secincharge = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').all() - # total_secincharges_in_area = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(work_type=b) - # worker = [] - # workertemp = [] - # flag = '' - # temp = detail.location - # try: + else: + y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) + a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) + b = a.area + comp_id = y.id + try: + detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=iid).first() + total_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').all() + total_caretakers_in_area = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=b) + worker = [] + workertemp = [] + flag = '' + temp = detail.location + try: - # if Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a).count() == 0: - # flag = 'no_worker' - # else: - # workertemp = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a) - # j = 1 - # for i in workertemp: - # worker.append(i) - - # except SectionIncharge.DoesNotExist: - # flag = 'no_worker' - - # except StudentComplain.DoesNotExist: - # return HttpResponse("

Not a valid complaint

") - # return render(request, "complaintModule/reassignworker.html", - # {'detail': detail, 'worker': worker, 'flag': - # flag, 'total_secincharge': total_secincharge,'a':a, 'wid':wid, 'total_secincharges_in_area':total_secincharges_in_area}) - - - -# @login_required -# def complaint_reassign_super(request,caretaker_id,iid): - # current_user = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - # sup = Supervisor.objects.select_related('sup_id','sup_id__user','sup_id__department').get(sup_id = y) - # this_area = sup.area - # if request.method == 'POST': - # a = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - # comp_id = y.id - - -#for SectionIncharge + if Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a).count() == 0: + flag = 'no_worker' + else: + workertemp = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) + j = 1 + for i in workertemp: + worker.append(i) + # if j%2 != 0: + # worker.append(i) + # j = j + 1 + + + except Caretaker.DoesNotExist: + flag = 'no_worker' + + except StudentComplain.DoesNotExist: + return HttpResponse("

Not a valid complaint

") + return render(request, "complaintModule/reassignworker.html", + {'detail': detail, 'worker': worker, 'flag': + flag, 'total_caretaker': total_caretaker,'a':a, 'wid':wid, 'total_caretakers_in_area':total_caretakers_in_area}) + +@login_required +def complaint_reassign_super(request,caretaker_id,iid): + current_user = get_object_or_404(User, username=request.user.username) + y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() + sup = Supervisor.objects.select_related('sup_id','sup_id__user','sup_id__department').get(sup_id = y) + this_area = sup.area + if request.method == 'POST': + a = get_object_or_404(User, username=request.user.username) + y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() + comp_id = y.id + + + + + @login_required def assign_worker(request, comp_id1): current_user = get_object_or_404(User, username=request.user.username) @@ -110,89 +121,88 @@ def assign_worker(request, comp_id1): a = get_object_or_404(User, username=request.user.username) y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() comp_id = y.id - - - complaint_details = StudentComplain.objects.all().filter(id=comp_id1) - - - - complaint_type=complaint_details[0].complaint_type - - supervisor=Supervisor.objects.all().filter(type=complaint_type) - if not supervisor.exists(): - return HttpResponse("

Supervisor does not exist of this complaint type

") - - supervisor_details=ExtraInfo.objects.all().filter(id=supervisor[0].sup_id.id) - - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=comp_id1).\ - update(status=1) - - sup = HoldsDesignation.objects.select_related('user','working','designation').filter(user = supervisor_details[0].user_id) - - - files=File.objects.all().filter(src_object_id=comp_id1) - - supervisor_username=User.objects.all().filter(id=supervisor_details[0].user_id) - file=forward_file(file_id= files.first().id, - receiver=supervisor_username[0].username, - receiver_designation=sup[0].designation, - file_extra_JSON= {}, - remarks = "", - file_attachment= None) - print(file) - - - return HttpResponseRedirect('/complaint/caretaker/') + if type == 'assign': + complaint_finish = request.POST.get('complaint_finish', '') + worker_id = request.POST.get('assign_worker', '') + w = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=worker_id) + StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').select_for_update().filter(id=comp_id1).\ + update(worker_id=w, status=1) + complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=comp_id1) + student = 0 + message = "Worker has been assigned to your complaint" + complaint_system_notif(request.user, complainer_details.complainer.user ,'assign_worker_alert',complainer_details.id,student,message) + + return HttpResponseRedirect('/complaint/caretaker/') + elif type == 'redirect': + assign_caretaker = request.POST.get('assign_caretaker', '') + c = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id=assign_caretaker) + c1 = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id=comp_id) + remark = 'Redirect complaint from ' + c1.area + StudentComplain.objects.select_for_update().filter(id=comp_id1).\ + update(location=c.area, remarks=remark) + complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=comp_id1) + student=0 + message = "Your Complaint has been redirected to another caretaker" + complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_redirect_alert',complainer_details.id,student,message) + return HttpResponseRedirect('/complaint/caretaker/') else: y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - + a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) + b = a.area comp_id = y.id try: - detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=comp_id1).first() - # total_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').all() - # total_caretakers_in_area = Supervisor.objects.select_related('sup_id') - # supervisors_in_area= HoldsDesignation.objects.select_related('user','working','designation').get(total_caretakers_in_area = dsgn) - # workertemp = [] - # worker = [] - # flag = '' - # temp = detail.location - # try: - # if Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a).count() == 0: - # flag = 'no_worker' - # else: - # workertemp1 = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a) - # workertemp = workertemp1.filter(worker_type=detail.complaint_type) - # j = 1 - # for i in workertemp: - # worker.append(i) - - # except SectionIncharge.DoesNotExist: - # flag = 'no_worker' + detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=comp_id1).first() + total_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').all() + total_caretakers_in_area = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=b and id!=a.id) + workertemp = [] + worker = [] + flag = '' + temp = detail.location + try: + #care = Caretaker.objects.filter(area=temp).first() + if Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a).count() == 0: + flag = 'no_worker' + else: + workertemp1 = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) + workertemp = workertemp1.filter(worker_type=detail.complaint_type) + j = 1 + for i in workertemp: + worker.append(i) + # if j%2 != 0: + # worker.append(i) + # j = j + 1 + + + except Caretaker.DoesNotExist: + flag = 'no_worker' except StudentComplain.DoesNotExist: return HttpResponse("

Not a valid complaint

") return render(request, "complaintModule/assignworker.html", - {'detail': detail}) - + {'detail': detail, 'worker': worker, 'flag': + flag, 'total_caretaker': total_caretaker,'a':a, 'total_caretakers_in_area':total_caretakers_in_area}) -#for SectionIncharge @login_required def discharge_worker(request,wid,cid): current_user = get_object_or_404(User, username=request.user.username) y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - this_worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=wid) - com_in_concern= StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid); + this_worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=wid) + com_in_concern= StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=cid); com_in_concern.worker_id=None; com_in_concern.status=0; StudentComplain.objects.select_for_update().filter(id=cid).\ update(worker_id=None, status=0) - url='/complaint/secincharge/detail2/'+cid; + #StudentComplain.objects.get(id=cid).delete() + url='/complaint/caretaker/detail2/'+cid; return HttpResponseRedirect(url) + + + + @login_required def caretaker_feedback(request): """ @@ -224,23 +234,23 @@ def caretaker_feedback(request): return render(request, "complaintModule/submit_feedback_caretaker.html", {'a': a}) -#for SectionIncharge @login_required def worker_id_know_more(request, work_id): """ function to know pending complaints assigned to the worker """ - this_worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=work_id) - num = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=this_worker).count(); - complaints_list = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=this_worker); + this_worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=work_id) + num = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=this_worker).count(); + complaints_list = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=this_worker); complaints_list_onhold = [] for i in complaints_list: if i.status == 1: complaints_list_onhold.append(i) numpend = len(complaints_list_onhold) - work_under_secincharge1 = this_worker.secincharge_id.staff_id.user.first_name - work_under_secincharge2 = this_worker.secincharge_id.staff_id.user.last_name - return render(request, "complaintModule/worker_id_know_more.html",{'this_worker':this_worker,'work_under_secincharge1':work_under_secincharge1,'work_under_secincharge2':work_under_secincharge2, 'num':num, 'complaints_list':complaints_list, 'complaints_list_onhold':complaints_list_onhold, 'numpend':numpend}) + work_under_caretaker1 = this_worker.caretaker_id.staff_id.user.first_name + work_under_caretaker2 = this_worker.caretaker_id.staff_id.user.last_name + return render(request, "complaintModule/worker_id_know_more.html",{'this_worker':this_worker,'work_under_caretaker1':work_under_caretaker1,'work_under_caretaker2':work_under_caretaker2, 'num':num, 'complaints_list':complaints_list, 'complaints_list_onhold':complaints_list_onhold, 'numpend':numpend}) + @@ -273,31 +283,12 @@ def check(request): print('----------------------------') print('----------------------------') print('----------------------------') - supervisor_list=Supervisor.objects.all() - caretaker_list=Caretaker.objects.all() - is_supervisor=False - is_caretaker=False - for i in supervisor_list: - if b.id==i.sup_id_id: - is_supervisor=True - break - for i in caretaker_list: - if b.id==i.staff_id_id: - is_caretaker=True - break - if is_supervisor: - return HttpResponseRedirect('/complaint/supervisor/') - elif is_caretaker: - return HttpResponseRedirect('/complaint/caretaker/') - - elif b.user_type == 'student': + if b.user_type == 'student': return HttpResponseRedirect('/complaint/user/') - # elif b.user_type == 'fx': - # return HttpResponseRedirect('/complaint/supervisor/') elif b.user_type == 'staff': - return HttpResponseRedirect('/complaint/user/') + return HttpResponseRedirect('/complaint/caretaker/') elif b.user_type == 'faculty': - return HttpResponseRedirect('/complaint/user/') + return HttpResponseRedirect('/complaint/supervisor/') else: return HttpResponse("

wrong user credentials

") else: @@ -347,11 +338,20 @@ def user(request): complaint_finish = datetime.now() + timedelta(days=4) elif comp_type == 'other': complaint_finish = datetime.now() + timedelta(days=3) - + y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) + #check if location given if location!="": - - user_details=User.objects.get(id=y.user_id) - + # x = StudentComplain(complainer=y, + # complaint_type=comp_type, + # location=location, + # specific_location=specific_location, + # details=details, + # status=status, + # complaint_finish=complaint_finish, + # upload_complaint=comp_file) + + + # x.save() obj1, created = StudentComplain.objects.get_or_create(complainer=y, complaint_type=comp_type, location=location, @@ -361,11 +361,27 @@ def user(request): complaint_finish=complaint_finish, upload_complaint=comp_file) + + historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') + history = [] + j = 1 + k = 1 + for i in historytemp: + history.append(i) + # if j%2 != 0: + # history.append(i) + # j = j+1 - - - - + + for h in history: + h.serial_no = k + k = k+1 + # if location == "hall1": + # dsgn = "hall1caretaker" + # elif location == "hall3": + # dsgn = "hall3caretaker" + # else : + # dsgn = "hall4caretaker" if location == "hall-1": dsgn ="hall1caretaker" elif location =="hall-3": @@ -392,38 +408,24 @@ def user(request): dsgn = "rewacaretaker" caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - c1=HoldsDesignation.objects.filter(user_id=y.user_id).all() - print(c1[0].designation) - file_id = create_file(uploader=user_details.username, - uploader_designation=c1[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=caretaker_name.designation, - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) - - # print(" wertyuioiuhygfdsdfghjk") - print(file_id) # This is to allow the student - student = 0 + student = 1 message = "A New Complaint has been lodged" complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - # complaint_system_notif(request.user, secincharge_name.staff_id.user,'lodge_comp_alert',obj1.id,1,message) - - messages.success(request,message) - + # return render(request, "complaintModule/complaint_user.html", + # {'history': history, 'comp_id': comp_id }) + # next = request.POST.get('next', '/') + messages.success(request,message) return HttpResponseRedirect('/complaint/user') else: a = get_object_or_404(User, username=request.user.username) y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - - user_details=User.objects.get(id=y.user_id) - + historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') + history=[] notification = Notification.objects.filter(recipient=a.id) notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) @@ -435,54 +437,45 @@ def user(request): # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') - c1=HoldsDesignation.objects.filter(user_id=y.user_id).all() - print(c1[0].designation) - # c2=Designation.objects.filter(i) - - - - outbox_files = view_outbox( - username=user_details.username, - designation=c1[0].designation, - src_module="complaint" - ) - print(outbox_files) - - outbox=[] - comp_list=set() - for i in outbox_files: - - outbox.append(i) - print(outbox) - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - if complaint[0].complainer.user.username == user_details.username : - comp_list.add(complaint) - # file_history = view_history(file_id=i['id']) - - # comp=File.objects.filter(uploader=file_history[0]['current_id']) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list.add(c) - # print(c[0]) - - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) + + j = 1 + for i in historytemp: + history.append(i) + # if j%2 != 0: + # history.append(i) + # j = j+1 + + for i in history: + i.serial_no = j + j = j+1 + + # if location == "hall-1": + # dsgn ="hall1caretaker" + # elif location =="hall-3": + # dsgn ="hall3caretaker" + # elif location =="hall-4": + # dsgn ="hall4caretaker" + # elif location =="CC1": + # dsgn ="CC convenor" + # elif location =="CC2": + # dsgn ="CC2 convener" + # elif location == "core_lab": + # dsgn = "corelabcaretaker" + # elif location =="LHTC": + # dsgn ="lhtccaretaker" + # elif location =="NR2": + # dsgn ="nr2caretaker" + # else: + # dsgn = "rewacaretaker" + # caretaker_name = HoldsDesignation.objects.get(designation__name = dsgn) - sorted_history = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) - print(complaint_final_list) + # complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert') return render(request, "complaintModule/complaint_user.html", - {'outbox': sorted_history,'notification':notification, 'comp_id': y.id, 'history':outbox}) - + {'history': history,'notification':notification, 'comp_id': y.id}) + return render(request, "complaintModule/complaint_user.html", + {'history': history, 'comp_id': comp_id }) @login_required def save_comp(request): """ @@ -530,15 +523,14 @@ def save_comp(request): upload_complaint =comp_file) x.save() - + # messages.info(request,'Complaint successfully launched.') + # return HttpResponseRedirect('/complaint/user/') return HttpResponseRedirect('/complaint/user/') - - @login_required def caretaker(request): """ - The function is used to display details to the caretaker such as registered complaints + The function is used to display details to the caretaker such as registered complaints and allows to assign workers @param: request - trivial. @@ -551,21 +543,21 @@ def caretaker(request): """ current_user = get_object_or_404(User, username=request.user.username) y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - + if request.method == 'POST': - # type = request.POST.get('submit', '') - # worker_type = request.POST.get('complaint_type', '') - # name = request.POST.get('name', '') - # phone = request.POST.get('phone_no', '') - # age = request.POST.get('age', '') - # try: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - # except Exception as e: - # a = None - # y = None - # intage = int(age) - # intphone = int(phone) + type = request.POST.get('submit', '') + worker_type = request.POST.get('complaint_type', '') + name = request.POST.get('name', '') + phone = request.POST.get('phone_no', '') + age = request.POST.get('age', '') + try: + y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) + a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) + except Exception as e: + a = None + y = None + intage = int(age) + intphone = int(phone) # if len(phone) == 10 and intage > 20 and intage < 50 and intphone > 1999999999: # x = Workers(caretaker_id=a, # name=name, @@ -575,252 +567,116 @@ def caretaker(request): # if not Workers.objects.filter(caretaker_id=a,name=name, age=age,phone=phone,worker_type=worker_type).exists(): # x.save() - # if len(phone) == 10 and intage > 20 and intage < 50 and intphone > 1999999999: - # obj, created = Workers.objects.get_or_create(caretaker_id=a, - # name=name, - # age=age, - # phone=phone, - # worker_type=worker_type) + if len(phone) == 10 and intage > 20 and intage < 50 and intphone > 1999999999: + obj, created = Workers.objects.get_or_create(caretaker_id=a, + name=name, + age=age, + phone=phone, + worker_type=worker_type) + + b = a.area + historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=b).order_by('-id') + history = [] + j = 1 + k = 1 + for i in historytemp: + history.append(i) + # if j%2 == 1: + # history.append(i) + # j = j+1 + for h in history: + h.serial_no = k + k=k+1 - # b = a.area - # historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=b).order_by('-id') - # history = [] - # j = 1 - # k = 1 - # for i in historytemp: - # history.append(i) - # # if j%2 == 1: - # # history.append(i) - # # j = j+1 - - # for h in history: - # h.serial_no = k - # k=k+1 - user_details=User.objects.get(id=y.user_id) - # if user_details.username=="shyams": - # desgn="hall3caretaker" - # if user_details.username=="hall4caretaker": - # desgn="hall4caretaker" - - # total_worker = [] - - # total_workertemp = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) - # j = 1 + total_worker = [] + total_workertemp = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) + j = 1 # for i in total_workertemp: # if j%2 != 0: # total_worker.append(i) # j = j + 1 - # for i in total_workertemp: - # total_worker.append(i) + for i in total_workertemp: + total_worker.append(i) complaint_assign_no = [] - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - # y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - user_details=User.objects.get(id=y.user_id) - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - print(caretaker_name.user.username) - print(user_details.username) - print(caretaker_name.designation) - - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - file_id = create_file(uploader=user_details.username, - uploader_designation=des[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=dsgn, - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - # return HttpResponseRedirect('/complaint/user') - - # for x in total_worker: - # worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=x.id) - # temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=worker).count() - # worker.total_complaint = temp - # complaint_assign_no.append(worker) + for x in total_worker: + worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=x.id) + temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=worker).count() + worker.total_complaint = temp + complaint_assign_no.append(worker) notification = Notification.objects.filter(recipient=current_user.id) notification = notification.filter(data__exact={'url':'complaint:detail2','module':'Complaint System'}) - - return HttpResponseRedirect('/complaint/caretaker') + return render(request, "complaintModule/complaint_caretaker.html", + {'history': history, 'comp_id': y.id, + 'notification': notification, 'total_worker': + total_worker, 'complaint_assign_no': complaint_assign_no}) else: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - - a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y.id) + y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) + a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) b = a.area history = [] - - - complaint_assign_no = [] - user_details=User.objects.get(id=y.user_id) - - notification = Notification.objects.filter(recipient=current_user.id) - notification = notification.filter(data__exact={'url':'complaint:detail2','module':'Complaint System'}) - user_details=User.objects.get(id=y.user_id) - - - des=HoldsDesignation.objects.filter(user=user_details).all() - print("######") - print(user_details.username) - print(des[0].designation) - print("&&&&&") - outbox_files = view_outbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) - - outbox=[] - comp_list=set() - for i in outbox_files: - # print(i) - outbox.append(i) - - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - print("********") - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - print("------") - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint[0].complainer.user.username) - - print("......") - if complaint[0].complainer.user.username== user_details.username : - comp_list.add(complaint) + historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=b).order_by('-id') + total_worker = [] + total_workertemp = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) + j = 1 + for i in total_workertemp: + total_worker.append(i) - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) - - sorted_history_out = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) - - inbox_files = view_inbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) - print(inbox_files) - - inbox=[] - comp_list_in=set() - for i in inbox_files: - # print(i) - inbox.append(i) - file_history_list=[] - for i in inbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list_in.add(complaint) - - complaint_final_list_in=[] - for i in comp_list_in: - complaint_final_list_in.append(i[0]) + complaint_assign_no = [] + complaint_assign_no = [] + + for x in total_worker: + worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=x.id) + temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=worker).count() + worker.total_complaint = temp + complaint_assign_no.append(worker) + + overduecomplaint = [] + j = 1 + k = 1 + for i in historytemp: + history.append(i) + # if j%2 != 0: + # history.append(i) + # j=j+1 + for i in history: + i.serial_no = k + k = k + 1 - # print(complaint_final_list_in) - sorted_history = sorted(complaint_final_list_in, key=attrgetter('complaint_date'), reverse=True) + if i.status != 2 and i.status !=3: + if i.complaint_finish < date.today(): + i.delay = date.today() - i.complaint_finish + overduecomplaint.append(i) + + notification = Notification.objects.filter(recipient=current_user.id) + notification = notification.filter(data__exact={'url':'complaint:detail2','module':'Complaint System'}) + + return render(request, "complaintModule/complaint_caretaker.html", - { 'history': sorted_history, - 'comp_id': y.id, - 'carehistory':sorted_history_out, - 'notification':notification, - 'care_id': a}) + { 'history': history, 'comp_id': y.id, 'total_worker': total_worker, + 'complaint_assign_no': total_worker, + 'notification':notification, + 'overduecomplaint': overduecomplaint, 'care_id': a}) @login_required def remove_worker_from_complaint(request,complaint_id): """ - The function is used by secincharge to remove a worker + The function is used by caretaker to remove a worker already assigned to a complaint @param: request - trivial complaint_id - used to get complaint_id registered """ - complaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complaint_id=complaint_id).update(worker_id='') + complaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complaint_id=complaint_id).update(worker_id='') return HttpResponseRedirect('/complaint/caretaker/') @@ -835,37 +691,6 @@ def changestatus(request, complaint_id, status): complaint_id - used to get complaint_id registered. status-used to get the current status of complaints - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - if status == '3': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/caretaker/') - elif status == '2': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/caretaker/') - else: - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status) - return HttpResponseRedirect('/complaint/caretaker/') - - - - -@login_required -def changestatussuper(request, complaint_id, status): - """ - The function is used by caretaker to change the status of a complaint. - @param: - request - trivial. - complaint_id - used to get complaint_id registered. - status-used to get the current status of complaints - @variables: issue - The issue object. supported - True if the user's intention is to support the issue. @@ -875,21 +700,21 @@ def changestatussuper(request, complaint_id, status): if status == '3': StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/supervisor/') + return HttpResponseRedirect('/complaint/caretaker/') elif status == '2': StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/supervisor/') + return HttpResponseRedirect('/complaint/caretaker/') else: StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ update(status=status) - return HttpResponseRedirect('/complaint/supervisor/') + return HttpResponseRedirect('/complaint/caretaker/') @login_required def removew(request, work_id): """ - The function is used by secincharge to remove workers. + The function is used by caretaker to remove workers. @param: request - trivial. work_id - id of the issue object which the user intends to support/unsupport. @@ -900,18 +725,15 @@ def removew(request, work_id): support_count - Total supporters of the above issue. context - Holds data needed to make necessary changes in the template. """ - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=work_id) - temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=worker).count() + worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=work_id) + temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=worker).count() if temp == 0: worker.delete() - return HttpResponseRedirect('/complaint/secincharge/') + return HttpResponseRedirect('/complaint/caretaker/') else: return HttpResponse('

Worker is assign some complaint

') - - - @login_required def submitfeedback(request, complaint_id): """ @@ -930,9 +752,9 @@ def submitfeedback(request, complaint_id): if request.method == 'POST': feedback = request.POST.get('feedback', '') rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ + StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() + a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).first() care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() rate = care.rating newrate = 0 @@ -946,26 +768,27 @@ def submitfeedback(request, complaint_id): Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) return HttpResponseRedirect('/complaint/user/') + return render(request,"complaintModule/feedback.html",{'a' : a}) else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) + a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=complaint_id) return render(request, "complaintModule/submit_feedback.html", {'a': a}) -#for SectionIncharge + + @login_required def deletecomplaint(request, comp_id1): """ function to delete complaint """ StudentComplain.objects.get(id=comp_id1).delete() - return HttpResponseRedirect('/complaint/secincharge/') - - + return HttpResponseRedirect('/complaint/caretaker/') def testEntry(): + # list1 = [('SKM','hall-1'),('HS','hall-3'),('PS','hall-4'),('MSR','Maa Saraswati Hostel'),('KKB','Maa Saraswati Hostel'), ('RP','Nagarjun Hostel'),('DS','Nagarjun Hostel'),('AV','Panini Hostel')] list1 = [('eecivil','NR2'),('eecivil','Rewa_Residency'),('eecivil','LHTC'),('eecivil','core_lab')] # to delete supervisors @@ -997,11 +820,9 @@ def supervisor(request): """ # print("--------------------------") # testEntry() - # print(request.type) - location = request.POST.get('Location', '') current_user = get_object_or_404(User, username=request.user.username) + y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - comp_id = y.id if request.method == 'POST' : try: y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) @@ -1009,231 +830,78 @@ def supervisor(request): except Exception as e: a = None y = None - all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=location).order_by('-id') + all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.area).order_by('-id') area = all_caretaker[0].area # ExtraInfo.objects.get(id=sup_id) all_complaint = [] - numtemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(location = area).filter(status = 0).count() + numtemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location = area).filter(status = 0).count() num = int(numtemp/2+0.5) - - - - - - - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - user_details=User.objects.get(id=y.user_id) - # c2=Supervisor.objects.all().filter(area=location) - print(caretaker_name.user.username) - print(user_details.username) - print(caretaker_name.designation) - - # sup = HoldsDesignation.objects.select_related('user','working','designation').get(user = y.id) - # print(sup.designation) - - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - - - file_id = create_file(uploader=user_details.username, - uploader_designation=des[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=str(caretaker_name.designation), - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - # return HttpResponseRedirect('/complaint/user') - - return HttpResponseRedirect('/complaint/supervisor') + all_complainttemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=a.area).order_by('-id') + j = 1 + for i in all_complainttemp: + all_complaint.append(i) + # if j%2 != 0: + # all_complaint.append(i) + # j = j + 1 + overduecomplaint = [] + for i in all_complaint: + if i.status != 2 and i.status != 3: + if i.complaint_finish < date.today(): + i.delay = date.today() - i.complaint_finish + overduecomplaint.append(i) + return render(request, "complaintModule/supervisor1.html", + {'all_caretaker': all_caretaker, 'all_complaint': all_complaint, + 'overduecomplaint': overduecomplaint, 'area': area,'num':num}) else: - - - all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').order_by('-id') + print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') + y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) + try: + a = get_object_or_404(Supervisor, sup_id=y) + except : + return HttpResponseRedirect('/') + + #print(a) + # if(len(a)==0) : + # return render('../dashboard/') + a = Supervisor.objects.select_related('sup_id','sup_id__user','sup_id__department').get(sup_id=y) + all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.area).order_by('-id') area = all_caretaker[0].area - numtemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location = area).filter(status = 0).count() num = int(numtemp/2+0.5) all_complaint = [] - user_details=User.objects.get(id=y.user_id) - - - + all_complainttemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=a.area).order_by('-id') + j = 1 + for i in all_complainttemp: + all_complaint.append(i) + # if j%2 != 0: + # all_complaint.append(i) + # j = j + 1 + overduecomplaint = [] + for i in all_complaint: + if i.status != 2 and i.status != 3: + if i.complaint_finish < date.today(): + i.delay = date.today() - i.complaint_finish + overduecomplaint.append(i) - - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - # print(y.user_id) - # print(user_details.username) - # print(des[0].user) - outbox_files = view_outbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) - - outbox=[] - comp_list=set() - for i in outbox_files: - # print(i) - outbox.append(i) - - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list.add(complaint) - # file_history = view_history(file_id=i['id']) - - # comp=File.objects.filter(uploader=file_history[0]['current_id']) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list.add(c) - # print(c[0]) - - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) - sorted_history_out = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) - - inbox_files = view_inbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) - inbox=[] - comp_list_in=set() - for i in inbox_files: - inbox.append(i) - # print(inbox[0]['id']) - - for i in inbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list_in.add(complaint) - # print(complaint[0]) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list_in.add(c) - # print(c[0]) - - # break - complaint_final_list_in=[] - for i in comp_list_in: - complaint_final_list_in.append(i[0]) - - sorted_history = sorted(complaint_final_list_in, key=attrgetter('complaint_date'), reverse=True) - print(complaint_final_list_in) return render(request, "complaintModule/supervisor1.html", - - {'history':sorted_history,'all_caretaker': all_caretaker, 'all_complaint': all_complaint,'outbox':sorted_history_out}) + {'all_caretaker': all_caretaker, 'all_complaint': all_complaint, + 'overduecomplaint': overduecomplaint, 'area': area, 'num' : num}) @login_required def caretaker_id_know_more(request,caretaker_id): this_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id = caretaker_id) - this_caretaker_area = this_caretaker.area + this_caretaker_area = this_caretaker.area; list_pending_complaints = [] - list_pending_complaintstemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(location = this_caretaker_area).filter(status = 0) + list_pending_complaintstemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location = this_caretaker_area).filter(status = 0) j = 1 for i in list_pending_complaintstemp: list_pending_complaints.append(i) - + # if j%2 != 0: + # list_pending_complaints.append(i) + # j = j + 1 + # num = StudentComplain.objects.filter(location = this_caretaker_area).filter(status = 0).count(); num = len(list_pending_complaints) return render(request, "complaintModule/caretaker_id_know_more.html",{'this_caretaker':this_caretaker , 'list_pending_complaints':list_pending_complaints, 'num':num}) @@ -1243,36 +911,6 @@ def search_complaint(request): @login_required def resolvepending(request, cid): - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - if request.method == 'POST': - newstatus = request.POST.get('yesorno','') - comment = request.POST.get('comment') - intstatus = 0 - if newstatus == 'Yes': - intstatus = 2 - else: - intstatus = 3 - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(status=intstatus) - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(comment=comment) - complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - student=0 - message = "Congrats! Your complaint has been resolved" - complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/caretaker/") - else: - # complainer_details = StudentComplain.objects.get(id=cid) - # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') - return render(request,"complaintModule/resolve_pending.html",{"a" : a,"thiscomplaint" : thiscomplaint}) - - - - -@login_required -def resolvependingsuper(request, cid): a = get_object_or_404(User, username=request.user.username) y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=cid) @@ -1292,37 +930,7 @@ def resolvependingsuper(request, cid): student=0 message = "Congrats! Your complaint has been resolved" complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/supervisor/") - else: - # complainer_details = StudentComplain.objects.get(id=cid) - # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') - return render(request,"complaintModule/resolve_pending.html",{"a" : a,"thiscomplaint" : thiscomplaint}) - - - - -@login_required -def resolvependingsuper(request, cid): - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - if request.method == 'POST': - newstatus = request.POST.get('yesorno','') - comment = request.POST.get('comment') - intstatus = 0 - if newstatus == 'Yes': - intstatus = 2 - else: - intstatus = 3 - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(status=intstatus) - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(comment=comment) - complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - student=0 - message = "Congrats! Your complaint has been resolved" - complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/supervisor/") + return HttpResponseRedirect("/complaint/caretaker/") else: # complainer_details = StudentComplain.objects.get(id=cid) # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') @@ -1330,7 +938,6 @@ def resolvependingsuper(request, cid): - def login1(request): if request.method == 'POST': u = request.POST.get('username', '') @@ -1349,10 +956,10 @@ def login1(request): @login_required def feedback_super(request, feedcomp_id): - detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=feedcomp_id) + detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=feedcomp_id) a=User.objects.get(username=detail3.complainer.user.username) y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() + temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).first() comp_id=temp.id loc = detail3.location care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=loc).first() @@ -1361,49 +968,47 @@ def feedback_super(request, feedcomp_id): @login_required def feedback_care(request, feedcomp_id): - detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=feedcomp_id) + detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=feedcomp_id) a=User.objects.get(username=detail2.complainer.user.username) y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() + temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).first() comp_id=temp.id return render(request, "complaintModule/feedback_care.html", {"detail2": detail2,"comp_id":comp_id}) -#for complainaint and caretaker + + @login_required def detail(request, detailcomp_id1): """ function that shows detail about complaint """ - detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) + detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=detailcomp_id1) if(detail.worker_id is None): worker_name = None worker_id = detail.worker_id else: worker_id = detail.worker_id.id - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) + worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=worker_id) worker_name = worker.name a=User.objects.get(username=detail.complainer.user.username) y=ExtraInfo.objects.all().select_related('user','department').get(user=a) num=0 if detail.upload_complaint != "": num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() + temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).first() comp_id=temp.id return render(request, "complaintModule/complaint_user_detail.html", {"detail": detail, "comp_id":detail.id,"num":num,"worker_name":worker_name}) - - -#for SectionIncharge @login_required def detail2(request, detailcomp_id1): - detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) + detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=detailcomp_id1) if(detail2.worker_id is None): worker_name = None worker_id = detail2.worker_id else: worker_id = detail2.worker_id.id - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) + worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=worker_id) worker_name = worker.name a=User.objects.get(username=detail2.complainer.user.username) y=ExtraInfo.objects.all().select_related('user','department').get(user=a) @@ -1411,474 +1016,20 @@ def detail2(request, detailcomp_id1): if detail2.upload_complaint != "": num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() + temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).first() comp_id=temp.id - return render(request, "complaintModule/complaint_secincharge_detail.html", {"detail2": detail2, "comp_id":detail2.id,"num":num,"worker_name":worker_name,"wid":worker_id}) - + return render(request, "complaintModule/complaint_caretaker_detail.html", {"detail2": detail2, "comp_id":detail2.id,"num":num,"worker_name":worker_name,"wid":worker_id}) @login_required def detail3(request, detailcomp_id1): - detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) + detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=detailcomp_id1) a=User.objects.get(username=detail3.complainer.user.username) y=ExtraInfo.objects.all().select_related('user','department').get(user=a) num=0 if detail3.upload_complaint != "": num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() + temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).first() comp_id=temp.id loc = detail3.location care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=loc).first() return render(request, "complaintModule/complaint_supervisor_detail.html", {"detail3": detail3,"comp_id":comp_id,"care":care,"num":num}) - - - - -@login_required - -def supervisorlodge(request): - """ - The function is used to register a complaint - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - num = 1 - comp_id = y.id - if request.method == 'POST': - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history = [] - j = 1 - k = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - - for h in history: - h.serial_no = k - k = k+1 - # if location == "hall1": - # dsgn = "hall1caretaker" - # elif location == "hall3": - # dsgn = "hall3caretaker" - # else : - # dsgn = "hall4caretaker" - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - return HttpResponseRedirect('/complaint/supervisor') - - else: - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history=[] - - notification = Notification.objects.filter(recipient=a.id) - notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) - # notification_message = [] - # for notification in x: - # to = User.objects.get(id=notification.actor_object_id).username - # from django.utils.timesince import timesince as timesince_ - # duration = timesince_(notification.timestamp,None) - # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') - - - - - j = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - for i in history: - i.serial_no = j - j = j+1 - - # if location == "hall-1": - # dsgn ="hall1caretaker" - # elif location =="hall-3": - # dsgn ="hall3caretaker" - # elif location =="hall-4": - # dsgn ="hall4caretaker" - # elif location =="CC1": - # dsgn ="CC convenor" - # elif location =="CC2": - # dsgn ="CC2 convener" - # elif location == "core_lab": - # dsgn = "corelabcaretaker" - # elif location =="LHTC": - # dsgn ="lhtccaretaker" - # elif location =="NR2": - # dsgn ="nr2caretaker" - # else: - # dsgn = "rewacaretaker" - # caretaker_name = HoldsDesignation.objects.get(designation__name = dsgn) - - # complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert') - return render(request, "complaintModule/supervisor1.html", - {'history': history,'notification':notification, 'comp_id': y.id}) - - return render(request, "complaintModule/complaint_user.html", - {'history': history, 'comp_id': comp_id }) - - - - -@login_required -def submitfeedbacksuper(request, complaint_id): - """ - The function is used by the complainant to enter feedback after the complaint has been resolved - @param: - request - trivial. - complaint_id - id of the registerd complaint. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - - if request.method == 'POST': - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() - rate = care.rating - newrate = 0 - if rate == 0: - newrate = rating - else: - a1 = int(rating) - b1 = int(rate) - c1 = int((a1+b1)/2) - newrate = c1 - - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) - return HttpResponseRedirect('/complaint/supervisor/') - return render(request,"complaintModule/feedback.html",{'a' : a}) - - else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) - return render(request, "complaintModule/submit_feedback.html", {'a': a}) - - - -@login_required - -def caretakerlodge(request): - """ - The function is used to register a complaint - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - num = 1 - comp_id = y.id - if request.method == 'POST': - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history = [] - j = 1 - k = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - - for h in history: - h.serial_no = k - k = k+1 - # if location == "hall1": - # dsgn = "hall1caretaker" - # elif location == "hall3": - # dsgn = "hall3caretaker" - # else : - # dsgn = "hall4caretaker" - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - return HttpResponseRedirect('/complaint/caretaker') - - else: - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history=[] - - notification = Notification.objects.filter(recipient=a.id) - notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) - # notification_message = [] - # for notification in x: - # to = User.objects.get(id=notification.actor_object_id).username - # from django.utils.timesince import timesince as timesince_ - # duration = timesince_(notification.timestamp,None) - # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') - - - - - j = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - for i in history: - i.serial_no = j - j = j+1 - - # if location == "hall-1": - # dsgn ="hall1caretaker" - # elif location =="hall-3": - # dsgn ="hall3caretaker" - # elif location =="hall-4": - # dsgn ="hall4caretaker" - # elif location =="CC1": - # dsgn ="CC convenor" - # elif location =="CC2": - # dsgn ="CC2 convener" - # elif location == "core_lab": - # dsgn = "corelabcaretaker" - # elif location =="LHTC": - # dsgn ="lhtccaretaker" - # elif location =="NR2": - # dsgn ="nr2caretaker" - # else: - # dsgn = "rewacaretaker" - # caretaker_name = HoldsDesignation.objects.get(designation__name = dsgn) - - # complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert') - return render(request, "complaintModule/complaint_caretaker.html", - {'history': history,'notification':notification, 'comp_id': y.id}) - - return render(request, "complaintModule/complaint_user.html", - {'history': history, 'comp_id': comp_id }) - - -@login_required -def submitfeedbackcaretaker(request, complaint_id): - """ - The function is used by the complainant to enter feedback after the complaint has been resolved - @param: - request - trivial. - complaint_id - id of the registerd complaint. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - - if request.method == 'POST': - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() - rate = care.rating - newrate = 0 - if rate == 0: - newrate = rating - else: - a1 = int(rating) - b1 = int(rate) - c1 = int((a1+b1)/2) - newrate = c1 - - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) - return HttpResponseRedirect('/complaint/caretaker/') - return render(request,"complaintModule/feedback.html",{'a' : a}) - - else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) - return render(request, "complaintModule/submit_feedback.html", {'a': a}) \ No newline at end of file diff --git a/FusionIIIT/applications/counselling_cell/migrations/0001_initial.py b/FusionIIIT/applications/counselling_cell/migrations/0001_initial.py index f0214910c..b87618488 100644 --- a/FusionIIIT/applications/counselling_cell/migrations/0001_initial.py +++ b/FusionIIIT/applications/counselling_cell/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models @@ -10,8 +10,8 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('globals', '0001_initial'), ('academic_information', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ diff --git a/FusionIIIT/applications/department/migrations/0001_initial.py b/FusionIIIT/applications/department/migrations/0001_initial.py index cb016ad8b..fc8a34834 100644 --- a/FusionIIIT/applications/department/migrations/0001_initial.py +++ b/FusionIIIT/applications/department/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models diff --git a/FusionIIIT/applications/department/models.py b/FusionIIIT/applications/department/models.py index f8e1392db..e04e9e578 100644 --- a/FusionIIIT/applications/department/models.py +++ b/FusionIIIT/applications/department/models.py @@ -5,6 +5,7 @@ # Create your models here. from applications.globals.models import ExtraInfo + class SpecialRequest(models.Model): request_maker = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) request_date = models.DateTimeField(default=date.today) diff --git a/FusionIIIT/applications/department/views.py b/FusionIIIT/applications/department/views.py index f138c77db..845171836 100644 --- a/FusionIIIT/applications/department/views.py +++ b/FusionIIIT/applications/department/views.py @@ -223,7 +223,7 @@ def staff_view(request): upload_announcement=upload_announcement, department = department, ann_date=ann_date) - department_notif(usrnm, recipients , message) + # department_notif(usrnm, recipients , message) context = browse_announcements() return render(request, 'department/dep_request.html', {"user_designation":user_info.user_type, diff --git a/FusionIIIT/applications/eis/migrations/0001_initial.py b/FusionIIIT/applications/eis/migrations/0001_initial.py index f3dbd4bf3..2fd2e65d3 100644 --- a/FusionIIIT/applications/eis/migrations/0001_initial.py +++ b/FusionIIIT/applications/eis/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.conf import settings @@ -49,7 +49,7 @@ class Migration(migrations.Migration): name='emp_techtransfer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('details', models.CharField(default=' ', max_length=500)), ('date_entry', models.DateField(blank=True, default=datetime.datetime.now, null=True)), ('start_date', models.DateField(blank=True, null=True)), @@ -61,7 +61,7 @@ class Migration(migrations.Migration): name='emp_session_chair', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('name', models.CharField(default=' ', max_length=500)), ('event', models.TextField(default=' ', max_length=2500)), ('s_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017)], null=True, verbose_name='year')), @@ -77,7 +77,7 @@ class Migration(migrations.Migration): name='emp_research_projects', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('ptype', models.CharField(default='Research', max_length=100)), ('pi', models.CharField(default=' ', max_length=1000)), ('co_pi', models.CharField(default=' ', max_length=1500)), @@ -96,7 +96,7 @@ class Migration(migrations.Migration): name='emp_research_papers', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('rtype', models.CharField(choices=[('Journal', 'Journal'), ('Conference', 'Conference')], default='Conference', max_length=500)), ('authors', models.CharField(blank=True, max_length=2500, null=True)), ('co_authors', models.CharField(blank=True, max_length=2500, null=True)), @@ -113,7 +113,7 @@ class Migration(migrations.Migration): ('end_date', models.DateField(blank=True, null=True)), ('date_acceptance', models.DateField(blank=True, null=True)), ('date_publication', models.DateField(blank=True, null=True)), - ('year', models.CharField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], max_length=10, null=True)), + ('year', models.CharField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], max_length=10, null=True)), ('a_month', models.CharField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, max_length=500, null=True)), ('doc_id', models.CharField(blank=True, max_length=50, null=True)), ('doc_description', models.CharField(blank=True, max_length=1000, null=True)), @@ -128,11 +128,11 @@ class Migration(migrations.Migration): name='emp_published_books', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('p_type', models.CharField(choices=[('Book', 'Book'), ('Monograph', 'Monograph'), ('Book Chapter', 'Book Chapter'), ('Handbook', 'Handbook'), ('Technical Report', 'Technical Report')], max_length=16)), ('title', models.CharField(default=' ', max_length=2500)), ('publisher', models.CharField(default=' ', max_length=2500)), - ('pyear', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('pyear', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('authors', models.CharField(default=' ', max_length=250)), ('date_entry', models.DateField(blank=True, default=datetime.datetime.now, null=True)), ('publication_date', models.DateField(blank=True, null=True)), @@ -143,12 +143,12 @@ class Migration(migrations.Migration): name='emp_patents', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('p_no', models.CharField(max_length=150)), ('title', models.CharField(max_length=1500)), ('earnings', models.IntegerField(default=0)), ('status', models.CharField(choices=[('Filed', 'Filed'), ('Granted', 'Granted'), ('Published', 'Published'), ('Owned', 'Owned')], max_length=15)), - ('p_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('p_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, null=True, verbose_name='Month')), ('date_entry', models.DateField(blank=True, default=datetime.datetime.now, null=True)), ('start_date', models.DateField(blank=True, null=True)), @@ -160,14 +160,14 @@ class Migration(migrations.Migration): name='emp_mtechphd_thesis', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('degree_type', models.IntegerField(default=1)), ('title', models.CharField(max_length=250)), ('supervisors', models.CharField(max_length=250)), ('co_supervisors', models.CharField(blank=True, max_length=250, null=True)), ('rollno', models.CharField(max_length=200)), ('s_name', models.CharField(max_length=5000)), - ('s_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('s_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, null=True, verbose_name='Month')), ('date_entry', models.DateField(blank=True, default=datetime.datetime.now, null=True)), ('start_date', models.DateField(blank=True, null=True)), @@ -181,14 +181,14 @@ class Migration(migrations.Migration): name='emp_keynote_address', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('type', models.CharField(choices=[('Keynote', 'Keynote'), ('Plenary Address', 'Plenary Address')], default='Keynote', max_length=140)), ('title', models.CharField(max_length=1000)), ('name', models.CharField(max_length=1000)), ('venue', models.CharField(max_length=1000)), ('page_no', models.CharField(max_length=100)), ('isbn_no', models.CharField(max_length=200)), - ('k_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('k_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, null=True, verbose_name='Month')), ('start_date', models.DateField(blank=True, null=True)), ('end_date', models.DateField(blank=True, null=True)), @@ -200,12 +200,12 @@ class Migration(migrations.Migration): name='emp_expert_lectures', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('l_type', models.CharField(choices=[('Expert Lecture', 'Expert Lecture'), ('Invited Talk', 'Invited Talk')], default='Expert Lecture', max_length=14)), ('title', models.CharField(max_length=1000)), ('place', models.CharField(max_length=1000)), ('l_date', models.DateField(blank=True, null=True)), - ('l_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('l_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, null=True, verbose_name='Month')), ('date_entry', models.DateField(blank=True, default=datetime.datetime.now, null=True)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), @@ -215,7 +215,7 @@ class Migration(migrations.Migration): name='emp_event_organized', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('type', models.CharField(choices=[('Training Program', 'Training Program'), ('Seminar', 'Seminar'), ('Short Term Program', 'Short Term Program'), ('Workshop', 'Workshop'), ('Any Other', 'Any Other')], max_length=180)), ('name', models.CharField(max_length=1000)), ('sponsoring_agency', models.CharField(max_length=150)), @@ -231,7 +231,7 @@ class Migration(migrations.Migration): name='emp_consultancy_projects', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('consultants', models.CharField(max_length=150)), ('title', models.CharField(max_length=1000)), ('client', models.CharField(max_length=1000)), @@ -249,10 +249,10 @@ class Migration(migrations.Migration): name='emp_confrence_organised', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('name', models.CharField(max_length=500)), ('venue', models.CharField(max_length=500)), - ('k_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('k_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], default=1, null=True, verbose_name='Month')), ('start_date', models.DateField(blank=True, null=True)), ('end_date', models.DateField(blank=True, null=True)), @@ -266,12 +266,12 @@ class Migration(migrations.Migration): name='emp_achievement', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pf_no', models.CharField(max_length=20)), + ('pf_no', models.IntegerField()), ('a_type', models.CharField(choices=[('Award', 'Award'), ('Honour', 'Honour'), ('Prize', 'Prize'), ('Other', 'Other')], default='Other', max_length=180)), ('details', models.TextField(default=' ', max_length=1550)), ('a_day', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19), (20, 20), (21, 21), (22, 22), (23, 23), (24, 24), (25, 25), (26, 26), (27, 27), (28, 28), (29, 29), (30, 30), (31, 31)], null=True, verbose_name='Day')), ('a_month', models.IntegerField(blank=True, choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12)], null=True, verbose_name='Month')), - ('a_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year')), + ('a_year', models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023)], null=True, verbose_name='year')), ('date_entry', models.DateField(default=datetime.datetime.now)), ('achievment_date', models.DateField(blank=True, null=True)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), diff --git a/FusionIIIT/applications/eis/migrations/0002_auto_20240420_1925.py b/FusionIIIT/applications/eis/migrations/0002_auto_20240420_1925.py new file mode 100644 index 000000000..24f151143 --- /dev/null +++ b/FusionIIIT/applications/eis/migrations/0002_auto_20240420_1925.py @@ -0,0 +1,53 @@ +# Generated by Django 3.1.5 on 2024-04-20 19:25 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('eis', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='emp_achievement', + name='a_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_confrence_organised', + name='k_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_expert_lectures', + name='l_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_keynote_address', + name='k_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_mtechphd_thesis', + name='s_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_patents', + name='p_year', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_published_books', + name='pyear', + field=models.IntegerField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], null=True, verbose_name='year'), + ), + migrations.AlterField( + model_name='emp_research_papers', + name='year', + field=models.CharField(blank=True, choices=[(1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), (2017, 2017), (2018, 2018), (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022), (2023, 2023), (2024, 2024)], max_length=10, null=True), + ), + ] diff --git a/FusionIIIT/applications/eis/models.py b/FusionIIIT/applications/eis/models.py index b43ae974e..e55712ab9 100644 --- a/FusionIIIT/applications/eis/models.py +++ b/FusionIIIT/applications/eis/models.py @@ -26,7 +26,7 @@ def get_absolute_url(self): class emp_techtransfer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() details = models.CharField(max_length=500, default=" ") date_entry = models.DateField(null=True, blank=True, default=datetime.datetime.now) start_date = models.DateField(null=True,blank=True) @@ -35,7 +35,7 @@ class emp_techtransfer(models.Model): class emp_session_chair(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() name = models.CharField(max_length=500, default=" ") event = models.TextField(max_length=2500, default=" ") YEAR_CHOICES = [] @@ -57,7 +57,7 @@ def __str__(self): class emp_research_projects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() ptype = models.CharField(max_length=100, default="Research") pi = models.CharField(max_length=1000, default=" ") co_pi = models.CharField(max_length=1500, default=" ") @@ -82,7 +82,7 @@ def __str__(self): class emp_research_papers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() R_TYPE_CHOICES = ( ('Journal', 'Journal'), ('Conference', 'Conference'), @@ -133,7 +133,7 @@ def __str__(self): class emp_published_books(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() PTYPE_TYPE_CHOICES = ( ('Book', 'Book'), ('Monograph', 'Monograph'), @@ -158,7 +158,7 @@ def __str__(self): class emp_patents(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() p_no = models.CharField(max_length=150) title = models.CharField(max_length=1500) earnings = models.IntegerField(default=0) @@ -186,7 +186,7 @@ def __str__(self): class emp_mtechphd_thesis(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() degree_type = models.IntegerField(default=1) title = models.CharField(max_length=250) supervisors = models.CharField(max_length=250) @@ -219,7 +219,7 @@ def __str__(self): class emp_keynote_address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() KEYNOTE_TYPE_CHOICES = ( ('Keynote', 'Keynote'), ('Plenary Address', 'Plenary Address'), @@ -248,7 +248,7 @@ def __str__(self): class emp_expert_lectures(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() LECTURE_TYPE_CHOICES = ( ('Expert Lecture', 'Expert Lecture'), ('Invited Talk', 'Invited Talk'), @@ -273,7 +273,7 @@ def __str__(self): class emp_event_organized(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() TYPE_CHOICES = ( ('Training Program', 'Training Program'), ('Seminar', 'Seminar'), @@ -301,7 +301,7 @@ def __str__(self): class emp_consultancy_projects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() consultants = models.CharField(max_length=150) title = models.CharField(max_length=1000) client = models.CharField(max_length=1000) @@ -323,7 +323,7 @@ def __str__(self): class emp_confrence_organised(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() name = models.CharField(max_length=500) venue = models.CharField(max_length=500) YEAR_CHOICES = [] @@ -353,7 +353,7 @@ def __str__(self): class emp_achievement(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) - pf_no = models.CharField(max_length=20) + pf_no = models.IntegerField() A_TYPE_CHOICES = ( ('Award', 'Award'), ('Honour', 'Honour'), diff --git a/FusionIIIT/applications/eis/views.py b/FusionIIIT/applications/eis/views.py index 656eee099..76a4532c2 100644 --- a/FusionIIIT/applications/eis/views.py +++ b/FusionIIIT/applications/eis/views.py @@ -275,12 +275,10 @@ # Main profile landing view def profile(request, username=None): - print("eis",username) user = get_object_or_404(User, username=username) if username else request.user - extra_info = get_object_or_404(ExtraInfo, user=user) -# if extra_info.user_type != 'fx': -# return redirect('/') + if extra_info.user_type != 'faculty': + return redirect('/') pf = extra_info.id form = ConfrenceForm() diff --git a/FusionIIIT/applications/establishment/migrations/0001_initial.py b/FusionIIIT/applications/establishment/migrations/0001_initial.py index d85fe198d..e1449d3b3 100644 --- a/FusionIIIT/applications/establishment/migrations/0001_initial.py +++ b/FusionIIIT/applications/establishment/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models diff --git a/FusionIIIT/applications/estate_module/migrations/0001_initial.py b/FusionIIIT/applications/estate_module/migrations/0001_initial.py index 899dbfccc..478a93b83 100644 --- a/FusionIIIT/applications/estate_module/migrations/0001_initial.py +++ b/FusionIIIT/applications/estate_module/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models diff --git a/FusionIIIT/applications/estate_module/static/estate_module/sidebar.js b/FusionIIIT/applications/estate_module/static/estate_module/sidebar.js index 449a7f5c8..462ebb004 100644 --- a/FusionIIIT/applications/estate_module/static/estate_module/sidebar.js +++ b/FusionIIIT/applications/estate_module/static/estate_module/sidebar.js @@ -36,7 +36,7 @@ $(document).ready(function () { .sidebar('setting', 'transition', 'overlay'); }); function newNotification() { - // console.log('A new Notification added!'); + console.log('A new Notification added!'); var notifactionName = document.createTextNode('Kanishka Munshi'); var notificationEmail = document.createTextNode('gmail@zlatan.com'); diff --git a/FusionIIIT/applications/examination/migrations/0001_initial.py b/FusionIIIT/applications/examination/migrations/0001_initial.py index 491333fc7..5db3c1b64 100644 --- a/FusionIIIT/applications/examination/migrations/0001_initial.py +++ b/FusionIIIT/applications/examination/migrations/0001_initial.py @@ -1,6 +1,7 @@ -# Generated by Django 3.1.5 on 2024-02-17 15:20 +# Generated by Django 3.1.5 on 2024-04-20 19:31 from django.db import migrations, models +import django.db.models.deletion class Migration(migrations.Migration): @@ -8,27 +9,17 @@ class Migration(migrations.Migration): initial = True dependencies = [ + ('academic_information', '0001_initial'), ] operations = [ - migrations.CreateModel( - name='authentication', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('authenticator_1', models.BooleanField(default=False)), - ('authenticator_2', models.BooleanField(default=False)), - ('authenticator_3', models.BooleanField(default=False)), - ('year', models.DateField(auto_now_add=True)), - ('course', models.CharField(default='', max_length=255)), - ], - ), migrations.CreateModel( name='grade', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('student', models.CharField(max_length=20)), ('curriculum', models.CharField(max_length=50)), - ('semester_id', models.CharField(max_length=10)), + ('semester_id', models.CharField(default='', max_length=10)), ('grade', models.CharField(default='B', max_length=5)), ], ), @@ -42,4 +33,16 @@ class Migration(migrations.Migration): ('grade', models.CharField(max_length=5)), ], ), + migrations.CreateModel( + name='authentication', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('authenticator_1', models.BooleanField(default=False)), + ('authenticator_2', models.BooleanField(default=False)), + ('authenticator_3', models.BooleanField(default=False)), + ('year', models.DateField(auto_now_add=True)), + ('course_year', models.IntegerField(default=2024)), + ('course_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='academic_information.course')), + ], + ), ] diff --git a/FusionIIIT/templates/complaintModule/complaint_secincharge_detail.html b/FusionIIIT/applications/examination/migrations/__init__.py similarity index 100% rename from FusionIIIT/templates/complaintModule/complaint_secincharge_detail.html rename to FusionIIIT/applications/examination/migrations/__init__.py diff --git a/FusionIIIT/applications/feeds/migrations/0001_initial.py b/FusionIIIT/applications/feeds/migrations/0001_initial.py index e989d0101..30ae94c92 100644 --- a/FusionIIIT/applications/feeds/migrations/0001_initial.py +++ b/FusionIIIT/applications/feeds/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models diff --git a/FusionIIIT/applications/feeds/views.py b/FusionIIIT/applications/feeds/views.py index fea8f5f42..4ef9c62c9 100644 --- a/FusionIIIT/applications/feeds/views.py +++ b/FusionIIIT/applications/feeds/views.py @@ -689,7 +689,6 @@ def profile(request, string): string- user's username @variables """ - print("user is this", request) if request.method == "POST": profile = Profile.objects.select_related().all().filter(user=request.user) Pr = None diff --git a/FusionIIIT/applications/filetracking/admin.py b/FusionIIIT/applications/filetracking/admin.py index 144ac4e2a..82b78df95 100644 --- a/FusionIIIT/applications/filetracking/admin.py +++ b/FusionIIIT/applications/filetracking/admin.py @@ -1,23 +1,7 @@ from django.contrib import admin -from .models import File, Tracking +# Register your models here. +from applications.filetracking.models import File, Tracking -class FileAdmin(admin.ModelAdmin): - list_display = ('uploader', 'designation', - 'subject', 'upload_date', 'is_read') - search_fields = ('uploader__user__username', 'subject', 'description') - list_filter = ('is_read',) - - -admin.site.register(File, FileAdmin) - - -class TrackingAdmin(admin.ModelAdmin): - list_display = ('file_id', 'current_id', 'receiver_id', - 'receive_date', 'forward_date', 'is_read') - search_fields = ('file_id__subject', - 'current_id__user__username', 'receiver_id__username') - list_filter = ('is_read',) - - -admin.site.register(Tracking, TrackingAdmin) +admin.site.register(File) +admin.site.register(Tracking) diff --git a/FusionIIIT/applications/filetracking/api/serializers.py b/FusionIIIT/applications/filetracking/api/serializers.py deleted file mode 100644 index bdae2024e..000000000 --- a/FusionIIIT/applications/filetracking/api/serializers.py +++ /dev/null @@ -1,24 +0,0 @@ -from applications.filetracking.models import File, Tracking -from django.core.files import File as DjangoFile -from rest_framework import serializers - - -class FileSerializer(serializers.ModelSerializer): - class Meta: - model = File - fields = '__all__' - - -class TrackingSerializer(serializers.ModelSerializer): - class Meta: - model = Tracking - fields = '__all__' - - -class FileHeaderSerializer(serializers.ModelSerializer): - ''' - This serializes everything except the attachments of a file and whether it is read or not - ''' - class Meta: - model = File - exclude = ['upload_file', 'is_read'] diff --git a/FusionIIIT/applications/filetracking/api/urls.py b/FusionIIIT/applications/filetracking/api/urls.py deleted file mode 100644 index 139f965ff..000000000 --- a/FusionIIIT/applications/filetracking/api/urls.py +++ /dev/null @@ -1,24 +0,0 @@ -from django.conf.urls import url -from .views import ( - CreateFileView, - ViewFileView, - ViewInboxView, - ViewOutboxView, - ViewHistoryView, - ForwardFileView, - DraftFileView, - CreateDraftFile, - GetDesignationsView, -) - -urlpatterns = [ - url(r'^file/$', CreateFileView.as_view(), name='create_file'), - url(r'^file/(?P\d+)/$', ViewFileView.as_view(), name='view_file'), - url(r'^inbox/$', ViewInboxView.as_view(), name='view_inbox'), - url(r'^outbox/$', ViewOutboxView.as_view(), name='view_outbox'), - url(r'^history/(?P\d+)/$', ViewHistoryView.as_view(), name='view_history'), - url(r'^forwardfile/(?P\d+)/$', ForwardFileView.as_view(), name='forward_file'), - url(r'^draft/$', DraftFileView.as_view(), name='view_drafts'), - url(r'^createdraft/$', CreateDraftFile.as_view(), name='create_draft'), - url(r'^designations/(?P\w+)/$', GetDesignationsView.as_view(), name='get_designations'), -] diff --git a/FusionIIIT/applications/filetracking/api/views.py b/FusionIIIT/applications/filetracking/api/views.py deleted file mode 100644 index 5f395ab41..000000000 --- a/FusionIIIT/applications/filetracking/api/views.py +++ /dev/null @@ -1,247 +0,0 @@ -import logging -from venv import logger -from django.forms import ValidationError -from rest_framework.views import APIView -from rest_framework.response import Response -from rest_framework import status, permissions -from rest_framework.authentication import TokenAuthentication -from ..models import File, Tracking -from ..sdk.methods import create_draft, create_file, view_drafts, view_file, delete_file, view_inbox, view_outbox, view_history, forward_file, get_designations - -class CreateFileView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def post(self, request): - try: - current_user = request.user.username - current_designation = request.data.get('designation') - receiver_username = request.data.get('receiver_username') - receiver_designation = request.data.get('receiver_designation') - subject = request.data.get('subject') - description = request.data.get('description') - - if None in [current_designation, receiver_username, receiver_designation, subject, description]: - return Response({'error': 'One or more required fields are missing.'}, status=status.HTTP_400_BAD_REQUEST) - - file_id = create_file(uploader=current_user, uploader_designation=current_designation, - receiver=receiver_username, receiver_designation=receiver_designation, subject=subject, description=description) - - return Response({'file_id': file_id}, status=status.HTTP_201_CREATED) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) - - -class ViewFileView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def get(self, request, file_id): - try: - file_details = view_file(int(file_id)) - # print(file_details) - return Response(file_details, status=status.HTTP_200_OK) - except ValueError: - return Response({'error': 'Invalid file ID format.'}, status=status.HTTP_400_BAD_REQUEST) - except File.DoesNotExist: - return Response({'error': 'File not found.'}, status=status.HTTP_404_NOT_FOUND) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) - - def delete(self, request, file_id): - try: - # file_details = view_file(int(file_id)) - # print(file_details) - success = delete_file(int(file_id)) - if success: - return Response({'message': 'File deleted successfully'}, - status=status.HTTP_204_NO_CONTENT) - else : - return - - except ValueError: - return Response({'error': 'Invalid file ID format'}, - status=status.HTTP_400_BAD_REQUEST) - except File.DoesNotExist: - return Response({'error': 'File not found'}, - status=status.HTTP_404_NOT_FOUND) - except ValidationError as e: - return Response(e.detail, status=status.HTTP_400_BAD_REQUEST) # Handle ValidationError specifically - except Exception as e: # Catch unexpected errors - logger.error(f"Unexpected error in DeleteFileView: {e}") - return Response({'error': 'An internal server error occurred'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -class ViewInboxView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def get(self, request): - """ - API endpoint to view inbox files. - - Expects query parameters: - - username (required): User requesting the inbox. - - designation (optional): Designation to filter files by. - - src_module (required): Source module to filter files by. - - Returns: - JSON response containing a list of serialized file data, including sender information. - """ - - username = request.query_params.get('username') - designation = request.query_params.get('designation') - src_module = request.query_params.get('src_module') - - - # if not username or not src_module: - # return Response({'error': 'Missing required query parameters: username and src_module.'}, status=400) - - inbox_files = view_inbox(username, designation, src_module) - return Response(inbox_files) - -class ViewOutboxView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - - def get(self, request): - """ - API endpoint to view outbox files. - - Expects query parameters: - - username (required): User requesting the outbox. - - designation (optional): Designation to filter files by. - - src_module (required): Source module to filter files by. - - Returns: - JSON response containing a paginated list of serialized file data. - """ - - username = request.query_params.get('username') - designation = request.query_params.get('designation') - src_module = request.query_params.get('src_module') - - - if not username or not src_module: - return Response({'error': 'Missing required query parameters: username and src_module.'}, status=400) - - outbox_files = view_outbox(username, designation, src_module) - return Response(outbox_files) - - -class ViewHistoryView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def get(self, request, file_id): - """ - View history of a particular file with the given file_id. - - Args: - request (rest_framework.request.Request): The incoming request object. - file_id (int): Primary key of the file to retrieve history for. - - Returns: - rest_framework.response.Response: JSON response containing serialized tracking history. - """ - - try: - history = view_history(file_id) - return Response(history) - except Tracking.DoesNotExist: - return Response({'error': f'File with ID {file_id} not found.'}, status=404) - except Exception as e: - logger.error(f"An unexpected error occurred: {e}") - return Response({'error': 'Internal server error.'}, status=500) - -class ForwardFileView(APIView): -# # # Authentication and permission classes (adjust based on your needs) - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def post(self, request, file_id): -# # Extract data from request.data - receiver = request.data.get('receiver') - receiver_designation = request.data.get('receiver_designation') - file_extra_JSON = request.data.get('file_extra_JSON', {}) - remarks = request.data.get('remarks', "") - - # Validate data - if not receiver or not receiver_designation: - raise ValidationError("Missing required fields: receiver and receiver_designation") - - # # Extract and validate file attachment (if present) - file_attachment = request.FILES.get('file_attachment') - if file_attachment: - if file_attachment.size > 10 * 1024 * 1024: # Adjust size limit as needed - raise ValidationError("File size exceeds limit (10 MB)") - - # Call forward_file function - try: - new_tracking_id = forward_file( - int(file_id), - receiver, - receiver_designation, - file_extra_JSON, - remarks, - file_attachment - ) - logging.info(f"Successfully forwarded file {file_id} with tracking ID: {new_tracking_id}") - except Exception as e: - logging.error(f"Error forwarding file {file_id}: {str(e)}") - raise ValidationError(str(e)) # Re-raise exception with a user-friendly message - - # Return response - return Response({'tracking_id': new_tracking_id}, status=status.HTTP_201_CREATED) - -class CreateDraftFile(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def post(self, request): - uploader = request.data.get('uploader') - uploader_designation = request.data.get('uploader_designation') - src_module = request.data.get('src_module', 'filetracking') - src_object_id = request.data.get('src_object_id', '') - file_extra_JSON = request.data.get('file_extra_JSON', {}) - attached_file = request.FILES.get('attached_file', None) - - try: - file_id = create_draft( - uploader=uploader, - uploader_designation=uploader_designation, - src_module=src_module, - src_object_id=src_object_id, - file_extra_JSON=file_extra_JSON, - attached_file=attached_file - ) - return Response({'file_id': file_id}, status=status.HTTP_201_CREATED) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - -class DraftFileView(APIView): - authentication_classes = [TokenAuthentication] - permission_classes = [permissions.IsAuthenticated] - - def get(self, request): - username = request.query_params.get('username') - designation = request.query_params.get('designation') - src_module = request.query_params.get('src_module') - - try: - draft_files = view_drafts(username, designation, src_module) - print(draft_files) - return Response(draft_files, status=status.HTTP_200_OK) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - - -class GetDesignationsView(APIView): - #authentication_classes = [TokenAuthentication] - #permission_classes = [permissions.IsAuthenticated] - - def get(self, request, username, *args, **kwargs): - user_designations = get_designations(username) - return Response({'designations': user_designations}) diff --git a/FusionIIIT/applications/filetracking/decorators.py b/FusionIIIT/applications/filetracking/decorators.py deleted file mode 100644 index dd900730e..000000000 --- a/FusionIIIT/applications/filetracking/decorators.py +++ /dev/null @@ -1,51 +0,0 @@ -from django.shortcuts import render, get_object_or_404 -from django.contrib.auth.models import User -from applications.globals.models import ExtraInfo, HoldsDesignation -from .sdk.methods import get_HoldsDesignation_obj - - -def user_check(request): - """ - This function is used to check if the user is a student or not. - Its return type is bool. - @param: - request - contains metadata about the requested page - - @Variables: - current_user - get user from request - user_details - extract details of the user from the database - desig_id - check for designation - student - designation for a student - final_user - final designation of the request(our user) - """ - try: - current_user = get_object_or_404(User, username=request.user.username) - user_details = ExtraInfo.objects.select_related('user','department').get(user=request.user) - des = HoldsDesignation.objects.all().select_related().filter(user=request.user).first() - if str(des.designation) == "student": - return True - else: - return False - except Exception as e: - return False - -def user_is_student(view_func): - def _wrapped_view(request, *args, **kwargs): - if user_check(request): - return render(request, 'filetracking/fileTrackingNotAllowed.html') - else: - return view_func(request, *args, **kwargs) - return _wrapped_view - -def dropdown_designation_valid(view_func): - def _wrapped_view(request, *args, **kwargs): - designation_name = request.session.get('currentDesignationSelected', 'default_value') #from dropdown - username = request.user - try: - designation_id = get_HoldsDesignation_obj( - username, designation_name).id - except: - return render(request, 'filetracking/invalid_designation.html', {'curr_des' : designation_name}) - else: - return view_func(request, *args, **kwargs) - return _wrapped_view diff --git a/FusionIIIT/applications/filetracking/migrations/0001_initial.py b/FusionIIIT/applications/filetracking/migrations/0001_initial.py index 3375630f7..6924ae1ff 100644 --- a/FusionIIIT/applications/filetracking/migrations/0001_initial.py +++ b/FusionIIIT/applications/filetracking/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models @@ -24,9 +24,6 @@ class Migration(migrations.Migration): ('upload_date', models.DateTimeField(auto_now_add=True)), ('upload_file', models.FileField(blank=True, upload_to='')), ('is_read', models.BooleanField(default=False)), - ('src_module', models.CharField(default='filetracking', max_length=100)), - ('src_object_id', models.CharField(max_length=100, null=True)), - ('file_extra_JSON', models.JSONField(null=True)), ('designation', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='upload_designation', to='globals.designation')), ('uploader', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='uploaded_files', to='globals.extrainfo')), ], @@ -43,7 +40,6 @@ class Migration(migrations.Migration): ('remarks', models.CharField(blank=True, max_length=250, null=True)), ('upload_file', models.FileField(blank=True, upload_to='')), ('is_read', models.BooleanField(default=False)), - ('tracking_extra_JSON', models.JSONField(null=True)), ('current_design', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='globals.holdsdesignation')), ('current_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ('file_id', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='filetracking.file')), diff --git a/FusionIIIT/applications/filetracking/models.py b/FusionIIIT/applications/filetracking/models.py index 87f91ced8..5f9581a08 100644 --- a/FusionIIIT/applications/filetracking/models.py +++ b/FusionIIIT/applications/filetracking/models.py @@ -16,25 +16,22 @@ class File(models.Model): is_read = models.BooleanField(default = False) - # additions for API - src_module = models.CharField(max_length=100, default='filetracking') - src_object_id = models.CharField(max_length=100,null=True) - file_extra_JSON = models.JSONField(null=True) - class Meta: db_table = 'File' - # def __str__(self): - # return str(self.ref_id) + #def __str__(self): + #return str(self.ref_id) class Tracking(models.Model): """ - This is File Tracing Table which contains the status of each individual file created by the user + This is File Tracing Table which contains the status of each indivisual file created by the user """ file_id = models.ForeignKey(File, on_delete=models.CASCADE, null=True) current_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) current_design = models.ForeignKey(HoldsDesignation, null=True, on_delete=models.CASCADE) + # receiver_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='receiver_id') + # receive_design = models.ForeignKey(HoldsDesignation, null=True, on_delete=models.CASCADE, related_name='rec_design') receiver_id = models.ForeignKey(User,null = True, on_delete=models.CASCADE, related_name='receiver_id') receive_design = models.ForeignKey(Designation, null=True, on_delete=models.CASCADE, related_name='rec_design') @@ -44,8 +41,5 @@ class Tracking(models.Model): upload_file = models.FileField(blank=True) is_read = models.BooleanField(default = False) - # additions for API - tracking_extra_JSON = models.JSONField(null=True) - class Meta: - db_table = 'Tracking' \ No newline at end of file + db_table = 'Tracking' diff --git a/FusionIIIT/applications/filetracking/sdk/methods.py b/FusionIIIT/applications/filetracking/sdk/methods.py deleted file mode 100644 index 0ea167fc6..000000000 --- a/FusionIIIT/applications/filetracking/sdk/methods.py +++ /dev/null @@ -1,429 +0,0 @@ -from amqp import NotFound -from django.contrib.auth.models import User -from applications.filetracking.models import Tracking, File -from applications.globals.models import Designation, HoldsDesignation, ExtraInfo -from applications.filetracking.api.serializers import FileSerializer, FileHeaderSerializer, TrackingSerializer -from django.core.exceptions import ValidationError -from typing import Any - - -def create_file( - uploader: str, - uploader_designation: str, - receiver: str, - receiver_designation: str, - subject: str = "", - description: str = "", - src_module: str = "filetracking", - src_object_id: str = "", - file_extra_JSON: dict = {}, - attached_file: Any = None) -> int: - ''' - This function is used to create a file object corresponding to any object of a module that needs to be tracked - ''' - - ''' - Functioning: - create base file with params - create tracking with params - if both complete then return id of file - else raise error - - also, delete file object if tracking isnt created - ''' - uploader_user_obj = get_user_object_from_username(uploader) - uploader_extrainfo_obj = get_ExtraInfo_object_from_username(uploader) - uploader_designation_obj = Designation.objects.get( - name=uploader_designation) - receiver_obj = get_user_object_from_username(receiver) - receiver_designation_obj = Designation.objects.get( - name=receiver_designation) - - new_file = File.objects.create( - uploader=uploader_extrainfo_obj, - subject=subject, - description=description, - designation=uploader_designation_obj, - src_module=src_module, - src_object_id=src_object_id, - file_extra_JSON=file_extra_JSON, - ) - - - if attached_file is not None: - new_file.upload_file.save(attached_file.name, attached_file, save=True) - - uploader_holdsdesignation_obj = HoldsDesignation.objects.get( - user=uploader_user_obj, designation=uploader_designation_obj) - - new_tracking = Tracking.objects.create( - file_id=new_file, - current_id=uploader_extrainfo_obj, - current_design=uploader_holdsdesignation_obj, - receiver_id=receiver_obj, - receive_design=receiver_designation_obj, - tracking_extra_JSON=file_extra_JSON, - remarks=f"File with id:{str(new_file.id)} created by {uploader} and sent to {receiver}" - # upload_file = None, dont add file for first tracking - ) - if new_tracking is None: - new_file.delete() - raise ValidationError('Tracking model data is incorrect') - else: - return new_file.id - - -def view_file(file_id: int) -> dict: - ''' - This function returns all the details of a given file - ''' - try: - requested_file = File.objects.get(id=file_id) - serializer = FileSerializer(requested_file) - file_details = serializer.data - return file_details - except File.DoesNotExist: - raise NotFound("File Not Found with provided ID") - - -def delete_file(file_id: int) -> bool: - ''' - This function is used to delete a file from being tracked, all the tracking history is deleted as well and returns true if the deletion was successful - ''' - try: - File.objects.filter(id=file_id).delete() - return True - except File.DoesNotExist: - return False - -# inbox and outbox could be sorted based on most recent linked tracking entry - -def view_inbox(username: str, designation: str, src_module: str) -> list: - ''' - This function is used to get all the files in the inbox of a particular user and designation - ''' - user_designation = Designation.objects.get(name=designation) - recipient_object = get_user_object_from_username(username) - received_files_tracking = Tracking.objects.select_related('file_id').filter( - receiver_id=recipient_object, - receive_design=user_designation, - file_id__src_module=src_module, - file_id__is_read=False).order_by('receive_date'); - received_files = [tracking.file_id for tracking in received_files_tracking] - - # remove duplicate file ids (from sending back and forth) - received_files_unique = uniqueList(received_files) - - received_files_serialized = list(FileHeaderSerializer( - received_files_unique, many=True).data) - - for file in received_files_serialized: - file['sent_by_user'] = get_last_file_sender(file['id']).username - file['sent_by_designation'] = get_last_file_sender_designation(file['id']).name - - return received_files_serialized - - -def view_outbox(username: str, designation: str, src_module: str) -> list: - ''' - This function is used to get all the files in the outbox of a particular user and designation - ''' - user_designation = get_designation_obj_from_name(designation=designation) - user_object = get_user_object_from_username(username) - user_HoldsDesignation_object = HoldsDesignation.objects.get( - user=user_object, designation=user_designation) - sender_ExtraInfo_object = get_ExtraInfo_object_from_username(username) - sent_files_tracking = Tracking.objects.select_related('file_id').filter( - current_id=sender_ExtraInfo_object, - current_design=user_HoldsDesignation_object, - file_id__src_module=src_module, - file_id__is_read=False).order_by('-receive_date') - sent_files = [tracking.file_id for tracking in sent_files_tracking] - - # remove duplicate file ids (from sending back and forth) - sent_files_unique = uniqueList(sent_files) - - sent_files_serialized = FileHeaderSerializer(sent_files_unique, many=True) - return sent_files_serialized.data - - - -def view_archived(username: str, designation: str, src_module: str) -> dict: - ''' - This function is used to get all the files in the archive of a particular user and designation - Archived file mean those which the user has ever interacted with, and are now finished or archived - ''' - user_designation = Designation.objects.get(name=designation) - user_object = get_user_object_from_username(username) - received_archived_tracking = Tracking.objects.select_related('file_id').filter( - receiver_id=user_object, - receive_design=user_designation, - file_id__src_module=src_module, - file_id__is_read=True) - - user_HoldsDesignation_object = HoldsDesignation.objects.get( - user=user_object, designation=user_designation) - sender_ExtraInfo_object = get_ExtraInfo_object_from_username(username) - sent_archived_tracking = Tracking.objects.select_related('file_id').filter( - current_id=sender_ExtraInfo_object, - current_design=user_HoldsDesignation_object, - file_id__src_module=src_module, - file_id__is_read=True) - - archived_tracking = received_archived_tracking | sent_archived_tracking - archived_files = [tracking.file_id for tracking in archived_tracking] - - # remove duplicate file ids (from sending back and forth) - archived_files_unique = uniqueList(archived_files) - - archived_files_serialized = FileHeaderSerializer(archived_files_unique, many=True) - return archived_files_serialized.data - - - -def archive_file(file_id: int) -> bool: - ''' - This function is used to archive a file and returns true if the archiving was successful - ''' - try: - File.objects.filter(id=file_id).update(is_read=True) - return True - except File.DoesNotExist: - return False - -def unarchive_file(file_id: int) -> bool: - ''' - This functions is used to unarchive a file and returns true if the unarchiving was successful - ''' - try: - File.objects.filter(id=file_id).update(is_read=False) - return True - except File.DoesNotExist: - return False - - - -def create_draft( - uploader: str, - uploader_designation: str, - src_module: str = "filetracking", - src_object_id: str = "", - file_extra_JSON: dict = {}, - attached_file: Any = None) -> int: - ''' - This function is used to create a draft file object corresponding to any object of a module that needs to be tracked - It is similar to create_file but is not sent to anyone - Later this file can be sent to someone by forward_file by using draft file_id - ''' - uploader_extrainfo_obj = get_ExtraInfo_object_from_username(uploader) - uploader_designation_obj = Designation.objects.get( - name=uploader_designation) - - new_file = File.objects.create( - uploader=uploader_extrainfo_obj, - designation=uploader_designation_obj, - src_module=src_module, - src_object_id=src_object_id, - file_extra_JSON=file_extra_JSON, - upload_file=attached_file - ) - return new_file.id - - -def view_drafts(username: str, designation: str, src_module: str) -> dict: - ''' - This function is used to get all the files in the drafts (has not been sent) of a particular user and designation - ''' - user_designation = Designation.objects.get(name=designation) - user_ExtraInfo_object = get_ExtraInfo_object_from_username(username) - draft_files = File.objects.filter( - tracking__isnull=True, uploader=user_ExtraInfo_object, designation=user_designation, src_module=src_module) - draft_files_serialized = FileHeaderSerializer(draft_files, many=True) - return draft_files_serialized.data - - - -def forward_file( - file_id: int, - receiver: str, - receiver_designation: str, - file_extra_JSON: dict, - remarks: str = "", - file_attachment: Any = None) -> int: - ''' - This function forwards the file and inserts a new tracking history into the file tracking table - Note that only the current owner(with appropriate designation) of the file has the ability to forward files - ''' - # HoldsDesignation and ExtraInfo object are used instead - # of Designation and User object because of the legacy code being that way - - current_owner = get_current_file_owner(file_id) - current_owner_designation = get_current_file_owner_designation(file_id) - current_owner_extra_info = ExtraInfo.objects.get(user=current_owner) - current_owner_holds_designation = HoldsDesignation.objects.get( - user=current_owner, designation=current_owner_designation) - receiver_obj = User.objects.get(username=receiver) - receiver_designation_obj = Designation.objects.get( - name=receiver_designation) - tracking_data = { - 'file_id': file_id, - 'current_id': current_owner_extra_info.id, - 'current_design': current_owner_holds_designation.id, - 'receiver_id': receiver_obj.id, - 'receive_design': receiver_designation_obj.id, - 'tracking_extra_JSON': file_extra_JSON, - 'remarks': remarks, - } - if file_attachment is not None: - tracking_data['upload_file'] = file_attachment - - tracking_entry = TrackingSerializer(data=tracking_data) - if tracking_entry.is_valid(): - tracking_entry.save() - return tracking_entry.instance.id - else: - raise ValidationError('forward data is incomplete') - - -def view_history(file_id: int) -> dict: - ''' - This function is used to get the history of a particular file with the given file_id - ''' - Tracking_history = Tracking.objects.filter( - file_id=file_id).order_by('-receive_date') - Tracking_history_serialized = TrackingSerializer( - Tracking_history, many=True) - return Tracking_history_serialized.data - - -# HELPER FUNCTIONS - -def get_current_file_owner(file_id: int) -> User: - ''' - This functions returns the current owner of the file. - The current owner is the latest recipient of the file - ''' - latest_tracking = Tracking.objects.filter( - file_id=file_id).order_by('-receive_date').first() - latest_recipient = latest_tracking.receiver_id - return latest_recipient - - -def get_current_file_owner_designation(file_id: int) -> Designation: - ''' - This function returns the designation of the current owner of the file. - The current owner is the latest recipient of the file - ''' - latest_tracking = Tracking.objects.filter( - file_id=file_id).order_by('-receive_date').first() - latest_recipient_designation = latest_tracking.receive_design - return latest_recipient_designation - -def get_last_file_sender(file_id: int) -> User: - ''' - This Function returns the last file sender, - one who has last forwarded/sent the file - ''' - latest_tracking = Tracking.objects.filter( - file_id=file_id).order_by('-receive_date').first() - latest_sender_extra_info = latest_tracking.current_id - return latest_sender_extra_info.user - -def get_last_file_sender_designation(file_id: int) -> Designation: - ''' - This Function returns the last file sender's Designation, - one who has last forwarded/sent the file - ''' - latest_tracking = Tracking.objects.filter( - file_id=file_id).order_by('receive_date').first() - latest_sender_holds_designation = latest_tracking.current_design - return latest_sender_holds_designation.designation - -def get_designations(username: str) -> list: - ''' - This function is used to return a list of all the designation names of a particular user - ''' - user = User.objects.get(username=username) - designations_held = HoldsDesignation.objects.filter(user=user) - designation_name = [hold_designation.designation.name for hold_designation in designations_held] - return designation_name - - -def get_user_object_from_username(username: str) -> User: - user = User.objects.get(username=username) - return user - -def get_ExtraInfo_object_from_username(username: str) -> ExtraInfo: - user = User.objects.get(username=username) - extrainfo = ExtraInfo.objects.get(user=user) - return extrainfo - -def uniqueList(l: list) -> list: - ''' - This function is used to return a list with unique elements - O(n) time and space - ''' - seen = set() - unique_list = [] - for item in l: - if item not in seen: - unique_list.append(item) - seen.add(item) - return unique_list - -def add_uploader_department_to_files_list(files: list) -> list: - ''' - This function is used to add the department of the uploader to the file - ''' - for file in files: - uploader_Extrainfo = file['uploader'] - if uploader_Extrainfo.department is None: - # for files created by staff or users that dont have department - file['uploader_department'] = 'FTS' - else: - file['uploader_department'] = ( - str(uploader_Extrainfo.department)).split(': ')[1] - - return files - -def get_designation_obj_from_name(designation: str) -> Designation: - des = Designation.objects.get(name = designation) - return des - -def get_HoldsDesignation_obj(username: str, designation:str) -> HoldsDesignation: - user_object = get_user_object_from_username(username=username) - user_designation = get_designation_obj_from_name(designation=designation) - obj = HoldsDesignation.objects.get( - user=user_object, designation=user_designation) - return obj - -def get_last_recv_tracking_for_user(file_id: int, username: str, designation: str)-> Tracking: - ''' - This returns the last tracking where username+designation recieved file_id - ''' - - recv_user_obj = get_user_object_from_username(username) - recv_design_obj = get_designation_obj_from_name(designation) - - last_tracking = Tracking.objects.filter(file_id=file_id, - receiver_id=recv_user_obj, - receive_design=recv_design_obj).order_by('-receive_date')[0] - return last_tracking - -def get_last_forw_tracking_for_user(file_id: int, username: str, designation: str) -> Tracking: - ''' - Returns the last tracking where the specified user forwarded the file. - ''' - - # Get user and designation objects - sender_user_obj = get_ExtraInfo_object_from_username(username) - sender_designation_obj = get_HoldsDesignation_obj(username=username, designation=designation) - - # Filter Tracking objects by file_id, sender_id, and sender_designation - last_tracking = Tracking.objects.filter(file_id=file_id, - current_id=sender_user_obj, - current_design=sender_designation_obj).order_by('-forward_date').first() - return last_tracking - -def get_extra_info_object_from_id(id: int): - return ExtraInfo.objects.get(id=id) diff --git a/FusionIIIT/applications/filetracking/urls.py b/FusionIIIT/applications/filetracking/urls.py index a451738de..1007cdbf6 100644 --- a/FusionIIIT/applications/filetracking/urls.py +++ b/FusionIIIT/applications/filetracking/urls.py @@ -1,47 +1,31 @@ -from django.conf.urls import url, include +from django.conf.urls import url from . import views -from .api import urls app_name = 'filetracking' urlpatterns = [ url(r'^$', views.filetracking, name='filetracking'), - url(r'^draftdesign/$', views.draft_design, name='draft_design'), - url(r'^drafts/(?P\d+)$', views.drafts_view, name='drafts_view'), - url(r'^outbox/(?P\d+)$', views.outbox_view, name='outbox_view'), - url(r'^inbox/(?P\d+)$', views.inbox_view, name='inbox_view'), + url(r'^drafts/$', views.drafts, name='drafts'), + url(r'^fileview/(?P\d+)$', views.fileview, name='fileview'), + url(r'^fileview1/(?P\d+)$', views.fileview1, name='fileview1'), + url(r'^fileview2/(?P\d+)$', views.fileview2, name='fileview2'), url(r'^outward/$', views.outward, name='outward'), url(r'^inward/$', views.inward, name='inward'), - url(r'^confirmdelete/(?P\d+)$', - views.confirmdelete, name='confirm_delete'), - url(r'^archive/(?P\d+)/$', views.archive_view, name='archive_view'), - url(r'^finish/(?P\d+)/$', views.archive_file, name='finish_file'), - url(r'^viewfile/(?P\d+)/$', views.view_file, name='view_file_view'), + url(r'^confirmdelete/(?P\d+)$', views.confirmdelete, name='confirm_delete'), + url(r'^archive/(?P\d+)/$', views.archive, name='archive'), + url(r'^finish/(?P\d+)/$', views.finish, name='finish'), url(r'^forward/(?P\d+)/$', views.forward, name='forward'), url(r'^ajax/$', views.AjaxDropdown1, name='ajax_dropdown1'), url(r'^ajax_dropdown/$', views.AjaxDropdown, name='ajax_dropdown'), - url(r'^test/$', views.test, name='test'), - url(r'^delete/(?P\d+)$', views.delete, name='delete'), - url(r'^forward_inward/(?P\d+)/$', - views.forward_inward, name='forward_inward'), + url(r'^test/$',views.test, name='test'), + url(r'^delete/(?P\d+)$',views.delete, name='delete'), + url(r'^forward_inward/(?P\d+)/$', views.forward_inward, name='forward_inward'), - # correction team 24 + ## correction team 24 url(r'^finish_design/$', views.finish_design, name='finish_design'), - url(r'^finish_fileview/(?P\d+)$', - views.finish_fileview, - name='finish_fileview'), + url(r'^finish_fileview/(?P\d+)$', views.finish_fileview, name='finish_fileview'), url(r'^archive_design/$', views.archive_design, name='archive_design'), - url(r'^archive_finish/(?P\d+)/$', - views.archive_finish, name='archive_finish'), - url(r'unarchive/(?P\d+)/$', - views.unarchive_file, name='unarchive'), - url(r'^getdesignations/(?P\w+)/$', views.get_designations_view, name="get_user_designations"), - url(r'^editdraft/(?P\w+)/$', views.edit_draft_view, name="edit_draft"), - - # REST api urls - url(r'^api/', include(urls)) - + url(r'^archive_finish/(?P\d+)/$', views.archive_finish, name='archive_finish'), ] - diff --git a/FusionIIIT/applications/filetracking/views.py b/FusionIIIT/applications/filetracking/views.py index a01d71ac1..ef5d8f347 100644 --- a/FusionIIIT/applications/filetracking/views.py +++ b/FusionIIIT/applications/filetracking/views.py @@ -8,19 +8,12 @@ from django.db import IntegrityError from django.core import serializers from django.contrib.auth.models import User -from django.http import JsonResponse from timeit import default_timer as time -from notification.views import office_module_notif, file_tracking_notif +from notification.views import office_module_notif,file_tracking_notif from .utils import * -from django.utils.dateparse import parse_datetime -from .sdk.methods import * -from .decorators import * -import json -@login_required(login_url="/accounts/login/") -@user_is_student -@dropdown_designation_valid +@login_required(login_url = "/accounts/login/") def filetracking(request): """ The function is used to create files by current user(employee). @@ -42,50 +35,39 @@ def filetracking(request): holdsdesignations - The HoldsDesignation object. context - Holds data needed to make necessary changes in the template. """ - - - if request.method == "POST": + if request.method =="POST": try: if 'save' in request.POST: uploader = request.user.extrainfo subject = request.POST.get('title') description = request.POST.get('desc') design = request.POST.get('design') - designation = Designation.objects.get(id=HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(id=design).designation_id) + designation = Designation.objects.get(id = HoldsDesignation.objects.select_related('user','working','designation').get(id = design).designation_id) upload_file = request.FILES.get('myfile') - if upload_file and upload_file.size / 1000 > 10240: - messages.error( - request, "File should not be greater than 10MB") - return redirect("/filetracking") - - extraJSON = { - 'remarks': request.POST.get('remarks'), - } + if(upload_file.size / 1000 > 10240): + messages.error(request,"File should not be greater than 10MB") + return redirect("/filetracking") File.objects.create( uploader=uploader, description=description, subject=subject, designation=designation, - upload_file=upload_file, - file_extra_JSON=extraJSON + upload_file=upload_file ) - messages.success(request, 'File Draft Saved Successfully') + messages.success(request,'File Draft Saved Successfully') if 'send' in request.POST: uploader = request.user.extrainfo subject = request.POST.get('title') description = request.POST.get('desc') design = request.POST.get('design') - designation = Designation.objects.get(id=HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(id=design).designation_id) + designation = Designation.objects.get(id = HoldsDesignation.objects.select_related('user','working','designation').get(id = design).designation_id) upload_file = request.FILES.get('myfile') - if upload_file and upload_file.size / 1000 > 10240: - messages.error( - request, "File should not be greater than 10MB") + if(upload_file.size / 1000 > 10240): + messages.error(request,"File should not be greater than 10MB") return redirect("/filetracking") file = File.objects.create( @@ -96,12 +78,12 @@ def filetracking(request): upload_file=upload_file ) + current_id = request.user.extrainfo remarks = request.POST.get('remarks') sender = request.POST.get('design') - current_design = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(id=sender) + current_design = HoldsDesignation.objects.select_related('user','working','designation').get(id=sender) receiver = request.POST.get('receiver') try: @@ -109,9 +91,8 @@ def filetracking(request): except Exception as e: messages.error(request, 'Enter a valid Username') return redirect('/filetracking/') - receive = request.POST.get('receive') + receive = request.POST.get('recieve') try: - print(receive) receive_design = Designation.objects.get(name=receive) except Exception as e: messages.error(request, 'Enter a valid Designation') @@ -128,61 +109,55 @@ def filetracking(request): remarks=remarks, upload_file=upload_file, ) - # office_module_notif(request.user, receiver_id) - file_tracking_notif(request.user, receiver_id, subject) - messages.success(request, 'File sent successfully') + #office_module_notif(request.user, receiver_id) + file_tracking_notif(request.user,receiver_id,subject) + messages.success(request,'File sent successfully') except IntegrityError: message = "FileID Already Taken.!!" return HttpResponse(message) - file = File.objects.select_related( - 'uploader__user', 'uploader__department', 'designation').all() - extrainfo = ExtraInfo.objects.select_related('user', 'department').all() - holdsdesignations = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').all() - - designation_name = request.session.get('currentDesignationSelected', 'default_value') - all_available_designations = request.session.get( - 'allDesignations', 'default_value2') - username = request.user - designation_id = get_HoldsDesignation_obj( - username, designation_name).id + file = File.objects.select_related('uploader__user','uploader__department','designation').all() + extrainfo = ExtraInfo.objects.select_related('user','department').all() + holdsdesignations = HoldsDesignation.objects.select_related('user','working','designation').all() + designations = get_designation(request.user) context = { 'file': file, 'extrainfo': extrainfo, 'holdsdesignations': holdsdesignations, - 'designation_name': designation_name, - 'designation_id': designation_id, - 'notifications': request.user.notifications.all() + 'designations': designations, } return render(request, 'filetracking/composefile.html', context) -@login_required(login_url="/accounts/login") -def draft_design(request): - """ - This function redirects the user to the drafts page of designation selected in dropdown - @param: - request - trivial. +@login_required(login_url = "/accounts/login") +def drafts(request): """ + The function is used to get the designation of the user and renders it on draft template. + + @param: + request - trivial. - dropdown_design = request.session.get( - 'currentDesignationSelected', 'default_value') - username = request.user - dropdown_HoldsDesignation_obj = get_HoldsDesignation_obj( - username, dropdown_design) + @variables: + + + context - Holds data needed to make necessary changes in the template. + """ + designation = get_designation(request.user) + context = { + 'designation': designation, + } + return render(request, 'filetracking/drafts.html', context) - return redirect('/filetracking/drafts/' + str(dropdown_HoldsDesignation_obj.id)) +@login_required(login_url = "/accounts/login") +def fileview(request,id): -@login_required(login_url="/accounts/login") -def drafts_view(request, id): """ - This function is used to view all the drafts created by the user ordered by upload date.it collects all the created files from File object. + This function is used to veiw all all created files by the user ordered by upload date.it collects all the created files from File object. @param: request - trivial @@ -191,38 +166,45 @@ def drafts_view(request, id): @parameters draft - file obeject containing all the files created by user context - holds data needed to render the template + + + """ + # draft = File.objects.select_related('uploader__user','uploader__department','designation').filter(uploader=request.user.extrainfo).order_by('-upload_date') + # extrainfo = ExtraInfo.objects.select_related('user','department').all() + extrainfo = ExtraInfo.objects.select_related('user','department').all() + + ids = File.objects.filter(uploader=request.user.extrainfo).order_by('-upload_date').values_list('id', flat=True) + draft_files_pk=[] + + for i in ids: + file_tracking_ids = Tracking.objects.filter(file_id=i).values_list('id', flat=True) + if(len(file_tracking_ids)==0): + draft_files_pk.append(i) + + draft_file_list=[] + for i in draft_files_pk: + draft_file_list.append(File.objects.get(pk=i)) - """ - user_HoldsDesignation_obj = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) - s = str(user_HoldsDesignation_obj).split(" - ") - designation = s[1] - draft_files = view_drafts( - username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation, - src_module='filetracking' - ) - - # Correct upload_date type - for f in draft_files: - f['upload_date'] = parse_datetime(f['upload_date']) - f['uploader'] = get_extra_info_object_from_id(f['uploader']) - - draft_files = add_uploader_department_to_files_list(draft_files) + user_designation = HoldsDesignation.objects.select_related('user','working','designation').get(pk=id) + s = str(user_designation).split(" - ") + designations = s[1] context = { - 'draft_files': draft_files, - 'designations': designation, - 'notifications': request.user.notifications.all() + + 'draft': draft_file_list, + 'extrainfo': extrainfo, + 'designations': designations, } - return render(request, 'filetracking/drafts.html', context) + return render(request, 'filetracking/fileview.html', context) -@login_required(login_url="/accounts/login") -def outbox_view(request, id): + +@login_required(login_url = "/accounts/login") +def fileview1(request,id): + """ The function is used to get all the files sent by user(employee) to other employees which are filtered from Tracking(table) objects by current user i.e. current_id. @@ -234,129 +216,97 @@ def outbox_view(request, id): id - user id @variables: - outward_files - File objects filtered by current_id i.e, present working user. + out - The Tracking object filtered by current_id i.e, present working user. context - Holds data needed to make necessary changes in the template. + + """ + outward_files = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department', + 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(current_id=request.user.extrainfo).order_by('-forward_date') - """ - user_HoldsDesignation_obj = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) - s = str(user_HoldsDesignation_obj).split(" - ") - designation = s[1] - - outward_files = view_outbox(username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation, - src_module='filetracking') - - for f in outward_files: - last_forw_tracking = get_last_forw_tracking_for_user(file_id=f['id'], - username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation) - f['sent_to_user'] = last_forw_tracking.receiver_id - f['sent_to_design'] = last_forw_tracking.receive_design - f['last_sent_date'] = last_forw_tracking.forward_date - - f['upload_date'] = parse_datetime(f['upload_date']) - f['uploader'] = get_extra_info_object_from_id(f['uploader']) - - outward_files = add_uploader_department_to_files_list(outward_files) - user_HoldsDesignation_obj = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) - s = str(user_HoldsDesignation_obj).split(" - ") - designation = s[1] + user_designation = HoldsDesignation.objects.select_related('user','working','designation').get(pk=id) context = { - 'out_files': outward_files, - 'viewer_designation': designation, - 'notifications': request.user.notifications.all() + + 'out': outward_files, + 'abcd': user_designation, } - return render(request, 'filetracking/outbox.html', context) + return render(request, 'filetracking/fileview1.html', context) -@login_required(login_url="/accounts/login") -def inbox_view(request, id): +@login_required(login_url = "/accounts/login") +def fileview2(request,id): + """ The function is used to fetch the files received by the user form other employees. These files are filtered by receiver id and ordered by receive date. @param: request - trivial. - id - HoldsDesignation object id + id - user id @variables: - inward_files - File object with additional sent by information + inward_file - The Tracking object filtered by receiver_id i.e, present working user. context - Holds data needed to make necessary changes in the template. """ + inward_file = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department', + 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(receiver_id=request.user).order_by('-receive_date') - user_HoldsDesignation_obj = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) - s = str(user_HoldsDesignation_obj).split(" - ") - designation = s[1] - inward_files = view_inbox( - username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation, - src_module='filetracking' - ) - - # correct upload_date type and add recieve_date - for f in inward_files: - f['upload_date'] = parse_datetime(f['upload_date']) - - last_recv_tracking = get_last_recv_tracking_for_user(file_id=f['id'], - username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation) - f['receive_date'] = last_recv_tracking.receive_date - f['uploader'] = get_extra_info_object_from_id(f['uploader']) - - inward_files = add_uploader_department_to_files_list(inward_files) + user_designation = HoldsDesignation.objects.select_related('user','working','designation').get(pk=id) + s = str(user_designation).split(" - ") + designations = s[1] context = { - 'in_file': inward_files, - 'designations': designation, - 'notifications': request.user.notifications.all() + + 'in_file': inward_file, + 'designations': designations, } - return render(request, 'filetracking/inbox.html', context) + return render(request, 'filetracking/fileview2.html', context) -@login_required(login_url="/accounts/login") +@login_required(login_url = "/accounts/login") def outward(request): """ - This function redirects the user to the outbox page of designation selected in dropdown + This function fetches the different designations of the user and renders it on outward template @param: request - trivial. - """ - - dropdown_design = request.session.get( - 'currentDesignationSelected', 'default_value') - username = request.user - dropdown_HoldsDesignation_obj = get_HoldsDesignation_obj( - username, dropdown_design) - - return redirect('/filetracking/outbox/' + str(dropdown_HoldsDesignation_obj.id)) + @variables: + context - Holds the different designation data of the user + + """ + designation = get_designation(request.user) + context = { + 'designation': designation, + } + return render( request, 'filetracking/outward.html', context) -@login_required(login_url="/accounts/login") +@login_required(login_url = "/accounts/login") def inward(request): - """ - This function redirects the user to the inbox page of designation selected in dropdown - @param: - request - trivial. """ + This function fetches the different designations of the user and renders it on inward template - dropdown_design = request.session.get( - 'currentDesignationSelected', 'default_value') - username = request.user - dropdown_HoldsDesignation_obj = get_HoldsDesignation_obj( - username, dropdown_design) + + @param: + request - trivial. - return redirect('/filetracking/inbox/' + str(dropdown_HoldsDesignation_obj.id)) + @variables: + context - Holds the different designation data of the user + """ + designation = get_designation(request.user) + context = { + + 'designation': designation, + } + return render(request, 'filetracking/inward.html', context) @login_required(login_url = "/accounts/login") def confirmdelete(request,id): + """ The function is used to confirm the deletion of a file. @param: @@ -366,87 +316,16 @@ def confirmdelete(request,id): @variables: context - Holds data needed to make necessary changes in the template. """ - file = File.objects.select_related( - 'uploader__user', 'uploader__department', 'designation').get(pk=id) + file = File.objects.select_related('uploader__user','uploader__department','designation').get(pk = id) context = { 'j': file, } - return render(request, 'filetracking/confirmdelete.html', context) - -@login_required(login_url="/accounts/login") -def view_file(request, id): - ''' - This function is used to view a particular file received by an employee from another. - This function also conditionally renders two forms 'forward_file' and 'archive_file' - based on if the user has necessary permissions or not. - The business permissions are as follows: - 1. User can forward file only if they are the last recipient of the file - 2. User can archive a file only if they have received it last and they are also the original owner of the file - - To forward the file and to archive the file separate views with POST request are called - - It displays the details file of a File and remarks as well as the attachments of all the users - who have been involved till that point of the workflow. - - @param: - request - Trivial. - id - ID of the file object which the user intends to forward to another employee. - - @variables: - file - The File object. - track - The Tracking object. - designation - the designations of the user - ''' - - file = get_object_or_404(File, id=id) - track = Tracking.objects.select_related('file_id__uploader__user', 'file_id__uploader__department', 'file_id__designation', 'current_id__user', 'current_id__department', - 'current_design__user', 'current_design__working', 'current_design__designation', 'receiver_id', 'receive_design').filter(file_id=file).order_by('receive_date') - designations = get_designation(request.user) - - forward_enable = False - archive_enable = False - - current_owner = get_current_file_owner(file.id) - file_uploader = get_user_object_from_username(file.uploader.user.username) - + return render(request, 'filetracking/confirmdelete.html',context) - if current_owner == request.user and file.is_read is False: - forward_enable = True - if current_owner == request.user and file_uploader == request.user and file.is_read is False: - archive_enable = True - context = { - 'designations': designations, - 'file': file, - 'track': track, - 'forward_enable': forward_enable, - 'archive_enable': archive_enable, - 'notifications': request.user.notifications.all() - } - return render(request, 'filetracking/viewfile.html', context) - -@login_required(login_url="/accounts/login") -def archive_file(request, id): - '''This function is used to archive a file. - It returns unauthorized access if the user is not file uploader - and the current owner of the file - ''' - if request.method == "POST": - file = get_object_or_404(File, id=id); - current_owner = get_current_file_owner(file.id) - file_uploader = get_user_object_from_username(file.uploader.user.username) - if current_owner == request.user and file_uploader == request.user: - file.is_read = True - file.save() - messages.success(request, 'File Archived') - else: - messages.error(request, 'Unauthorized access') - - return render(request, 'filetracking/composefile.html') - -@login_required(login_url="/accounts/login") +@login_required(login_url = "/accounts/login") def forward(request, id): """ The function is used to forward files received by user(employee) from other @@ -472,215 +351,198 @@ def forward(request, id): holdsdesignations = HoldsDesignation objects. context - Holds data needed to make necessary changes in the template. """ - + file = get_object_or_404(File, id=id) - track = Tracking.objects.select_related('file_id__uploader__user', 'file_id__uploader__department', 'file_id__designation', 'current_id__user', 'current_id__department', - 'current_design__user', 'current_design__working', 'current_design__designation', 'receiver_id', 'receive_design').filter(file_id=file).order_by('receive_date') - + track = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department', + 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id=file) + if request.method == "POST": - if 'finish' in request.POST: - file.is_read = True - file.save() - if 'send' in request.POST: - current_id = request.user.extrainfo - remarks = request.POST.get('remarks') - track.update(is_read=True) - - sender = request.POST.get('sender') - current_design = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(id=sender) - - receiver = request.POST.get('receiver') - try: - receiver_id = User.objects.get(username=receiver) - except Exception as e: - messages.error(request, 'Enter a valid destination') - designations = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').filter(user=request.user) - - context = { - - 'designations': designations, - 'file': file, - 'track': track, - } - return render(request, 'filetracking/forward.html', context) - receive = request.POST.get('receive') - try: - receive_design = Designation.objects.get(name=receive) - except Exception as e: - messages.error(request, 'Enter a valid Designation') - designations = get_designation(request.user) - - context = { - - 'designations': designations, - 'file': file, - 'track': track, - } - return render(request, 'filetracking/forward.html', context) - - upload_file = request.FILES.get('myfile') - - Tracking.objects.create( - file_id=file, - current_id=current_id, - current_design=current_design, - receive_design=receive_design, - receiver_id=receiver_id, - remarks=remarks, - upload_file=upload_file, - ) - messages.success(request, 'File sent successfully') + if 'finish' in request.POST: + file.complete_flag = True + file.save() - designations = get_designation(request.user) + if 'send' in request.POST: + current_id = request.user.extrainfo + remarks = request.POST.get('remarks') + track.update(is_read=True) - designation_name = request.session.get('currentDesignationSelected', 'default_value') - all_available_designations = request.session.get( - 'allDesignations', 'default_value2') + sender = request.POST.get('sender') + current_design = HoldsDesignation.objects.select_related('user','working','designation').get(id=sender) - username = request.user - designation_id = get_HoldsDesignation_obj( - username, designation_name).id + receiver = request.POST.get('receiver') + try: + receiver_id = User.objects.get(username=receiver) + except Exception as e: + messages.error(request, 'Enter a valid destination') + designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) + + context = { + + 'designations': designations, + 'file': file, + 'track': track, + } + return render(request, 'filetracking/forward.html', context) + receive = request.POST.get('recieve') + try: + receive_design = Designation.objects.get(name=receive) + except Exception as e: + messages.error(request, 'Enter a valid Designation') + designations = get_designation(request.user) + context = { + + 'designations': designations, + 'file': file, + 'track': track, + } + return render(request, 'filetracking/forward.html', context) + + + upload_file = request.FILES.get('myfile') + + Tracking.objects.create( + file_id=file, + current_id=current_id, + current_design=current_design, + receive_design=receive_design, + receiver_id=receiver_id, + remarks=remarks, + upload_file=upload_file, + ) + messages.success(request, 'File sent successfully') + + + designations = get_designation(request.user) context = { - 'designations': designations, + + 'designations':designations, 'file': file, 'track': track, - 'designation_name': designation_name, - 'designation_id': designation_id, - - 'notifications': request.user.notifications.all() } return render(request, 'filetracking/forward.html', context) -@login_required(login_url="/accounts/login") +@login_required(login_url = "/accounts/login") def archive_design(request): - """ - This function redirects the user to the archive page of designation selected in dropdown - @param: - request - trivial. - """ - dropdown_design = request.session.get( - 'currentDesignationSelected', 'default_value') - username = request.user - dropdown_HoldsDesignation_obj = get_HoldsDesignation_obj( - username, dropdown_design) + designation = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - return redirect('/filetracking/archive/' + str(dropdown_HoldsDesignation_obj.id)) - - -@login_required(login_url="/accounts/login") -def archive_view(request, id): - """ - The function is used to fetch the files in the user's archive - (those which have passed by user and been archived/finished) + context = { + 'designation': designation, + } + return render( request, 'filetracking/archive_design.html', context) + + - @param: - request - trivial. - id - HoldsDesignation object id - @variables: - archive_files - File object with additional information - context - Holds data needed to make necessary changes in the template. - """ - user_HoldsDesignation_obj = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) - s = str(user_HoldsDesignation_obj).split(" - ") - designation = s[1] +@login_required(login_url = "/accounts/login") +def archive(request , id): - archive_files = view_archived( - username=user_HoldsDesignation_obj.user, - designation=user_HoldsDesignation_obj.designation, - src_module='filetracking' - ) + draft = File.objects.select_related('uploader__user','uploader__department','designation').filter(is_read=True).order_by('-upload_date') - # correct upload_date type and add receive_date - for f in archive_files: - f['upload_date'] = parse_datetime(f['upload_date']) - f['designation'] = Designation.objects.get(id=f['designation']) - f['uploader'] = get_extra_info_object_from_id(f['uploader']) - archive_files = add_uploader_department_to_files_list(archive_files) + extrainfo = ExtraInfo.objects.select_related('user','department').all() + # designations = Designation.objects.filter(upload_designation=extrainfo.id) + abcd = HoldsDesignation.objects.select_related('user','working','designation').get(pk=id) + s = str(abcd).split(" - ") + designations = s[1] + #designations = HoldsDesignation.objects.filter(user=request.user) + # for x in designations: + # if abcd==x: + # designations=abcd context = { - 'archive_files': archive_files, - 'designations': designation, - 'notifications': request.user.notifications.all() + + 'draft': draft, + 'extrainfo': extrainfo, + 'designations': designations, } - return render(request, 'filetracking/archive.html', context) -@login_required(login_url="/accounts/login") + + return render(request, 'filetracking/archive.html' , context) + + +@login_required(login_url = "/accounts/login") def archive_finish(request, id): - # file = get_object_or_404(File, ref_id=id) - file1 = get_object_or_404(File, id=id) + file1 = get_object_or_404(File, id=id) ##file = get_object_or_404(File, ref_id=id) track = Tracking.objects.filter(file_id=file1) + + return render(request, 'filetracking/archive_finish.html', {'file': file1, 'track': track}) -@login_required(login_url="/accounts/login") + + +@login_required(login_url = "/accounts/login") def finish_design(request): - designation = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').filter(user=request.user) + designation = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) context = { 'designation': designation, - 'notifications': request.user.notifications.all() } - return render(request, 'filetracking/finish_design.html', context) + return render( request, 'filetracking/finish_design.html', context) -@login_required(login_url="/accounts/login") +@login_required(login_url = "/accounts/login") def finish_fileview(request, id): - out = Tracking.objects.select_related('file_id__uploader__user', 'file_id__uploader__department', 'file_id__designation', 'current_id__user', 'current_id__department', - 'current_design__user', 'current_design__working', 'current_design__designation', 'receiver_id', 'receive_design').filter(file_id__uploader=request.user.extrainfo, is_read=False).order_by('-forward_date') + out = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department', + 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id__uploader=request.user.extrainfo, is_read=False).order_by('-forward_date') + + + + + abcd = HoldsDesignation.objects.select_related('user','working','designation').get(pk=id) - abcd = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(pk=id) context = { 'out': out, 'abcd': abcd, - 'notifications': request.user.notifications.all() } return render(request, 'filetracking/finish_fileview.html', context) -@login_required(login_url="/accounts/login") + + +@login_required(login_url = "/accounts/login") def finish(request, id): - # file = get_object_or_404(File, ref_id=id) - file1 = get_object_or_404(File, id=id) + file1 = get_object_or_404(File, id=id) ##file = get_object_or_404(File, ref_id=id) track = Tracking.objects.filter(file_id=file1) + if request.method == "POST": - if 'Finished' in request.POST: - File.objects.filter(pk=id).update(is_read=True) - track.update(is_read=True) - messages.success(request, 'File Archived') + if 'Finished' in request.POST: + File.objects.filter(pk=id).update(is_read=True) + track.update(is_read=True) + messages.success(request,'File Archived') - return render(request, 'filetracking/finish.html', {'file': file1, 'track': track, 'fileid': id, - 'notifications': request.user.notifications.all()}) + + -def AjaxDropdown1(request): + + + return render(request, 'filetracking/finish.html', {'file': file1, 'track': track,'fileid':id}) + + + +def AjaxDropdown1(request): """ This function returns the designation of receiver on the forward or compose file template. @param: request - trivial. - + @variables: context - return the httpresponce containing the matched designation of the user @@ -691,19 +553,20 @@ def AjaxDropdown1(request): hold = Designation.objects.filter(name__startswith=value) holds = serializers.serialize('json', list(hold)) context = { - 'holds': holds + 'holds' : holds } return HttpResponse(JsonResponse(context), content_type='application/json') def AjaxDropdown(request): + """ This function returns the usernames of receiver on the forward or compose file template. @param: request - trivial. - + @variables: context - return the httpresponce containing the matched username @@ -726,20 +589,24 @@ def test(request): @login_required(login_url = "/accounts/login") def delete(request,id): + """ The function is used the delete of a file and it returns to the drafts page. @param: request - trivial. id - id of the file that is going to be deleted - + """ - file = File.objects.get(pk=id) + file = File.objects.get(pk = id) file.delete() - return redirect('/filetracking/draftdesign/') + return redirect('/filetracking/drafts/') + + def forward_inward(request,id): + """ This function is used forward the files which are available in the inbox of the user . @param: @@ -750,157 +617,21 @@ def forward_inward(request,id): file - file object track - tracking object of the file context - necessary data to render - + """ file = get_object_or_404(File, id=id) file.is_read = True - track = Tracking.objects.select_related('file_id__uploader__user', 'file_id__uploader__department', 'file_id__designation', 'current_id__user', 'current_id__department', - 'current_design__user', 'current_design__working', 'current_design__designation', 'receiver_id', 'receive_design').filter(file_id=file) + track = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department', + 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id=file) designations = get_designation(request.user) context = { - - 'designations': designations, + + 'designations':designations, 'file': file, 'track': track, - 'notifications': request.user.notifications.all() } return render(request, 'filetracking/forward.html', context) -def get_designations_view(request, username): - designations = get_designations(username) - return JsonResponse(designations, safe=False) - -def unarchive_file(request, id): - try: - file = get_object_or_404(File, id=id) - file.is_read = False - file.save() - messages.success(request, 'File unarchived') - except File.DoesNotExist: - messages.error(request, 'File does not exist') - except Exception as e: - messages.error(request, 'Unable to unarchive: {}'.format(str(e))) - - return render(request, 'filetracking/archive.html') - - -@login_required(login_url="/accounts/login") -def edit_draft_view(request, id, *args, **kwargs): - """ - The function is used to edit and send drafted files, and also alter their title and subject - along with their remarks and attachments - - @param: - request - trivial. - id - id of the file object which the user intends to forward to other employee. - @variables: - file - The File object. - track - The Tracking object. - remarks = Remarks posted by user. - receiver = Receiver to be selected by user for forwarding file. - receiver_id = Receiver_id who has been selected for forwarding file. - upload_file = File attached by user. - extrainfo = ExtraInfo object. - holdsdesignations = HoldsDesignation objects. - context - Holds data needed to make necessary changes in the template. - """ - - file = get_object_or_404(File, id=id) - track = Tracking.objects.select_related('file_id__uploader__user', 'file_id__uploader__department', 'file_id__designation', 'current_id__user', 'current_id__department', - 'current_design__user', 'current_design__working', 'current_design__designation', 'receiver_id', 'receive_design').filter(file_id=file).order_by('receive_date') - - if request.method == "POST": - if 'send' in request.POST: - current_id = request.user.extrainfo - remarks = request.POST.get('remarks') - subject = request.POST.get('subject') - description = request.POST.get('description') - - file.subject = subject - file.description = description - file.save() - track.update(is_read=True) - - sender = request.POST.get('sender') - current_design = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').get(id=sender) - - receiver = request.POST.get('receiver') - try: - receiver_id = User.objects.get(username=receiver) - except Exception as e: - messages.error(request, 'Enter a valid destination') - designations = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').filter(user=request.user) - - context = { - - 'designations': designations, - 'file': file, - 'track': track, - 'notifications': request.user.notifications.all() - } - return render(request, 'filetracking/editdraft.html', context) - receive = request.POST.get('receive') - try: - receive_design = Designation.objects.get(name=receive) - except Exception as e: - messages.error(request, 'Enter a valid Designation') - designations = get_designation(request.user) - - context = { - - 'designations': designations, - 'file': file, - 'notifications': request.user.notifications.all() - } - return render(request, 'filetracking/editdraft.html', context) - - upload_file = request.FILES.get('myfile') - - Tracking.objects.create( - file_id=file, - current_id=current_id, - current_design=current_design, - receive_design=receive_design, - receiver_id=receiver_id, - remarks=remarks, - upload_file=upload_file, - ) - messages.success(request, 'File sent successfully') - - designations = get_designation(request.user) - - designation_name = request.session.get('currentDesignationSelected', 'default_value') - all_available_designations = request.session.get( - 'allDesignations', 'default_value2') - - - username = request.user - designation_id = get_HoldsDesignation_obj( - username, designation_name).id - - remarks = None - receive = None - receiver = None - - if file.file_extra_JSON and file.file_extra_JSON['remarks']: - remarks = file.file_extra_JSON['remarks'] - - context = { - 'designations': designations, - 'file': file, - 'track': track, - 'designation_name': designation_name, - 'designation_id': designation_id, - 'remarks' : remarks, - 'notifications': request.user.notifications.all() - } - - return render(request, 'filetracking/editdraft.html', context) - - - diff --git a/FusionIIIT/applications/finance_accounts/migrations/0001_initial.py b/FusionIIIT/applications/finance_accounts/migrations/0001_initial.py index 8d45f1fc1..4dfa8fed7 100644 --- a/FusionIIIT/applications/finance_accounts/migrations/0001_initial.py +++ b/FusionIIIT/applications/finance_accounts/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models diff --git a/FusionIIIT/applications/globals/migrations/0001_initial.py b/FusionIIIT/applications/globals/migrations/0001_initial.py index 7fc43ccef..1fc3a8925 100644 --- a/FusionIIIT/applications/globals/migrations/0001_initial.py +++ b/FusionIIIT/applications/globals/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import applications.globals.models import datetime @@ -39,7 +39,7 @@ class Migration(migrations.Migration): ('title', models.CharField(choices=[('Mr.', 'Mr.'), ('Mrs.', 'Mrs.'), ('Ms.', 'Ms.'), ('Dr.', 'Dr.'), ('Professor', 'Prof.'), ('Shreemati', 'Shreemati'), ('Shree', 'Shree')], default='Dr.', max_length=20)), ('sex', models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], default='M', max_length=2)), ('date_of_birth', models.DateField(default=datetime.date(1970, 1, 1))), - ('user_status', models.CharField(choices=[('NEW', 'NEW'), ('PRESENT', 'PRESENT')], default='PRESENT', max_length=50)), + ('user_status', models.CharField(choices=[('PRESENT', 'PRESENT'), ('NEW', 'NEW')], default='PRESENT', max_length=50)), ('address', models.TextField(default='', max_length=1000)), ('phone_no', models.BigIntegerField(default=9999999999, null=True)), ('user_type', models.CharField(choices=[('student', 'student'), ('staff', 'staff'), ('compounder', 'compounder'), ('faculty', 'faculty')], max_length=20)), @@ -106,7 +106,7 @@ class Migration(migrations.Migration): ('working', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='current_designation', to=settings.AUTH_USER_MODEL)), ], options={ - 'unique_together': {('working', 'designation'), ('user', 'designation')}, + 'unique_together': {('user', 'designation'), ('working', 'designation')}, }, ), ] diff --git a/FusionIIIT/applications/globals/models.py b/FusionIIIT/applications/globals/models.py index d51fbcb69..31eedcfb4 100644 --- a/FusionIIIT/applications/globals/models.py +++ b/FusionIIIT/applications/globals/models.py @@ -64,6 +64,8 @@ class Constants: DESIGNATIONS = ( ('academic', 'Academic Designation'), ('administrative', 'Administrative Designation'), + + ) USER_STATUS = { ("NEW", "NEW"), diff --git a/FusionIIIT/applications/globals/views.py b/FusionIIIT/applications/globals/views.py index 74be358d3..5b023abb5 100644 --- a/FusionIIIT/applications/globals/views.py +++ b/FusionIIIT/applications/globals/views.py @@ -1,4 +1,3 @@ -from audioop import reverse import json from django.contrib.auth import logout @@ -29,7 +28,6 @@ from Fusion.settings.common import LOGIN_URL from notifications.models import Notification from .models import * -from applications.hostel_management.models import (HallCaretaker,HallWarden) def index(request): context = {} @@ -734,25 +732,11 @@ def dashboard(request): for i in b : name_ = get_object_or_404(Designation, id = i) roll_.append(str(name_.name)) - - hall_caretakers = HallCaretaker.objects.all().select_related() - hall_wardens = HallWarden.objects.all().select_related() - - hall_caretaker_user = [] - for caretaker in hall_caretakers: - hall_caretaker_user.append(caretaker.staff.id.user) - - hall_warden_user = [] - for warden in hall_wardens: - hall_warden_user.append(warden.faculty.id.user) - context={ 'notifications':notifs, 'Curr_desig' : roll_, 'club_details' : coordinator_club(request), 'designation' : designation, - 'hall_caretaker': hall_caretaker_user, - 'hall_warden': hall_warden_user, } # a=HoldsDesignation.objects.select_related('user','working','designation').filter(designation = user) @@ -787,9 +771,8 @@ def profile(request, username=None): username: Username of the user. If None, displays the profile of currently logged-in user """ - - user = get_object_or_404(User, Q(username=username)) if username else request.user + editable = request.user == user print("editable",editable) profile = get_object_or_404(ExtraInfo, Q(user=user)) @@ -1061,7 +1044,7 @@ def profile(request, username=None): return render(request, "globals/student_profile4.html", context) if 'achievementsubmit' in request.POST or 'deleteach' in request.POST: return render(request, "globals/student_profile5.html", context) - # print("context",context) + print("context",context) return render(request, "globals/student_profile.html", context) else: return redirect("/") diff --git a/FusionIIIT/applications/gymkhana/migrations/0001_initial.py b/FusionIIIT/applications/gymkhana/migrations/0001_initial.py index 546d7fb81..e140005a1 100644 --- a/FusionIIIT/applications/gymkhana/migrations/0001_initial.py +++ b/FusionIIIT/applications/gymkhana/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models @@ -11,9 +11,9 @@ class Migration(migrations.Migration): initial = True dependencies = [ + ('academic_information', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('globals', '0001_initial'), - ('academic_information', '0001_initial'), ] operations = [ diff --git a/FusionIIIT/applications/health_center/admin.py b/FusionIIIT/applications/health_center/admin.py index 7299eff00..0116b8a3e 100644 --- a/FusionIIIT/applications/health_center/admin.py +++ b/FusionIIIT/applications/health_center/admin.py @@ -1,6 +1,8 @@ from django.contrib import admin -from .models import * +from .models import (Ambulance_request, Appointment, Complaint, Counter, + Doctor, Expiry, Hospital, Hospital_admit, Medicine, + Prescribed_medicine, Prescription, Schedule, Stock) admin.site.register(Doctor) admin.site.register(Appointment) @@ -14,8 +16,4 @@ admin.site.register(Prescription) admin.site.register(Medicine) admin.site.register(Prescribed_medicine) -admin.site.register(Doctors_Schedule) -admin.site.register(Pathologist_Schedule) -admin.site.register(Announcements) -admin.site.register(SpecialRequest) -admin.site.register(Pathologist) \ No newline at end of file +admin.site.register(Schedule) diff --git a/FusionIIIT/applications/health_center/api/serializers.py b/FusionIIIT/applications/health_center/api/serializers.py index 06fe901c1..dfb72d68a 100644 --- a/FusionIIIT/applications/health_center/api/serializers.py +++ b/FusionIIIT/applications/health_center/api/serializers.py @@ -41,24 +41,10 @@ class Meta: model=Expiry fields=('__all__') -class DoctorsScheduleSerializer(serializers.ModelSerializer): +class ScheduleSerializer(serializers.ModelSerializer): class Meta: - model=Doctors_Schedule - fields=('__all__') -class PathologistScheduleSerializer(serializers.ModelSerializer): - - class Meta: - model=Pathologist_Schedule - fields=('__all__') - - - - -class AnnouncementSerializer(serializers.ModelSerializer): - - class Meta: - model=Announcements + model=Schedule fields=('__all__') @@ -99,10 +85,4 @@ class HospitalAdmitSerializer(serializers.ModelSerializer): class Meta: model=Hospital_admit - fields=('__all__') - -class MedicalReliefSerializer(serializers.ModelSerializer): - - class Meta: - model=medical_relief fields=('__all__') \ No newline at end of file diff --git a/FusionIIIT/applications/health_center/api/urls.py b/FusionIIIT/applications/health_center/api/urls.py index 49fee2d6e..661279c87 100644 --- a/FusionIIIT/applications/health_center/api/urls.py +++ b/FusionIIIT/applications/health_center/api/urls.py @@ -7,5 +7,6 @@ url(r'^compounder/$', views.compounder_view_api, name='compounder_view_api'), url(r'^compounder/request$', views.compounder_request_api , name='compounder_request_api'), url(r'^student/$', views.student_view_api, name='student_view'), - url(r'^student/request$', views.student_request_api, name='student_request_api') -] \ No newline at end of file + url(r'^student/request$', views.student_request_api, name='student_request_api') + +] diff --git a/FusionIIIT/applications/health_center/api/views.py b/FusionIIIT/applications/health_center/api/views.py index f82665a69..41912ed50 100644 --- a/FusionIIIT/applications/health_center/api/views.py +++ b/FusionIIIT/applications/health_center/api/views.py @@ -5,6 +5,7 @@ from datetime import datetime, timedelta, time,date from django.db import transaction from notification.views import healthcare_center_notif + from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework import status @@ -57,7 +58,7 @@ def student_request_api(request): doctor_id = request.data['doctor_id'] except: return Response({'message': 'Please enter doctor id'}, status=status.HTTP_404_NOT_FOUND) - request.data['schedule'] =get_object_or_404(Doctors_Schedule,doctor_id=request.data['doctor_id'],day=day).id + request.data['schedule'] =get_object_or_404(Schedule,doctor_id=request.data['doctor_id'],day=day).id comp_id = ExtraInfo.objects.filter(user_type='compounder') serializer = serializers.AppointmentSerializer(data=request.data) if serializer.is_valid(): @@ -109,7 +110,7 @@ def student_view_api(request): medicines = serializers.PrescribedMedicineSerializer(Prescribed_medicine.objects.all(),many=True).data complaints = serializers.ComplaintSerializer(Complaint.objects.filter(user_id=user_id).order_by('-date'),many=True).data days = Constants.DAYS_OF_WEEK - schedule=serializers.ScheduleSerializer(Doctors_Schedule.objects.all().order_by('doctor_id'),many=True).data + schedule=serializers.ScheduleSerializer(Schedule.objects.all().order_by('doctor_id'),many=True).data doctors=serializers.DoctorSerializer(Doctor.objects.filter(active=True),many=True).data count=Counter.objects.all() if count: @@ -170,11 +171,11 @@ def compounder_request_api(request): day = request.data['day'] except: return Response({'message': 'Please enter valid day'}, status=status.HTTP_404_NOT_FOUND) - sc = Doctor.objects.filter(doctor_id=doctor_id, day=day) + sc = Schedule.objects.filter(doctor_id=doctor_id, day=day) if sc.count() == 0: serializer = serializers.ScheduleSerializer(data=request.data) else: - sc = get_object_or_404(Doctors_Schedule,doctor_id=doctor_id,day=day) + sc = get_object_or_404(Schedule,doctor_id=doctor_id,day=day) serializer = serializers.ScheduleSerializer(sc,data=request.data,partial=True) if serializer.is_valid(): serializer.save() @@ -190,7 +191,7 @@ def compounder_request_api(request): day = request.data['day'] except: return Response({'message': 'Please enter valid day'}, status=status.HTTP_404_NOT_FOUND) - sc = get_object_or_404(Doctors_Schedule,doctor_id=doctor_id,day=day) + sc = get_object_or_404(Schedule,doctor_id=doctor_id,day=day) sc.delete() resp={'message':'Schedule Deleted successfully'} return Response(data=resp,status=status.HTTP_200_OK) @@ -326,7 +327,7 @@ def compounder_view_api(request): appointments_future= serializers.AppointmentSerializer(Appointment.objects.filter(date__gt=datetime.now()).order_by('date'),many=True).data stocks = serializers.StockSerializer(Stock.objects.all(),many=True).data days = Constants.DAYS_OF_WEEK - schedule= serializers.ScheduleSerializer(Doctors_Schedule.objects.all().order_by('doctor_id'),many=True).data + schedule= serializers.ScheduleSerializer(Schedule.objects.all().order_by('doctor_id'),many=True).data expired= serializers.ExpirySerializer(Expiry.objects.filter(expiry_date__lt=datetime.now(),returned=False).order_by('expiry_date'),many=True).data live_meds= serializers.ExpirySerializer(Expiry.objects.filter(returned=False).order_by('quantity'),many=True).data count= Counter.objects.all() @@ -338,7 +339,7 @@ def compounder_view_api(request): Counter.objects.create(count=0,fine=0) count= serializers.CounterSerializer(Counter.objects.get()).data hospitals=serializers.HospitalSerializer(Hospital.objects.all(),many=True).data - schedule= serializers.ScheduleSerializer(Doctors_Schedule.objects.all().order_by('day','doctor_id'),many=True).data + schedule= serializers.ScheduleSerializer(Schedule.objects.all().order_by('day','doctor_id'),many=True).data doctors= serializers.DoctorSerializer(Doctor.objects.filter(active=True).order_by('id'),many=True).data resp= {'days': days, 'count': count,'expired':expired, @@ -350,4 +351,6 @@ def compounder_view_api(request): else: resp = {'message': 'invalid request'} - return Response(data=resp,status=status.HTTP_404_NOT_FOUND) # compounder view ends \ No newline at end of file + return Response(data=resp,status=status.HTTP_404_NOT_FOUND) # compounder view ends + + diff --git a/FusionIIIT/applications/health_center/migrations/0001_initial.py b/FusionIIIT/applications/health_center/migrations/0001_initial.py index 072d80def..ee068099e 100644 --- a/FusionIIIT/applications/health_center/migrations/0001_initial.py +++ b/FusionIIIT/applications/health_center/migrations/0001_initial.py @@ -1,6 +1,5 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 -import datetime from django.db import migrations, models import django.db.models.deletion @@ -14,6 +13,14 @@ class Migration(migrations.Migration): ] operations = [ + migrations.CreateModel( + name='Appointment', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('description', models.CharField(max_length=50)), + ('date', models.DateField()), + ], + ), migrations.CreateModel( name='Counter', fields=[ @@ -21,15 +28,14 @@ class Migration(migrations.Migration): ('count', models.IntegerField(default=0)), ('fine', models.IntegerField(default=0)), ('doc_count', models.IntegerField(default=0)), - ('patho_count', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Doctor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('doctor_name', models.CharField(choices=[(0, 'Dr.Sharma'), (1, 'Dr.Vinay')], max_length=50)), - ('doctor_phone', models.CharField(max_length=15)), + ('doctor_name', models.IntegerField(choices=[(0, 'Dr.Sharma'), (1, 'Dr.Vinay')])), + ('doctor_phone', models.CharField(max_length=10)), ('specialization', models.CharField(max_length=100)), ('active', models.BooleanField(default=True)), ], @@ -42,27 +48,6 @@ class Migration(migrations.Migration): ('phone', models.CharField(max_length=10)), ], ), - migrations.CreateModel( - name='medical_relief', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('description', models.CharField(max_length=200)), - ('file', models.FileField(upload_to='medical_files/')), - ('file_id', models.IntegerField(default=0)), - ('compounder_forward_flag', models.BooleanField(default=False)), - ('acc_admin_forward_flag', models.BooleanField(default=False)), - ], - ), - migrations.CreateModel( - name='Pathologist', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('pathologist_name', models.CharField(choices=[(0, 'Dr.Ajay'), (1, 'Dr.Rahul')], max_length=50)), - ('pathologist_phone', models.CharField(max_length=15)), - ('specialization', models.CharField(max_length=100)), - ('active', models.BooleanField(default=True)), - ], - ), migrations.CreateModel( name='Stock', fields=[ @@ -73,17 +58,15 @@ class Migration(migrations.Migration): ], ), migrations.CreateModel( - name='SpecialRequest', + name='Schedule', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('request_date', models.DateTimeField(default=datetime.date.today)), - ('brief', models.CharField(default='--', max_length=20)), - ('request_details', models.CharField(max_length=200)), - ('upload_request', models.FileField(blank=True, upload_to='')), - ('status', models.CharField(default='Pending', max_length=50)), - ('remarks', models.CharField(default='--', max_length=300)), - ('request_receiver', models.CharField(default='--', max_length=30)), - ('request_ann_maker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='special_requests_made', to='globals.extrainfo')), + ('day', models.IntegerField(choices=[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday')])), + ('from_time', models.TimeField(blank=True, null=True)), + ('to_time', models.TimeField(blank=True, null=True)), + ('room', models.IntegerField()), + ('date', models.DateField(auto_now=True)), + ('doctor_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.doctor')), ], ), migrations.CreateModel( @@ -93,7 +76,7 @@ class Migration(migrations.Migration): ('details', models.CharField(max_length=100)), ('date', models.DateField()), ('test', models.CharField(blank=True, max_length=200, null=True)), - ('file_id', models.IntegerField(default=0)), + ('appointment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='health_center.appointment')), ('doctor_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='health_center.doctor')), ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], @@ -109,18 +92,6 @@ class Migration(migrations.Migration): ('prescription_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.prescription')), ], ), - migrations.CreateModel( - name='Pathologist_Schedule', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('day', models.CharField(choices=[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday')], max_length=10)), - ('from_time', models.TimeField(blank=True, null=True)), - ('to_time', models.TimeField(blank=True, null=True)), - ('room', models.IntegerField()), - ('date', models.DateField(auto_now=True)), - ('pathologist_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.pathologist')), - ], - ), migrations.CreateModel( name='Medicine', fields=[ @@ -158,18 +129,6 @@ class Migration(migrations.Migration): ('medicine_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.stock')), ], ), - migrations.CreateModel( - name='Doctors_Schedule', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('day', models.CharField(choices=[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday')], max_length=10)), - ('from_time', models.TimeField(blank=True, null=True)), - ('to_time', models.TimeField(blank=True, null=True)), - ('room', models.IntegerField()), - ('date', models.DateField(auto_now=True)), - ('doctor_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.doctor')), - ], - ), migrations.CreateModel( name='Complaint', fields=[ @@ -180,29 +139,20 @@ class Migration(migrations.Migration): ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], ), - migrations.CreateModel( - name='Appointment', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('description', models.CharField(max_length=50)), - ('date', models.DateField()), - ('doctor_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.doctor')), - ('schedule', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='health_center.doctors_schedule')), - ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), - ], + migrations.AddField( + model_name='appointment', + name='doctor_id', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='health_center.doctor'), ), - migrations.CreateModel( - name='Announcements', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('ann_date', models.DateTimeField(default='04-04-2021')), - ('message', models.CharField(max_length=200)), - ('batch', models.CharField(default='Year-1', max_length=40)), - ('department', models.CharField(default='ALL', max_length=40)), - ('programme', models.CharField(max_length=10)), - ('upload_announcement', models.FileField(default=' ', null=True, upload_to='health_center/upload_announcement')), - ('anno_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='announcements_made', to='globals.extrainfo')), - ], + migrations.AddField( + model_name='appointment', + name='schedule', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='health_center.schedule'), + ), + migrations.AddField( + model_name='appointment', + name='user_id', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo'), ), migrations.CreateModel( name='Ambulance_request', diff --git a/FusionIIIT/applications/health_center/models.py b/FusionIIIT/applications/health_center/models.py index 37f076d08..4daaae0de 100644 --- a/FusionIIIT/applications/health_center/models.py +++ b/FusionIIIT/applications/health_center/models.py @@ -1,10 +1,7 @@ - from django.db import models -from datetime import date from applications.globals.models import ExtraInfo - # Create your models here. @@ -24,32 +21,16 @@ class Constants: (1, 'Dr.Vinay'), ) - - NAME_OF_PATHOLOGIST = ( - (0, 'Dr.Ajay'), - (1, 'Dr.Rahul'), - - ) class Doctor(models.Model): - doctor_name = models.CharField(choices=Constants.NAME_OF_DOCTOR, max_length=50) - doctor_phone = models.CharField(max_length=15) + doctor_name = models.IntegerField(choices=Constants.NAME_OF_DOCTOR) + doctor_phone = models.CharField(max_length=10) specialization = models.CharField(max_length=100) active = models.BooleanField(default=True) def __str__(self): return self.doctor_name -class Pathologist(models.Model): - pathologist_name = models.CharField(choices=Constants.NAME_OF_PATHOLOGIST, max_length=50) - pathologist_phone = models.CharField(max_length=15) - specialization = models.CharField(max_length=100) - active = models.BooleanField(default=True) - - def __str__(self): - return self.pathologist_name - - class Complaint(models.Model): user_id = models.ForeignKey(ExtraInfo,on_delete=models.CASCADE) feedback = models.CharField(max_length=100, null=True, blank=False) #This is the feedback given by the compounder @@ -84,7 +65,7 @@ class Hospital(models.Model): def __str__(self): return self.hospital_name - + class Expiry(models.Model): medicine_id=models.ForeignKey(Stock,on_delete=models.CASCADE) quantity = models.IntegerField(default=0) @@ -96,19 +77,9 @@ class Expiry(models.Model): def __str__(self): return self.medicine_id.medicine_name -class Doctors_Schedule(models.Model): +class Schedule(models.Model): doctor_id = models.ForeignKey(Doctor,on_delete=models.CASCADE) - # pathologist_id = models.ForeignKey(Pathologist,on_delete=models.CASCADE, default=0) - day = models.CharField(choices=Constants.DAYS_OF_WEEK, max_length=10) - from_time = models.TimeField(null=True,blank=True) - to_time = models.TimeField(null=True,blank=True) - room = models.IntegerField() - date = models.DateField(auto_now=True) - -class Pathologist_Schedule(models.Model): - # doctor_id = models.ForeignKey(Doctor,on_delete=models.CASCADE) - pathologist_id = models.ForeignKey(Pathologist,on_delete=models.CASCADE) - day = models.CharField(choices=Constants.DAYS_OF_WEEK, max_length=10) + day = models.IntegerField(choices=Constants.DAYS_OF_WEEK) from_time = models.TimeField(null=True,blank=True) to_time = models.TimeField(null=True,blank=True) room = models.IntegerField() @@ -119,14 +90,10 @@ class Counter(models.Model): count=models.IntegerField(default=0) fine=models.IntegerField(default=0) doc_count=models.IntegerField(default=0) - patho_count=models.IntegerField(default=0) def doctor_count(self): self.doc_count+=1 return "" - def pathologist_count(self): - self.doc_count+=1 - return "" def increment(self): self.count+=1 return "" @@ -138,12 +105,8 @@ def range_count(self): dif=0 elif self.count<=4: dif=self.doc_count-self.count - elif self.count<=4: - dif=self.count-self.doc_count - elif self.count<=4: - dif=self.patho_count-self.count else: - dif=self.count-self.patho_count + dif=self.count-self.doc_count return range(dif) def empty_fine(self): self.count=0 @@ -157,7 +120,7 @@ class Appointment(models.Model): user_id = models.ForeignKey(ExtraInfo,on_delete=models.CASCADE) doctor_id = models.ForeignKey(Doctor,on_delete=models.CASCADE) description = models.CharField(max_length=50) - schedule = models.ForeignKey(Doctors_Schedule, on_delete=models.CASCADE,null=True, blank=True) + schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE,null=True, blank=True) date = models.DateField() def __str__(self): @@ -170,8 +133,7 @@ class Prescription(models.Model): details = models.CharField(max_length=100) date = models.DateField() test = models.CharField(max_length=200, null=True, blank=True) - file_id=models.IntegerField(default=0) - # appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE,null=True, blank=True) + appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE,null=True, blank=True) def __str__(self): return self.details @@ -203,36 +165,3 @@ class Hospital_admit(models.Model): admission_date = models.DateField() discharge_date = models.DateField(null=True, blank=True) reason = models.CharField(max_length=50) - -class Announcements(models.Model): - anno_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='announcements_made') - ann_date = models.DateTimeField(default="04-04-2021") - message = models.CharField(max_length=200) - batch = models.CharField(max_length=40,default="Year-1") - department = models.CharField(max_length=40,default="ALL") - programme = models.CharField(max_length=10) - upload_announcement = models.FileField(upload_to='health_center/upload_announcement', null=True, default=" ") - def __str__(self): - return str(self.anno_id.user.username) - - -class SpecialRequest(models.Model): - request_ann_maker = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='special_requests_made') - request_date = models.DateTimeField(default=date.today) - brief = models.CharField(max_length=20, default='--') - request_details = models.CharField(max_length=200) - upload_request = models.FileField(blank=True) - status = models.CharField(max_length=50,default='Pending') - remarks = models.CharField(max_length=300, default="--") - request_receiver = models.CharField(max_length=30, default="--") - - def __str__(self): - return str(self.request_ann_maker.user.username) - -class medical_relief(models.Model): - description = models.CharField(max_length=200) - file = models.FileField(upload_to='medical_files/') - file_id=models.IntegerField(default=0) - compounder_forward_flag = models.BooleanField(default=False) - acc_admin_forward_flag = models.BooleanField(default=False) - diff --git a/FusionIIIT/applications/health_center/urls.py b/FusionIIIT/applications/health_center/urls.py index 77d89dd0a..b599cdd44 100644 --- a/FusionIIIT/applications/health_center/urls.py +++ b/FusionIIIT/applications/health_center/urls.py @@ -1,7 +1,6 @@ -from django import views from django.conf.urls import url,include -from .views import * +from .views import compounder_view, healthcenter, student_view, schedule_entry,doctor_entry,compounder_entry app_name = 'healthcenter' @@ -13,15 +12,12 @@ #views url(r'^compounder/$', compounder_view, name='compounder_view'), url(r'^student/$', student_view, name='student_view'), - url(r'announcement/', announcement, name='announcement'), #database entry url(r'^schedule_entry', schedule_entry, name='schedule_entry'), url(r'^doctor_entry', doctor_entry, name='doctor_entry'), url(r'^compounder_entry', compounder_entry, name='compounder_entry'), - # url(r'^fetch_designations', fetch_designations, name='fetch_designations'), - url(r'^medical_relief', medicalrelief, name='medical_relief'), #api url(r'^api/',include('applications.health_center.api.urls')) -] \ No newline at end of file +] diff --git a/FusionIIIT/applications/health_center/utils.py b/FusionIIIT/applications/health_center/utils.py index c47f90d06..f965c5f60 100644 --- a/FusionIIIT/applications/health_center/utils.py +++ b/FusionIIIT/applications/health_center/utils.py @@ -2,15 +2,12 @@ from datetime import datetime, timedelta from applications.globals.models import ExtraInfo from django.core import serializers -from applications.filetracking.models import File -from applications.globals.models import ExtraInfo, HoldsDesignation, Designation, DepartmentInfo from django.http import HttpResponse, JsonResponse from notification.views import healthcare_center_notif from .models import (Ambulance_request, Appointment, Complaint, Doctor, Expiry, Hospital, Hospital_admit, Medicine, - Prescribed_medicine, Prescription, Doctors_Schedule,Pathologist_Schedule, - Stock, Announcements, SpecialRequest, Pathologist, medical_relief) -from applications.filetracking.sdk.methods import * + Prescribed_medicine, Prescription, Schedule, + Stock) def datetime_handler(date): ''' @@ -68,31 +65,6 @@ def compounder_view_handler(request): ) data={'status':1, 'doctor':doctor, 'specialization':specialization, 'phone':phone} return JsonResponse(data) - - # updating new pathologist info in db - elif 'add_pathologist' in request.POST: - doctor=request.POST.get('new_pathologist') - specialization=request.POST.get('specialization') - phone=request.POST.get('phone') - Pathologist.objects.create( - pathologist_name=doctor, - pathologist_phone=phone, - specialization=specialization, - active=True - ) - data={'status':1, 'pathologist_name':doctor, 'specialization':specialization, 'pathologist_phone':phone} - return JsonResponse(data) - - # making announcements from compounder - elif 'add' in request.POST: - ven=request.POST.get('venue') - announcement=request.POST.get('announcement') - Announcement.objects.create( - venue=ven, - announcement=announcement, - ) - data={ 'venue':ven, 'announcement':announcement } - return JsonResponse(data) # remove doctor by changing active status elif 'remove_doctor' in request.POST: @@ -101,14 +73,6 @@ def compounder_view_handler(request): doc=Doctor.objects.get(id=doctor).doctor_name data={'status':1, 'id':doctor, 'doc':doc} return JsonResponse(data) - - # remove pathologist by changing active status - elif 'remove_pathologist' in request.POST: - doctor=request.POST.get('pathologist_active') - Pathologist.objects.filter(id=doctor).update(active=False) - doc=Pathologist.objects.get(id=doctor).pathologist_name - data={'status':1, 'id':doctor, 'doc':doc} - return JsonResponse(data) # discharge patients elif 'discharge' in request.POST: @@ -142,64 +106,31 @@ def compounder_view_handler(request): return JsonResponse(data) # edit schedule for doctors - elif 'edit_1' in request.POST: + elif 'edit' in request.POST: doctor = request.POST.get('doctor') day = request.POST.get('day') time_in = request.POST.get('time_in') time_out = request.POST.get('time_out') room = request.POST.get('room') - schedule = Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day) + schedule = Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day) doctor_id = Doctor.objects.get(id=doctor) if schedule.count() == 0: - Doctors_Schedule.objects.create(doctor_id=doctor_id, day=day, room=room, + Schedule.objects.create(doctor_id=doctor_id, day=day, room=room, from_time=time_in, to_time=time_out) else: - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(room=room) - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(from_time=time_in) - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(to_time=time_out) + Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(room=room) + Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(from_time=time_in) + Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(to_time=time_out) data={'status':1} return JsonResponse(data) - # remove schedule for a doctor elif 'rmv' in request.POST: doctor = request.POST.get('doctor') - day = request.POST.get('day') - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day).delete() + Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day).delete() data = {'status': 1} return JsonResponse(data) - - - # edit schedule for pathologists - elif 'edit12' in request.POST: - doctor = request.POST.get('pathologist') - day = request.POST.get('day') - time_in = request.POST.get('time_in') - time_out = request.POST.get('time_out') - room = request.POST.get('room') - pathologist_id = Pathologist.objects.get(id=doctor) - schedule = Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=doctor, day=day) - if schedule.count() == 0: - Pathologist_Schedule.objects.create(pathologist_id=pathologist_id, day=day, room=room, - from_time=time_in, to_time=time_out) - else: - Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(room=room) - Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(from_time=time_in) - Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(to_time=time_out) - data={'status':1} - return JsonResponse(data) - - - # remove schedule for a doctor - elif 'rmv1' in request.POST: - doctor = request.POST.get('pathologist') - - day = request.POST.get('day') - Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=doctor, day=day).delete() - data = {'status': 1} - return JsonResponse(data) - elif 'add_medicine' in request.POST: medicine = request.POST.get('new_medicine') @@ -375,39 +306,21 @@ def compounder_view_handler(request): doctor = Doctor.objects.get(id=doctor_id) details = request.POST.get('details') tests = request.POST.get('tests') - # app = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id,date=datetime.now()) - # if app: - # appointment = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').get(user_id=user_id,date=datetime.now()) - # else: - # appointment = None - designation=request.POST.get('user') - uploaded_file = request.FILES.get('file') - d = HoldsDesignation.objects.get(user__username=designation) - form_object=Prescription( + app = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id,date=datetime.now()) + if app: + appointment = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').get(user_id=user_id,date=datetime.now()) + else: + appointment = None + Prescription.objects.create( user_id=user, doctor_id=doctor, details=details, date=datetime.now(), - test=tests, - # appointment=appointment - ) - form_object.save() - request_object = Prescription.objects.get(pk=form_object.pk) - send_file_id = create_file( - uploader=request.user.username, - uploader_designation=request.session['currentDesignationSelected'], - receiver=designation, - receiver_designation=d.designation, - src_module="health_center", - src_object_id=str(request_object.id), - file_extra_JSON={"value": 2}, - attached_file=uploaded_file + test=tests, + appointment=appointment ) - request_object.file_id=send_file_id - request_object.save() - query = Medicine.objects.select_related('patient','patient__user','patient__department').filter(patient=user) - prescribe = Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').all().last() + prescribe = Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','appointment','appointment__user_id','appointment__user_id__user','appointment__user_id__department','appointment__doctor_id','appointment__schedule','appointment__schedule__doctor_id').all().last() for medicine in query: medicine_id = medicine.medicine_id quantity = medicine.quantity @@ -446,18 +359,13 @@ def compounder_view_handler(request): else: status = 0 Medicine.objects.select_related('patient','patient__user','patient__department').all().delete() - healthcare_center_notif(request.user, user.user, 'presc') data = {'status': status} return JsonResponse(data) elif 'cancel_presc' in request.POST: presc_id = request.POST.get('cancel_presc') - prescription=Prescription.objects.filter(pk=presc_id) - is_deleted = delete_file(id=presciption.file_id) - prescription.delete() - - + Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','appointment','appointment__user_id','appointment__user_id__user','appointment__user_id__department','appointment__doctor_id','appointment__schedule','appointment__schedule__doctor_id').filter(pk=presc_id).delete() data = {'status': 1} return JsonResponse(data) elif 'medicine' in request.POST: @@ -465,35 +373,6 @@ def compounder_view_handler(request): thresh = Stock.objects.get(id=med_id).threshold data = {'thresh': thresh} return JsonResponse(data) - elif 'compounder_forward' in request.POST: - acc_admin_des_id = Designation.objects.get(name="Accounts Admin") - user_ids = HoldsDesignation.objects.filter(designation_id=acc_admin_des_id.id).values_list('user_id', flat=True) - acc_admins = ExtraInfo.objects.get(user_id=user_ids[0]) - user=ExtraInfo.objects.get(pk=acc_admins.id) - forwarded_file_id=forward_file( - file_id=request.POST['file_id'], - receiver=acc_admins.id, - receiver_designation="Accounts Admin", - file_extra_JSON= {"value": 2}, - remarks="Forwarded File with id: "+ str(request.POST['file_id'])+"to Accounts Admin "+str(acc_admins.id), - file_attachment=None, - ) - - medical_relief_instance = medical_relief.objects.get(file_id=request.POST['file_id']) - medical_relief_instance.compounder_forward_flag = True - medical_relief_instance.save() - - healthcare_center_notif(request.user,user.user,'rel_approve') - - - - - data = {'status': 1} - return JsonResponse(data) - - - - def student_view_handler(request): @@ -543,14 +422,12 @@ def student_view_handler(request): healthcare_center_notif(request.user, cmp.user, 'appoint_req') return JsonResponse(data) - - elif 'doctor' in request.POST: doctor_id = request.POST.get('doctor') - days =Dotors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id).values('day') + days = Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id).values('day') today = datetime.today() time = datetime.today().time() - sch = Doctors_Schedule.objects.select_related('doctor_id').filter(date__gte=today) + sch = Schedule.objects.select_related('doctor_id').filter(date__gte=today) for day in days: for i in range(0, 7): @@ -559,14 +436,12 @@ def student_view_handler(request): d = day.get('day') if dayi == d: - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=dayi).update(date=date) + Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=dayi).update(date=date) sch.filter(date=today, to_time__lt=time).delete() schedule = sch.filter(doctor_id=doctor_id).order_by('date') schedules = serializers.serialize('json', schedule) return HttpResponse(schedules, content_type='json') - - elif 'feed_submit' in request.POST: user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) feedback = request.POST.get('feedback') @@ -587,72 +462,4 @@ def student_view_handler(request): Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(pk=app_id).delete() data = {'status': 1} return JsonResponse(data) - elif 'medical_relief_submit' in request.POST: - designation = request.POST.get('designation') - # print("# #") - # print(designation) - user=ExtraInfo.objects.get(pk=designation) - description = request.POST.get('description') - - # Retrieve the uploaded file from request.FILES - uploaded_file = request.FILES.get('file') - # Create an instance of the medical_relief model - form_object = medical_relief( - description=description, - file=uploaded_file - ) - - # Save the form object - form_object.save() - - # Retrieve the form object you just saved - request_object = medical_relief.objects.get(pk=form_object.pk) - - # Retrieve HoldsDesignation instances - d = HoldsDesignation.objects.get(user__username=designation) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - # Create a file entry using the create_file utility function - send_file_id = create_file( - uploader=request.user.username, - uploader_designation=request.session['currentDesignationSelected'], - receiver=designation, - receiver_designation=d.designation, - src_module="health_center", - src_object_id=str(request_object.id), - file_extra_JSON={"value": 2}, - attached_file=uploaded_file - ) - healthcare_center_notif(request.user,user.user,'rel_forward') - request_object.file_id = send_file_id - request_object.save() - - # file_details_dict = view_file(file_id=send_file_id) - # print(file_details_dict) - return JsonResponse({'status': 1}) - - elif 'acc_admin_forward' in request.POST: - file_id=request.POST['file_id'] - rec=File.objects.get(id=file_id) - des=Designation.objects.get(pk=rec.designation_id) - user=ExtraInfo.objects.get(pk=rec.uploader_id) - - forwarded_file_id=forward_file( - file_id=request.POST['file_id'], - receiver=rec.uploader_id, - receiver_designation=des.name, - file_extra_JSON= {"value": 2}, - remarks="Forwarded File with id: "+ str(request.POST['file_id'])+"to"+str(rec.id), - file_attachment=None, - ) - medical_relief_instance = medical_relief.objects.get(file_id=request.POST['file_id']) - medical_relief_instance.acc_admin_forward_flag = True - medical_relief_instance.save() - - healthcare_center_notif(request.user,user.user,'rel_approved') - - return JsonResponse({'status':1}) - - - \ No newline at end of file diff --git a/FusionIIIT/applications/health_center/views.py b/FusionIIIT/applications/health_center/views.py index 3af92e083..cd2bba84f 100644 --- a/FusionIIIT/applications/health_center/views.py +++ b/FusionIIIT/applications/health_center/views.py @@ -1,22 +1,19 @@ import json -from datetime import date, datetime, timedelta, time +from datetime import datetime, timedelta, time import xlrd import os from applications.globals.models import ExtraInfo, HoldsDesignation, Designation, DepartmentInfo -from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core import serializers from django.http import HttpResponse, HttpResponseRedirect, JsonResponse -from django.shortcuts import get_object_or_404, render, redirect +from django.shortcuts import render from notification.views import healthcare_center_notif -from applications.health_center.api.serializers import MedicalReliefSerializer from .models import (Ambulance_request, Appointment, Complaint, Constants, - Counter, Doctor,Pathologist, Expiry, Hospital, Hospital_admit, - Medicine, Prescribed_medicine, Prescription, Doctors_Schedule,Pathologist_Schedule, - Stock,SpecialRequest,Announcements,medical_relief) + Counter, Doctor, Expiry, Hospital, Hospital_admit, + Medicine, Prescribed_medicine, Prescription, Schedule, + Stock) from .utils import datetime_handler, compounder_view_handler, student_view_handler -from applications.filetracking.sdk.methods import * @@ -43,7 +40,7 @@ def healthcenter(request): def compounder_view(request): ''' - This function handles post requests for compounder and render pages accordingly + This function handles post reques for compounder and render pages accordingly @param: request - contains metadata about the requested page @@ -67,14 +64,12 @@ def compounder_view(request): doctors: retrieve Doctor class objects from database ''' # compounder view starts here - usertype = ExtraInfo.objects.select_related('user','department').get(user=request.user).user_type if usertype == 'compounder': if request.method == 'POST': return compounder_view_handler(request) else: - notifs = request.user.notifications.all() all_complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').all() all_hospitals = Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').all().order_by('-admission_date') hospitals_list = Hospital.objects.all().order_by('hospital_name') @@ -83,74 +78,30 @@ def compounder_view(request): appointments_future=Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(date__gt=datetime.now()).order_by('date') users = ExtraInfo.objects.select_related('user','department').filter(user_type='student') stocks = Stock.objects.all() - days = Constants.DAYS_OF_WEEK - schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('doctor_id') - schedule1=Pathologist_Schedule.objects.select_related('pathologist_id').all().order_by('pathologist_id') + schedule=Schedule.objects.select_related('doctor_id').all().order_by('doctor_id') expired=Expiry.objects.select_related('medicine_id').filter(expiry_date__lt=datetime.now(),returned=False).order_by('expiry_date') live_meds=Expiry.objects.select_related('medicine_id').filter(returned=False).order_by('quantity') count=Counter.objects.all() - - medicines_presc=Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id').all() - print(medicines_presc) + presc_hist=Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','appointment','appointment__user_id','appointment__user_id__user','appointment__user_id__department','appointment__doctor_id','appointment__schedule','appointment__schedule__doctor_id').all().order_by('-date') + medicines_presc=Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id','prescription_id__appointment','prescription_id__appointment__user_id','prescription_id__appointment__user_id__user','prescription_id__appointment__user_id__department','prescription_id__appointment__doctor_id','prescription_id__appointment__schedule','prescription_id__appointment__schedule__doctor_id','medicine_id').all() if count: Counter.objects.all().delete() Counter.objects.create(count=0,fine=0) count=Counter.objects.get() hospitals=Hospital.objects.all() - schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') - schedule1=Pathologist_Schedule.objects.select_related('pathologist_id').all().order_by('day','pathologist_id') - + schedule=Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') doctors=Doctor.objects.filter(active=True).order_by('id') - pathologists=Pathologist.objects.filter(active=True).order_by('id') - prescription= Prescription.objects.all() - report=[] - for pre in prescription: - dic={} - dic['id']=pre.pk - dic['user_id']=pre.user_id_id - dic['doctor_id'] = pre.doctor_id # Use dot notation - dic['date'] = pre.date # Use dot notation - dic['details'] = pre.details # Use dot notation - dic['test'] = pre.test # Use dot notation - if pre.file_id: - dic['file'] = view_file(file_id=pre.file_id)['upload_file'] - else: - dic['file']=None - report.append(dic) - - - - + + doct= ["Dr. G S Sandhu", "Dr. Jyoti Garg", "Dr. Arvind Nath Gupta"] - #adding file tracking inbox part for compounder - - inbox_files=view_inbox(username=request.user.username,designation='Compounder',src_module='health_center') - medicalrelief=medical_relief.objects.all() - - inbox=[] - for ib in inbox_files: - dic={} - for mr in medicalrelief: - if mr.file_id==int(ib['id']): - dic['id']=ib['id'] - dic['uploader']=ib['uploader'] - dic['upload_date']=datetime.fromisoformat(ib['upload_date']).date() - dic['desc']=mr.description - dic['file']=view_file(file_id=ib['id'])['upload_file'] - dic['status']=mr.compounder_forward_flag - dic['status1']=mr.acc_admin_forward_flag - inbox.append(dic) - - # print(inbox_files) - - + return render(request, 'phcModule/phc_compounder.html', {'days': days, 'users': users, 'count': count,'expired':expired, 'stocks': stocks, 'all_complaints': all_complaints, 'all_hospitals': all_hospitals, 'hospitals':hospitals, 'all_ambulances': all_ambulances, - 'appointments_today': appointments_today, 'doctors': doctors, 'pathologists':pathologists, - 'appointments_future': appointments_future, 'schedule': schedule, 'schedule1': schedule1, 'live_meds': live_meds, 'presc_hist': report, 'medicines_presc': medicines_presc, 'hospitals_list': hospitals_list,'inbox_files':inbox}) + 'appointments_today': appointments_today, 'doctors': doctors, 'doct': doct, + 'appointments_future': appointments_future, 'schedule': schedule, 'live_meds': live_meds, 'presc_hist': presc_hist, 'medicines_presc': medicines_presc, 'hospitals_list': hospitals_list}) elif usertype == 'student': return HttpResponseRedirect("/healthcenter/student") # compounder view ends @@ -175,46 +126,23 @@ def student_view(request): doctors: retrieve Doctor class objects from database ''' # student view starts here - usertype = ExtraInfo.objects.select_related('user','department').get(user=request.user).user_type if usertype == 'student' or usertype == 'faculty' or usertype == 'staff': if request.method == 'POST': return student_view_handler(request) else: - notifs = request.user.notifications.all() users = ExtraInfo.objects.all() user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) hospitals = Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').filter(user_id=user_id).order_by('-admission_date') appointments = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id).order_by('-date') ambulances = Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date_request') - - medicines = Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id','medicine_id').all() + prescription = Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','appointment','appointment__user_id','appointment__user_id__user','appointment__user_id__department','appointment__doctor_id','appointment__schedule','appointment__schedule__doctor_id').filter(user_id=user_id).order_by('-date') + medicines = Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id','prescription_id__appointment','prescription_id__appointment__user_id','prescription_id__appointment__user_id__user','prescription_id__appointment__user_id__department','prescription_id__appointment__doctor_id','prescription_id__appointment__schedule','prescription_id__appointment__schedule__doctor_id','medicine_id').all() complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date') days = Constants.DAYS_OF_WEEK - schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('doctor_id') - schedule1=Pathologist_Schedule.objects.select_related('pathologist_id').all().order_by('pathologist_id') + schedule=Schedule.objects.select_related('doctor_id').all().order_by('doctor_id') doctors=Doctor.objects.filter(active=True) - pathologists=Pathologist.objects.filter(active=True) - - #prescription - prescription= Prescription.objects.filter(user_id=request.user.username) - report=[] - for pre in prescription: - dic={} - dic['id']=pre.id - dic['doctor_id'] = pre.doctor_id # Use dot notation - dic['date'] = pre.date # Use dot notation - dic['details'] = pre.details # Use dot notation - dic['test'] = pre.test # Use dot notation - if pre.file_id: - dic['file'] = view_file(file_id=pre.file_id)['upload_file'] - else: - dic['file']=None - - - report.append(dic) - count=Counter.objects.all() if count: @@ -222,58 +150,14 @@ def student_view(request): Counter.objects.create(count=0,fine=0) count=Counter.objects.get() - designations = Designation.objects.filter() - holdsDesignations = [] - - for d in designations: - if d.name == "Compounder": - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - acc_admin_inbox=view_inbox(username=request.user.username,designation='Accounts Admin',src_module='health_center') - medicalrelief=medical_relief.objects.all() - acc_ib=[] - for ib in acc_admin_inbox: - dic={} - - for mr in medicalrelief: - if mr.file_id == int(ib['id']): - dic['id']=ib['id'] - dic['uploader']=ib['uploader'] - dic['upload_date']=datetime.fromisoformat(ib['upload_date']).date() - dic['desc']=mr.description - dic['file']=view_file(file_id=ib['id'])['upload_file'] - dic['status']=mr.acc_admin_forward_flag - acc_ib.append(dic) - uploader_outbox=view_outbox(username=request.user.username,designation=request.session['currentDesignationSelected'] ,src_module='health_center') - - - uploader_inbox=view_inbox(username=request.user.username,designation=request.session['currentDesignationSelected'],src_module='health_center') - medicalRelief=[] - - for out in uploader_outbox: - dic={} - - for mr in medicalrelief: - if mr.file_id==int(out['id']): - dic['id']=out['id'] - dic['upload_date']=datetime.fromisoformat(out['upload_date']).date() - dic['desc']=mr.description - dic['file']=view_file(file_id=out['id'])['upload_file'] - dic['status']=mr.acc_admin_forward_flag - dic['approval_date']='' - - for inb in uploader_inbox: - if dic['id']==inb['id']: - dic['approval_date']=datetime.fromisoformat(inb['upload_date']).date() - medicalRelief.append(dic) - + doct= ["Dr. G S Sandhu", "Dr. Jyoti Garg", "Dr. Arvind Nath Gupta"] + return render(request, 'phcModule/phc_student.html', {'complaints': complaints, 'medicines': medicines, - 'ambulances': ambulances, 'doctors': doctors, 'pathologists':pathologists, 'days': days,'count':count, + 'ambulances': ambulances, 'doctors': doctors, 'days': days,'count':count, 'hospitals': hospitals, 'appointments': appointments, - 'prescription': report, 'schedule': schedule, 'schedule1': schedule1,'users': users, 'curr_date': datetime.now().date(),'holdsDesignations':holdsDesignations,'acc_admin_inbox':acc_ib,'medicalRelief':medicalRelief}) + 'prescription': prescription, 'schedule': schedule, 'users': users,'doct': doct, 'curr_date': datetime.now().date()}) elif usertype == 'compounder': return HttpResponseRedirect("/healthcenter/compounder") # student view ends @@ -354,36 +238,6 @@ def doctor_entry(request): pass return HttpResponse("Hello") -def pathologist_entry(request): - ''' - This function inputs new pathologist' details into Doctor class in database - @param: - request - contains metadata about the requested page - - ''' - excel = xlrd.open_workbook(os.path.join(os.getcwd(), 'dbinsertscripts/healthcenter/Pathologist-List.xlsx')) - z = excel.sheet_by_index(0) - - for i in range(1, 5): - try: - name = str(z.cell(i,0).value) - print(name) - phone = str(int(z.cell(i,1).value)) - print(phone) - spl = str(z.cell(i,2).value) - u = Pathologist.objects.create( - pathologist_name = name, - pathologist_phone = phone, - specialization=spl - ) - print("Pathologist done -> ") - except Exception as e: - print(e) - print(i) - pass - return HttpResponse("Hello") - - def compounder_entry(request): ''' This function inputs new compounder details into Doctor class in database @@ -456,154 +310,4 @@ def compounder_entry(request): print(e) print(i) pass - return HttpResponse("Hello") - -@login_required(login_url='/accounts/login') -def publish(request): - return render(request,'../templates/health_center/publish.html' ,{}) - - -def browse_announcements(): - """ - This function is used to browse Announcements Department-Wise - made by different faculties and admin. - - @variables: - cse_ann - Stores CSE Department Announcements - ece_ann - Stores ECE Department Announcements - me_ann - Stores ME Department Announcements - sm_ann - Stores SM Department Announcements - all_ann - Stores Announcements intended for all Departments - context - Dictionary for storing all above data - - """ - cse_ann = Announcements.objects.filter(department="CSE") - ece_ann = Announcements.objects.filter(department="ECE") - me_ann = Announcements.objects.filter(department="ME") - sm_ann = Announcements.objects.filter(department="SM") - all_ann = Announcements.objects.filter(department="ALL") - - context = { - "cse" : cse_ann, - "ece" : ece_ann, - "me" : me_ann, - "sm" : sm_ann, - "all" : all_ann - } - - return context - -def get_to_request(username): - """ - This function is used to get requests for the receiver - - @variables: - req - Contains request queryset - - """ - req = SpecialRequest.objects.filter(request_receiver=username) - return req - - - -@login_required(login_url='/accounts/login') -def announcement(request): - """ - This function is contains data for Requests and Announcement Related methods. - Data is added to Announcement Table using this function. - - @param: - request - contains metadata about the requested page - - @variables: - usrnm, user_info, ann_anno_id - Stores data needed for maker - batch, programme, message, upload_announcement, - department, ann_date, user_info - Gets and store data from FORM used for Announcements for Students. - - """ - usrnm = get_object_or_404(User, username=request.user.username) - user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() - num = 1 - ann_anno_id = user_info.id - requests_received = get_to_request(usrnm) - if request.method == 'POST': - formObject = Announcements() - # formObject.key = Projects.objects.get(id=request.session['projectId']) - user_info = ExtraInfo.objects.all().select_related('user','department').get(id=ann_anno_id) - getstudents = ExtraInfo.objects.select_related('user') - recipients = User.objects.filter(extrainfo__in=getstudents) - # formObject.anno_id=1 - formObject.anno_id=user_info - formObject.batch = request.POST['batch'] - formObject.programme = request.POST['programme'] - formObject.message = request.POST['announcement'] - formObject. upload_announcement = request.FILES.get('upload_announcement') - formObject.department = request.POST['department'] - formObject.ann_date = date.today() - #formObject.amount = request.POST['amount'] - formObject.save() - return redirect('../../compounder/') - - # batch = request.POST.get('batch', '') - # programme = request.POST.get('programme', '') - # message = request.POST.get('announcement', '') - # upload_announcement = request.FILES.get('upload_announcement') - # department = request.POST.get('department') - # ann_date = date.today() - # user_info = ExtraInfo.objects.all().select_related('user','department').get(id=ann_anno_id) - # getstudents = ExtraInfo.objects.select_related('user') - # recipients = User.objects.filter(extrainfo__in=getstudents) - - # obj1, created = Announcements.objects.get_or_create(anno_id=user_info, - # batch=batch, - # programme=programme, - # message=message, - # upload_announcement=upload_announcement, - # department = department, - # ann_date=ann_date) - # # department_notif(usrnm, recipients , message) - - context = browse_announcements() - return render(request, 'health_center/make_announce_comp.html', {"user_designation":user_info.user_type, - "announcements":context, - "request_to":requests_received - }) - -# def fetch_designations(request): -# designations = Designation.objects.all() - -# holdsDesignations = [] - -# for d in designations: -# if d.name == "Compounder" or d.name == "Accounts Admin": -# list = HoldsDesignation.objects.filter(designation=d) -# holdsDesignations.append(list) - -# return render(request, 'phcModule/medical_relief.html', {'holdsDesignations' : holdsDesignations}) - -def medicalrelief(request): - print(request) - - - if request.method == 'POST': - # print(request.POST['name']) - formObject = medical_relief() - formObject.description = request.POST['description'] - formObject.file = request.POST['file'] - formObject.save() - request_object = medical_relief.objects.get(pk=formObject.pk) - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - print(d) - print(d1) - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="health_center", - src_object_id= str(request_object.id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - - return render(request, 'phcModule/medical_relief.html', {'holdsDesignations' : holdsDesignations}) \ No newline at end of file + return HttpResponse("Hello") \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/admin.py b/FusionIIIT/applications/hostel_management/admin.py index 8e8917269..0ab767ac1 100644 --- a/FusionIIIT/applications/hostel_management/admin.py +++ b/FusionIIIT/applications/hostel_management/admin.py @@ -5,20 +5,10 @@ admin.site.register(Hall) admin.site.register(HallCaretaker) admin.site.register(HallWarden) - +admin.site.register(GuestRoomDetail) admin.site.register(GuestRoomBooking) admin.site.register(StaffSchedule) admin.site.register(HostelNoticeBoard) admin.site.register(HostelStudentAttendence) admin.site.register(HallRoom) -admin.site.register(WorkerReport) -admin.site.register(HostelInventory) -admin.site.register(HostelFine) -admin.site.register(HostelLeave) -admin.site.register(HostelComplaint) -admin.site.register(StudentDetails) -admin.site.register(HostelAllotment) -admin.site.register(GuestRoom) -admin.site.register(HostelTransactionHistory) -admin.site.register(HostelHistory) - +admin.site.register(WorkerReport) \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/forms.py b/FusionIIIT/applications/hostel_management/forms.py index 8a1780d27..a727bd069 100644 --- a/FusionIIIT/applications/hostel_management/forms.py +++ b/FusionIIIT/applications/hostel_management/forms.py @@ -1,33 +1,9 @@ from django import forms -from .models import HostelNoticeBoard, Hall, GuestRoomBooking +from .models import HostelNoticeBoard, Hall class HostelNoticeBoardForm(forms.ModelForm): class Meta: model = HostelNoticeBoard fields = ('hall', 'head_line', 'content', 'description') - -class HallForm(forms.ModelForm): - class Meta: - model = Hall - fields = ['hall_id', 'hall_name', 'max_accomodation', 'assigned_batch','type_of_seater'] - -class GuestRoomBookingForm(forms.ModelForm): - class Meta: - model = GuestRoomBooking - fields = ( - 'hall', - 'guest_name', - 'guest_phone', - 'guest_email', - 'guest_address', - 'rooms_required', - 'total_guest', - 'purpose', - 'arrival_date', - 'arrival_time', - 'departure_date', - 'departure_time', - 'nationality', - 'room_type' - ) \ No newline at end of file + \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/management/commands/copy_data.py b/FusionIIIT/applications/hostel_management/management/commands/copy_data.py deleted file mode 100644 index 370583025..000000000 --- a/FusionIIIT/applications/hostel_management/management/commands/copy_data.py +++ /dev/null @@ -1,36 +0,0 @@ -from applications.academic_information.models import Student -from applications.hostel_management.models import StudentDetails -from django.contrib.auth.models import User - - -def copy_data(): - - # Fetch data from the Student table with a join to the User table - student_data = Student.objects.all() - - # Iterate over the student data and create StudentDetails instances - for student_instance in student_data: - # Extract data from the related User instance - id = student_instance.id_id - user_instance = User.objects.filter(username=id).first(); - user_instance = User.objects.get(username=id) - - # Create a StudentDetails instance using data from the Student and User instances - student_details_instance = StudentDetails( - id=student_instance.id_id, - first_name=user_instance.first_name, - last_name=user_instance.last_name, - programme=student_instance.programme, - batch=student_instance.batch, - room_num=student_instance.room_no, - hall_no=student_instance.hall_no, - specialization=student_instance.specialization, - # parent_contact=student_instance.parent_contact, - # address=student_instance.address - ) - - # Save the StudentDetails instance to the database - student_details_instance.save() - -# Call the function to initiate the data copying process -copy_data() diff --git a/FusionIIIT/applications/hostel_management/migrations/0001_initial.py b/FusionIIIT/applications/hostel_management/migrations/0001_initial.py index 8659d1649..ef1639d4c 100644 --- a/FusionIIIT/applications/hostel_management/migrations/0001_initial.py +++ b/FusionIIIT/applications/hostel_management/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models @@ -12,9 +12,9 @@ class Migration(migrations.Migration): initial = True dependencies = [ + ('academic_information', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('globals', '0001_initial'), - ('academic_information', '0001_initial'), ] operations = [ diff --git a/FusionIIIT/applications/hostel_management/models.py b/FusionIIIT/applications/hostel_management/models.py index 9c20f9b6e..9b667d9e2 100644 --- a/FusionIIIT/applications/hostel_management/models.py +++ b/FusionIIIT/applications/hostel_management/models.py @@ -48,14 +48,7 @@ class Hall(models.Model): hall_name = models.CharField(max_length=50) max_accomodation = models.IntegerField(default=0) number_students = models.PositiveIntegerField(default=0) - assigned_batch = models.CharField(max_length=50, null=True, blank=True) - TYPE_OF_SEATER_CHOICES = [ - ('single', 'Single Seater'), - ('double', 'Double Seater'), - ('triple', 'Triple Seater'), - ] - - type_of_seater = models.CharField(max_length=50, choices=TYPE_OF_SEATER_CHOICES, default='single') + def __str__(self): return self.hall_id @@ -88,6 +81,20 @@ def __str__(self): return str(self.hall) + ' (' + str(self.faculty.id.user.username) + ')' +class GuestRoomDetail(models.Model): + """ + Records information related to guest rooms in Hall of Residences. + + 'hall' refers to the related Hall of Residence. + 'room_no' stores the guest room number. + 'room_status' stores the current status of the guest room from the available choices in 'ROOM_STATUS'. + """ + hall = models.ForeignKey(Hall, on_delete=models.CASCADE) + room_no = models.CharField(max_length=4, unique=True) + room_status = models.CharField(max_length=20, choices=HostelManagementConstants.ROOM_STATUS, default='Available') + + def __str__(self): + return self.room_no class GuestRoomBooking(models.Model): @@ -109,34 +116,26 @@ class GuestRoomBooking(models.Model): """ hall = models.ForeignKey(Hall, on_delete=models.CASCADE) intender = models.ForeignKey(User, on_delete=models.CASCADE) - guest_name = models.CharField(max_length=255) - guest_phone = models.CharField(max_length=255) - guest_email = models.CharField(max_length=255, blank=True) + guest_name = models.CharField(max_length=100) + guest_phone = models.CharField(max_length=15) + guest_email = models.CharField(max_length=40, blank=True) guest_address = models.TextField(blank=True) - rooms_required = models.IntegerField(default=1, null=True, blank=True) - guest_room_id = models.CharField(max_length=255, blank=True) + rooms_required = models.IntegerField(default=1,null=True,blank=True) + guest_room_id = models.ManyToManyField(GuestRoomDetail) total_guest = models.IntegerField(default=1) purpose = models.TextField() arrival_date = models.DateField(auto_now_add=False, auto_now=False) arrival_time = models.TimeField(auto_now_add=False, auto_now=False) departure_date = models.DateField(auto_now_add=False, auto_now=False) departure_time = models.TimeField(auto_now_add=False, auto_now=False) - status = models.CharField(max_length=255, choices=HostelManagementConstants.BOOKING_STATUS ,default ="Pending") + status = models.CharField(max_length=15, choices=HostelManagementConstants.BOOKING_STATUS ,default ="Pending") booking_date = models.DateField(auto_now_add=False, auto_now=False, default=timezone.now) - nationality = models.CharField(max_length=255, blank=True) - ROOM_TYPES = [ - ('single', 'Single'), - ('double', 'Double'), - ('triple', 'Triple'), - # Add more room types as needed - ] - room_type = models.CharField(max_length=10, choices=ROOM_TYPES ,default='single') + nationality = models.CharField(max_length=20, blank=True) def __str__(self): return '%s ----> %s - %s' % (self.id, self.guest_name, self.status) - class StaffSchedule(models.Model): """ Records schedule of staffs in various Hall of Residences. @@ -147,8 +146,8 @@ class StaffSchedule(models.Model): 'start_time' stores the start time of a schedule. 'end_time' stores the end time of a schedule. """ - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE) + hall = models.ForeignKey(Hall, on_delete=models.CASCADE) + staff_id = models.ForeignKey(Staff, on_delete=models.ForeignKey) staff_type = models.CharField(max_length=100, default='Caretaker') day = models.CharField(max_length=15, choices=HostelManagementConstants.DAYS_OF_WEEK) start_time = models.TimeField(null=True,blank=True) @@ -235,137 +234,6 @@ class WorkerReport(models.Model): absent = models.IntegerField(default= 0) total_day = models.IntegerField(default=31) remark = models.CharField(max_length=100) - def str(self): - return str(self.worker_name)+'->' + str(self.month) + '-' + str(self.absent) - - -class HostelInventory(models.Model): - """ - Model to store hostel inventory information. - """ - - inventory_id = models.AutoField(primary_key=True) - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - inventory_name = models.CharField(max_length=100) - cost = models.DecimalField(max_digits=10, decimal_places=2) - quantity = models.PositiveIntegerField(default=0) - - def __str__(self): - return self.inventory_name - - -class HostelLeave(models.Model): - student_name = models.CharField(max_length=100) - roll_num = models.CharField(max_length=20) - reason = models.TextField() - phone_number = models.CharField(max_length=20, null=True,blank=True) - start_date = models.DateField(default=timezone.now) - end_date = models.DateField() - status = models.CharField(max_length=20, default='pending') - remark = models.TextField(blank=True, null=True) - file_upload = models.FileField(upload_to='hostel_management/', null=True, blank=True) - - def _str_(self): - return f"{self.student_name}'s Leave" - -# changes - -class HostelComplaint(models.Model): - hall_name = models.CharField(max_length=100) - student_name = models.CharField(max_length=100) - roll_number = models.CharField(max_length=20) - description = models.TextField() - contact_number = models.CharField(max_length=15) - - def __str__(self): - return f"Complaint from {self.student_name} in {self.hall_name}" - - -class HostelAllotment(models.Model): - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - assignedCaretaker = models.ForeignKey(Staff, on_delete=models.CASCADE ,null=True) - assignedWarden = models.ForeignKey(Faculty, on_delete=models.CASCADE ,null=True) - assignedBatch=models.CharField(max_length=50) - def __str__(self): - return str(self.hall)+ str(self.assignedCaretaker)+str(self.assignedWarden) + str(self.assignedBatch) - -class StudentDetails(models.Model): - id = models.CharField(primary_key=True, max_length=20) - first_name = models.CharField(max_length=100,blank=True,null=True) - last_name = models.CharField(max_length=100,blank=True,null=True) - programme = models.CharField(max_length=100,blank=True,null=True) - batch = models.CharField(max_length=100,blank=True,null=True) - room_num= models.CharField(max_length=20,blank=True,null=True) - hall_no= models.CharField(max_length=20,blank=True,null=True) - hall_id=models.CharField(max_length=20,blank=True,null=True) - specialization = models.CharField(max_length=100,blank=True,null=True) - parent_contact = models.CharField(max_length=20, blank=True, null=True) - address = models.CharField(max_length=255, blank=True, null=True) - - def __str__(self): - return self.first_name - - - -class GuestRoom(models.Model): - """ - 'hall' foreign key: the hostel to which the room belongs - 'room' guest room number - 'vacant' boolean value to determine if the room is vacant - 'occupied_till', date field that tells the next time the room will be vacant, null if 'vacant' == True - """ - ROOM_TYPES = [ - ('single', 'Single'), - ('double', 'Double'), - ('triple', 'Triple'), - ] - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - room = models.CharField(max_length=255) - occupied_till = models.DateField(null=True, blank=True) - vacant = models.BooleanField(default=True) - room_type = models.CharField(max_length=10, choices=ROOM_TYPES ,default='single') - @property - def _vacant(self) -> bool: - if self.occupied_till and self.occupied_till > timezone.now(): - self.vacant = False - self.vacant = True - - - -class HostelFine(models.Model): - fine_id = models.AutoField(primary_key=True) - student = models.ForeignKey(Student, on_delete=models.CASCADE) - hall = models.ForeignKey(Hall, on_delete=models.CASCADE,default=1) - student_name = models.CharField(max_length=100) - amount = models.DecimalField(max_digits=10, decimal_places=2) - STATUS_CHOICES = [ - ('Pending', 'Pending'), - ('Paid', 'Paid'), - ] - status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='Pending') - reason = models.TextField() - - def __str__(self): - return f"{self.student_name}'s Fine - {self.amount} - {self.status}" - - -class HostelTransactionHistory(models.Model): - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - change_type = models.CharField(max_length=100) # Example: 'Caretaker', 'Warden', 'Batch' - previous_value = models.CharField(max_length=255) - new_value = models.CharField(max_length=255) - timestamp = models.DateTimeField(auto_now_add=True) - - def __str__(self): - return f"{self.change_type} change in {self.hall} at {self.timestamp}" - -class HostelHistory(models.Model): - hall = models.ForeignKey(Hall, on_delete=models.CASCADE) - timestamp = models.DateTimeField(default=timezone.now) - caretaker = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True, related_name='caretaker_history') - batch = models.CharField(max_length=50, null=True) - warden = models.ForeignKey(Faculty, on_delete=models.SET_NULL, null=True, related_name='warden_history') - - def __str__(self): - return f"History for {self.hall.hall_name} - {self.timestamp}" \ No newline at end of file + def str(self): + return str(self.worker_name)+'->' + str(self.month) + '-' + str(self.absent) \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/urls.py b/FusionIIIT/applications/hostel_management/urls.py index 95fcdeeb8..f0ea19b1d 100644 --- a/FusionIIIT/applications/hostel_management/urls.py +++ b/FusionIIIT/applications/hostel_management/urls.py @@ -1,18 +1,11 @@ from django.urls import path from . import views -from django.contrib.auth import views as auth_views -from django.urls import include -from django.contrib import admin -from django.conf.urls import url, include app_name = 'hostelmanagement' urlpatterns = [ - - path('admin/', admin.site.urls), #Home path('', views.hostel_view, name="hostel_view"), - path('/hello', views.hostel_view, name="hello"), #Notice Board path('notice_form/', views.notice_board, name="notice_board"), @@ -35,84 +28,4 @@ #Worker Report path('worker_report/', views.generate_worker_report, name='workerreport'), path('pdf/', views.GeneratePDF.as_view(), name="pdf"), - - - - #for superUser - - path('hostel-notices/', views.hostel_notice_board, name='hostel_notices_board'), - # //caretaker and warden can see all leaves - path('all_leave_data/', views.all_leave_data, name='all_leave_data'), - # caretaker or wardern can approve leave - path('update_leave_status/', views.update_leave_status, name='update_leave_status'), - # //apply for leave - path('create_hostel_leave/', views.create_hostel_leave, name='create_hostel_leave'), - - # caretaker and warden can get all complaints - path('hostel_complaints/', views.hostel_complaint_list, name='hostel_complaint_list'), - - path('register_complaint/', views.PostComplaint.as_view(), name='PostComplaint'), - -# Student can view his leave status - path('my_leaves/', views.my_leaves.as_view(), name='my_leaves'), - path('get_students/', views.get_students, name='get_students'), - - - - - - path('assign-batch/', views.AssignBatchView.as_view(),name='AssignBatchView'), - path('hall-ids/', views.HallIdView.as_view(), name='hall'), - path('assign-caretaker', views.AssignCaretakerView.as_view(), name='AssignCaretakerView'), - path('assign-warden',views.AssignWardenView.as_view(), name='AssignWardenView'), - path('add-hostel', views.AddHostelView.as_view(), name='add_hostel'), - path('admin-hostel-list', views.AdminHostelListView.as_view(), name='admin_hostel_list'), # URL for displaying the list of hostels - path('delete-hostel//', views.DeleteHostelView.as_view(), name='delete_hostel'), - - path('check-hall-exists/', views.CheckHallExistsView.as_view(), name='check_hall_exists'), - path('accounts/', include('django.contrib.auth.urls')), - path('logout/', views.logout_view, name='logout_view'), - # path('logout/', auth_views.LogoutView.as_view(), name='logout'), - - # !! My Change - path('allotted_rooms//', views.alloted_rooms, name="alloted_rooms"), - - path('all_staff//', views.all_staff, name='all_staff'), - path('staff//', views.StaffScheduleView.as_view(), name='staff_schedule'), - - # !!? Inventory - path('inventory/', views.HostelInventoryView.as_view(), name='hostel_inventory_list'), - path('inventory//modify/', views.HostelInventoryUpdateView.as_view(), name='hostel_inventory_update'), - path('inventory//delete/', views.HostelInventoryView.as_view(), name='hostel_inventory_delete'), - path('inventory//', views.HostelInventoryView.as_view(), name='hostel_inventory_by_hall'), - path('inventory/form/', views.get_inventory_form, name='get_inventory_form'), - path('inventory/edit_inventory//', views.edit_inventory, name='edit_inventory'), - path('allotted_rooms/', views.alloted_rooms_main, name="alloted_rooms"), - path('all_staff/', views.all_staff, name='all_staff'), - - #guest room - path('book_guest_room/', views.request_guest_room, name="book_guest_room"), - path('update_guest_room/', views.update_guest_room, name="update_guest_room"), - path('available_guest_rooms/', views.available_guestrooms_api, name='available_guestrooms_api'), - - - # !!todo: Add Fine Functionality - path('fine/', views.impose_fine_view, name='fine_form_show'), - path('fine/impose/', views.HostelFineView.as_view(), name='fine_form_show'), - path('fine/impose/list/', views.hostel_fine_list, name='fine_list_show'), - path('fine/impose/edit//', views.show_fine_edit_form, name='hostel_fine_edit'), - path('fine/impose/update//', views.update_student_fine, name='update_student_fine'), - path('fine/impose/list/update//', views.HostelFineUpdateView.as_view(), name='fine_update'), - path('fine/delete//', views.HostelFineUpdateView.as_view(), name='fine_delete'), - path('fine/show/', views.student_fine_details, name='fine_show'), - - - - path('student//name/', views.get_student_name, name='find_name'), - - - path('edit-student//', views.EditStudentView.as_view(), name='edit_student'), - path('remove-student//', views.RemoveStudentView.as_view(), name='remove-student'), - - ] \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/utils.py b/FusionIIIT/applications/hostel_management/utils.py index 101ae76df..7c7a76648 100644 --- a/FusionIIIT/applications/hostel_management/utils.py +++ b/FusionIIIT/applications/hostel_management/utils.py @@ -2,8 +2,6 @@ from xhtml2pdf import pisa from io import BytesIO from django.http import HttpResponse -from django.db import transaction -from datetime import datetime from .models import * import re @@ -56,65 +54,22 @@ def render_to_pdf(template_src, context_dict={}): return HttpResponse(result.getvalue(), content_type='application/pdf') return None -def save_worker_report_sheet(excel, sheet, user_id): +def save_worker_report_sheet(excel,sheet,user_id): """ This function saves details of worker report sheet into the database. """ - try: - # Iterate over each row in the sheet - for row in range(0, sheet.nrows): - worker_id = str(sheet.cell_value(row, 0)) - worker_name = str(sheet.cell_value(row, 1)) - # Initialize present days counter - present = 0 - - # Loop through columns starting from the third column (index 2) - for col in range(2, sheet.ncols): - # Check if the cell value is 1 (indicating the worker was present) - if int(sheet.cell_value(row, col)) == 1: - present += 1 - - # Calculate total working days - working_days = sheet.ncols - 2 - - # Calculate the number of days the worker was absent - absent = working_days - present - - # Get today's date, month, and year - today_date = datetime.today() - month = today_date.month - year = today_date.year - - # Get the hall associated with the current user - hall_no = HallCaretaker.objects.get(staff__id=user_id).hall - # print("hall no ~~~~ ",hall_no) - # print("month ~~~~ ",month, year) - # Save the data in a transaction - with transaction.atomic(): - # Create and save a new WorkerReport instance - new_report = WorkerReport.objects.create(worker_id=worker_id, hall=hall_no, worker_name=worker_name, - month=month, year=year, absent=absent, total_day=working_days, remark="none") - new_report.save() - except Exception as e: - print("Error:", e) - # Handle the error here, such as logging it or displaying a message to the user - -# def save_worker_report_sheet(excel,sheet,user_id): -# """ -# This function saves details of worker report sheet into the database. -# """ -# month = excel.sheet_names()[0][:2] -# year = excel.sheet_names()[0][3:] -# for row in range(1, sheet.nrows): -# worker_id = str(sheet.cell(row,0).value) -# worker_name = str(sheet.cell(row,1).value) -# present = 0 -# for col in range(2, sheet.ncols): -# if int(sheet.cell(row,col).value) == 1: -# present += 1 -# working_days = sheet.ncols - 2 -# absent = working_days-present -# hall_no = HallCaretaker.objects.get(staff__id=user_id).hall -# print(month,year) -# new_report = WorkerReport.objects.create(worker_id=worker_id, hall=hall_no, worker_name=worker_name, month=month, year=year, absent=absent, total_day=working_days, remark="none") -# new_report.save() \ No newline at end of file + month = excel.sheet_names()[0][:2] + year = excel.sheet_names()[0][3:] + for row in range(1, sheet.nrows): + worker_id = str(sheet.cell(row,0).value) + worker_name = str(sheet.cell(row,1).value) + present = 0 + for col in range(2, sheet.ncols): + if int(sheet.cell(row,col).value) == 1: + present += 1 + working_days = sheet.ncols - 2 + absent = working_days-present + hall_no = HallCaretaker.objects.get(staff__id=user_id).hall + print(month,year) + new_report = WorkerReport.objects.create(worker_id=worker_id, hall=hall_no, worker_name=worker_name, month=month, year=year, absent=absent, total_day=working_days, remark="none") + new_report.save() \ No newline at end of file diff --git a/FusionIIIT/applications/hostel_management/views.py b/FusionIIIT/applications/hostel_management/views.py index 78f317135..0015748a4 100644 --- a/FusionIIIT/applications/hostel_management/views.py +++ b/FusionIIIT/applications/hostel_management/views.py @@ -1,45 +1,8 @@ -from django.core.serializers import serialize -from django.http import HttpResponseBadRequest -from .models import HostelLeave, HallCaretaker -from applications.hostel_management.models import HallCaretaker, HallWarden -from django.http import JsonResponse, HttpResponse -from django.db import IntegrityError -from rest_framework.exceptions import NotFound -from django.shortcuts import redirect -from django.template import loader -from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.http import HttpResponseRedirect -from django.shortcuts import render, HttpResponse -from django.views.decorators.csrf import csrf_exempt -from rest_framework.permissions import IsAuthenticated -from .models import HallCaretaker, HallWarden from django.urls import reverse -from .models import StudentDetails -from rest_framework.exceptions import APIException - - - -from django.shortcuts import render, redirect - -from .models import HostelLeave -from rest_framework.authentication import SessionAuthentication, BasicAuthentication -from django.utils.decorators import method_decorator -from django.contrib.auth.decorators import login_required -from django.db.models import Q - -from rest_framework.views import APIView -from rest_framework.response import Response -from rest_framework.authentication import SessionAuthentication -from rest_framework.permissions import IsAuthenticated -from rest_framework import status - - - from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User -# from .models import HostelStudentAttendance -from django.http import JsonResponse from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from applications.academic_information.models import Student @@ -47,46 +10,18 @@ from django.db.models import Q import datetime from datetime import time, datetime, date -from time import mktime, time, localtime +from time import mktime, time,localtime from .models import * import xlrd -from .forms import GuestRoomBookingForm, HostelNoticeBoardForm +from .forms import HostelNoticeBoardForm import re from django.http import HttpResponse from django.template.loader import get_template from django.views.generic import View from django.db.models import Q from django.contrib import messages -from .utils import render_to_pdf, save_worker_report_sheet, get_caretaker_hall +from .utils import render_to_pdf, save_worker_report_sheet,get_caretaker_hall from .utils import add_to_room, remove_from_room -from rest_framework.views import APIView -from rest_framework.response import Response -from rest_framework import status -from django.http import JsonResponse -from rest_framework.authentication import SessionAuthentication -from rest_framework.permissions import IsAuthenticated -import json - -from django.utils.decorators import method_decorator -from django.contrib.auth.decorators import user_passes_test -from django.contrib.auth import logout -from django.contrib.auth.decorators import login_required -from Fusion.settings.common import LOGIN_URL -from django.shortcuts import get_object_or_404, redirect, render -from django.db import transaction -from .forms import HallForm -from notification.views import hostel_notifications -from django.db.models.signals import post_save -from django.dispatch import receiver -from django.db import transaction - - -def is_superuser(user): - return user.is_authenticated and user.is_superuser - - -# //! My change - @login_required def hostel_view(request, context={}): @@ -104,335 +39,94 @@ def hostel_view(request, context={}): all_hall - stores all the hall of residence all_notice - stores all notices of hostels (latest first) """ - # Check if the user is a superuser - is_superuser = request.user.is_superuser - + all_hall = Hall.objects.all() halls_student = {} for hall in all_hall: - halls_student[hall.hall_id] = Student.objects.filter( - hall_no=int(hall.hall_id[4])).select_related('id__user') + halls_student[hall.hall_id] = Student.objects.filter(hall_no=int(hall.hall_id[4])).select_related('id__user') hall_staffs = {} for hall in all_hall: - hall_staffs[hall.hall_id] = StaffSchedule.objects.filter( - hall=hall).select_related('staff_id__id__user') + hall_staffs[hall.hall_id] = StaffSchedule.objects.filter(hall=hall).select_related('staff_id__id__user') all_notice = HostelNoticeBoard.objects.all().order_by("-id") hall_notices = {} for hall in all_hall: - hall_notices[hall.hall_id] = HostelNoticeBoard.objects.filter( - hall=hall).select_related('hall', 'posted_by__user') - - pending_guest_room_requests = {} - for hall in all_hall: - pending_guest_room_requests[hall.hall_id] = GuestRoomBooking.objects.filter( - hall=hall, status='Pending').select_related('hall', 'intender') - - - guest_rooms = {} - for hall in all_hall: - guest_rooms[hall.hall_id] = GuestRoom.objects.filter( - hall=hall,vacant=True).select_related('hall') - user_guest_room_requests = GuestRoomBooking.objects.filter( - intender=request.user).order_by("-arrival_date") - - halls = Hall.objects.all() - # Create a list to store additional details - hostel_details = [] - - # Loop through each hall and fetch assignedCaretaker and assignedWarden - for hall in halls: - try: - caretaker = HallCaretaker.objects.filter(hall=hall).first() - warden = HallWarden.objects.filter(hall=hall).first() - except HostelAllotment.DoesNotExist: - assigned_caretaker = None - assigned_warden = None - - vacant_seat=(hall.max_accomodation-hall.number_students) - hostel_detail = { - 'hall_id': hall.hall_id, - 'hall_name': hall.hall_name, - 'seater_type':hall.type_of_seater, - 'max_accomodation': hall.max_accomodation, - 'number_students': hall.number_students, - 'vacant_seat':vacant_seat, - 'assigned_batch': hall.assigned_batch, - 'assigned_caretaker': caretaker.staff.id.user.username if caretaker else None, - 'assigned_warden': warden.faculty.id.user.username if warden else None, - } - - hostel_details.append(hostel_detail) + hall_notices[hall.hall_id] = HostelNoticeBoard.objects.filter(hall=hall).select_related('hall','posted_by__user') Staff_obj = Staff.objects.all().select_related('id__user') hall1 = Hall.objects.get(hall_id='hall1') - hall3 = Hall.objects.get(hall_id='hall3') - hall4 = Hall.objects.get(hall_id='hall4') + hall3=Hall.objects.get(hall_id='hall3') + hall4=Hall.objects.get(hall_id='hall4') hall1_staff = StaffSchedule.objects.filter(hall=hall1) hall3_staff = StaffSchedule.objects.filter(hall=hall3) hall4_staff = StaffSchedule.objects.filter(hall=hall4) hall_caretakers = HallCaretaker.objects.all().select_related() hall_wardens = HallWarden.objects.all().select_related() - all_students = Student.objects.all().select_related('id__user') - all_students_id = [] - for student in all_students: - all_students_id.append(student.id_id) - # print(all_students) - hall_student = "" - current_hall = "" - get_avail_room = [] - get_hall = get_caretaker_hall(hall_caretakers, request.user) - if get_hall: - get_hall_num = re.findall('[0-9]+', str(get_hall.hall_id)) - hall_student = Student.objects.filter(hall_no=int( - str(get_hall_num[0]))).select_related('id__user') - current_hall = 'hall'+str(get_hall_num[0]) + hall_student="" + current_hall="" + get_avail_room=[] + get_hall=get_caretaker_hall(hall_caretakers,request.user) + if get_hall: + get_hall_num=re.findall('[0-9]+',str(get_hall.hall_id)) + hall_student=Student.objects.filter(hall_no=int(str(get_hall_num[0]))).select_related('id__user') + current_hall='hall'+str(get_hall_num[0]) + for hall in all_hall: - total_rooms = HallRoom.objects.filter(hall=hall) + total_rooms=HallRoom.objects.filter(hall=hall) for room in total_rooms: - if (room.room_cap > room.room_occupied): + if(room.room_cap>room.room_occupied): get_avail_room.append(room) - hall_caretaker_user = [] + hall_caretaker_user=[] for caretaker in hall_caretakers: hall_caretaker_user.append(caretaker.staff.id.user) hall_warden_user = [] for warden in hall_wardens: hall_warden_user.append(warden.faculty.id.user) - - all_students = Student.objects.all().select_related('id__user') - all_students_id = [] - for student in all_students: - all_students_id.append(student.id_id) - + todays_date = date.today() current_year = todays_date.year current_month = todays_date.month if current_month != 1: - worker_report = WorkerReport.objects.filter(Q(hall__hall_id=current_hall, year=current_year, month=current_month) | Q( - hall__hall_id=current_hall, year=current_year, month=current_month-1)) + worker_report = WorkerReport.objects.filter(Q(hall__hall_id=current_hall, year=current_year, month=current_month) | Q(hall__hall_id=current_hall, year=current_year, month=current_month-1)) else: - worker_report = WorkerReport.objects.filter( - hall__hall_id=current_hall, year=current_year-1, month=12) + worker_report = WorkerReport.objects.filter(hall__hall_id=current_hall, year=current_year-1, month=12) attendance = HostelStudentAttendence.objects.all().select_related() halls_attendance = {} for hall in all_hall: - halls_attendance[hall.hall_id] = HostelStudentAttendence.objects.filter( - hall=hall).select_related() - - user_complaints = HostelComplaint.objects.filter( - roll_number=request.user.username) - user_leaves = HostelLeave.objects.filter(roll_num=request.user.username) - my_leaves = [] - for leave in user_leaves: - my_leaves.append(leave) - my_complaints = [] - for complaint in user_complaints: - my_complaints.append(complaint) - - all_leaves = HostelLeave.objects.all() - all_complaints = HostelComplaint.objects.all() - - add_hostel_form = HallForm() - warden_ids = Faculty.objects.all().select_related('id__user') - - # //! My change for imposing fines - user_id = request.user - staff_fine_caretaker = user_id.extrainfo.id - students = Student.objects.all() - - fine_user = request.user - - if request.user.id in Staff.objects.values_list('id__user', flat=True): - staff_fine_caretaker = request.user.extrainfo.id - - caretaker_fine_id = HallCaretaker.objects.filter( - staff_id=staff_fine_caretaker).first() - if caretaker_fine_id: - hall_fine_id = caretaker_fine_id.hall_id - hostel_fines = HostelFine.objects.filter( - hall_id=hall_fine_id).order_by('fine_id') - context['hostel_fines'] = hostel_fines - - # caretaker_fine_id = HallCaretaker.objects.get(staff_id=staff_fine_caretaker) - # hall_fine_id = caretaker_fine_id.hall_id - # hostel_fines = HostelFine.objects.filter(hall_id=hall_fine_id).order_by('fine_id') - - if request.user.id in Staff.objects.values_list('id__user', flat=True): - staff_inventory_caretaker = request.user.extrainfo.id - - caretaker_inventory_id = HallCaretaker.objects.filter( - staff_id=staff_inventory_caretaker).first() - - if caretaker_inventory_id: - hall_inventory_id = caretaker_inventory_id.hall_id - inventories = HostelInventory.objects.filter( - hall_id=hall_inventory_id).order_by('inventory_id') - - # Serialize inventory data - inventory_data = [] - for inventory in inventories: - inventory_data.append({ - 'inventory_id': inventory.inventory_id, - 'hall_id': inventory.hall_id, - 'inventory_name': inventory.inventory_name, - # Convert DecimalField to string - 'cost': str(inventory.cost), - 'quantity': inventory.quantity, - }) - - inventory_data.sort(key=lambda x: x['inventory_id']) - context['inventories'] = inventory_data - - # all students details for caretaker and warden - if request.user.id in Staff.objects.values_list('id__user', flat=True): - staff_student_info = request.user.extrainfo.id - - if HallCaretaker.objects.filter(staff_id=staff_student_info).exists(): - hall_caretaker_id = HallCaretaker.objects.get( - staff_id=staff_student_info).hall_id - - hall_num = Hall.objects.get(id=hall_caretaker_id) - hall_number = int(''.join(filter(str.isdigit,hall_num.hall_id))) - - - # hostel_students_details = Student.objects.filter(hall_no=hall_number) - # context['hostel_students_details']= hostel_students_details - - hostel_students_details = [] - students = Student.objects.filter(hall_no=hall_number) - - a_room=[] - t_rooms = HallRoom.objects.filter(hall=hall_num) - for room in t_rooms: - if (room.room_cap > room.room_occupied): - a_room.append(room) - - # print(a_room) - # Retrieve additional information for each student - for student in students: - student_info = {} - student_info['student_id'] = student.id.id - student_info['first_name'] = student.id.user.first_name - student_info['programme'] = student.programme - student_info['batch'] = student.batch - student_info['hall_number'] = student.hall_no - student_info['room_number'] = student.room_no - student_info['specialization'] = student.specialization - # student_info['parent_contact'] = student.parent_contact - - # Fetch address and phone number from ExtraInfo model - extra_info = ExtraInfo.objects.get(user=student.id.user) - student_info['address'] = extra_info.address - student_info['phone_number'] = extra_info.phone_no - - hostel_students_details.append(student_info) - - # Sort the hostel_students_details list by roll number - hostel_students_details = sorted(hostel_students_details, key=lambda x: x['student_id']) - - - context['hostel_students_details'] = hostel_students_details - context['av_room'] = a_room - - if request.user.id in Faculty.objects.values_list('id__user', flat=True): - staff_student_info = request.user.extrainfo.id - if HallWarden.objects.filter(faculty_id=staff_student_info).exists(): - hall_warden_id = HallWarden.objects.get( - faculty_id=staff_student_info).hall_id - - hall_num = Hall.objects.get(id=hall_warden_id) - - hall_number = int(''.join(filter(str.isdigit,hall_num.hall_id))) - - # hostel_students_details = Student.objects.filter(hall_no=hall_number) - # context['hostel_students_details']= hostel_students_details + halls_attendance[hall.hall_id] = HostelStudentAttendence.objects.filter(hall=hall).select_related() - hostel_students_details = [] - students = Student.objects.filter(hall_no=hall_number) - # Retrieve additional information for each student - for student in students: - student_info = {} - student_info['student_id'] = student.id.id - student_info['first_name'] = student.id.user.first_name - student_info['programme'] = student.programme - student_info['batch'] = student.batch - student_info['hall_number'] = student.hall_no - student_info['room_number'] = student.room_no - student_info['specialization'] = student.specialization - # student_info['parent_contact'] = student.parent_contact - - # Fetch address and phone number from ExtraInfo model - extra_info = ExtraInfo.objects.get(user=student.id.user) - student_info['address'] = extra_info.address - student_info['phone_number'] = extra_info.phone_no - - hostel_students_details.append(student_info) - hostel_students_details = sorted(hostel_students_details, key=lambda x: x['student_id']) - - - context['hostel_students_details'] = hostel_students_details - - - - - # print(request.user.username); - if Student.objects.filter(id_id=request.user.username).exists(): - user_id = request.user.username - student_fines = HostelFine.objects.filter(student_id=user_id) - # print(student_fines) - context['student_fines'] = student_fines - - hostel_transactions = HostelTransactionHistory.objects.order_by('-timestamp') - - # Retrieve all hostel history entries - hostel_history = HostelHistory.objects.order_by('-timestamp') context = { - + 'all_hall': all_hall, 'all_notice': all_notice, - 'staff': Staff_obj, - 'hall1_staff': hall1_staff, - 'hall3_staff': hall3_staff, - 'hall4_staff': hall4_staff, - 'hall_caretaker': hall_caretaker_user, - 'hall_warden': hall_warden_user, - 'room_avail': get_avail_room, - 'hall_student': hall_student, + 'staff':Staff_obj, + 'hall1_staff' : hall1_staff, + 'hall3_staff' : hall3_staff, + 'hall4_staff' : hall4_staff, + 'hall_caretaker' : hall_caretaker_user, + 'hall_warden' : hall_warden_user, + 'room_avail' : get_avail_room, + 'hall_student':hall_student, 'worker_report': worker_report, 'halls_student': halls_student, - 'current_hall': current_hall, + 'current_hall' : current_hall, 'hall_staffs': hall_staffs, 'hall_notices': hall_notices, 'attendance': halls_attendance, - 'guest_rooms': guest_rooms, - 'pending_guest_room_requests': pending_guest_room_requests, - 'user_guest_room_requests': user_guest_room_requests, - 'all_students_id': all_students_id, - 'is_superuser': is_superuser, - 'warden_ids': warden_ids, - 'add_hostel_form': add_hostel_form, - 'hostel_details': hostel_details, - 'all_students_id': all_students_id, - 'my_complaints': my_complaints, - 'my_leaves': my_leaves, - 'all_leaves': all_leaves, - 'all_complaints': all_complaints, - 'staff_fine_caretaker': staff_fine_caretaker, - 'students': students, - 'hostel_transactions':hostel_transactions, - 'hostel_history':hostel_history, **context } return render(request, 'hostelmanagement/hostel.html', context) - + + + def staff_edit_schedule(request): """ This function is responsible for creating a new or updating an existing staff schedule. @@ -450,33 +144,31 @@ def staff_edit_schedule(request): hall_caretakers - stores all hall caretakers. """ if request.method == 'POST': - start_time = datetime.datetime.strptime( - request.POST["start_time"], '%H:%M').time() - end_time = datetime.datetime.strptime( - request.POST["end_time"], '%H:%M').time() - staff_name = request.POST["Staff_name"] - staff_type = request.POST["staff_type"] - day = request.POST["day"] + start_time= datetime.datetime.strptime(request.POST["start_time"],'%H:%M').time() + end_time= datetime.datetime.strptime(request.POST["end_time"],'%H:%M').time() + staff_name=request.POST["Staff_name"] + staff_type=request.POST["staff_type"] + day=request.POST["day"] - staff = Staff.objects.get(pk=staff_name) + staff=Staff.objects.get(pk=staff_name) try: - staff_schedule = StaffSchedule.objects.get(staff_id=staff) - staff_schedule.day = day - staff_schedule.start_time = start_time - staff_schedule.end_time = end_time - staff_schedule.staff_type = staff_type + staff_schedule=StaffSchedule.objects.get(staff_id=staff) + staff_schedule.day=day + staff_schedule.start_time=start_time + staff_schedule.end_time=end_time + staff_schedule.staff_type=staff_type staff_schedule.save() messages.success(request, 'Staff schedule updated successfully.') except: hall_caretakers = HallCaretaker.objects.all() - get_hall = "" - get_hall = get_caretaker_hall(hall_caretakers, request.user) - StaffSchedule(hall=get_hall, staff_id=staff, day=day, - staff_type=staff_type, start_time=start_time, end_time=end_time).save() + get_hall="" + get_hall=get_caretaker_hall(hall_caretakers,request.user) + StaffSchedule(hall=get_hall,staff_id=staff,day=day,staff_type=staff_type,start_time=start_time,end_time=end_time).save() messages.success(request, 'Staff schedule created successfully.') return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) + def staff_delete_schedule(request): """ This function is responsible for deleting an existing staff schedule. @@ -489,9 +181,9 @@ def staff_delete_schedule(request): staff_schedule - stores staff schedule related to 'staff' """ if request.method == 'POST': - staff_dlt_id = request.POST["dlt_schedule"] - staff = Staff.objects.get(pk=staff_dlt_id) - staff_schedule = StaffSchedule.objects.get(staff_id=staff) + staff_dlt_id=request.POST["dlt_schedule"] + staff=Staff.objects.get(pk=staff_dlt_id) + staff_schedule=StaffSchedule.objects.get(staff_id=staff) staff_schedule.delete() return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) @@ -517,9 +209,9 @@ def notice_board(request): head_line = form.cleaned_data['head_line'] content = form.cleaned_data['content'] description = form.cleaned_data['description'] - + new_notice = HostelNoticeBoard.objects.create(hall=hall, posted_by=request.user.extrainfo, head_line=head_line, content=content, - description=description) + description=description) new_notice.save() messages.success(request, 'Notice created successfully.') @@ -538,12 +230,11 @@ def delete_notice(request): notice - stores HostelNoticeBoard object related to 'notice_id' """ if request.method == 'POST': - notice_id = request.POST["dlt_notice"] - notice = HostelNoticeBoard.objects.get(pk=notice_id) + notice_id=request.POST["dlt_notice"] + notice=HostelNoticeBoard.objects.get(pk=notice_id) notice.delete() return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - def edit_student_rooms_sheet(request): """ This function is used to edit the room and hall of a multiple students. @@ -566,40 +257,40 @@ def edit_student_rooms_sheet(request): hall_no = str(int(hall_no)) room_no = row[2].value - block = str(room_no[0]) + block=str(room_no[0]) room = re.findall('[0-9]+', room_no) is_valid = True student = Student.objects.filter(id=roll_no.strip()) hall = Hall.objects.filter(hall_id="hall"+hall_no[0]) if student and hall.exists(): - Room = HallRoom.objects.filter( - hall=hall[0], block_no=block, room_no=str(room[0])) + Room = HallRoom.objects.filter(hall=hall[0],block_no=block,room_no=str(room[0])) if Room.exists() and Room[0].room_occupied < Room[0].room_cap: continue else: is_valid = False - # print('Room unavailable!') + print('Room unavailable!') messages.error(request, 'Room unavailable!') break else: is_valid = False - # print("Wrong Credentials entered!") + print("Wrong Credentials entered!") messages.error(request, 'Wrong credentials entered!') break if not is_valid: return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - + for row in all_rows: if row[0].value == "Roll No": continue roll_no = row[0].value if row[0].ctype == 2: roll_no = str(int(roll_no)) + hall_no = str(int(row[1].value)) room_no = row[2].value - block = str(room_no[0]) + block=str(room_no[0]) room = re.findall('[0-9]+', room_no) is_valid = True student = Student.objects.filter(id=roll_no.strip()) @@ -624,8 +315,8 @@ def edit_student_room(request): """ if request.method == "POST": roll_no = request.POST["roll_no"] - hall_room_no = request.POST["hall_room_no"] - index = hall_room_no.find('-') + hall_room_no=request.POST["hall_room_no"] + index=hall_room_no.find('-') room_no = hall_room_no[index+1:] hall_no = hall_room_no[:index] student = Student.objects.get(id=roll_no) @@ -634,13 +325,12 @@ def edit_student_room(request): messages.success(request, 'Student room changed successfully.') return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - def edit_attendance(request): """ This function is used to edit the attendance of a student. @param: request - HttpRequest object containing metadata about the user request. - + @variables: student_id = The student whose attendance has to be updated. hall = The hall of the concerned student. @@ -648,18 +338,17 @@ def edit_attendance(request): """ if request.method == "POST": roll_no = request.POST["roll_no"] - + student = Student.objects.get(id=roll_no) hall = Hall.objects.get(hall_id='hall'+str(student.hall_no)) date = datetime.datetime.today().strftime('%Y-%m-%d') - if HostelStudentAttendence.objects.filter(student_id=student, date=date).exists() == True: - messages.error( - request, f'{student.id.id} is already marked present on {date}') + if HostelStudentAttendence.objects.filter(student_id=student,date=date).exists() == True: + messages.error(request, f'{student.id.id} is already marked present on {date}') return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - record = HostelStudentAttendence.objects.create(student_id=student, - hall=hall, date=date, present=True) + record = HostelStudentAttendence.objects.create(student_id=student, \ + hall=hall, date=date, present=True) record.save() messages.success(request, f'Attendance of {student.id.id} recorded.') @@ -667,110 +356,35 @@ def edit_attendance(request): return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) -# @login_required -# def generate_worker_report(request): -# """ -# This function is used to read uploaded worker report spreadsheet(.xls) and generate WorkerReport instance and save it in the database. -# @param: -# request - HttpRequest object containing metadata about the user request. - -# @variables: -# files - stores uploaded worker report file -# excel - stores the opened spreadsheet file raedy for data extraction. -# user_id - stores user id of the current user. -# sheet - stores a sheet from the uploaded spreadsheet. -# """ -# if request.method == "POST": -# try: -# files = request.FILES['upload_report'] -# excel = xlrd.open_workbook(file_contents=files.read()) -# user_id = request.user.extrainfo.id -# if str(excel.sheets()[0].cell(0, 0).value)[:5].lower() == str(HallCaretaker.objects.get(staff__id=user_id).hall): -# for sheet in excel.sheets(): -# save_worker_report_sheet(excel, sheet, user_id) -# return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - -# return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) -# except: -# messages.error( -# request, "Please upload a file in valid format before submitting") -# return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - -# class GeneratePDF(View): -# def get(self, request, *args, **kwargs): -# """ -# This function is used to generate worker report in pdf format available for download. -# @param: -# request - HttpRequest object containing metadata about the user request. - -# @variables: -# months - stores number of months for which the authorized user wants to generate worker report. -# toadys_date - stores current date. -# current_year - stores current year retrieved from 'todays_date'. -# current_month - stores current month retrieved from 'todays_date'. -# template - stores template returned by 'get_template' method. -# hall_caretakers - stores all hall caretakers. -# worker_report - stores 'WorkerReport' instances according to 'months'. -# """ -# months = int(request.GET.get('months')) -# todays_date = date.today() -# current_year = todays_date.year -# current_month = todays_date.month - -# template = get_template('hostelmanagement/view_report.html') - -# hall_caretakers = HallCaretaker.objects.all() -# get_hall = "" -# get_hall = get_caretaker_hall(hall_caretakers, request.user) - -# if months < current_month: -# worker_report = WorkerReport.objects.filter( -# hall=get_hall, month__gte=current_month-months, year=current_year) -# else: -# worker_report = WorkerReport.objects.filter(Q(hall=get_hall, year=current_year, month__lte=current_month) | Q( -# hall=get_hall, year=current_year-1, month__gte=12-months+current_month)) - -# worker = { -# 'worker_report': worker_report -# } -# html = template.render(worker) -# pdf = render_to_pdf('hostelmanagement/view_report.html', worker) -# if pdf: -# response = HttpResponse(pdf, content_type='application/pdf') -# filename = "Invoice_%s.pdf" % ("12341231") -# content = "inline; filename='%s'" % (filename) -# download = request.GET.get("download") -# if download: -# content = "attachment; filename='%s'" % (filename) -# response['Content-Disposition'] = content -# return response -# return HttpResponse("Not found") @login_required def generate_worker_report(request): + """ + This function is used to read uploaded worker report spreadsheet(.xls) and generate WorkerReport instance and save it in the database. + @param: + request - HttpRequest object containing metadata about the user request. + + @variables: + files - stores uploaded worker report file + excel - stores the opened spreadsheet file raedy for data extraction. + user_id - stores user id of the current user. + sheet - stores a sheet from the uploaded spreadsheet. + """ if request.method == "POST": - try: - files = request.FILES.get('upload_report') - if files: - # Check if the file has a valid extension - file_extension = files.name.split('.')[-1].lower() - if file_extension not in ['xls', 'xlsx']: - messages.error(request, "Invalid file format. Please upload a .xls or .xlsx file.") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - excel = xlrd.open_workbook(file_contents=files.read()) - user_id = request.user.extrainfo.id - for sheet in excel.sheets(): - # print('111111111111111111111111111111111111',sheet[0]) - save_worker_report_sheet(excel, sheet, user_id) + try: + files = request.FILES['upload_report'] + excel = xlrd.open_workbook(file_contents=files.read()) + user_id = request.user.extrainfo.id + if str(excel.sheets()[0].cell(0,0).value)[:5].lower() == str(HallCaretaker.objects.get(staff__id=user_id).hall): + for sheet in excel.sheets(): + save_worker_report_sheet(excel,sheet,user_id) return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - else: - messages.error(request, "No file uploaded") - except Exception as e: - messages.error(request, f"Error processing file: {str(e)}") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) + + return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) + except: + messages.error(request,"Please upload a file in valid format before submitting") + return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) class GeneratePDF(View): @@ -791,7 +405,6 @@ def get(self, request, *args, **kwargs): """ months = int(request.GET.get('months')) - # print('~~~~month',months) todays_date = date.today() current_year = todays_date.year current_month = todays_date.month @@ -799,1324 +412,27 @@ def get(self, request, *args, **kwargs): template = get_template('hostelmanagement/view_report.html') hall_caretakers = HallCaretaker.objects.all() - get_hall = "" - get_hall = get_caretaker_hall(hall_caretakers, request.user) - # print('~~~~~ get_hall' , get_hall) - # print('monthalert("You are not authorized to access this page"); window.location.href = "/hostelmanagement/"') - - -@login_required -def create_hostel_leave(request): - - if request.method == 'GET': - return render(request, 'hostelmanagement/create_leave.html') - elif request.method == 'POST': - data = request.POST # Assuming you are sending form data via POST request - student_name = data.get('student_name') - roll_num = data.get('roll_num') - phone_number = data.get('phone_number') # Retrieve phone number from form data - reason = data.get('reason') - start_date = data.get('start_date', timezone.now()) - end_date = data.get('end_date') - - - # Create HostelLeave object and save to the database - leave = HostelLeave.objects.create( - student_name=student_name, - roll_num=roll_num, - phone_number=phone_number, # Include phone number in the object creation - reason=reason, - start_date=start_date, - end_date=end_date, - - ) - caretakers = HallCaretaker.objects.all() - sender = request.user - type = "leave_request" - for caretaker in caretakers: - try: - # Send notification - hostel_notifications(sender, caretaker.staff.id.user, type) - except Exception as e: - # Handle notification sending error - print(f"Error sending notification to caretaker {caretaker.staff.user.username}: {e}") - - return JsonResponse({'message': 'HostelLeave created successfully'}, status=status.HTTP_201_CREATED) - -# hostel_complaints_list caretaker can see all hostel complaints - -@login_required -def hostel_complaint_list(request): - user_id = request.user.id - - try: - # Assuming the user's profile is stored in extrainfo - staff = request.user.extrainfo.id - except AttributeError: - staff = None - - if staff is not None and HallCaretaker.objects.filter(staff_id=staff).exists(): - complaints = HostelComplaint.objects.all() - return render(request, 'hostelmanagement/hostel_complaint.html', {'complaints': complaints}) - else: - return HttpResponse('') - - -@login_required -def get_students(request): - try: - staff = request.user.extrainfo.id - print(staff) - except AttributeError: - staff = None - - if HallCaretaker.objects.filter(staff_id=staff).exists(): - hall_id = HallCaretaker.objects.get(staff_id=staff).hall_id - print(hall_id) - hall_no = Hall.objects.get(id=hall_id) - print(hall_no) - student_details = StudentDetails.objects.filter(hall_id=hall_no) - - return render(request, 'hostelmanagement/student_details.html', {'students': student_details}) - - elif HallWarden.objects.filter(faculty_id=staff).exists(): - hall_id = HallWarden.objects.get(faculty_id=staff).hall_id - student_details = StudentDetails.objects.filter(hall_id=hall_no) - - return render(request, 'hostelmanagement/student_details.html', {'students': student_details}) - else: - return HttpResponse('') - -# Student can post complaints - - -class PostComplaint(APIView): - # Assuming you are using session authentication - authentication_classes = [SessionAuthentication] - # Allow only authenticated users to access the view - permission_classes = [IsAuthenticated] - - def dispatch(self, request, *args, **kwargs): - # print(request.user.username) - if not request.user.is_authenticated: - # Redirect to the login page if user is not authenticated - return redirect('/hostelmanagement') - return super().dispatch(request, *args, **kwargs) - - def get(self, request): - return render(request, 'hostelmanagement/post_complaint_form.html') - - def post(self, request): - hall_name = request.data.get('hall_name') - student_name = request.data.get('student_name') - roll_number = request.data.get('roll_number') - description = request.data.get('description') - contact_number = request.data.get('contact_number') - - # Assuming the student's name is stored in the user object - student_name = request.user.username - - complaint = HostelComplaint.objects.create( - hall_name=hall_name, - student_name=student_name, - roll_number=roll_number, - description=description, - contact_number=contact_number - ) - - # Use JavaScript to display a pop-up message after submission - return HttpResponse('') - - -# // student can see his leave status - -class my_leaves(View): - @method_decorator(login_required, name='dispatch') - def get(self, request, *args, **kwargs): - try: - # Get the user ID from the request's user - user_id = str(request.user) - - # Retrieve leaves registered by the current student based on their roll number - my_leaves = HostelLeave.objects.filter(roll_num__iexact=user_id) - # Construct the context to pass to the template - context = { - 'leaves': my_leaves - } - - # Render the template with the context data - return render(request, 'hostelmanagement/my_leaves.html', context) - - except User.DoesNotExist: - # Handle the case where the user with the given ID doesn't exist - return HttpResponse(f"User with ID {user_id} does not exist.") - - -class HallIdView(APIView): - authentication_classes = [] # Allow public access for testing - permission_classes = [] # Allow any user to access the view - - def get(self, request, *args, **kwargs): - hall_id = HostelAllotment.objects.values('hall_id') - return Response(hall_id, status=status.HTTP_200_OK) - - -@login_required(login_url=LOGIN_URL) -def logout_view(request): - logout(request) - return redirect("/") - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class AssignCaretakerView(APIView): - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - template_name = 'hostelmanagement/assign_caretaker.html' - - def get(self, request, *args, **kwargs): - hall = Hall.objects.all() - caretaker_usernames = Staff.objects.all() - return render(request, self.template_name, {'halls': hall, 'caretaker_usernames': caretaker_usernames}) - - def post(self, request, *args, **kwargs): - hall_id = request.data.get('hall_id') - caretaker_username = request.data.get('caretaker_username') - - try: - hall = Hall.objects.get(hall_id=hall_id) - caretaker_staff = Staff.objects.get( - id__user__username=caretaker_username) - - # Retrieve the previous caretaker for the hall, if any - prev_hall_caretaker = HallCaretaker.objects.filter(hall=hall).first() - # print(prev_hall_caretaker.staff.id) - # Delete any previous assignments of the caretaker in HallCaretaker table - HallCaretaker.objects.filter(staff=caretaker_staff).delete() - - # Delete any previous assignments of the caretaker in HostelAllotment table - HostelAllotment.objects.filter( - assignedCaretaker=caretaker_staff).delete() - - # Delete any previously assigned caretaker to the same hall - HallCaretaker.objects.filter(hall=hall).delete() - - # Assign the new caretaker to the hall in HallCaretaker table - hall_caretaker = HallCaretaker.objects.create( - hall=hall, staff=caretaker_staff) - - # # Update the assigned caretaker in Hostelallottment table - hostel_allotments = HostelAllotment.objects.filter(hall=hall) - for hostel_allotment in hostel_allotments: - hostel_allotment.assignedCaretaker = caretaker_staff - hostel_allotment.save() - - # Retrieve the current warden for the hall - current_warden = HallWarden.objects.filter(hall=hall).first() - - try: - history_entry = HostelTransactionHistory.objects.create( - hall=hall, - change_type='Caretaker', - previous_value= prev_hall_caretaker.staff.id if (prev_hall_caretaker and prev_hall_caretaker.staff) else 'None', - new_value=caretaker_username - ) - except Exception as e: - print("Error creating HostelTransactionHistory:", e) - - - # Create hostel history - try: - HostelHistory.objects.create( - hall=hall, - caretaker=caretaker_staff, - batch=hall.assigned_batch, - warden=current_warden.faculty if( current_warden and current_warden.faculty) else None - ) - except Exception as e: - print ("Error creating history",e) - return Response({'message': f'Caretaker {caretaker_username} assigned to Hall {hall_id} successfully'}, status=status.HTTP_201_CREATED) - - except Hall.DoesNotExist: - return Response({'error': f'Hall with ID {hall_id} not found'}, status=status.HTTP_404_NOT_FOUND) - except Staff.DoesNotExist: - return Response({'error': f'Caretaker with username {caretaker_username} not found'}, status=status.HTTP_404_NOT_FOUND) - except Exception as e: - return JsonResponse({'status': 'error', 'error': str(e)}, status=500) - - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class AssignBatchView(View): - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - # Assuming the HTML file is directly in the 'templates' folder - template_name = 'hostelmanagement/assign_batch.html' - - def get(self, request, *args, **kwargs): - hall = Hall.objects.all() - return render(request, self.template_name, {'halls': hall}) - - def update_student_hall_allotment(self, hall, assigned_batch): - hall_number = int(''.join(filter(str.isdigit, hall.hall_id))) - students = Student.objects.filter(batch=int(assigned_batch)) - - - for student in students: - student.hall_no = hall_number - student.save() - - - def post(self, request, *args, **kwargs): - try: - with transaction.atomic(): # Start a database transaction - - data = json.loads(request.body.decode('utf-8')) - hall_id = data.get('hall_id') - - hall = Hall.objects.get(hall_id=hall_id) - # previous_batch = hall.assigned_batch # Get the previous batch - previous_batch = hall.assigned_batch if hall.assigned_batch is not None else 0 # Get the previous batch - hall.assigned_batch = data.get('batch') - hall.save() - - - - - - # Update the assignedBatch field in HostelAllotment table for the corresponding hall - room_allotments = HostelAllotment.objects.filter(hall=hall) - for room_allotment in room_allotments: - room_allotment.assignedBatch = hall.assigned_batch - room_allotment.save() - - # retrieve the current caretaker and current warden for the hall - current_caretaker =HallCaretaker.objects.filter(hall=hall).first() - current_warden = HallWarden.objects.filter(hall=hall).first() - - # Record the transaction history - HostelTransactionHistory.objects.create( - hall=hall, - change_type='Batch', - previous_value=previous_batch, - new_value=hall.assigned_batch - ) - - # Create hostel history - try: - HostelHistory.objects.create( - hall=hall, - caretaker=current_caretaker.staff if (current_caretaker and current_caretaker.staff) else None, - - batch=hall.assigned_batch, - warden=current_warden.faculty if( current_warden and current_warden.faculty) else None - - ) - except Exception as e: - print ("Error creating history",e) - - self.update_student_hall_allotment(hall, hall.assigned_batch) - print("batch assigned successssssssssssssssssss") - messages.success(request, 'batch assigned succesfully') - - return JsonResponse({'status': 'success', 'message': 'Batch assigned successfully'}, status=200) - - except Hall.DoesNotExist: - return JsonResponse({'status': 'error', 'error': f'Hall with ID {hall_id} not found'}, status=404) - - except Exception as e: - return JsonResponse({'status': 'error', 'error': str(e)}, status=500) - - def test_func(self): - # Check if the user is a superuser - return self.request.user.is_superuser - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class AssignWardenView(APIView): - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - template_name = 'hostelmanagement/assign_warden.html' - - def post(self, request, *args, **kwargs): - hall_id = request.data.get('hall_id') - warden_id = request.data.get('warden_id') - try: - hall = Hall.objects.get(hall_id=hall_id) - warden = Faculty.objects.get(id__user__username=warden_id) - - # Retrieve the previous caretaker for the hall, if any - prev_hall_warden = HallWarden.objects.filter(hall=hall).first() - - # Delete any previous assignments of the warden in Hallwarden table - HallWarden.objects.filter(faculty=warden).delete() - - # Delete any previous assignments of the warden in HostelAllotment table - HostelAllotment.objects.filter(assignedWarden=warden).delete() - - # Delete any previously assigned warden to the same hall - HallWarden.objects.filter(hall=hall).delete() - - # Assign the new warden to the hall in Hallwarden table - hall_warden = HallWarden.objects.create(hall=hall, faculty=warden) - - #current caretker - current_caretaker =HallCaretaker.objects.filter(hall=hall).first() - print(current_caretaker) - - # Update the assigned warden in Hostelallottment table - hostel_allotments = HostelAllotment.objects.filter(hall=hall) - for hostel_allotment in hostel_allotments: - hostel_allotment.assignedWarden = warden - hostel_allotment.save() - - try: - history_entry = HostelTransactionHistory.objects.create( - hall=hall, - change_type='Warden', - previous_value= prev_hall_warden.faculty.id if (prev_hall_warden and prev_hall_warden.faculty) else 'None', - new_value=warden - ) - except Exception as e: - print("Error creating HostelTransactionHistory:", e) - - - # Create hostel history - try: - HostelHistory.objects.create( - hall=hall, - caretaker=current_caretaker.staff if (current_caretaker and current_caretaker.staff) else None, - - batch=hall.assigned_batch, - warden=warden - ) - except Exception as e: - print ("Error creating history",e) - - - return Response({'message': f'Warden {warden_id} assigned to Hall {hall_id} successfully'}, status=status.HTTP_201_CREATED) - - except Hall.DoesNotExist: - return Response({'error': f'Hall with ID {hall_id} not found'}, status=status.HTTP_404_NOT_FOUND) - except Faculty.DoesNotExist: - return Response({'error': f'Warden with username {warden_id} not found'}, status=status.HTTP_404_NOT_FOUND) - except Exception as e: - return JsonResponse({'status': 'error', 'error': str(e)}, status=500) - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class AddHostelView(View): - template_name = 'hostelmanagement/add_hostel.html' - - def get(self, request, *args, **kwargs): - form = HallForm() - return render(request, self.template_name, {'form': form}) - - def post(self, request, *args, **kwargs): - form = HallForm(request.POST) - if form.is_valid(): - hall_id = form.cleaned_data['hall_id'] - - # # Check if a hall with the given hall_id already exists - # if Hall.objects.filter(hall_id=hall_id).exists(): - # messages.error(request, f'Hall with ID {hall_id} already exists.') - # return redirect('hostelmanagement:add_hostel') - - # Check if a hall with the given hall_id already exists - if Hall.objects.filter(hall_id=hall_id).exists(): - error_message = f'Hall with ID {hall_id} already exists.' - - return HttpResponse(error_message, status=400) - - # If not, create a new hall - form.save() - messages.success(request, 'Hall added successfully!') - # Redirect to the view showing all hostels - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - # return render(request, 'hostelmanagement/admin_hostel_list.html') - - # If form is not valid, render the form with errors - return render(request, self.template_name, {'form': form}) - - -class CheckHallExistsView(View): - - def get(self, request, *args, **kwargs): - - hall_id = request.GET.get('hall_id') - try: - hall = Hall.objects.get(hall_id=hall_id) - exists = True - except Hall.DoesNotExist: - exists = False - messages.MessageFailure(request, f'Hall {hall_id} already exist.') - return JsonResponse({'exists': exists}) - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class AdminHostelListView(View): - template_name = 'hostelmanagement/admin_hostel_list.html' - - def get(self, request, *args, **kwargs): - halls = Hall.objects.all() - # Create a list to store additional details - hostel_details = [] - - # Loop through each hall and fetch assignedCaretaker and assignedWarden - for hall in halls: - try: - caretaker = HallCaretaker.objects.filter(hall=hall).first() - warden = HallWarden.objects.filter(hall=hall).first() - except HostelAllotment.DoesNotExist: - assigned_caretaker = None - assigned_warden = None - - hostel_detail = { - 'hall_id': hall.hall_id, - 'hall_name': hall.hall_name, - 'max_accomodation': hall.max_accomodation, - 'number_students': hall.number_students, - 'assigned_batch': hall.assigned_batch, - 'assigned_caretaker': caretaker.staff.id.user.username if caretaker else None, - 'assigned_warden': warden.faculty.id.user.username if warden else None, - } - - hostel_details.append(hostel_detail) - - return render(request, self.template_name, {'hostel_details': hostel_details}) - - -@method_decorator(user_passes_test(is_superuser), name='dispatch') -class DeleteHostelView(View): - def get(self, request, hall_id, *args, **kwargs): - # Get the hall instance - hall = get_object_or_404(Hall, hall_id=hall_id) - - # Delete related entries in other tables - hostelallotments = HostelAllotment.objects.filter(hall=hall) - hostelallotments.delete() - - # Delete the hall - hall.delete() - messages.success(request, f'Hall {hall_id} deleted successfully.') - - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - -class HallIdView(APIView): - authentication_classes = [] # Allow public access for testing - permission_classes = [] # Allow any user to access the view - - def get(self, request, *args, **kwargs): - hall_id = HostelAllotment.objects.values('hall_id') - return Response(hall_id, status=status.HTTP_200_OK) - - -@login_required(login_url=LOGIN_URL) -def logout_view(request): - logout(request) - return redirect("/") - - -# //! alloted_rooms -def alloted_rooms(request, hall_id): - """ - This function returns the allotted rooms in a particular hall. - - @param: - request - HttpRequest object containing metadata about the user request. - hall_id - Hall ID for which the allotted rooms need to be retrieved. - - @variables: - allotted_rooms - stores all the rooms allotted in the given hall. - """ - # Query the hall by hall_id - hall = Hall.objects.get(hall_id=hall_id) - # Query all rooms allotted in the given hall - allotted_rooms = HallRoom.objects.filter(hall=hall, room_occupied__gt=0) - # Prepare a list of room details to be returned - room_details = [] - for room in allotted_rooms: - room_details.append({ - 'hall': room.hall.hall_id, - 'room_no': room.room_no, - 'block_no': room.block_no, - 'room_cap': room.room_cap, - 'room_occupied': room.room_occupied - }) - return JsonResponse(room_details, safe=False) - - -def alloted_rooms_main(request): - """ - This function returns the allotted rooms in all halls. - - @param: - request - HttpRequest object containing metadata about the user request. - - @variables: - all_halls - stores all the halls. - all_rooms - stores all the rooms allotted in all halls. - """ - # Query all halls - all_halls = Hall.objects.all() - - # Query all rooms allotted in all halls - all_rooms = [] - for hall in all_halls: - all_rooms.append(HallRoom.objects.filter( - hall=hall, room_occupied__gt=0)) - - # Prepare a list of room details to be returned - room_details = [] - for rooms in all_rooms: - for room in rooms: - room_details.append({ - 'hall': room.hall.hall_name, - 'room_no': room.room_no, - 'block_no': room.block_no, - 'room_cap': room.room_cap, - 'room_occupied': room.room_occupied - }) - - # Return the room_details as JSON response - return render(request, 'hostelmanagement/alloted_rooms_main.html', {'allotted_rooms': room_details, 'halls': all_halls}) - - -# //! all_staff -def all_staff(request, hall_id): - """ - This function returns all staff information for a specific hall. - - @param: - request - HttpRequest object containing metadata about the user request. - hall_id - The ID of the hall for which staff information is requested. - - - @variables: - all_staff - stores all staff information for the specified hall. - """ - - # Query all staff information for the specified hall - all_staff = StaffSchedule.objects.filter(hall_id=hall_id) - - # Prepare a list of staff details to be returned - staff_details = [] - for staff in all_staff: - staff_details.append({ - 'type': staff.staff_type, - 'staff_id': staff.staff_id_id, - 'hall_id': staff.hall_id, - 'day': staff.day, - 'start_time': staff.start_time, - 'end_time': staff.end_time - }) - - # Return the staff_details as JSON response - return JsonResponse(staff_details, safe=False) - - -# //! Edit Stuff schedule -class StaffScheduleView(APIView): - """ - API endpoint for creating or editing staff schedules. - """ - - authentication_classes = [] # Allow public access for testing - permission_classes = [] # Allow any user to access the view - - def patch(self, request, staff_id): - staff = get_object_or_404(Staff, pk=staff_id) - staff_type = request.data.get('staff_type') - start_time = request.data.get('start_time') - end_time = request.data.get('end_time') - day = request.data.get('day') - - - if start_time and end_time and day and staff_type: - # Check if staff schedule exists for the given day - existing_schedule = StaffSchedule.objects.filter( - staff_id=staff_id).first() - if existing_schedule: - existing_schedule.start_time = start_time - existing_schedule.end_time = end_time - existing_schedule.day = day - existing_schedule.staff_type = staff_type - existing_schedule.save() - return Response({"message": "Staff schedule updated successfully."}, status=status.HTTP_200_OK) - else: - # If staff schedule doesn't exist for the given day, return 404 - return Response({"error": "Staff schedule does not exist for the given day."}, status=status.HTTP_404_NOT_FOUND) - - return Response({"error": "Please provide start_time, end_time, and day."}, status=status.HTTP_400_BAD_REQUEST) - - -# //! Hostel Inventory - -@login_required -def get_inventory_form(request): - user_id = request.user - # print("user_id",user_id) - staff = user_id.extrainfo.id - # print("staff",staff) - - # Check if the user is present in the HallCaretaker table - if HallCaretaker.objects.filter(staff_id=staff).exists(): - # If the user is a caretaker, allow access - halls = Hall.objects.all() - return render(request, 'hostelmanagement/inventory_form.html', {'halls': halls}) - else: - # If the user is not a caretaker, redirect to the login page - # return redirect('login') # Adjust 'login' to your login URL name - return HttpResponse(f'') - - -@login_required -def edit_inventory(request, inventory_id): - # Retrieve hostel inventory object - inventory = get_object_or_404(HostelInventory, pk=inventory_id) - - # Check if the user is a caretaker - user_id = request.user - staff_id = user_id.extrainfo.id - - if HallCaretaker.objects.filter(staff_id=staff_id).exists(): - halls = Hall.objects.all() - - # Prepare inventory data for rendering - inventory_data = { - 'inventory_id': inventory.inventory_id, - 'hall_id': inventory.hall_id, - 'inventory_name': inventory.inventory_name, - 'cost': str(inventory.cost), # Convert DecimalField to string - 'quantity': inventory.quantity, - } - - # Render the inventory update form with inventory data - return render(request, 'hostelmanagement/inventory_update_form.html', {'inventory': inventory_data, 'halls': halls}) - else: - # If the user is not a caretaker, show a message and redirect - return HttpResponse('') - - -class HostelInventoryUpdateView(APIView): - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - - @method_decorator(login_required) - def dispatch(self, *args, **kwargs): - return super().dispatch(*args, **kwargs) - - def post(self, request, inventory_id): - user_id = request.user - staff_id = user_id.extrainfo.id - - if not HallCaretaker.objects.filter(staff_id=staff_id).exists(): - return Response({'error': 'You are not authorized to update this hostel inventory'}, status=status.HTTP_401_UNAUTHORIZED) - - hall_id = request.data.get('hall_id') - inventory_name = request.data.get('inventory_name') - cost = request.data.get('cost') - quantity = request.data.get('quantity') - - # Validate required fields - if not all([hall_id, inventory_name, cost, quantity]): - return Response({'error': 'All fields are required'}, status=status.HTTP_400_BAD_REQUEST) - - # Retrieve hostel inventory object - hostel_inventory = get_object_or_404(HostelInventory, pk=inventory_id) - - # Update hostel inventory object - hostel_inventory.hall_id = hall_id - hostel_inventory.inventory_name = inventory_name - hostel_inventory.cost = cost - hostel_inventory.quantity = quantity - hostel_inventory.save() - - # Return success response - return Response({'message': 'Hostel inventory updated successfully'}, status=status.HTTP_200_OK) - - -class HostelInventoryView(APIView): - """ - API endpoint for CRUD operations on hostel inventory. - """ - # permission_classes = [IsAuthenticated] - - # authentication_classes = [] # Allow public access for testing - # permission_classes = [] # Allow any user to access the view - - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - - @method_decorator(login_required) - def dispatch(self, *args, **kwargs): - return super().dispatch(*args, **kwargs) - - def get(self, request, hall_id): - user_id = request.user - staff_id = user_id.extrainfo.id - - if not HallCaretaker.objects.filter(staff_id=staff_id).exists(): - return HttpResponse('') - - # Retrieve hostel inventory objects for the given hall ID - inventories = HostelInventory.objects.filter(hall_id=hall_id) - - # Get all hall IDs - halls = Hall.objects.all() - - # Serialize inventory data - inventory_data = [] - for inventory in inventories: - inventory_data.append({ - 'inventory_id': inventory.inventory_id, - 'hall_id': inventory.hall_id, - 'inventory_name': inventory.inventory_name, - 'cost': str(inventory.cost), # Convert DecimalField to string - 'quantity': inventory.quantity, - }) - - inventory_data.sort(key=lambda x: x['inventory_id']) - - # Return inventory data as JSON response - return render(request, 'hostelmanagement/inventory_list.html', {'halls': halls, 'inventories': inventory_data}) - - def post(self, request): - user_id = request.user - staff_id = user_id.extrainfo.id - - if not HallCaretaker.objects.filter(staff_id=staff_id).exists(): - return Response({'error': 'You are not authorized to create a new hostel inventory'}, status=status.HTTP_401_UNAUTHORIZED) - - # Extract data from request - hall_id = request.data.get('hall_id') - inventory_name = request.data.get('inventory_name') - cost = request.data.get('cost') - quantity = request.data.get('quantity') - - # Validate required fields - if not all([hall_id, inventory_name, cost, quantity]): - return Response({'error': 'All fields are required'}, status=status.HTTP_400_BAD_REQUEST) - - # Create hostel inventory object - try: - hostel_inventory = HostelInventory.objects.create( - hall_id=hall_id, - inventory_name=inventory_name, - cost=cost, - quantity=quantity - ) - return Response({'message': 'Hostel inventory created successfully', 'hall_id': hall_id}, status=status.HTTP_201_CREATED) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - def delete(self, request, inventory_id): - user_id = request.user - staff_id = user_id.extrainfo.id - - if not HallCaretaker.objects.filter(staff_id=staff_id).exists(): - return Response({'error': 'You are not authorized to delete this hostel inventory'}, status=status.HTTP_401_UNAUTHORIZED) - - inventory = get_object_or_404(HostelInventory, pk=inventory_id) - inventory.delete() - return Response({'message': 'Hostel inventory deleted successfully'}, status=status.HTTP_204_NO_CONTENT) - - -def update_allotment(request, pk): - if request.method == 'POST': - try: - allotment = HostelAllottment.objects.get(pk=pk) - except HostelAllottment.DoesNotExist: - return JsonResponse({'error': 'HostelAllottment not found'}, status=404) - - try: - allotment.assignedWarden = Faculty.objects.get( - id=request.POST['warden_id']) - allotment.assignedCaretaker = Staff.objects.get( - id=request.POST['caretaker_id']) - allotment.assignedBatch = request.POST.get( - 'student_batch', allotment.assignedBatch) - allotment.save() - return JsonResponse({'success': 'HostelAllottment updated successfully'}) - except (Faculty.DoesNotExist, Staff.DoesNotExist, IntegrityError): - return JsonResponse({'error': 'Invalid data or integrity error'}, status=400) - - return JsonResponse({'error': 'Invalid request method'}, status=405) - - -@login_required -def request_guest_room(request): - """ - This function is used by the student to book a guest room. - @param: - request - HttpRequest object containing metadata about the user request. - """ - if request.method == "POST": - form = GuestRoomBookingForm(request.POST) - - if form.is_valid(): - # print("Inside valid") - hall = form.cleaned_data['hall'] - guest_name = form.cleaned_data['guest_name'] - guest_phone = form.cleaned_data['guest_phone'] - guest_email = form.cleaned_data['guest_email'] - guest_address = form.cleaned_data['guest_address'] - rooms_required = form.cleaned_data['rooms_required'] - total_guest = form.cleaned_data['total_guest'] - purpose = form.cleaned_data['purpose'] - arrival_date = form.cleaned_data['arrival_date'] - arrival_time = form.cleaned_data['arrival_time'] - departure_date = form.cleaned_data['departure_date'] - departure_time = form.cleaned_data['departure_time'] - nationality = form.cleaned_data['nationality'] - room_type = form.cleaned_data['room_type'] # Add room type - - - max_guests = { - 'single': 1, - 'double': 2, - 'triple': 3, - } - # Fetch available room count based on room type and hall - available_rooms_count = GuestRoom.objects.filter( - hall=hall, room_type=room_type, vacant=True - ).count() - - # Check if there are enough available rooms - if available_rooms_count < rooms_required: - messages.error(request, "Not enough available rooms.") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - # Check if the number of guests exceeds the capacity of selected rooms - if total_guest > rooms_required * max_guests.get(room_type, 1): - messages.error(request, "Number of guests exceeds the capacity of selected rooms.") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - - newBooking = GuestRoomBooking.objects.create(hall=hall, intender=request.user, guest_name=guest_name, guest_address=guest_address, - guest_phone=guest_phone, guest_email=guest_email, rooms_required=rooms_required, total_guest=total_guest, purpose=purpose, - arrival_date=arrival_date, arrival_time=arrival_time, departure_date=departure_date, departure_time=departure_time, nationality=nationality,room_type=room_type) - newBooking.save() - messages.success(request, "Room request submitted successfully!") - - - # Get the caretaker for the selected hall - hall_caretaker = HallCaretaker.objects.get(hall=hall) - caretaker = hall_caretaker.staff.id.user - # Send notification to caretaker - hostel_notifications(sender=request.user, recipient=caretaker, type='guestRoom_request') - - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - else: - messages.error(request, "Something went wrong") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - -@login_required -def update_guest_room(request): - if request.method == "POST": - if 'accept_request' in request.POST: - status = request.POST['status'] - guest_room_request = GuestRoomBooking.objects.get( - pk=request.POST['accept_request']) - guest_room_instance = GuestRoom.objects.get( - hall=guest_room_request.hall, room=request.POST['guest_room_id']) - - # Assign the guest room ID to guest_room_id field - guest_room_request.guest_room_id = str(guest_room_instance.id) - - # Update the assigned guest room's occupancy details - guest_room_instance.occupied_till = guest_room_request.departure_date - guest_room_instance.vacant = False # Mark the room as occupied - guest_room_instance.save() - - # Update the occupied_till field of the room_booked - room_booked = GuestRoom.objects.get( - hall=guest_room_request.hall, room=request.POST['guest_room_id']) - room_booked.occupied_till = guest_room_request.departure_date - room_booked.save() - - # Save the guest room request after updating the fields - guest_room_request.status = status - guest_room_request.save() - messages.success(request, "Request accepted successfully!") - - hostel_notifications(sender=request.user,recipient=guest_room_request.intender,type='guestRoom_accept') - - - elif 'reject_request' in request.POST: - guest_room_request = GuestRoomBooking.objects.get( - pk=request.POST['reject_request']) - guest_room_request.status = 'Rejected' - guest_room_request.save() - - messages.success(request, "Request rejected successfully!") - - hostel_notifications(sender=request.user,recipient=guest_room_request.intender,type='guestRoom_reject') - - else: - messages.error(request, "Invalid request!") - return HttpResponseRedirect(reverse("hostelmanagement:hostel_view")) - - -def available_guestrooms_api(request): - if request.method == 'GET': - - hall_id = request.GET.get('hall_id') - room_type = request.GET.get('room_type') - - if hall_id and room_type: - available_rooms_count = GuestRoom.objects.filter(hall_id=hall_id, room_type=room_type, vacant=True).count() - return JsonResponse({'available_rooms_count': available_rooms_count}) - - return JsonResponse({'error': 'Invalid request'}, status=400) - - -# //Caretaker can approve or reject leave applied by the student -@csrf_exempt -def update_leave_status(request): - if request.method == 'POST': - leave_id = request.POST.get('leave_id') - status = request.POST.get('status') - try: - leave = HostelLeave.objects.get(id=leave_id) - leave.status = status - leave.remark = request.POST.get('remark') - leave.save() - - # Send notification to the student - sender = request.user # Assuming request.user is the caretaker - - student_id = leave.roll_num # Assuming student is a foreign key field in HostelLeave model - recipient = User.objects.get(username=student_id) - type = "leave_accept" if status == "Approved" else "leave_reject" - hostel_notifications(sender, recipient, type) - - return JsonResponse({'status': status,'remarks':leave.remark,'message': 'Leave status updated successfully.'}) - except HostelLeave.DoesNotExist: - return JsonResponse({'status': 'error', 'message': 'Leave not found.'}, status=404) - else: - return JsonResponse({'status': 'error', 'message': 'Only POST requests are allowed.'}, status=405) - - -# //! Manage Fine -# //! Add Fine Functionality - - -@login_required -def show_fine_edit_form(request,fine_id): - user_id = request.user - staff = user_id.extrainfo.id - caretaker = HallCaretaker.objects.get(staff_id=staff) - hall_id = caretaker.hall_id - - fine = HostelFine.objects.filter(fine_id=fine_id) - - - - return render(request, 'hostelmanagement/impose_fine_edit.html', {'fines': fine[0]}) - -@login_required -def update_student_fine(request,fine_id): - if request.method == 'POST': - fine = HostelFine.objects.get(fine_id=fine_id) - print("------------------------------------------------") - print(request.POST) - fine.amount = request.POST.get('amount') - fine.status = request.POST.get('status') - fine.reason = request.POST.get('reason') - fine.save() - - return HttpResponse({'message': 'Fine has edited successfully'}, status=status.HTTP_200_OK) - - -@login_required -def impose_fine_view(request): - user_id = request.user - staff = user_id.extrainfo.id - students = Student.objects.all() - - if HallCaretaker.objects.filter(staff_id=staff).exists(): - return render(request, 'hostelmanagement/impose_fine.html', {'students': students}) - - return HttpResponse(f'') - - -class HostelFineView(APIView): - """ - API endpoint for imposing fines on students. - """ - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - - @method_decorator(login_required) - def dispatch(self, *args, **kwargs): - return super().dispatch(*args, **kwargs) - - def post(self, request): - # Check if the user is a caretaker - user_id = request.user - staff = user_id.extrainfo.id - - try: - caretaker = HallCaretaker.objects.get(staff_id=staff) - except HallCaretaker.DoesNotExist: - return HttpResponse(f'') - - hall_id = caretaker.hall_id - - # Extract data from the request - student_id = request.data.get('student_id') - student_name = request.data.get('student_fine_name') - amount = request.data.get('amount') - reason = request.data.get('reason') - - # Validate the data - if not all([student_id, student_name, amount, reason]): - return HttpResponse({'error': 'Incomplete data provided.'}, status=status.HTTP_400_BAD_REQUEST) - - # Create the HostelFine object - try: - fine = HostelFine.objects.create( - student_id=student_id, - student_name=student_name, - amount=amount, - reason=reason, - hall_id=hall_id - ) - # Sending notification to the student about the imposed fine - - - - recipient = User.objects.get(username=student_id) - - sender = request.user - - type = "fine_imposed" - hostel_notifications(sender, recipient, type) - - return HttpResponse({'message': 'Fine imposed successfully.'}, status=status.HTTP_201_CREATED) - except Exception as e: - return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -@login_required -def get_student_name(request, username): - try: - user = User.objects.get(username=username) - full_name = f"{user.first_name} {user.last_name}" if user.first_name or user.last_name else "" - return JsonResponse({"name": full_name}) - except User.DoesNotExist: - return JsonResponse({"error": "User not found"}, status=404) - - -@login_required -def hostel_fine_list(request): - user_id = request.user - staff = user_id.extrainfo.id - caretaker = HallCaretaker.objects.get(staff_id=staff) - hall_id = caretaker.hall_id - hostel_fines = HostelFine.objects.filter( - hall_id=hall_id).order_by('fine_id') - - if HallCaretaker.objects.filter(staff_id=staff).exists(): - return render(request, 'hostelmanagement/hostel_fine_list.html', {'hostel_fines': hostel_fines}) - - return HttpResponse(f'') - - -@login_required -def student_fine_details(request): - user_id = request.user.username - # print(user_id) - # staff=user_id.extrainfo.id - - # Check if the user_id exists in the Student table - # if HallCaretaker.objects.filter(staff_id=staff).exists(): - # return HttpResponse('') - - if not Student.objects.filter(id_id=user_id).exists(): - return HttpResponse('') - - # # Check if the user_id exists in the HostelFine table - if not HostelFine.objects.filter(student_id=user_id).exists(): - return HttpResponse('') - - # # Retrieve the fines associated with the current student - student_fines = HostelFine.objects.filter(student_id=user_id) - - return render(request, 'hostelmanagement/student_fine_details.html', {'student_fines': student_fines}) - - # return JsonResponse({'message': 'Nice'}, status=status.HTTP_200_OK) - - -class HostelFineUpdateView(APIView): - authentication_classes = [SessionAuthentication] - permission_classes = [IsAuthenticated] - - @method_decorator(login_required) - def dispatch(self, *args, **kwargs): - return super().dispatch(*args, **kwargs) - - def post(self, request, fine_id): - user_id = request.user - staff = user_id.extrainfo.id - - data = request.data - fine_idd = data.get('fine_id') - status_ = data.get('status') - # print("fine_idd",fine_idd) - # print("status_",status_) - - try: - caretaker = HallCaretaker.objects.get(staff_id=staff) - except HallCaretaker.DoesNotExist: - return Response({'error': 'You are not authorized to access this page'}, status=status.HTTP_403_FORBIDDEN) - - hall_id = caretaker.hall_id - - # Convert fine_id to integer - fine_id = int(fine_id) - - # Get hostel fine object - try: - hostel_fine = HostelFine.objects.get( - hall_id=hall_id, fine_id=fine_id) - except HostelFine.DoesNotExist: - raise NotFound(detail="Hostel fine not found") - - # Validate required fields - if status_ not in ['Pending', 'Paid']: - return Response({'error': 'Invalid status value'}, status=status.HTTP_400_BAD_REQUEST) - - # # Update status of the hostel fine - hostel_fine.status = status_ - hostel_fine.save() - - # Return success response - return Response({'message': 'Hostel fine status updated successfully!'}, status=status.HTTP_200_OK) - - def delete(self, request, fine_id): - user_id = request.user - staff = user_id.extrainfo.id - - try: - caretaker = HallCaretaker.objects.get(staff_id=staff) - except HallCaretaker.DoesNotExist: - return Response({'error': 'You are not authorized to access this page'}, status=status.HTTP_403_FORBIDDEN) - - hall_id = caretaker.hall_id - - # Convert fine_id to integer - fine_id = int(fine_id) - - # Get hostel fine object - try: - hostel_fine = HostelFine.objects.get( - hall_id=hall_id, fine_id=fine_id) - hostel_fine.delete() - except HostelFine.DoesNotExist: - raise NotFound(detail="Hostel fine not found") - - return Response({'message': 'Fine deleted successfully.'}, status=status.HTTP_204_NO_CONTENT) - - - - -class EditStudentView(View): - template_name = 'hostelmanagement/edit_student.html' - - def get(self, request, student_id): - student = Student.objects.get(id=student_id) - - context = {'student': student} - return render(request, self.template_name, context) - - def post(self, request, student_id): - student = Student.objects.get(id=student_id) - - # Update student details - student.id.user.first_name = request.POST.get('first_name') - student.id.user.last_name = request.POST.get('last_name') - student.programme = request.POST.get('programme') - student.batch = request.POST.get('batch') - student.hall_no = request.POST.get('hall_number') - student.room_no = request.POST.get('room_number') - student.specialization = request.POST.get('specialization') - - student.save() - - # Update phone number and address from ExtraInfo model - student.id.phone_no = request.POST.get('phone_number') - student.id.address = request.POST.get('address') - student.id.save() - student.save() - messages.success(request, 'Student details updated successfully.') - return redirect("hostelmanagement:hostel_view") - -class RemoveStudentView(View): - def post(self, request, student_id): - try: - student = Student.objects.get(id=student_id) - student.hall_no = 0 - student.save() - messages.success(request, 'Student removed successfully.') - return redirect("hostelmanagement:hostel_view") - return JsonResponse({'status': 'success', 'message': 'Student removed successfully'}) - except Student.DoesNotExist: - return JsonResponse({'status': 'error', 'message': 'Student not found'}, status=404) - except Exception as e: - return JsonResponse({'status': 'error', 'message': str(e)}, status=500) - - def dispatch(self, request, *args, **kwargs): - if request.method != 'POST': - return JsonResponse({'status': 'error', 'message': 'Method Not Allowed'}, status=405) - return super().dispatch(request, *args, **kwargs) - - diff --git a/FusionIIIT/applications/hr2/migrations/0001_initial.py b/FusionIIIT/applications/hr2/migrations/0001_initial.py index 733f5b0bb..83b197c8f 100644 --- a/FusionIIIT/applications/hr2/migrations/0001_initial.py +++ b/FusionIIIT/applications/hr2/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import django.core.validators from django.db import migrations, models diff --git a/FusionIIIT/applications/income_expenditure/migrations/0001_initial.py b/FusionIIIT/applications/income_expenditure/migrations/0001_initial.py index e772edafa..1501efdb9 100644 --- a/FusionIIIT/applications/income_expenditure/migrations/0001_initial.py +++ b/FusionIIIT/applications/income_expenditure/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion diff --git a/FusionIIIT/applications/iwdModuleV2/migrations/0001_initial.py b/FusionIIIT/applications/iwdModuleV2/migrations/0001_initial.py index b86a5c530..bbde8386c 100644 --- a/FusionIIIT/applications/iwdModuleV2/migrations/0001_initial.py +++ b/FusionIIIT/applications/iwdModuleV2/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion diff --git a/FusionIIIT/applications/iwdModuleV2/models.py b/FusionIIIT/applications/iwdModuleV2/models.py index a0834f1bb..a5c40c7b2 100644 --- a/FusionIIIT/applications/iwdModuleV2/models.py +++ b/FusionIIIT/applications/iwdModuleV2/models.py @@ -1,5 +1,5 @@ from django.db import models -from datetime import date + # Create your models here. @@ -160,51 +160,3 @@ class NoOfTechnicalBidTimes(models.Model): key = models.ForeignKey(Projects, on_delete=models.CASCADE, unique=True) number = models.IntegerField() -class Requests(models.Model): - name = models.CharField(max_length=200) - description = models.CharField(max_length=200) - area = models.CharField(max_length=200) - requestCreatedBy = models.CharField(max_length=200) - engineerProcessed = models.IntegerField(default=0) - directorApproval = models.IntegerField(default=0) - deanProcessed = models.IntegerField(default=0) - status = models.CharField(max_length=200) - issuedWorkOrder = models.IntegerField(default=0) - workCompleted = models.IntegerField(default=0) - billGenerated = models.IntegerField(default=0) - billProcessed = models.IntegerField(default=0) - billSettled = models.IntegerField(default=0) - -class WorkOrder(models.Model): - # request_id = models.IntegerField() - request_id = models.ForeignKey(Requests, on_delete=models.CASCADE) - name = models.CharField(max_length=200) - date = models.DateField(default=date.today) - agency = models.CharField(max_length=200) - amount = models.IntegerField(default=0) - deposit = models.IntegerField(default=0) - alloted_time = models.CharField(max_length=200) - start_date = models.DateField() - completion_date = models.DateField() - -class Inventory(models.Model): - name = models.CharField(max_length=200) - quantity = models.IntegerField(default=0) - cost = models.IntegerField(default=0) - -class UsedItems(models.Model): - # requestId = models.IntegerField() - request_id = models.ForeignKey(Requests, on_delete=models.CASCADE) - itemName = models.CharField(max_length=200) - cost = models.IntegerField(default=0) - quantity = models.IntegerField(default=0) - date = models.DateField(default=date.today) - -class Bills(models.Model): - # requestId = models.IntegerField() - request_id = models.ForeignKey(Requests, on_delete=models.CASCADE) - file = models.FileField() - -class Budget(models.Model): - name = models.CharField(max_length=200) - budgetIssued = models.IntegerField(default=0) diff --git a/FusionIIIT/applications/iwdModuleV2/urls.py b/FusionIIIT/applications/iwdModuleV2/urls.py index 0c0830cea..6ad401098 100644 --- a/FusionIIIT/applications/iwdModuleV2/urls.py +++ b/FusionIIIT/applications/iwdModuleV2/urls.py @@ -36,46 +36,5 @@ url(r'milestoneView/$', views.milestoneView, name='Milestones'), url(r'addendumView/$', views.addendumView, name='Addendum View'), url('agreementView/$', views.agreementView, name='Agreement VIew'), - url(r'corrigendumView/$', views.corrigendumView, name='Corrigendum View'), - url('requestsView/',views.requestsView, name='Requests view'), - url('createdRequestsView/',views.createdRequests, name='Created Requests view'), - url('handleEngineerProcessRequests/', views.handleEngineerProcessRequests, name='Engineer-Process-Requests'), - url('engineerProcessedRequestsView/',views.engineerProcessedRequests, name='Engineer-Processed-Requests view'), - url('handleDeanProcessRequests/', views.handleDeanProcessRequests, name='Dean-Process-Requests'), - url('deanProcessedRequestsView/',views.deanProcessedRequests, name='Dean-Processed-Requests view'), - url('handleDirectorApprovalRequests/', views.handleDirectorApprovalRequests, name='Director-Approval-Requests'), - url('handleDirectorRejectionRequests/', views.handleDirectorRejectionRequests, name='Director-Rejection-Requests'), - url('updateRejectedRequests/', views.updateRejectedRequests, name='Update-Rejected-Requests'), - url('handleUpdateRequests/', views.handleUpdateRequests, name='Handle-Update-Requests'), - # url('rejectedRequests/', views.rejectedRequests, name='Rejected-Requests'), - url('rejectedRequestsView/',views.rejectedRequests, name='Rejected Requests view'), - url('requestsStatus/', views.requestsStatus, name='Requests-Status'), - url('fetchDesignations/', views.fetchDesignations, name='Fetch-Designations'), - url('fetchRequest/', views.fetchRequest, name='Fetch-Request'), - url('issueWorkOrder/', views.issueWorkOrder, name='Issue Work Order'), - url('workOrder/', views.workOrder, name='Work Order'), - url('inventory/', views.inventory, name='Inventory'), - url('addItemsView/', views.addItemsView, name='Add Items View'), - url('addItems/', views.addItems, name='Add Items'), - url('editInventoryView/', views.editInventoryView, name='Edit Inventory View'), - url('editInventory/', views.editInventory, name='Edit Inventory'), - url('requestsInProgess/', views.requestsInProgess, name='Requests In Progress'), - url('workCompleted/', views.workCompleted, name='Work Completed'), - url('requestFromInventory/', views.requestFromInventory, name='Request From Inventory'), - url('editInventoryAfterRequest/', views.editInventoryAfterRequest, name='Edit-Inventory-After-Request'), - url('generateFinalBill/', views.generateFinalBill, name='Generate-Final-Bill'), - url('handleBillGeneratedRequests/', views.handleBillGeneratedRequests, name='Handle-Bill-Generated-Requests'), - url('generatedBillsView/', views.generatedBillsView, name='Generated-Bills-View'), - url('handleProcessedBills/', views.handleProcessedBills, name='Handle-Processed-Bills'), - url('auditDocumentView/', views.auditDocumentView, name='Audit-Document-View'), - url('auditDocument/', views.auditDocument, name='Audit-Document'), - url('settleBillsView/', views.settleBillsView, name='Settle-Bills-View'), - url('handleSettleBillRequests/', views.handleSettleBillRequests, name='Handle-Settle-Bill-Requests'), - url('viewBudget/', views.viewBudget, name='View-Budget'), - url('budget/', views.budget, name='Budget'), - url('addBudget/', views.addBudget, name='Add-Budget'), - url('editBudgetView/', views.editBudgetView, name='Edit-Budget-View'), - url('editBudget/', views.editBudget, name='Edit-Budget'), - # url('billsView/',views.billsView, name='Bills View'), - + url(r'corrigendumView/$', views.corrigendumView, name='Corrigendum View') ] diff --git a/FusionIIIT/applications/iwdModuleV2/views.py b/FusionIIIT/applications/iwdModuleV2/views.py index 38a7e4ee7..2b36550fc 100644 --- a/FusionIIIT/applications/iwdModuleV2/views.py +++ b/FusionIIIT/applications/iwdModuleV2/views.py @@ -1,20 +1,9 @@ from django.shortcuts import render, redirect -from django.urls import reverse -from django.db.models import Q + from applications.globals.models import * -from django.contrib.auth.decorators import login_required from .models import * from django.http import HttpResponseRedirect -from applications.filetracking.sdk.methods import * -from applications.globals.models import ExtraInfo, HoldsDesignation, Designation -from datetime import datetime -from reportlab.lib.pagesizes import letter -from reportlab.pdfgen import canvas -from reportlab.platypus import Table, TableStyle -from reportlab.lib import colors -from django.http import HttpResponse -from io import BytesIO -from django.core.files.base import File as DjangoFile + # Create your views here. @@ -28,27 +17,17 @@ # owing to length and inherent extensiveness of code. Rather than, whosoever read this code is advised to do so # in conjunction with SRS. After that, everything will become easier. -# def dashboard(request): -# eligible = False -# userObj = request.user -# userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) -# for p in userDesignationObjects: -# if p.designation.name == 'Admin IWD': -# eligible = True -# break -# return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -#Junior Engineer, Electrical Engineer (Civil), Electrical_AE, Electrical_JE, EE, Civil_AE, Civil_JE - def dashboard(request): - eligible = "" + eligible = False userObj = request.user userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) for p in userDesignationObjects: - eligible = p.designation.name - print(eligible) + if p.designation.name == 'Admin IWD': + eligible = True + break return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) + def page1_1(request): if request.method == 'POST': formObject = PageOneDetails() @@ -128,8 +107,7 @@ def page2_1(request): def corrigendumInput(request): if request.method == 'POST': - existingObject = CorrigendumTable.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = CorrigendumTable.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = CorrigendumTable() @@ -150,8 +128,7 @@ def corrigendumInput(request): def addendumInput(request): if request.method == 'POST': - existingObject = Addendum.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = Addendum.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = Addendum() @@ -168,8 +145,7 @@ def addendumInput(request): def PreBidForm(request): if request.method == 'POST': - existingObject = PreBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = PreBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = PreBidDetails() @@ -185,11 +161,9 @@ def PreBidForm(request): def noOfEntriesTechnicalBid(request): formNoTechnicalObjects = NoOfTechnicalBidTimes() - formNoTechnicalObjects.key = Projects.objects.get( - id=request.session['projectId']) + formNoTechnicalObjects.key = Projects.objects.get(id=request.session['projectId']) if request.method == 'POST': - existingObject = NoOfTechnicalBidTimes.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = NoOfTechnicalBidTimes.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formNoTechnicalObjects.number = int(request.POST['number']) @@ -200,11 +174,9 @@ def noOfEntriesTechnicalBid(request): def TechnicalBidForm(request): formObject = TechnicalBidDetails() - numberOfTechnicalBidTimes = NoOfTechnicalBidTimes.objects.get( - key=Projects.objects.get(id=request.session['projectId'])).number + numberOfTechnicalBidTimes = NoOfTechnicalBidTimes.objects.get(key=Projects.objects.get(id=request.session['projectId'])).number if request.method == 'POST': - existingObject = TechnicalBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = TechnicalBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = TechnicalBidDetails() @@ -212,14 +184,12 @@ def TechnicalBidForm(request): formObject.sNo = request.POST['sNo'] formObject.requirements = request.POST['requirements'] formObject.save() - TechnicalBidContractorDetails.objects.filter( - key=formObject).all().delete() + TechnicalBidContractorDetails.objects.filter(key=formObject).all().delete() for w in range(numberOfTechnicalBidTimes): formContractorObject = TechnicalBidContractorDetails() formContractorObject.key = formObject formContractorObject.name = request.POST[str(w) + 'name'] - formContractorObject.description = request.POST[str( - w) + 'Description'] + formContractorObject.description = request.POST[str(w) + 'Description'] formContractorObject.save() return redirect('iwdModuleV2/noOfEntriesFinancialBid') return render(request, 'iwdModuleV2/page2_support_4_technicalbid.html', @@ -228,15 +198,12 @@ def TechnicalBidForm(request): def noOfEntriesFinancialBid(request): listOfContractors = [] - objectTechnicalBid = TechnicalBidDetails.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) - objects = TechnicalBidContractorDetails.objects.filter( - key=objectTechnicalBid) + objectTechnicalBid = TechnicalBidDetails.objects.get(key=Projects.objects.get(id=request.session['projectId'])) + objects = TechnicalBidContractorDetails.objects.filter(key=objectTechnicalBid) for t in objects: listOfContractors.append(t.name) if request.method == 'POST': - existingObject = FinancialBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = FinancialBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = FinancialBidDetails() @@ -250,8 +217,7 @@ def noOfEntriesFinancialBid(request): formContractorObject.name = listOfContractors[f] formContractorObject.totalCost = request.POST[listOfContractors[f] + 'totalCost'] formContractorObject.estimatedCost = request.POST[listOfContractors[f] + 'estimatedCost'] - formContractorObject.percentageRelCost = request.POST[ - listOfContractors[f] + 'percentageRelCost'] + formContractorObject.percentageRelCost = request.POST[listOfContractors[f] + 'percentageRelCost'] formContractorObject.perFigures = request.POST[listOfContractors[f] + 'perFigures'] formContractorObject.save() return redirect('iwdModuleV2/letterOfIntent') @@ -261,8 +227,7 @@ def noOfEntriesFinancialBid(request): def letterOfIntent(request): if request.method == 'POST': - existingObject = LetterOfIntentDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = LetterOfIntentDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = LetterOfIntentDetails() @@ -279,8 +244,7 @@ def letterOfIntent(request): def workOrderForm(request): if request.method == 'POST': - existingObject = WorkOrderForm.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = WorkOrderForm.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = WorkOrderForm() @@ -303,8 +267,7 @@ def workOrderForm(request): def AgreementInput(request): if request.method == 'POST': - existingObject = Agreement.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + existingObject = Agreement.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) if existingObject.count() == 1: existingObject.delete() formObject = Agreement() @@ -328,8 +291,7 @@ def milestonesForm(request): formObject.timeAllowed = request.POST['timeAllowed'] formObject.save() return redirect('iwdModuleV2/page3_1') - Milestones.objects.filter(key=Projects.objects.get( - id=request.session['projectId'])).all().delete() + Milestones.objects.filter(key=Projects.objects.get(id=request.session['projectId'])).all().delete() return render(request, 'iwdModuleV2/page2_support_9_milestone.html', {}) @@ -359,42 +321,35 @@ def ExtensionOfTimeForm(request): def page1View(request): - if request.POST: - request.session['projectId'] = request.POST['id'] - projectPageOne = PageOneDetails.objects.get( - id=Projects.objects.get(id=request.session['projectId'])) + request.session['projectId'] = request.POST['id'] + projectPageOne = PageOneDetails.objects.get(id=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Page1.html', {'x': projectPageOne}) def page2View(request): - projectPageTwo = PageTwoDetails.objects.get( - id=Projects.objects.get(id=request.session['projectId'])) + projectPageTwo = PageTwoDetails.objects.get(id=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Page2.html', {'x': projectPageTwo}) def AESView(request): - objects = AESDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + objects = AESDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/AA&ES.html', {'AES': objects}) def financialBidView(request): elements = [] - objects = FinancialBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + objects = FinancialBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) for f in objects: contractorObjects = FinancialContractorDetails.objects.filter(key=f) for w in contractorObjects: - obj = [f.sNo, f.description, w.name, w.estimatedCost, - w.percentageRelCost, w.perFigures, w.totalCost] + obj = [f.sNo, f.description, w.name, w.estimatedCost, w.percentageRelCost, w.perFigures, w.totalCost] elements.append(obj) return render(request, 'iwdModuleV2/Page2_financialbid.html', {'financial': elements}) def technicalBidView(request): elements = [] - objects = TechnicalBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + objects = TechnicalBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) for f in objects: contractorObjects = TechnicalBidContractorDetails.objects.filter(key=f) for w in contractorObjects: @@ -404,976 +359,45 @@ def technicalBidView(request): def preBidDetailsView(request): - preBidObjects = PreBidDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + preBidObjects = PreBidDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Page2_pre-bid.html', {'preBidDetails': preBidObjects}) def corrigendumView(request): - corrigendumObject = CorrigendumTable.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) + corrigendumObject = CorrigendumTable.objects.get(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/corrigendum.html', {'corrigendum': corrigendumObject}) def addendumView(request): - addendumObject = Addendum.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) + addendumObject = Addendum.objects.get(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Addendum.html', {'x': addendumObject}) def letterOfIntentView(request): - letterOfIntentObject = LetterOfIntentDetails.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) + letterOfIntentObject = LetterOfIntentDetails.objects.get(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/letterOfIntent.html', {'x': letterOfIntentObject}) def workOrderFormView(request): - workOrderFormObject = WorkOrderForm.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) + workOrderFormObject = WorkOrderForm.objects.get(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/WorkOrderForm.html', {'x': workOrderFormObject}) def agreementView(request): - agreementObject = Agreement.objects.get( - key=Projects.objects.get(id=request.session['projectId'])) + agreementObject = Agreement.objects.get(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Agreement.html', {'agreement': agreementObject}) def milestoneView(request): - milestoneObjects = Milestones.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + milestoneObjects = Milestones.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Page2_milestones.html', {'milestones': milestoneObjects}) def page3View(request): - pageThreeDetails = PageThreeDetails.objects.get( - id=Projects.objects.get(id=request.session['projectId'])) + pageThreeDetails = PageThreeDetails.objects.get(id=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/Page3.html', {'x': pageThreeDetails}) def extensionFormView(request): - extensionObjects = ExtensionOfTimeDetails.objects.filter( - key=Projects.objects.get(id=request.session['projectId'])) + extensionObjects = ExtensionOfTimeDetails.objects.filter(key=Projects.objects.get(id=request.session['projectId'])) return render(request, 'iwdModuleV2/ExtensionForm.html', {'extension': extensionObjects}) - -designations_list = ["Junior Engineer", "Executive Engineer (Civil)", "Electrical_AE", "Electrical_JE", "EE", "Civil_AE", "Civil_JE", "Dean (P&D)", "Director", "Accounts Admin", "Admin IWD", "Auditor"] - -@login_required -def fetchDesignations(request): - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/requestsView.html', {'holdsDesignations' : holdsDesignations}) - -@login_required -def requestsView(request): - if request.method == 'POST': - formObject = Requests() - # formObject.key = Projects.objects.get(id=request.session['projectId']) - formObject.name = request.POST['name'] - formObject.description = request.POST['description'] - formObject.area = request.POST['area'] - formObject.engineerProcessed = 0 - formObject.directorApproval = 0 - formObject.deanProcessed = 0 - formObject.requestCreatedBy = request.user.username - formObject.status = "Pending" - formObject.issuedWorkOrder = 0 - formObject.workCompleted = 0 - formObject.billGenerated = 0 - formObject.billProcessed = 0 - formObject.billSettled = 0 - formObject.save() - print(request.user) - print(request.user.username) - request_object = Requests.objects.get(pk=formObject.pk) - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - print(d) - print(d1) - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_object.id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible' : eligible}) - -@login_required -def createdRequests(request): - obj = [] - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/createdRequests.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def handleEngineerProcessRequests(request): - if request.method == 'POST': - - request_id = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - Requests.objects.filter(id=request_id).update(engineerProcessed=1, status="Approved by the engineer") - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - - return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -@login_required -def engineerProcessedRequests(request): - - obj = [] - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/engineerProcessedRequests.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def handleDeanProcessRequests(request): - if request.method == 'POST': - - request_id = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - Requests.objects.filter(id=request_id).update(deanProcessed=1, status="Approved by the dean") - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -@login_required -def deanProcessedRequests(request): - obj = [] - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/deanProcessedRequests.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def handleDirectorApprovalRequests(request): - if request.method == 'POST': - request_id = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - Requests.objects.filter(id=request_id).update(directorApproval=1, status="Approved by the director") - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -@login_required -def handleDirectorRejectionRequests(request): - if request.method == 'POST': - request_id = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_id), - file_extra_JSON= {"value": 2}, - attached_file = None) - - Requests.objects.filter(id=request_id).update(directorApproval=-1, status="Rejected by the director") - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -@login_required -def rejectedRequests(request): - obj = [] - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object.directorApproval == -1: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/rejectedRequests.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def updateRejectedRequests(request): - request_id = request.POST.get("id", 0) - - d1 = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - designations = Designation.objects.filter() - - holdsDesignations = [] - obj = [] - - request_object = Requests.objects.get(id=request_id) - - obj = [request_object.id, request_object.name, request_object.description, request_object.area] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/updateRequests.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def handleUpdateRequests(request): - if request.method == 'POST': - request_id = request.POST.get("id", 0) - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - Requests.objects.filter(id=request_id).update(name=request.POST['name'], - description=request.POST['description'], - area=request.POST['area'], - engineerProcessed=0, - directorApproval=0, - deanProcessed=0, - requestCreatedBy=request.user.username, - status="Pending", - issuedWorkOrder=0, - workCompleted=0, - billGenerated=0, - billProcessed=0, - billSettled=0) - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(request_id), - file_extra_JSON= {"value": 2}, - attached_file = None) - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible' : eligible}) - -@login_required -def issueWorkOrder(request): - obj = [] - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - uploader = result['sent_by_designation'] - if uploader == 'Director': - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - return render(request, 'iwdModuleV2/issueWorkOrder.html', {'obj' : obj}) - -@login_required -def fetchRequest(request): - request_id = request.POST.get("id", 0) - req_request = Requests.objects.get(id=request_id) - return render(request, 'iwdModuleV2/workOrder.html', {'req' : req_request}) - -@login_required -def workOrder(request): - if request.method == 'POST': - request_instance = Requests.objects.get(pk=request.POST['id']) - formObject = WorkOrder() - formObject.request_id = request_instance - formObject.name = request.POST['name'] - formObject.date = request.POST['date'] - formObject.agency = request.POST['agency'] - formObject.amount = request.POST['amount'] - formObject.deposit = request.POST['deposit'] - formObject.alloted_time = request.POST['time'] - formObject.start_date = request.POST['startDate'] - formObject.completion_date = request.POST['completionDate'] - formObject.save() - - Requests.objects.filter(id=request.POST['id']).update(status="Work Order issued", issuedWorkOrder=1) - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for result in inbox_files: - if result['src_object_id'] == request.POST['id'] and result['sent_by_designation'] == 'Director': - delete_file(file_id = result['id']) - break - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - obj = [] - - for result in inbox_files: - uploader = result['sent_by_designation'] - if uploader == 'Director': - src_object_id = result['src_object_id'] - request_object = Requests.objects.filter(id=src_object_id).first() - if request_object: - element = [request_object.id, request_object.name, request_object.area, request_object.description, request_object.requestCreatedBy] - obj.append(element) - - return render(request, 'iwdModuleV2/issueWorkOrder.html', {'obj' : obj}) - -@login_required -def requestsStatus(request): - obj = [] - requestsObject = Requests.objects.all() - for x in requestsObject: - element = [x.id, x.name, x.area, x.description, x.requestCreatedBy, x.status] - obj.append(element) - return render(request, 'iwdModuleV2/requestsStatus.html', {'obj' : obj}) - -@login_required -def inventory(request): - items = Inventory.objects.filter() - obj = [] - for i in items: - element = [i.id, i.name, i.quantity, i.cost] - obj.append(element) - return render(request, 'iwdModuleV2/inventory.html', {'obj' : obj}) - -@login_required -def addItemsView(request): - return render(request, 'iwdModuleV2/addItemsView.html') - -@login_required -def addItems(request): - if request.method == "POST": - formObject = Inventory() - formObject.name = request.POST['name'] - formObject.quantity = request.POST['quantity'] - formObject.cost = request.POST['cost'] - formObject.save() - return render(request, 'iwdModuleV2/addItemsView.html') - -@login_required -def editInventoryView(request): - items = Inventory.objects.filter() - obj = [] - for i in items: - element = [i.id, i.name, i.quantity, i.cost] - obj.append(element) - return render(request, 'iwdModuleV2/editInventory.html', {'obj' : obj}) - -@login_required -def editInventory(request): - if request.method == "POST": - itemId = request.POST['id'] - itemName = request.POST['name'] - itemQuantity = request.POST['quantity'] - itemCost = request.POST['cost'] - if itemQuantity == "0": - Inventory.objects.filter(id=itemId).delete() - else: - Inventory.objects.filter(id=itemId).update(name=itemName, quantity=itemQuantity, cost=itemCost) - items = Inventory.objects.filter() - obj = [] - for i in items: - element = [i.id, i.name, i.quantity, i.cost] - obj.append(element) - return render(request, 'iwdModuleV2/editInventory.html', {'obj' : obj}) - -@login_required -def requestsInProgess(request): - obj = [] - requestsObject = Requests.objects.filter(issuedWorkOrder=1, billGenerated=0) - for x in requestsObject: - element = [x.id, x.name, x.area, x.description, x.requestCreatedBy, x.workCompleted] - obj.append(element) - return render(request, 'iwdModuleV2/requestsInProgress.html', {'obj' : obj}) - -@login_required -def workCompleted(request): - if request.method == 'POST': - Requests.objects.filter(id=request.POST['id']).update(workCompleted=1, status="Work Completed") - obj = [] - requestsObject = Requests.objects.filter(issuedWorkOrder=1, billGenerated=0) - for x in requestsObject: - element = [x.id, x.name, x.area, x.description, x.requestCreatedBy, x.workCompleted] - obj.append(element) - return render(request, 'iwdModuleV2/requestsInProgress.html', {'obj' : obj}) - -@login_required -def requestFromInventory(request): - if request.method == 'POST': - requestId = request.POST['id'] - Req = Requests.objects.filter(id=requestId) - Items = Inventory.objects.filter() - req = [] - items = [] - for x in Req: - element = [x.id, x.name, x.area, x.description, x.requestCreatedBy, x.workCompleted] - req.append(element) - - for x in Items: - element = [x.id, x.name, x.quantity, x.cost] - items.append(element) - print(items) - return render(request, 'iwdModuleV2/requestFromInventory.html', {'req' : req, 'items' : items}) - -@login_required -def editInventoryAfterRequest(request): - if request.method == 'POST': - selectedItem = Inventory.objects.get(id=request.POST['selected_item_id']) - q = int(selectedItem.quantity) - if q == int(request.POST['quantity']): - Inventory.objects.filter(id=request.POST['selected_item_id']).delete() - else: - Inventory.objects.filter(id=request.POST['selected_item_id']).update(quantity=(q-int(request.POST['quantity']))) - formObject = UsedItems() - request_instance = Requests.objects.get(pk=request.POST['id']) - formObject.request_id = request_instance - formObject.itemName = selectedItem.name - formObject.cost = selectedItem.cost - formObject.quantity = request.POST['quantity'] - formObject.date = datetime.now().date() - formObject.save() - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - return render(request, 'iwdModuleV2/dashboard.html', {'eligible': eligible}) - -@login_required -def generateFinalBill(request): - if request.method == 'POST': - requestId = request.POST.get("id", 0) - - usedItems = UsedItems.objects.filter(request_id=requestId) - workOrder = WorkOrder.objects.get(request_id=requestId) - - itemsList = [] - - for used in usedItems: - element = [used.itemName, used.quantity, used.cost, used.date] - itemsList.append(element) - - filename = f"Request_id_{requestId}_final_bill.pdf" - - buffer = BytesIO() - - c = canvas.Canvas(buffer, pagesize=letter) - - c.setFont("Helvetica", 12) - - y_position = 750 - - rid = f"Request Id : {requestId}" - agency = f"Agency : {workOrder.agency}" - - c.drawString(100, y_position, rid) - y_position -= 20 - - c.drawString(100, y_position, agency) - y_position -= 20 - - c.drawString(100, y_position - 40, "Items:") - - data = [["Item Name", "Quantity", "Cost (in Rupees)", "Date of Purchase", "Total Amount"]] - for item in itemsList: - data.append([item[0], str(item[1]), "{:.2f}".format(item[2]), item[3], "{:.2f}".format(item[1] * item[2])]) - - total_amount_to_be_paid = sum(item[1] * item[2] for item in itemsList) - - c.drawString(100, y_position - 80, f"Total Amount (in Rupees): {total_amount_to_be_paid:.2f}") - - table = Table(data) - table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey), - ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), - ('ALIGN', (0, 0), (-1, -1), 'CENTER'), - ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), - ('BOTTOMPADDING', (0, 0), (-1, 0), 12), - ('BACKGROUND', (0, 1), (-1, -1), colors.beige), - ('GRID', (0, 0), (-1, -1), 1, colors.black)])) - - table.wrapOn(c, 400, 600) - table.drawOn(c, 100, y_position - 60) - - c.save() - - buffer.seek(0) - - response = HttpResponse(content_type='application/pdf') - response['Content-Disposition'] = f'attachment; filename="{filename}"' - response.write(buffer.getvalue()) - - return response - -@login_required -def handleBillGeneratedRequests(request): - if request.method == 'POST': - requestId = request.POST.get("id", 0) - Requests.objects.filter(id=requestId).update(status="Bill Generated", billGenerated=1) - obj = [] - requestsObject = Requests.objects.filter(issuedWorkOrder=1, billGenerated=0) - for x in requestsObject: - element = [x.id, x.name, x.area, x.description, x.requestCreatedBy, x.workCompleted] - obj.append(element) - return render(request, 'iwdModuleV2/requestsInProgress.html', {'obj' : obj}) - -@login_required -def generatedBillsView(request): - request_object = Requests.objects.filter(billGenerated=1, billProcessed=0) - obj = [] - for x in request_object: - element = [x.id, x.name, x.description, x.area, x.requestCreatedBy] - obj.append(element) - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - for x in designations_list: - if d.name == x: - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/generatedBillsRequestsView.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def handleProcessedBills(request): - if request.method == 'POST': - requestId = request.POST.get("id", 0) - request_instance = Requests.objects.get(pk=requestId) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(requestId), - file_extra_JSON= {"value": 2}, - attached_file = request.FILES['bill']) - - formObject = Bills() - formObject.request_id = request_instance - formObject.file = request.FILES['bill'] - formObject.save() - - Requests.objects.filter(id=requestId).update(status="Final Bill Processed", billProcessed=1) - - request_object = Requests.objects.filter(billGenerated=1, billProcessed=0) - obj = [] - for x in request_object: - element = [x.id, x.name, x.description, x.area, x.requestCreatedBy] - obj.append(element) - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - - return render(request, 'iwdModuleV2/dashboard.html', {'obj' : obj, 'eligible': eligible}) - -@login_required -def auditDocumentView(request): - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - obj = [] - - for x in inbox_files: - requestId = x['src_object_id'] - files = Bills.objects.get(request_id=requestId) - element = [files.request_id.id, files.file, files.file.url] - obj.append(element) - - designations = Designation.objects.filter() - - holdsDesignations = [] - - for d in designations: - if d.name == "Engineer" or d.name == "Dean" or d.name == "Director" or d.name == "Accounts Admin" or d.name == "Admin IWD": - list = HoldsDesignation.objects.filter(designation=d) - holdsDesignations.append(list) - - return render(request, 'iwdModuleV2/auditDocumentView.html', {'obj' : obj, 'holdsDesignations' : holdsDesignations}) - -@login_required -def auditDocument(request): - if request.method == 'POST': - requestId = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.POST['designation']) - d1 = HoldsDesignation.objects.get(user__username=request.user) - - create_file(uploader=request.user.username, - uploader_designation=d1.designation, - receiver=request.POST['designation'], - receiver_designation=d.designation, - src_module="IWD", - src_object_id= str(requestId), - file_extra_JSON= {"value": 2}, - attached_file = None) - - inbox_files = view_inbox( - username=request.user, - designation=d1.designation, - src_module="IWD" - ) - - for result in inbox_files: - print(result['src_object_id']) - if result['src_object_id'] == requestId: - delete_file(file_id = result['id']) - break - - Requests.objects.filter(id=requestId).update(status="Bill Audited") - - eligible = "" - userObj = request.user - userDesignationObjects = HoldsDesignation.objects.filter(user=userObj) - for p in userDesignationObjects: - eligible = p.designation.name - - return render(request, 'iwdModuleV2/dashboard.html', {'eligible' : eligible}) - -@login_required -def settleBillsView(request): - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - obj = [] - - for x in inbox_files: - requestId = x['src_object_id'] - bills_object = Bills.objects.filter(request_id=requestId).first() - element = [bills_object.request_id.id, bills_object.file, bills_object.file.url] - obj.append(element) - - return render(request, 'iwdModuleV2/settleBillsView.html', {'obj' : obj}) - -@login_required -def handleSettleBillRequests(request): - if request.method == 'POST': - request_id = request.POST.get("id", 0) - - d = HoldsDesignation.objects.get(user__username=request.user) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - for p in inbox_files: - if p['src_object_id'] == request_id: - delete_file(file_id = p['id']) - break - - Requests.objects.filter(id=request_id).update(status="Final Bill Settled", billSettled=1) - - inbox_files = view_inbox( - username=request.user, - designation=d.designation, - src_module="IWD" - ) - - obj = [] - - for x in inbox_files: - request_id = x['src_object_id'] - bills_object = Bills.objects.get(request_id=request_id) - element = [request_id, bills_object.file, bills_object.file.url] - obj.append(element) - - return render(request, 'iwdModuleV2/settleBillsView.html', {'obj' : obj}) - -@login_required -def viewBudget(request): - - budget_object = Budget.objects.filter() - - obj = [] - - for x in budget_object: - element = [x.id, x.name, x.budgetIssued] - obj.append(element) - - return render(request, 'iwdModuleV2/viewBudget.html', {'obj' : obj}) - -@login_required -def budget(request): - budget_object = Budget.objects.filter() - - obj = [] - - for x in budget_object: - element = [x.id, x.name, x.budgetIssued] - obj.append(element) - - return render(request, 'iwdModuleV2/budget.html', {'obj' : obj}) - -@login_required -def addBudget(request): - if request.method == 'POST': - formObject = Budget() - formObject.name = request.POST['name'] - formObject.budgetIssued = request.POST['budget'] - formObject.save() - return render(request, 'iwdModuleV2/addBudget.html', {}) - -@login_required -def editBudgetView(request): - budget_object = Budget.objects.filter() - - obj = [] - - for x in budget_object: - element = [x.id, x.name, x.budgetIssued] - obj.append(element) - - return render(request, 'iwdModuleV2/editBudget.html', {'obj' : obj}) - -@login_required -def editBudget(request): - if request.method == "POST": - budgetId = request.POST['id'] - budgetName = request.POST['name'] - budgetIssued = request.POST['budget'] - Budget.objects.filter(id=budgetId).update(name=budgetName, budgetIssued=budgetIssued) - items = Budget.objects.filter() - obj = [] - for i in items: - element = [i.id, i.name, i.budgetIssued] - obj.append(element) - return render(request, 'iwdModuleV2/editBudget.html', {'obj' : obj}) - - diff --git a/FusionIIIT/applications/leave/migrations/0001_initial.py b/FusionIIIT/applications/leave/migrations/0001_initial.py index b6fa10f0c..d9ce4e044 100644 --- a/FusionIIIT/applications/leave/migrations/0001_initial.py +++ b/FusionIIIT/applications/leave/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models diff --git a/FusionIIIT/applications/notifications_extension/api/serializers.py b/FusionIIIT/applications/notifications_extension/api/serializers.py deleted file mode 100644 index 899c50e57..000000000 --- a/FusionIIIT/applications/notifications_extension/api/serializers.py +++ /dev/null @@ -1,6 +0,0 @@ -from rest_framework import serializers -from notifications.models import Notification -class NotificationSerializer(serializers.ModelSerializer): - class Meta: - model = Notification - fields = '__all__' \ No newline at end of file diff --git a/FusionIIIT/applications/notifications_extension/api/urls.py b/FusionIIIT/applications/notifications_extension/api/urls.py deleted file mode 100644 index 62238c007..000000000 --- a/FusionIIIT/applications/notifications_extension/api/urls.py +++ /dev/null @@ -1,53 +0,0 @@ -# urls.py -from django.urls import path -from .views import ( - LeaveModuleNotificationAPIView, - PlacementCellNotificationAPIView, - AcademicsModuleNotificationAPIView, - OfficeModuleNotificationAPIView, - CentralMessNotificationAPIView, - VisitorsHostelNotificationAPIView, - HealthcareCenterNotificationAPIView, - FileTrackingNotificationAPIView, - ScholarshipPortalNotificationAPIView, - ComplaintSystemNotificationAPIView, - OfficeDeanPnDNotificationAPIView, - OfficeDeanSNotificationAPIView, - GymkhanaVotingNotificationAPIView, - GymkhanaSessionNotificationAPIView, - GymkhanaEventNotificationAPIView, - AssistantshipClaimNotificationAPIView, - DepartmentNotificationAPIView, - OfficeDeanRSPCNotificationAPIView, - ResearchProceduresNotificationAPIView, - HostelModuleNotificationAPIView, - MarkAsRead, - Delete, - NotificationsList, -) - -urlpatterns = [ - path('notifications/', NotificationsList.as_view(), name='notifications' ), - path('delete/', Delete.as_view(),name='delete'), - path('mark_as_read/', MarkAsRead.as_view(),name='mark_as_read'), - path('leave_module_notification/', LeaveModuleNotificationAPIView.as_view(), name='leave_module_notification'), - path('placement_cell_notification/', PlacementCellNotificationAPIView.as_view(), name='placement_cell_notification'), - path('academics_module_notification/', AcademicsModuleNotificationAPIView.as_view(), name='academics_module_notification'), - path('office_module_notification/', OfficeModuleNotificationAPIView.as_view(), name='office_module_notification'), - path('central_mess_notification/', CentralMessNotificationAPIView.as_view(), name='central_mess_notification'), - path('visitors_hostel_notification/', VisitorsHostelNotificationAPIView.as_view(), name='visitors_hostel_notification'), - path('healthcare_center_notification/', HealthcareCenterNotificationAPIView.as_view(), name='healthcare_center_notification'), - path('file_tracking_notification/', FileTrackingNotificationAPIView.as_view(), name='file_tracking_notification'), - path('scholarship_portal_notification/', ScholarshipPortalNotificationAPIView.as_view(), name='scholarship_portal_notification'), - path('complaint_system_notification/', ComplaintSystemNotificationAPIView.as_view(), name='complaint_system_notification'), - path('office_dean_PnD_notification/', OfficeDeanPnDNotificationAPIView.as_view(), name='office_dean_PnD_notification'), - path('office_dean_S_notification/', OfficeDeanSNotificationAPIView.as_view(), name='office_dean_S_notification'), - path('gymkhana_voting/', GymkhanaVotingNotificationAPIView.as_view(), name='gymkhana_voting'), - path('gymkhana_session/', GymkhanaSessionNotificationAPIView.as_view(), name='gymkhana_session'), - path('gymkhana_event/', GymkhanaEventNotificationAPIView.as_view(), name='gymkhana_event'), - path('assistantship_claim/', AssistantshipClaimNotificationAPIView.as_view(), name='assistantship_claim'), - path('department_notification/', DepartmentNotificationAPIView.as_view(), name='department_notification'), - path('office_dean_RSPC_notification/', OfficeDeanRSPCNotificationAPIView.as_view(), name='office_dean_RSPC_notification'), - path('research_procedures_notification/', ResearchProceduresNotificationAPIView.as_view(), name='research_procedures_notification'), - path('hostel_notifications/', HostelModuleNotificationAPIView.as_view(), name='hostel_notifications'), -] diff --git a/FusionIIIT/applications/notifications_extension/api/views.py b/FusionIIIT/applications/notifications_extension/api/views.py deleted file mode 100644 index c5017f79f..000000000 --- a/FusionIIIT/applications/notifications_extension/api/views.py +++ /dev/null @@ -1,371 +0,0 @@ -# views.py -from rest_framework.views import APIView -from django.contrib.auth import get_user_model -from rest_framework.response import Response -from notifications.utils import slug2id -from django.shortcuts import get_object_or_404 -from rest_framework.generics import ListAPIView -from notifications.models import Notification -from rest_framework import status -from .serializers import NotificationSerializer -from notification.views import (leave_module_notif, - placement_cell_notif, - academics_module_notif, - office_module_notif, - central_mess_notif, - visitors_hostel_notif, - healthcare_center_notif, - file_tracking_notif, - scholarship_portal_notif, - complaint_system_notif, - office_dean_PnD_notif, - office_module_DeanS_notif, - gymkhana_voting, - gymkhana_session, - gymkhana_event, - AssistantshipClaim_notify, - AssistantshipClaim_faculty_notify, - AssistantshipClaim_acad_notify, - AssistantshipClaim_account_notify, - department_notif, - office_module_DeanRSPC_notif, - research_procedures_notif, - hostel_notifications) - - - -class LeaveModuleNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - date = request.data.get('date') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - leave_module_notif(sender, recipient, type, date) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class PlacementCellNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - placement_cell_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class AcademicsModuleNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - academics_module_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class OfficeModuleNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - office_module_notif(sender, recipient) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) -class CentralMessNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - message = request.data.get('message') - - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - - # Trigger the notification function - central_mess_notif(sender, recipient, type, message) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class VisitorsHostelNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - visitors_hostel_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class HealthcareCenterNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - - # Trigger the notification function - healthcare_center_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class FileTrackingNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - title = request.data.get('title') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - file_tracking_notif(sender, recipient, title) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) -class ScholarshipPortalNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - scholarship_portal_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class ComplaintSystemNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - complaint_id = request.data.get('complaint_id') - student = request.data.get('student') - message = request.data.get('message') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - complaint_system_notif(sender, recipient, type, complaint_id, student, message) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class OfficeDeanPnDNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - office_dean_PnD_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class OfficeDeanSNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - office_module_DeanS_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class GymkhanaVotingNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - title = request.data.get('title') - desc = request.data.get('desc') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - gymkhana_voting(sender, recipient, type, title, desc) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class GymkhanaSessionNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - club = request.data.get('club') - desc = request.data.get('desc') - venue = request.data.get('venue') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - gymkhana_session(sender, recipient, type, club, desc, venue) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class GymkhanaEventNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - club = request.data.get('club') - event_name = request.data.get('event_name') - desc = request.data.get('desc') - venue = request.data.get('venue') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - gymkhana_event(sender, recipient, type, club, event_name, desc, venue) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class AssistantshipClaimNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - month = request.data.get('month') - year = request.data.get('year') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - AssistantshipClaim_notify(sender, recipient, month, year) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) -class AssistantshipClaimFacultyNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - AssistantshipClaim_faculty_notify(sender, recipient) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class AssistantshipClaimAcadNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - AssistantshipClaim_acad_notify(sender, recipient) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class AssistantshipClaimAccountNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - stu = request.data.get('stu') - recipient_id = request.data.get('recipient') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - AssistantshipClaim_account_notify(sender, stu, recipient) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class DepartmentNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - department_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) -class OfficeDeanRSPCNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - office_module_DeanRSPC_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class ResearchProceduresNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - research_procedures_notif(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class HostelModuleNotificationAPIView(APIView): - def post(self, request, *args, **kwargs): - # Extract data from the request, you can customize this based on your needs - sender = request.user - recipient_id = request.data.get('recipient') - type = request.data.get('type') - User = get_user_model() - recipient = User.objects.get(pk=recipient_id) - # Trigger the notification function - hostel_notifications(sender, recipient, type) - - return Response({'message': 'Notification sent successfully'}, status=status.HTTP_201_CREATED) - -class MarkAsRead(APIView): - - def put(self,request,**args): - notification_id = self.request.query_params.get('id') - notification = get_object_or_404( - Notification, recipient=request.user, id=notification_id) - - notification.mark_as_read() - - return Response({'message': "Successfully marked as read"}, status=status.HTTP_200_OK) - -class Delete(APIView): - - def delete(self,request, **args): - notification_id = self.request.query_params.get('id') - notification = get_object_or_404( - Notification, recipient=request.user, id=notification_id) - - notification.delete() - - return Response({'message': "Notification deleted succesfully"}, status=status.HTTP_200_OK) - -class NotificationsList(ListAPIView): - # queryset = Notification.objects.all(actor_object_id=) - serializer_class = NotificationSerializer - def get_queryset(self): - return Notification.objects.all().filter(recipient_id=self.request.user.id) \ No newline at end of file diff --git a/FusionIIIT/applications/notifications_extension/urls.py b/FusionIIIT/applications/notifications_extension/urls.py index b5690994b..c5b2da49d 100644 --- a/FusionIIIT/applications/notifications_extension/urls.py +++ b/FusionIIIT/applications/notifications_extension/urls.py @@ -4,12 +4,8 @@ from django.conf.urls import include, url from . import views -# from .api import urls - app_name = 'notifications' urlpatterns = [ pattern(r'^mark-as-read-and-redirect/(?P\d+)/$', views.mark_as_read_and_redirect, name='mark_as_read_and_redirect'), - pattern(r'^delete/(?P\d+)/$', views.delete, name='delete'), - url(r'^api/',include('applications.notifications_extension.api.urls')), ] + urlpatterns diff --git a/FusionIIIT/applications/notifications_extension/views.py b/FusionIIIT/applications/notifications_extension/views.py index a41c99af7..ca1e40bf8 100644 --- a/FusionIIIT/applications/notifications_extension/views.py +++ b/FusionIIIT/applications/notifications_extension/views.py @@ -3,16 +3,8 @@ from notifications.utils import id2slug, slug2id from django.shortcuts import get_object_or_404, redirect from notifications.models import Notification -import Fusion.settings as FusionIIIT_settings -def delete(request, slug=None): - notification_id = slug2id(slug) - notification = get_object_or_404( - Notification, recipient=request.user, id=notification_id) - notification.delete() - previous_page = request.META.get('HTTP_REFERER', '/') - # Redirect to the previous page or the home page if the referrer is not available - return HttpResponseRedirect(previous_page) - # return HttpResponseRedirect('dashboard/') + + def mark_as_read_and_redirect(request, slug=None): notification_id = slug2id(slug) notification = get_object_or_404( @@ -21,10 +13,9 @@ def mark_as_read_and_redirect(request, slug=None): # This conditional statement is True only in # case of complaint_module. - # return redirect('notifications:all') - - if(notification.data['module'] == 'Complaint System'): - complaint_id=notification.description - return HttpResponseRedirect(reverse(notification.data['url'],kwargs={'detailcomp_id1':complaint_id})) + print(notification.data['url']) + if (notification.data['module'] == 'Complaint System'): + complaint_id = notification.description + return HttpResponseRedirect(reverse(notification.data['url'], kwargs={'detailcomp_id1': complaint_id})) else: return HttpResponseRedirect(reverse(notification.data['url'])) diff --git a/FusionIIIT/applications/office_module/migrations/0001_initial.py b/FusionIIIT/applications/office_module/migrations/0001_initial.py index c488a504c..521c8e886 100644 --- a/FusionIIIT/applications/office_module/migrations/0001_initial.py +++ b/FusionIIIT/applications/office_module/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models @@ -10,10 +10,10 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('filetracking', '0001_initial'), - ('globals', '0001_initial'), ('academic_information', '0001_initial'), + ('filetracking', '0001_initial'), ('leave', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ diff --git a/FusionIIIT/applications/online_cms/migrations/0001_initial.py b/FusionIIIT/applications/online_cms/migrations/0001_initial.py index 2990b152b..4e3377ab7 100644 --- a/FusionIIIT/applications/online_cms/migrations/0001_initial.py +++ b/FusionIIIT/applications/online_cms/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion @@ -9,8 +9,8 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('globals', '0001_initial'), ('academic_information', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ diff --git a/FusionIIIT/applications/online_cms/migrations/0002_student_grades.py b/FusionIIIT/applications/online_cms/migrations/0002_student_grades.py new file mode 100644 index 000000000..e81789975 --- /dev/null +++ b/FusionIIIT/applications/online_cms/migrations/0002_student_grades.py @@ -0,0 +1,28 @@ +# Generated by Django 3.1.5 on 2024-04-20 19:25 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('academic_information', '0001_initial'), + ('online_cms', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Student_grades', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('semester', models.IntegerField(default=1)), + ('year', models.IntegerField(default=2016)), + ('roll_no', models.TextField(max_length=2000)), + ('total_marks', models.DecimalField(decimal_places=2, default=0, max_digits=10)), + ('grade', models.TextField(max_length=2000)), + ('batch', models.TextField(max_length=2000)), + ('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.course')), + ], + ), + ] diff --git a/FusionIIIT/applications/online_cms/models.py b/FusionIIIT/applications/online_cms/models.py index f9bfdd6b5..dec5422fb 100644 --- a/FusionIIIT/applications/online_cms/models.py +++ b/FusionIIIT/applications/online_cms/models.py @@ -206,7 +206,7 @@ def __str__(self): class Student_grades(models.Model): course_id = models.ForeignKey(Course, on_delete=models.CASCADE) - semester = models.DecimalField(max_digits=10, decimal_places=2, default=0) + semester = models.IntegerField(default=1) year = models.IntegerField(default=2016) roll_no = models.TextField(max_length=2000) total_marks = models.DecimalField(max_digits=10, decimal_places=2, default=0) diff --git a/FusionIIIT/applications/placement_cell/forms.py b/FusionIIIT/applications/placement_cell/forms.py index aea81b795..54fb122ba 100644 --- a/FusionIIIT/applications/placement_cell/forms.py +++ b/FusionIIIT/applications/placement_cell/forms.py @@ -410,7 +410,7 @@ class SendInvite(forms.Form): company - name of company """ company = forms.ModelChoiceField(required=True, queryset=NotifyStudent.objects.all(), label="company") - rollno = forms.CharField(label="rollno", widget=forms.TextInput(attrs={'min': 0}), required=False) + rollno = forms.IntegerField(label="rollno", widget=forms.NumberInput(attrs={'min': 0}), required=False) programme = forms.ChoiceField(choices = Con.PROGRAMME, required=False, label="programme", widget=forms.Select(attrs={'style': "height:45px", 'onchange': "changeDeptForSend()", @@ -483,7 +483,6 @@ def clean_company_name(self): return company_name - def current_year(): return date.today().year @@ -546,87 +545,6 @@ class SearchPbiRecord(forms.Form): label="cname", required=False) - -class SendInvitation(forms.Form): - """ - The form is used to send invite to students about upcoming placement or pbi events. - @variables: - company - name of company - """ - company = forms.ModelChoiceField(required=True, queryset=NotifyStudent.objects.all(), label="company") - rollno = forms.IntegerField(label="rollno", widget=forms.NumberInput(attrs={'min': 0}), required=False) - programme = forms.ChoiceField(choices = Con.PROGRAMME, required=False, - label="programme", widget=forms.Select(attrs={'style': "height:45px", - 'onchange': "changeDeptForSend()", - 'id': "id_programme_send"})) - - dep_btech = forms.MultipleChoiceField(choices = Constants.BTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_bdes = forms.MultipleChoiceField(choices = Constants.BDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mtech = forms.MultipleChoiceField(choices = Constants.MTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mdes = forms.MultipleChoiceField(choices = Constants.MDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_phd = forms.MultipleChoiceField(choices = Constants.PHD_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - cpi = forms.DecimalField(label="cpi", required=False) - no_of_days = forms.CharField(required=True, widget=forms.NumberInput(attrs={ 'min':0, - 'max':30, - 'max_length': 10, - 'class': 'form-control'})) - - -class AddPlacementSchedule(forms.Form): - """ - The form is used to placement or pbi schedule. - @variables: - time - time of placement activity - ctc - salary - company_name - name of company - placement_type - placement type (placement/pbi) - location - location of company - description - description of company - placement_date - date of placement activity - """ - time = forms.TimeField(label='time', widget=forms.widgets.TimeInput(attrs={'type': "time", - 'value':"00:00", - 'min':"0:00", - 'max':"24:00"})) - ctc = forms.DecimalField(label="ctc", widget=forms.NumberInput(attrs={ 'min':0, 'step': 0.25}) ) - company_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'list': 'company_dropdown1', - 'id': 'company_input'}), - label="company_name") - placement_type = forms.ChoiceField(widget=forms.Select(attrs={'style': "height:45px"}), label="placement_type", - choices=Constants.PLACEMENT_TYPE) - location = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="location") - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - attached_file = forms.FileField(required=False) - placement_date = forms.DateField(label='placement_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean_ctc(self): - ctc = self.cleaned_data['ctc'] - # print('form validation \n\n\n\n', ctc) - if ctc <= 0: - raise forms.ValidationError("CTC must be positive value") - - return ctc - - def clean_company_name(self): - company_name = self.cleaned_data['company_name'] - # print('form validation \n\n\n\n', ctc) - if NotifyStudent.objects.filter(company_name=company_name): - raise forms.ValidationError("company_name must be unique") - - return company_name - - class SearchHigherRecord(forms.Form): """ The form is used to search from higher study record based on various parameters . @@ -671,7 +589,7 @@ class ManagePlacementRecord(forms.Form): stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, 'class': 'field'}), label="stuname", required=False) - roll = forms.CharField(widget=forms.TextInput(attrs={ 'min':0, + roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, 'max_length': 10, 'class': 'form-control'}), label="roll", required=False) diff --git a/FusionIIIT/applications/placement_cell/migrations/0001_initial.py b/FusionIIIT/applications/placement_cell/migrations/0001_initial.py index 95f070aef..257c98609 100644 --- a/FusionIIIT/applications/placement_cell/migrations/0001_initial.py +++ b/FusionIIIT/applications/placement_cell/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models diff --git a/FusionIIIT/applications/placement_cell/models.py b/FusionIIIT/applications/placement_cell/models.py index 53f8d8ea4..d9837608e 100644 --- a/FusionIIIT/applications/placement_cell/models.py +++ b/FusionIIIT/applications/placement_cell/models.py @@ -1,4 +1,6 @@ +# imports import datetime + from django.db import models from django.utils import timezone from django.utils.translation import gettext as _ @@ -54,7 +56,6 @@ class Constants: ('CSE', 'CSE'), ('ME','ME'), ('ECE','ECE'), - ('SM','SM'), ) BDES_DEP = ( diff --git a/FusionIIIT/applications/placement_cell/urls.py b/FusionIIIT/applications/placement_cell/urls.py index 190638861..9f3e77307 100644 --- a/FusionIIIT/applications/placement_cell/urls.py +++ b/FusionIIIT/applications/placement_cell/urls.py @@ -13,7 +13,6 @@ url(r'^student_records/$', views.student_records, name='student_records'), url(r'^manage_records/$', views.manage_records, name='manage_records'), url(r'^statistics/$', views.placement_statistics, name='placement_statistics'), - url(r'^delete_placement_statistics/$', views.delete_placement_statistics, name='delete_placement_statistics'), url(r'^cv/(?P[a-zA-Z0-9\.]{1,20})/$', views.cv, name="cv"), diff --git a/FusionIIIT/applications/placement_cell/views.py b/FusionIIIT/applications/placement_cell/views.py index 25ecadebd..80c8f12d7 100644 --- a/FusionIIIT/applications/placement_cell/views.py +++ b/FusionIIIT/applications/placement_cell/views.py @@ -29,7 +29,6 @@ from notification.views import placement_cell_notif from applications.globals.models import (DepartmentInfo, ExtraInfo, HoldsDesignation) -from applications.academic_information.models import Student from .forms import (AddAchievement, AddChairmanVisit, AddCourse, AddEducation, AddExperience, AddReference, AddPatent, AddProfile, AddProject, AddPublication, AddSchedule, AddSkill, ManageHigherRecord, @@ -144,2804 +143,92 @@ ''' logger = logging.getLogger('django.server') -@login_required -def placement__Statistics(request): - ''' - logic of the view shown under Placement Statistics tab - ''' - user = request.user - - - statistics_tab = 1 - strecord_tab=1 - delete_operation = 0 - pagination_placement = 0 - pagination_pbi = 0 - pagination_higher = 0 - is_disabled = 0 - paginator = '' - page_range = '' - officer_statistics_past_pbi_search = 0 - officer_statistics_past_higher_search = 0 - - profile = get_object_or_404(ExtraInfo, Q(user=user)) - studentrecord = StudentRecord.objects.select_related('unique_id','record_id').all() - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) +def get_reference_list(request): + if request.method == 'POST': + # arr = request.POST.getlist('arr[]') + # print(arr) + # print(type(arr)) + user = request.user + profile = get_object_or_404(ExtraInfo, Q(user=user)) + student = get_object_or_404(Student, Q(id=profile.id)) + print(student) + reference_objects = Reference.select_related('unique_id').objects.filter(unique_id=student) + reference_objects = serializers.serialize('json', list(reference_objects)) + context = { + 'reference_objs': reference_objects + } + return JsonResponse(context) +# Ajax for the company name dropdown for CompanyName when filling AddSchedule +def company_name_dropdown(request): + if request.method == 'POST': + current_value = request.POST.get('current_value') + company_names = CompanyDetails.objects.filter(Q(company_name__startswith=current_value)) + company_name = [] + for name in company_names: + company_name.append(name.company_name) - #working here to fetch all placement record - all_records=PlacementRecord.objects.all() - print(all_records) + context = { + 'company_names': company_name + } + return JsonResponse(context) +# Ajax for all the roles in the dropdown +def checking_roles(request): + if request.method == 'POST': + current_value = request.POST.get('current_value') + all_roles = Role.objects.filter(Q(role__startswith=current_value)) + role_name = [] + for role in all_roles: + role_name.append(role.role) + return JsonResponse({'all_roles': role_name}) +@login_required +def placement(request): + ''' + function include the functionality of first tab of UI + for student, placement officer & placement chairman - invitecheck=0 - for r in records: - r['name__count'] = 0 - r['year__count'] = 0 - r['placement_type__count'] = 0 - tcse = dict() - tece = dict() - tme = dict() - tadd = dict() - for y in years: - tcse[y['year']] = 0 - tece[y['year']] = 0 - tme[y['year']] = 0 - for r in records: - if r['year'] == y['year']: - if r['placement_type'] != "HIGHER STUDIES": - for z in studentrecord: - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "CSE": - tcse[y['year']] = tcse[y['year']]+1 - r['name__count'] = r['name__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ECE": - tece[y['year']] = tece[y['year']]+1 - r['year__count'] = r['year__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ME": - tme[y['year']] = tme[y['year']]+1 - r['placement_type__count'] = r['placement_type__count']+1 - tadd[y['year']] = tcse[y['year']]+tece[y['year']]+tme[y['year']] - y['year__count'] = [tadd[y['year']], tcse[y['year']], tece[y['year']], tme[y['year']]] + placement officer & placement chairman + - can add schedule + - can delete schedule + student + - accepted or declined schedule - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) + ''' + user = request.user + profile = get_object_or_404(ExtraInfo, Q(user=user)) + schedule_tab = 1 + placementstatus = '' + form5 = AddSchedule(initial={}) current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - if len(current1)!=0 or len(current2)!=0: - delete_operation = 1 - if len(current) == 0: - current = None - pbirecord= '' - placementrecord= '' - higherrecord= '' - total_query=0 - total_query1 = 0 - total_query2= 0 - p="" - p1="" - p2="" - placement_search_record=" " - pbi_search_record=" " - higher_search_record=" " - # results of the searched query under placement tab - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - - - - - print("IS VALID") - - - - #for student name - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except Exception as e: - print("Error") - print(e) - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - - - # for student CTC - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - - #for company name - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - - #for student roll - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - #for admission year - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - - - - - """placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name, - id__icontains=rollno)))))))) - #print("In if:", placementrecord) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) - print("Agein p:",p) - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno))))))) - - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - print(p) - - - total_query = p.count() + # If the user is Student + if current: + student = get_object_or_404(Student, Q(id=profile.id)) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except Exception as e: - print(e) - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - no_records=1 - print(placementrecord) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - if total_query!=0: - placement_search_record=p - # results of the searched query under pbi tab - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - p1 = PlacementRecord.objects.filter( - Q(placement_type="PBI", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - """else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] -""" - total_query1 = p1.count() - - if total_query1 > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query1 > 30 and total_query1 <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - if total_query1!=0: - pbi_search_record=p1 - - # results of the searched query under higher studies tab - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - # getting all the variables send through form - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - # result of the query when year is given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - - p2 = PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", name__icontains=stuname, year__icontains=year)) - - """else: - # result of the query when year is not given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - total_query2 = p2.count() - - if total_query2 > 30: - pagination_higher = 1 - paginator = Paginator(p2, 30) - page = request.GET.get('page', 1) - p2 = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query2 > 30 and total_query2 <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - except: - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - if total_query2!=0: - higher_search_record=p2 - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - - - 'all_records': all_records, #for flashing all placement Schedule - - 'placement_search_record': placement_search_record, - 'pbi_search_record': pbi_search_record, - 'higher_search_record': higher_search_record, - - - - 'statistics_tab' : statistics_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'delete_operation' : delete_operation, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/placementstatistics.html', context) - - - -def get_reference_list(request): - if request.method == 'POST': - # arr = request.POST.getlist('arr[]') - # print(arr) - # print(type(arr)) - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - student = get_object_or_404(Student, Q(id=profile.id)) - print(student) - reference_objects = Reference.select_related('unique_id').objects.filter(unique_id=student) - reference_objects = serializers.serialize('json', list(reference_objects)) - - context = { - 'reference_objs': reference_objects - } - return JsonResponse(context) - - -# Ajax for the company name dropdown for CompanyName when filling AddSchedule -def company_name_dropdown(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - company_names = CompanyDetails.objects.filter(Q(company_name__startswith=current_value)) - company_name = [] - for name in company_names: - company_name.append(name.company_name) - - context = { - 'company_names': company_name - } - - return JsonResponse(context) - - -# Ajax for all the roles in the dropdown -def checking_roles(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - all_roles = Role.objects.filter(Q(role__startswith=current_value)) - role_name = [] - for role in all_roles: - role_name.append(role.role) - return JsonResponse({'all_roles': role_name}) - -@login_required -def Placement__Schedule(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) - - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.select_related('unique_id').create( - unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() - if 'profilesubmit' in request.POST: - about_me = request.POST.get('about') - age = request.POST.get('age') - address = request.POST.get('address') - contact = request.POST.get('contact') - pic = request.POST.get('pic') - # futu = request.POST.get('futu') - # print(studentplacement_obj.future_aspect) - # print('fut=', fut) - # print('futu=', futu) - # if studentplacement_obj.future_aspect == "HIGHER STUDIES": - # if futu == 2: - # studentplacement_obj.future_aspect = "PLACEMENT" - # elif studentplacement_obj.future_aspect == "PLACEMENT": - # if futu == None: - # studentplacement_obj.future_aspect = "HIGHER STUDIES" - extrainfo_obj = ExtraInfo.objects.get(user=user) - extrainfo_obj.about_me = about_me - extrainfo_obj.age = age - extrainfo_obj.address = address - extrainfo_obj.phone_no = contact - extrainfo_obj.profile_picture = pic - extrainfo_obj.save() - profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - has_obj = Has.objects.select_related('skill_id','unique_id').create(unique_id=student, - skill_id=Skill.objects.get(skill=skill), - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.select_related('unique_id').create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.select_related('unique_id').create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.select_related('unique_id').create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.select_related('unique_id').create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.select_related('unique_id').create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.get(Q(pk=hid)) - hs.delete() - - placementschedule = PlacementSchedule.objects.select_related('notify_id').filter( - Q(placement_date__gte=date.today())).values_list('notify_id', flat=True) - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(unique_id=student, - notify_id__in=placementschedule)).order_by('-timestamp') - - - check_invitation_date(placementstatus) - - # facult and other staff view only statistics - if not (current or current1 or current2): - return redirect('/placement/statistics/') - - # delete the schedule - if 'deletesch' in request.POST: - delete_sch_key = request.POST['delete_sch_key'] - try: - placement_schedule = PlacementSchedule.objects.select_related('notify_id').get(pk = delete_sch_key) - NotifyStudent.objects.get(pk=placement_schedule.notify_id.id).delete() - placement_schedule.delete() - messages.success(request, 'Schedule Deleted Successfully') - except Exception as e: - messages.error(request, 'Problem Occurred for Schedule Delete!!!') - - # saving all the schedule details - if 'schedulesubmit' in request.POST: - form5 = AddSchedule(request.POST, request.FILES) - if form5.is_valid(): - company_name = form5.cleaned_data['company_name'] - placement_date = form5.cleaned_data['placement_date'] - location = form5.cleaned_data['location'] - ctc = form5.cleaned_data['ctc'] - time = form5.cleaned_data['time'] - attached_file = form5.cleaned_data['attached_file'] - placement_type = form5.cleaned_data['placement_type'] - role_offered = request.POST.get('role') - description = form5.cleaned_data['description'] - - try: - comp_name = CompanyDetails.objects.filter(company_name=company_name)[0] - except: - CompanyDetails.objects.create(company_name=company_name) - - try: - role = Role.objects.filter(role=role_offered)[0] - except: - role = Role.objects.create(role=role_offered) - role.save() - - - notify = NotifyStudent.objects.create(placement_type=placement_type, - company_name=company_name, - description=description, - ctc=ctc, - timestamp=timezone.now()) - - schedule = PlacementSchedule.objects.select_related('notify_id').create(notify_id=notify, - title=company_name, - description=description, - placement_date=placement_date, - attached_file = attached_file, - role=role, - location=location, time=time) - - notify.save() - schedule.save() - messages.success(request, "Schedule Added Successfull!!") - - - schedules = PlacementSchedule.objects.select_related('notify_id').all() - - - context = { - 'current': current, - 'current1': current1, - 'current2': current2, - 'schedule_tab': schedule_tab, - 'schedules': schedules, - 'placementstatus': placementstatus, - 'form5': form5, - } - - return render(request, 'placementModule/placement.html', context) - - - -def invite_status(request): - ''' - function to check the invitation status - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus_placement = [] - placementstatus_pbi = [] - mnplacement_tab = 1 - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - placement_get_request = False - pbi_get_request = False - - # invitation status for placement - if 'studentplacementsearchsubmit' in request.POST: - mnplacement_post = 1 - mnpbi_post = 0 - form = ManagePlacementRecord(request.POST) - - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - request.session['mn_stuname'] = stuname - request.session['mn_ctc'] = ctc - request.session['mn_cname'] = cname - request.session['mn_rollno'] = rollno - - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - # pagination stuff starts from here - total_query = placementstatus_placement.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request from pagination with some page number - if request.GET.get('placement_page') != None: - mnplacement_post = 1 - mnpbi_post = 0 - no_pagination = 1 - try: - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=request.session['mn_cname'], - ctc__gte=request.session['mn_ctc'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['mn_stuname'])), - id__icontains=request.session['mn_rollno'])) - ))))) - except: - placementstatus_placement = [] - - if placementstatus_placement != '': - total_query = placementstatus_placement.count() - else: - total_query = 0 - - if total_query > 30: - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('placement_page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - # invitation status for pbi - if 'studentpbisearchsubmit' in request.POST: - mnpbi_tab = 1 - mnpbi_post = 1 - mnplacement_post = 0 - form = ManagePbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - request.session['mn_pbi_stuname'] = stuname - request.session['mn_pbi_ctc'] = ctc - request.session['mn_pbi_cname'] = cname - request.session['mn_pbi_rollno'] = rollno - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - total_query = placementstatus_pbi.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - if request.GET.get('pbi_page') != None: - mnpbi_tab = 1 - mnpbi_post = 1 - no_pagination = 1 - try: - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=request.session['mn_pbi_cname'], - ctc__gte=request.session['mn_pbi_ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['mn_pbi_stuname'])), - id__icontains=request.session['mn_pbi_rollno'])) - ))))) - except: - placementstatus_pbi = '' - - if placementstatus_pbi != '': - total_query = placementstatus_pbi.count() - else: - total_query = 0 - if total_query > 30: - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - - if 'pdf_gen_invitation_status' in request.POST: - - placementstatus = None - if 'pdf_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'pdf_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - return render_to_pdf('placementModule/pdf_invitation_status.html', context) - - if 'excel_gen_invitation_status' in request.POST: - - placementstatus = None - if 'excel_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'excel_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) - - - return export_to_xls_invitation_status(placementstatus) - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'mnplacement_tab': mnplacement_tab, - 'placementstatus_placement': placementstatus_placement, - 'placementstatus_pbi': placementstatus_pbi, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - - - - - - - invitecheck=0 - for r in records: - r['name__count'] = 0 - r['year__count'] = 0 - r['placement_type__count'] = 0 - tcse = dict() - tece = dict() - tme = dict() - tadd = dict() - for y in years: - tcse[y['year']] = 0 - tece[y['year']] = 0 - tme[y['year']] = 0 - for r in records: - if r['year'] == y['year']: - if r['placement_type'] != "HIGHER STUDIES": - for z in studentrecord: - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "CSE": - tcse[y['year']] = tcse[y['year']]+1 - r['name__count'] = r['name__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ECE": - tece[y['year']] = tece[y['year']]+1 - r['year__count'] = r['year__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ME": - tme[y['year']] = tme[y['year']]+1 - r['placement_type__count'] = r['placement_type__count']+1 - tadd[y['year']] = tcse[y['year']]+tece[y['year']]+tme[y['year']] - y['year__count'] = [tadd[y['year']], tcse[y['year']], tece[y['year']], tme[y['year']]] - - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) - - - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - if len(current1)!=0 or len(current2)!=0: - delete_operation = 1 - if len(current) == 0: - current = None - pbirecord= '' - placementrecord= '' - higherrecord= '' - total_query=0 - total_query1 = 0 - total_query2= 0 - p="" - p1="" - p2="" - placement_search_record=" " - pbi_search_record=" " - higher_search_record=" " - # results of the searched query under placement tab - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - - - - - print("IS VALID") - - - - #for student name - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except Exception as e: - print("Error") - print(e) - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - - - # for student CTC - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - - #for company name - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - - #for student roll - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - #for admission year - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - - - - - """placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name, - id__icontains=rollno)))))))) - #print("In if:", placementrecord) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) - print("Agein p:",p) - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno))))))) - - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - print(p) - - - total_query = p.count() - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except Exception as e: - print(e) - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - no_records=1 - print(placementrecord) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - if total_query!=0: - placement_search_record=p - # results of the searched query under pbi tab - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - p1 = PlacementRecord.objects.filter( - Q(placement_type="PBI", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - """else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] -""" - total_query1 = p1.count() - - if total_query1 > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query1 > 30 and total_query1 <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - if total_query1!=0: - pbi_search_record=p1 - - # results of the searched query under higher studies tab - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - # getting all the variables send through form - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - # result of the query when year is given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - - p2 = PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", name__icontains=stuname, year__icontains=year)) - - """else: - # result of the query when year is not given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - total_query2 = p2.count() - - if total_query2 > 30: - pagination_higher = 1 - paginator = Paginator(p2, 30) - page = request.GET.get('page', 1) - p2 = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query2 > 30 and total_query2 <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - except: - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - if total_query2!=0: - higher_search_record=p2 - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - - - 'all_records': all_records, #for flashing all placement Schedule - - 'placement_search_record': placement_search_record, - 'pbi_search_record': pbi_search_record, - 'higher_search_record': higher_search_record, - - - - 'statistics_tab' : statistics_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'delete_operation' : delete_operation, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/placementstatistics.html', context) - - - -def get_reference_list(request): - if request.method == 'POST': - - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - student = get_object_or_404(Student, Q(id=profile.id)) - print(student) - reference_objects = Reference.select_related('unique_id').objects.filter(unique_id=student) - reference_objects = serializers.serialize('json', list(reference_objects)) - - context = { - 'reference_objs': reference_objects - } - return JsonResponse(context) - - -# Ajax for the company name dropdown for CompanyName when filling AddSchedule -def company_name_dropdown(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - company_names = CompanyDetails.objects.filter(Q(company_name__startswith=current_value)) - company_name = [] - for name in company_names: - company_name.append(name.company_name) - - context = { - 'company_names': company_name - } - - return JsonResponse(context) - - -# Ajax for all the roles in the dropdown -def checking_roles(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - all_roles = Role.objects.filter(Q(role__startswith=current_value)) - role_name = [] - for role in all_roles: - role_name.append(role.role) - return JsonResponse({'all_roles': role_name}) - -@login_required -def Placement__Schedule(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) - - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.select_related('unique_id').create( - unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() - if 'profilesubmit' in request.POST: - about_me = request.POST.get('about') - age = request.POST.get('age') - address = request.POST.get('address') - contact = request.POST.get('contact') - pic = request.POST.get('pic') - # futu = request.POST.get('futu') - # print(studentplacement_obj.future_aspect) - # print('fut=', fut) - # print('futu=', futu) - # if studentplacement_obj.future_aspect == "HIGHER STUDIES": - # if futu == 2: - # studentplacement_obj.future_aspect = "PLACEMENT" - # elif studentplacement_obj.future_aspect == "PLACEMENT": - # if futu == None: - # studentplacement_obj.future_aspect = "HIGHER STUDIES" - extrainfo_obj = ExtraInfo.objects.get(user=user) - extrainfo_obj.about_me = about_me - extrainfo_obj.age = age - extrainfo_obj.address = address - extrainfo_obj.phone_no = contact - extrainfo_obj.profile_picture = pic - extrainfo_obj.save() - profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - has_obj = Has.objects.select_related('skill_id','unique_id').create(unique_id=student, - skill_id=Skill.objects.get(skill=skill), - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.select_related('unique_id').create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.select_related('unique_id').create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.select_related('unique_id').create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.select_related('unique_id').create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.select_related('unique_id').create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.get(Q(pk=hid)) - hs.delete() - - placementschedule = PlacementSchedule.objects.select_related('notify_id').filter( - Q(placement_date__gte=date.today())).values_list('notify_id', flat=True) - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(unique_id=student, - notify_id__in=placementschedule)).order_by('-timestamp') - - - check_invitation_date(placementstatus) - - # facult and other staff view only statistics - if not (current or current1 or current2): - return redirect('/placement/statistics/') - - # delete the schedule - if 'deletesch' in request.POST: - delete_sch_key = request.POST['delete_sch_key'] - try: - placement_schedule = PlacementSchedule.objects.select_related('notify_id').get(pk = delete_sch_key) - NotifyStudent.objects.get(pk=placement_schedule.notify_id.id).delete() - placement_schedule.delete() - messages.success(request, 'Schedule Deleted Successfully') - except Exception as e: - messages.error(request, 'Problem Occurred for Schedule Delete!!!') - - # saving all the schedule details - if 'schedulesubmit' in request.POST: - form5 = AddSchedule(request.POST, request.FILES) - if form5.is_valid(): - company_name = form5.cleaned_data['company_name'] - placement_date = form5.cleaned_data['placement_date'] - location = form5.cleaned_data['location'] - ctc = form5.cleaned_data['ctc'] - time = form5.cleaned_data['time'] - attached_file = form5.cleaned_data['attached_file'] - placement_type = form5.cleaned_data['placement_type'] - role_offered = request.POST.get('role') - description = form5.cleaned_data['description'] - - try: - comp_name = CompanyDetails.objects.filter(company_name=company_name)[0] - except: - CompanyDetails.objects.create(company_name=company_name) - - try: - role = Role.objects.filter(role=role_offered)[0] - except: - role = Role.objects.create(role=role_offered) - role.save() - - - notify = NotifyStudent.objects.create(placement_type=placement_type, - company_name=company_name, - description=description, - ctc=ctc, - timestamp=timezone.now()) - - schedule = PlacementSchedule.objects.select_related('notify_id').create(notify_id=notify, - title=company_name, - description=description, - placement_date=placement_date, - attached_file = attached_file, - role=role, - location=location, time=time) - - notify.save() - schedule.save() - messages.success(request, "Schedule Added Successfull!!") - - - schedules = PlacementSchedule.objects.select_related('notify_id').all() - - - context = { - 'current': current, - 'current1': current1, - 'current2': current2, - 'schedule_tab': schedule_tab, - 'schedules': schedules, - 'placementstatus': placementstatus, - 'form5': form5, - } - - return render(request, 'placementModule/placement.html', context) - - - -def invite_status(request): - ''' - function to check the invitation status - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus_placement = [] - placementstatus_pbi = [] - mnplacement_tab = 1 - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - placement_get_request = False - pbi_get_request = False - - # invitation status for placement - if 'studentplacementsearchsubmit' in request.POST: - mnplacement_post = 1 - mnpbi_post = 0 - form = ManagePlacementRecord(request.POST) - - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - request.session['mn_stuname'] = stuname - request.session['mn_ctc'] = ctc - request.session['mn_cname'] = cname - request.session['mn_rollno'] = rollno - - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - # pagination stuff starts from here - total_query = placementstatus_placement.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request from pagination with some page number - if request.GET.get('placement_page') != None: - mnplacement_post = 1 - mnpbi_post = 0 - no_pagination = 1 - try: - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=request.session['mn_cname'], - ctc__gte=request.session['mn_ctc'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['mn_stuname'])), - id__icontains=request.session['mn_rollno'])) - ))))) - except: - placementstatus_placement = [] - - if placementstatus_placement != '': - total_query = placementstatus_placement.count() - else: - total_query = 0 - - if total_query > 30: - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('placement_page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - # invitation status for pbi - if 'studentpbisearchsubmit' in request.POST: - mnpbi_tab = 1 - mnpbi_post = 1 - mnplacement_post = 0 - form = ManagePbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - request.session['mn_pbi_stuname'] = stuname - request.session['mn_pbi_ctc'] = ctc - request.session['mn_pbi_cname'] = cname - request.session['mn_pbi_rollno'] = rollno - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - total_query = placementstatus_pbi.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - if request.GET.get('pbi_page') != None: - mnpbi_tab = 1 - mnpbi_post = 1 - no_pagination = 1 - try: - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=request.session['mn_pbi_cname'], - ctc__gte=request.session['mn_pbi_ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['mn_pbi_stuname'])), - id__icontains=request.session['mn_pbi_rollno'])) - ))))) - except: - placementstatus_pbi = '' - - if placementstatus_pbi != '': - total_query = placementstatus_pbi.count() - else: - total_query = 0 - if total_query > 30: - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - - if 'pdf_gen_invitation_status' in request.POST: - - placementstatus = None - if 'pdf_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'pdf_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - return render_to_pdf('placementModule/pdf_invitation_status.html', context) - - if 'excel_gen_invitation_status' in request.POST: - - placementstatus = None - if 'excel_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'excel_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - - return export_to_xls_invitation_status(placementstatus) - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'mnplacement_tab': mnplacement_tab, - 'placementstatus_placement': placementstatus_placement, - 'placementstatus_pbi': placementstatus_pbi, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - - -@login_required -def placement(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) + # Student view for showing accepted or declined schedule + if request.method == 'POST': + if 'studentapprovesubmit' in request.POST: + status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( + pk=request.POST['studentapprovesubmit']).update( + invitation='ACCEPTED', + timestamp=timezone.now()) + if 'studentdeclinesubmit' in request.POST: + status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( + Q(pk=request.POST['studentdeclinesubmit'])).update( + invitation='REJECTED', + timestamp=timezone.now()) if 'educationsubmit' in request.POST: form = AddEducation(request.POST) @@ -2963,7 +250,16 @@ def placement(request): address = request.POST.get('address') contact = request.POST.get('contact') pic = request.POST.get('pic') - + # futu = request.POST.get('futu') + # print(studentplacement_obj.future_aspect) + # print('fut=', fut) + # print('futu=', futu) + # if studentplacement_obj.future_aspect == "HIGHER STUDIES": + # if futu == 2: + # studentplacement_obj.future_aspect = "PLACEMENT" + # elif studentplacement_obj.future_aspect == "PLACEMENT": + # if futu == None: + # studentplacement_obj.future_aspect = "HIGHER STUDIES" extrainfo_obj = ExtraInfo.objects.get(user=user) extrainfo_obj.about_me = about_me extrainfo_obj.age = age @@ -3905,6 +1201,7 @@ def student_records(request): unique_id=student, no_of_days=no_of_days) for student in students] ) for st in students: + #print(request.user, '-----------------------', st.id.user,'-----------------') placement_cell_notif(request.user, st.id.user, "") students = '' @@ -4528,68 +1825,6 @@ def manage_records(request): -@login_required -def delete_invite_status(request): - ''' - function to delete the invitation that has been sent to the students - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus = [] - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - - if 'deleteinvitationstatus' in request.POST: - delete_invit_status_key = request.POST['deleteinvitationstatus'] - - try: - PlacementStatus.objects.select_related('unique_id','notify_id').get(pk=delete_invit_status_key).delete() - messages.success(request, 'Invitation Deleted Successfully') - except Exception as e: - logger.error(e) - - if 'pbi_tab_active' in request.POST: - mnpbi_tab = 1 - else: - mnplacement_tab = 1 - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'placementstatus': placementstatus, - # 'current':current, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - @login_required def placement_statistics(request): @@ -4740,7 +1975,47 @@ def placement_statistics(request): id__icontains=rollno)) ))) - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT",name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) + p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) + + + + + """placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( + Q(record_id__in=PlacementRecord.objects.filter( + Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), + unique_id__in=Student.objects.filter( + (Q(id__in=ExtraInfo.objects.filter( + Q(user__in=User.objects.filter( + first_name__icontains=first_name, + last_name__icontains=last_name, + id__icontains=rollno)))))))) + #print("In if:", placementrecord) + else: + s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( + Q(user__in=User.objects.filter( + first_name__icontains=first_name, + last_name__icontains=last_name), + id__icontains=rollno)) + ))) + + p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) + print("Agein p:",p) + placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( + Q(record_id__in=PlacementRecord.objects.filter( + Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), + unique_id__in=Student.objects.filter( + (Q(id__in=ExtraInfo.objects.filter( + Q(user__in=User.objects.filter( + first_name__icontains=first_name, + last_name__icontains=last_name), + id__icontains=rollno))))))) + + request.session['first_name'] = first_name + request.session['last_name'] = last_name + request.session['ctc'] = ctc + request.session['cname'] = cname + request.session['rollno'] = rollno + request.session['year'] = form.cleaned_data['year']""" print(p) @@ -5330,20 +2605,20 @@ def cv(request, username): extracurricularcheck = '1' - + # print(achievementcheck,' ',educationcheck,' ',publicationcheck,' ',patentcheck,' ',internshipcheck,' ',projectcheck,' \n\n\n') user = get_object_or_404(User, Q(username=username)) profile = get_object_or_404(ExtraInfo, Q(user=user)) - student_info=get_object_or_404(Student,Q(id=user.username)) - - batch=student_info.batch - now = datetime.datetime.now() - print("year----->",now.year) - if now.year-batch<=4: - roll=now.year-batch + if int(str(profile.id)[:2]) == 20: + if (now.month>4): + roll = 1+now.year-int(str(profile.id)[:4]) + else: + roll = now.year-int(str(profile.id)[:4]) else: - roll=4 - + if (now.month>4): + roll = 1+(now.year)-int("20"+str(profile.id)[0:2]) + else: + roll = (now.year)-int("20"+str(profile.id)[0:2]) student = get_object_or_404(Student, Q(id=profile.id)) skills = Has.objects.select_related('skill_id','unique_id').filter(Q(unique_id=student)) @@ -5420,6 +2695,7 @@ def export_to_xls_std_records(qs): wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Report') + # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() @@ -5430,6 +2706,7 @@ def export_to_xls_std_records(qs): for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) + # Sheet body, remaining rows font_style = xlwt.XFStyle() for student in qs: @@ -5455,128 +2732,6 @@ def export_to_xls_std_records(qs): wb.save(response) return response -def resume(request, username): - # Retrieve data or whatever you need - """ - The function is used to generate the cv in the pdf format. - Embeds the data into the predefined template. - @param: - request - trivial - username - name of user whose cv is to be generated - @variables: - user = stores current user - profile = stores extrainfo of user - current = Stores all working students from HoldsDesignation for the respective degignation - achievementcheck = variable for achievementcheck in form for cv generation - educationcheck = variable for educationcheck in form for cv generation - publicationcheck = variable for publicationcheck in form for cv generation - patentcheck = variable for patentcheck in form for cv generation - internshipcheck = variable for internshipcheck in form for cv generation - projectcheck = variable for projectcheck in form for cv generation - coursecheck = variable for coursecheck in form for cv generation - skillcheck = variable for skillcheck in form for cv generation - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - import datetime - now = stores current timestamp - roll = roll of the user - student = variable storing the profile data - studentplacement = variable storing the placement data - skills = variable storing the skills data - education = variable storing the education data - course = variable storing the course data - experience = variable storing the experience data - project = variable storing the project data - achievement = variable storing the achievement data - publication = variable storing the publication data - patent = variable storing the patent data - """ - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - if current: - if request.method == 'POST': - achievementcheck = request.POST.get('achievementcheck') - educationcheck = request.POST.get('educationcheck') - publicationcheck = request.POST.get('publicationcheck') - patentcheck = request.POST.get('patentcheck') - internshipcheck = request.POST.get('internshipcheck') - projectcheck = request.POST.get('projectcheck') - coursecheck = request.POST.get('coursecheck') - skillcheck = request.POST.get('skillcheck') - reference_list = request.POST.getlist('reference_checkbox_list') - extracurricularcheck = request.POST.get('extracurricularcheck') - conferencecheck = request.POST.get('conferencecheck') - else: - conferencecheck = '1' - achievementcheck = '1' - educationcheck = '1' - publicationcheck = '1' - patentcheck = '1' - internshipcheck = '1' - projectcheck = '1' - coursecheck = '1' - skillcheck = '1' - extracurricularcheck = '1' - - - # print(achievementcheck,' ',educationcheck,' ',publicationcheck,' ',patentcheck,' ',internshipcheck,' ',projectcheck,' \n\n\n') - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - now = datetime.datetime.now() - if int(str(profile.id)[:2]) == 20: - if (now.month>4): - roll = 1+now.year-int(str(profile.id)[:4]) - else: - roll = now.year-int(str(profile.id)[:4]) - else: - if (now.month>4): - roll = 1+(now.year)-int("20"+str(profile.id)[0:2]) - else: - roll = (now.year)-int("20"+str(profile.id)[0:2]) - - student = get_object_or_404(Student, Q(id=profile.id)) - skills = Has.objects.select_related('skill_id','unique_id').filter(Q(unique_id=student)) - education = Education.objects.select_related('unique_id').filter(Q(unique_id=student)) - reference = Reference.objects.filter(id__in=reference_list) - course = Course.objects.select_related('unique_id').filter(Q(unique_id=student)) - experience = Experience.objects.select_related('unique_id').filter(Q(unique_id=student)) - project = Project.objects.select_related('unique_id').filter(Q(unique_id=student)) - achievement = Achievement.objects.select_related('unique_id').filter(Q(unique_id=student)) - extracurricular = Extracurricular.objects.select_related('unique_id').filter(Q(unique_id=student)) - conference = Conference.objects.select_related('unique_id').filter(Q(unique_id=student)) - publication = Publication.objects.select_related('unique_id').filter(Q(unique_id=student)) - patent = Patent.objects.select_related('unique_id').filter(Q(unique_id=student)) - today = datetime.date.today() - - if len(reference) == 0: - referencecheck = '0' - else: - referencecheck = '1' - - return render_to_pdf('placementModule/cv.html', {'pagesize': 'A4', 'user': user, 'references': reference, - 'profile': profile, 'projects': project, - 'skills': skills, 'educations': education, - 'courses': course, 'experiences': experience, - 'referencecheck': referencecheck, - 'achievements': achievement, - 'extracurriculars': extracurricular, - 'publications': publication, - 'patents': patent, 'roll': roll, - 'achievementcheck': achievementcheck, - 'extracurricularcheck': extracurricularcheck, - 'educationcheck': educationcheck, - 'publicationcheck': publicationcheck, - 'patentcheck': patentcheck, - 'conferencecheck': conferencecheck, - 'conferences': conference, - 'internshipcheck': internshipcheck, - 'projectcheck': projectcheck, - 'coursecheck': coursecheck, - 'skillcheck': skillcheck, - 'today':today}) - def export_to_xls_invitation_status(qs): @@ -5586,7 +2741,7 @@ def export_to_xls_invitation_status(qs): wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Report') - + # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() @@ -5597,7 +2752,7 @@ def export_to_xls_invitation_status(qs): for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) - + # Sheet body, remaining rows font_style = xlwt.XFStyle() for student in qs: @@ -5631,6 +2786,7 @@ def check_invitation_date(placementstatus): if ps.invitation=='PENDING': dt = ps.timestamp+datetime.timedelta(days=ps.no_of_days) if dt/', views.edit_discipline_form, name='edit_discipline_form'), path('admin_instigate_semester//', views.instigate_semester, name='instigate_semester'), path('admin_replicate_curriculum//', views.replicate_curriculum, name='replicate_curriculum'), - - - - #new - path('view_course_proposal_forms/',views.view_course_proposal_forms,name='view_course_proposal_forms'), - path('faculty_view_all_courses/', views.faculty_view_all_courses, name='faculty_view_all_courses'), - path('faculty_view_a_course//',views.faculty_view_a_course,name="faculty_view_a_course"), - path('reject_form//', views.reject_form, name='reject_form'), - path('new_course_proposal_file/',views.new_course_proposal_file,name='new_course_proposal_file'), - path('update_course_proposal_file//',views.update_course_proposal_file,name='update_course_proposal_file'), - - path('view_a_course_proposal_form//',views.view_a_course_proposal_form,name='view_a_course_proposal_form'), - path('filetracking//',views.filetracking,name='filetracking'), - path('inward_files/',views.inward_files,name='inward_files'), - path('forward_course_forms//',views.forward_course_forms,name='forward_course_forms'), - path('view_inward_files//',views.view_inward_files,name='view_inward_files'), - path('outward_files/',views.outward_files,name='outward_files'), -] +] \ No newline at end of file diff --git a/FusionIIIT/applications/programme_curriculum/views.py b/FusionIIIT/applications/programme_curriculum/views.py index a1e40c6d1..db3f430fe 100644 --- a/FusionIIIT/applications/programme_curriculum/views.py +++ b/FusionIIIT/applications/programme_curriculum/views.py @@ -1,20 +1,19 @@ from django.db.models.query_utils import Q from django.http import request -from django.shortcuts import get_object_or_404, render, HttpResponse,redirect +from django.shortcuts import get_object_or_404, render, HttpResponse from django.http import HttpResponse, HttpResponseRedirect -# import itertools +import itertools from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User -from .models import Programme, Discipline, Curriculum, Semester, Course, Batch, CourseSlot,NewProposalFile,Proposal_Tracking -from .forms import ProgrammeForm, DisciplineForm, CurriculumForm, SemesterForm, CourseForm, BatchForm, CourseSlotForm, ReplicateCurriculumForm,NewCourseProposalFile,CourseProposalTrackingFile +from .models import Programme, Discipline, Curriculum, Semester, Course, Batch, CourseSlot +from .forms import ProgrammeForm, DisciplineForm, CurriculumForm, SemesterForm, CourseForm, BatchForm, CourseSlotForm, ReplicateCurriculumForm from .filters import CourseFilter, BatchFilter, CurriculumFilter -from django.db import IntegrityError -from django.utils import timezone -from notification.views import prog_and_curr_notif # from applications.academic_information.models import Student -from applications.globals.models import (DepartmentInfo, Designation,ExtraInfo, Faculty, HoldsDesignation) +from applications.globals.models import (DepartmentInfo, Designation, + ExtraInfo, Faculty, HoldsDesignation) + # ------------module-functions---------------# @login_required(login_url='/accounts/login') @@ -29,15 +28,11 @@ def programme_curriculum(request): user_details - Gets the information about the logged in user. des - Gets the designation about the looged in user. """ - user=request.user - user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic": - return HttpResponseRedirect('/programme_curriculum/programmes/') - elif 'hod' in request.session['currentDesignationSelected'].lower() : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') - elif request.session['currentDesignationSelected'] == "acadadmin" : + elif str(request.user) == "acadadmin" : return HttpResponseRedirect('/programme_curriculum/admin_programmes') return HttpResponseRedirect('/programme_curriculum/programmes/') @@ -56,24 +51,12 @@ def view_all_programmes(request): pg - PG programmes phd - PHD programmes """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' - ug = Programme.objects.filter(category='UG') pg = Programme.objects.filter(category='PG') phd = Programme.objects.filter(category='PHD') - url+='view_all_programmes.html' - return render(request, url, {'ug': ug, 'pg': pg, 'phd': phd}) + + return render(request, 'programme_curriculum/view_all_programmes.html', {'ug': ug, 'pg': pg, 'phd': phd}) def view_curriculums_of_a_programme(request, programme_id): @@ -89,18 +72,6 @@ def view_curriculums_of_a_programme(request, programme_id): working_curriculum - Curriculums that are affective past_curriculum - Curriculums thet are obsolete """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' - program = get_object_or_404(Programme, Q(id=programme_id)) curriculums = program.curriculums @@ -110,31 +81,19 @@ def view_curriculums_of_a_programme(request, programme_id): working_curriculums = curriculums.filter(working_curriculum=1) past_curriculums = curriculums.filter(working_curriculum=0) - url+='view_curriculums_of_a_programme.html' - return render(request,url, {'program': program, 'past_curriculums': past_curriculums, 'working_curriculums': working_curriculums, 'curriculumfilter': curriculumfilter}) + + return render(request,'programme_curriculum/view_curriculums_of_a_programme.html', {'program': program, 'past_curriculums': past_curriculums, 'working_curriculums': working_curriculums, 'curriculumfilter': curriculumfilter}) def view_all_working_curriculums(request): - """ views all the working curriculums offered by the institute """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - - url+='faculty/' - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' curriculums = Curriculum.objects.filter(working_curriculum=1) curriculumfilter = CurriculumFilter(request.GET, queryset=curriculums) curriculums = curriculumfilter.qs - return render(request,url+'view_all_working_curriculums.html',{'curriculums':curriculums, 'curriculumfilter': curriculumfilter}) + return render(request,'programme_curriculum/view_all_working_curriculums.html',{'curriculums':curriculums, 'curriculumfilter': curriculumfilter}) def view_semesters_of_a_curriculum(request, curriculum_id): """ @@ -147,18 +106,6 @@ def view_semesters_of_a_curriculum(request, curriculum_id): transpose_semester_slots - semester_slots 2D list is transpose for viewing in HTML . semester_credits - Total Credits for each semester. """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - - - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' curriculum = get_object_or_404(Curriculum, Q(id=curriculum_id)) semesters = curriculum.semesters semester_slots = [] @@ -184,113 +131,54 @@ def view_semesters_of_a_curriculum(request, curriculum_id): max_credit = max(max_credit, course.credit) credits_sum = credits_sum + max_credit semester_credits.append(credits_sum) + + print (semester_credits) transpose_semester_slots = list(zip(*semester_slots)) - return render(request, url+'view_semesters_of_a_curriculum.html', {'curriculum': curriculum, 'semesters': semesters, 'semester_slots': transpose_semester_slots, 'semester_credits': semester_credits}) + return render(request, 'programme_curriculum/view_semesters_of_a_curriculum.html', {'curriculum': curriculum, 'semesters': semesters, 'semester_slots': transpose_semester_slots, 'semester_credits': semester_credits}) def view_a_semester_of_a_curriculum(request, semester_id): """ views a specfic semester of a specfic curriculum """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' semester = get_object_or_404(Semester, Q(id=semester_id)) course_slots = semester.courseslots - return render(request, url+'view_a_semester_of_a_curriculum.html', {'semester': semester, 'course_slots': course_slots}) + return render(request, 'programme_curriculum/view_a_semester_of_a_curriculum.html', {'semester': semester, 'course_slots': course_slots}) def view_a_courseslot(request, courseslot_id): """ view a course slot """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' course_slot = get_object_or_404(CourseSlot, Q(id=courseslot_id)) - return render(request, url+'view_a_courseslot.html', {'course_slot': course_slot}) + return render(request, 'programme_curriculum/view_a_courseslot.html', {'course_slot': course_slot}) def view_all_courses(request): """ views all the course slots of a specfic semester """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' courses = Course.objects.all() coursefilter = CourseFilter(request.GET, queryset=courses) courses = coursefilter.qs - return render(request, url+'view_all_courses.html', {'courses': courses, 'coursefilter': coursefilter}) + return render(request, 'programme_curriculum/view_all_courses.html', {'courses': courses, 'coursefilter': coursefilter}) def view_a_course(request, course_id): """ views the details of a Course """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - - url+='faculty/' - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' course = get_object_or_404(Course, Q(id=course_id)) - return render(request, url+'view_a_course.html', {'course': course}) + return render(request, 'programme_curriculum/view_a_course.html', {'course': course}) def view_all_discplines(request): """ views the details of a Course """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - url+='faculty/' - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' disciplines = Discipline.objects.all() - return render(request, url+'view_all_disciplines.html', {'disciplines': disciplines}) + return render(request, 'programme_curriculum/view_all_disciplines.html', {'disciplines': disciplines}) def view_all_batches(request): """ views the details of a Course """ - url='programme_curriculum/' - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "acadadmin": - return render(request, 'programme_curriculum/admin_programmes/') - elif request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" or request.session['currentDesignationSelected']== "Dean Academic" : - - url+='faculty/' - elif 'hod' in request.session['currentDesignationSelected'].lower(): - url+='faculty/' batches = Batch.objects.all().order_by('year') @@ -302,7 +190,7 @@ def view_all_batches(request): batches = batches.filter(running_batch=True) - return render(request, url+'view_all_batches.html', {'batches': batches, 'finished_batches': finished_batches, 'batchfilter': batchfilter}) + return render(request, 'programme_curriculum/view_all_batches.html', {'batches': batches, 'finished_batches': finished_batches, 'batchfilter': batchfilter}) @@ -321,12 +209,10 @@ def admin_view_all_programmes(request): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') ug = Programme.objects.filter(category='UG') pg = Programme.objects.filter(category='PG') @@ -335,6 +221,7 @@ def admin_view_all_programmes(request): return render(request, 'programme_curriculum/acad_admin/admin_view_all_programmes.html', {'ug': ug, 'pg': pg, "phd": phd}) +@login_required(login_url='/accounts/login') def admin_view_curriculums_of_a_programme(request, programme_id): """ This function is used to Display Curriculum of a specific Programmes. @@ -350,12 +237,10 @@ def admin_view_curriculums_of_a_programme(request, programme_id): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') program = get_object_or_404(Programme, Q(id=programme_id)) curriculums = program.curriculums @@ -370,17 +255,16 @@ def admin_view_curriculums_of_a_programme(request, programme_id): return render(request,'programme_curriculum/acad_admin/admin_view_curriculums_of_a_programme.html', {'program': program, 'past_curriculums': past_curriculums, 'working_curriculums': working_curriculums, 'curriculumfilter': curriculumfilter}) +@login_required(login_url='/accounts/login') def admin_view_all_working_curriculums(request): """ views all the working curriculums offered by the institute """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculums = Curriculum.objects.filter(working_curriculum=1) @@ -391,17 +275,16 @@ def admin_view_all_working_curriculums(request): return render(request,'programme_curriculum/acad_admin/admin_view_all_working_curriculums.html',{'curriculums':curriculums, 'curriculumfilter': curriculumfilter}) +@login_required(login_url='/accounts/login') def admin_view_semesters_of_a_curriculum(request, curriculum_id): """ gets all the semesters of a specfic curriculum """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculum = get_object_or_404(Curriculum, Q(id=curriculum_id)) semesters = curriculum.semesters @@ -428,6 +311,8 @@ def admin_view_semesters_of_a_curriculum(request, curriculum_id): max_credit = max(max_credit, course.credit) credits_sum = credits_sum + max_credit semester_credits.append(credits_sum) + + print (semester_credits) transpose_semester_slots = list(zip(*semester_slots)) @@ -436,6 +321,7 @@ def admin_view_semesters_of_a_curriculum(request, curriculum_id): return render(request, 'programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html', {'curriculum': curriculum, 'semesters': semesters, 'semester_slots': transpose_semester_slots, 'semester_credits': semester_credits, 'all_batches':all_batches}) +@login_required(login_url='/accounts/login') def admin_view_a_semester_of_a_curriculum(request, semester_id): """ This function is used to Display all Semester of a Curriculum. @@ -449,12 +335,10 @@ def admin_view_a_semester_of_a_curriculum(request, semester_id): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') semester = get_object_or_404(Semester, Q(id=semester_id)) course_slots = semester.courseslots @@ -462,17 +346,17 @@ def admin_view_a_semester_of_a_curriculum(request, semester_id): return render(request, 'programme_curriculum/acad_admin/admin_view_a_semester_of_a_curriculum.html', {'semester': semester, 'course_slots': course_slots}) + +@login_required(login_url='/accounts/login') def admin_view_a_courseslot(request, courseslot_id): """ view a course slot """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') edit = request.POST.get('edit', -1) course_slot = get_object_or_404(CourseSlot, Q(id=courseslot_id)) @@ -482,17 +366,16 @@ def admin_view_a_courseslot(request, courseslot_id): return render(request, 'programme_curriculum/acad_admin/admin_view_a_courseslot.html', {'course_slot': course_slot}) +@login_required(login_url='/accounts/login') def admin_view_all_courses(request): """ views all the course slots of a specfic semester """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') courses = Course.objects.all() @@ -504,49 +387,46 @@ def admin_view_all_courses(request): return render(request, 'programme_curriculum/acad_admin/admin_view_all_courses.html', {'courses': courses, 'coursefilter': coursefilter}) +@login_required(login_url='/accounts/login') def admin_view_a_course(request, course_id): """ views the details of a Course """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') course = get_object_or_404(Course, Q(id=course_id)) return render(request, 'programme_curriculum/acad_admin/admin_view_a_course.html', {'course': course}) +@login_required(login_url='/accounts/login') def admin_view_all_discplines(request): """ views the details of a Course """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') disciplines = Discipline.objects.all() return render(request, 'programme_curriculum/acad_admin/admin_view_all_disciplines.html', {'disciplines': disciplines}) +@login_required(login_url='/accounts/login') def admin_view_all_batches(request): """ views the details of a Course """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') batches = Batch.objects.all().order_by('year') @@ -562,17 +442,15 @@ def admin_view_all_batches(request): return render(request, 'programme_curriculum/acad_admin/admin_view_all_batches.html', {'batches': batches, 'finished_batches': finished_batches, 'batchfilter': batchfilter}) - +@login_required(login_url='/accounts/login') def add_discipline_form(request): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') form = DisciplineForm() submitbutton= request.POST.get('Submit') @@ -586,16 +464,15 @@ def add_discipline_form(request): return render(request, 'programme_curriculum/acad_admin/add_discipline_form.html',{'form':form}) +@login_required(login_url='/accounts/login') def edit_discipline_form(request, discipline_id): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') discipline = get_object_or_404(Discipline, Q(id=discipline_id)) form = DisciplineForm(instance=discipline) @@ -610,17 +487,15 @@ def edit_discipline_form(request, discipline_id): return render(request, 'programme_curriculum/acad_admin/add_discipline_form.html',{'form':form}) - +@login_required(login_url='/accounts/login') def add_programme_form(request): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') form = ProgrammeForm() submitbutton= request.POST.get('Submit') @@ -636,17 +511,15 @@ def add_programme_form(request): return render(request,'programme_curriculum/acad_admin/add_programme_form.html',{'form':form, 'submitbutton': submitbutton}) - +@login_required(login_url='/accounts/login') def edit_programme_form(request, programme_id): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') programme = get_object_or_404(Programme, Q(id=programme_id)) form = ProgrammeForm(instance=programme) @@ -661,6 +534,7 @@ def edit_programme_form(request, programme_id): return render(request, 'programme_curriculum/acad_admin/add_programme_form.html',{'form':form, 'submitbutton': submitbutton}) +@login_required(login_url='/accounts/login') def add_curriculum_form(request): """ This function is used to add Curriculum and Semester into Curriculum and Semester table. @@ -671,12 +545,10 @@ def add_curriculum_form(request): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') programme_id = request.GET.get('programme_id', -1) @@ -714,12 +586,10 @@ def edit_curriculum_form(request, curriculum_id): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculum = get_object_or_404(Curriculum, Q(id=curriculum_id)) @@ -757,16 +627,15 @@ def edit_curriculum_form(request, curriculum_id): return render(request, 'programme_curriculum/acad_admin/add_curriculum_form.html',{'form':form, 'submitbutton': submitbutton}) +@login_required(login_url='/accounts/login') def add_course_form(request): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') form = CourseForm() submitbutton= request.POST.get('Submit') @@ -774,61 +643,47 @@ def add_course_form(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): - new_course = form.save(commit=False) - new_course.version=1.0 - new_course.save() + form.save() course = Course.objects.last() messages.success(request, "Added successful") return HttpResponseRedirect("/programme_curriculum/admin_course/" + str(course.id) + "/") - return render(request,'programme_curriculum/acad_admin/course_form.html',{'form':form,'submitbutton': submitbutton}) + return render(request,'programme_curriculum/acad_admin/add_course_form.html',{'form':form}) +@login_required(login_url='/accounts/login') def update_course_form(request, course_id): + #user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student": # or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" + if str(des.designation) == "student": # or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') course = get_object_or_404(Course, Q(id=course_id)) - previous = Course.objects.all().filter(code=course.code).order_by('version').last() - course.version=previous.version - version_error='' form = CourseForm(instance=course) submitbutton= request.POST.get('Submit') if submitbutton: if request.method == 'POST': - form = CourseForm(request.POST) - if form.is_valid() : - previous.latest_version=False - previous.save() - form.latest_version=True - new_course = form.save(commit=False) - if(new_course.version>previous.version): - form.save() - course = Course.objects.last() - messages.success(request, "Added successful") - return HttpResponseRedirect("/programme_curriculum/admin_course/" + str(course.id) + "/") - else: - version_error+=f'The version should be greater than {previous.version}' - - return render(request,'programme_curriculum/acad_admin/course_form.html',{'course':course, 'form':form, 'submitbutton': submitbutton,'version_error':version_error}) + form = CourseForm(request.POST, instance=course) + if form.is_valid(): + form.save() + messages.success(request, "Updated "+ course.name +" successful") + return HttpResponseRedirect("/programme_curriculum/admin_course/" + str(course_id) + "/") + return render(request,'programme_curriculum/acad_admin/add_course_form.html',{'course':course, 'form':form, 'submitbutton': submitbutton}) + +@login_required(login_url='/accounts/login') def add_courseslot_form(request): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculum_id = request.GET.get('curriculum_id', -1) submitbutton= request.POST.get('Submit') @@ -846,16 +701,15 @@ def add_courseslot_form(request): return render(request, 'programme_curriculum/acad_admin/add_courseslot_form.html',{'form':form, 'submitbutton': submitbutton, 'curriculum_id': curriculum_id}) +@login_required(login_url='/accounts/login') def edit_courseslot_form(request, courseslot_id): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') courseslot = get_object_or_404(CourseSlot, Q(id=courseslot_id)) curriculum_id = courseslot.semester.curriculum.id @@ -875,12 +729,10 @@ def delete_courseslot(request, courseslot_id): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') courseslot = get_object_or_404(CourseSlot, Q(id=courseslot_id)) submitbutton= request.POST.get('Submit') @@ -895,16 +747,15 @@ def delete_courseslot(request, courseslot_id): return render(request, 'programme_curriculum/view_a_courseslot.html', {'course_slot': courseslot}) +@login_required(login_url='/accounts/login') def add_batch_form(request): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculum_id = request.GET.get('curriculum_id', -1) form = BatchForm(initial={'curriculum': curriculum_id}) @@ -919,16 +770,15 @@ def add_batch_form(request): return render(request, 'programme_curriculum/acad_admin/add_batch_form.html',{'form':form, 'submitbutton': submitbutton}) +@login_required(login_url='/accounts/login') def edit_batch_form(request, batch_id): user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') curriculum_id = request.GET.get('curriculum_id', -1) batch = get_object_or_404(Batch, Q(id=batch_id)) @@ -947,6 +797,7 @@ def edit_batch_form(request, batch_id): return render(request,'programme_curriculum/acad_admin/add_batch_form.html',{'batch':batch, 'form':form, 'submitbutton':submitbutton}) +@login_required(login_url='/accounts/login') def instigate_semester(request, semester_id): """ This function is used to add the semester information. @@ -958,12 +809,10 @@ def instigate_semester(request, semester_id): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') semester = get_object_or_404(Semester, Q(id=semester_id)) @@ -989,6 +838,7 @@ def instigate_semester(request, semester_id): return render(request,'programme_curriculum/acad_admin/instigate_semester_form.html',{'semester':semester, 'form':form, 'submitbutton':submitbutton, 'curriculum_id':curriculum_id}) +@login_required(login_url='/accounts/login') def replicate_curriculum(request, curriculum_id): """ This function is used to replicate the previous curriculum into a new curriculum. @@ -999,12 +849,10 @@ def replicate_curriculum(request, curriculum_id): """ user_details = ExtraInfo.objects.get(user = request.user) des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + if str(des.designation) == "student" or str(des.designation) == "Associate Professor" or str(des.designation) == "Professor" or str(des.designation) == "Assistant Professor" : return HttpResponseRedirect('/programme_curriculum/programmes/') elif str(request.user) == "acadadmin" : pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - return HttpResponseRedirect('/programme_curriculum/programmes/') old_curriculum = get_object_or_404(Curriculum, Q(id=curriculum_id)) programme = old_curriculum.programme @@ -1046,430 +894,4 @@ def replicate_curriculum(request, curriculum_id): messages.success(request, "Added successful") return HttpResponseRedirect('/programme_curriculum/admin_curriculum_semesters/' + str(curriculum.id) + '/') - return render(request, 'programme_curriculum/acad_admin/add_curriculum_form.html',{'form':form, 'submitbutton': submitbutton}) - -#new - -@login_required(login_url='/accounts/login') -def view_course_proposal_forms(request): - data="" - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).last() - - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" : - pass - elif request.session['currentDesignationSelected'] == "acadadmin" or request.session['currentDesignationSelected'] == "student" : - return HttpResponseRedirect('/programme_curriculum/programmes/') - else: - data='Files Cannot be sent with current Designation Switch to "Professor or Assistant Professor or Associate Professor"' - courseProposal = NewProposalFile.objects.filter(uploader=des.user,designation=request.session['currentDesignationSelected'],is_update=False) - updatecourseProposal = NewProposalFile.objects.filter(uploader=des.user,designation=request.session['currentDesignationSelected'],is_update=True) - - return render(request, 'programme_curriculum/faculty/view_course_proposal_forms.html',{'courseProposals': courseProposal,'updateProposals':updatecourseProposal,'data':data}) - -@login_required(login_url='/accounts/login') -def faculty_view_all_courses(request): - """ views all the course slots of a specfic semester """ - - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student" : - return HttpResponseRedirect('/programme_curriculum/programmes/') - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - elif request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor": - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - - courses = Course.objects.all() - - coursefilter = CourseFilter(request.GET, queryset=courses) - - courses = coursefilter.qs - - return render(request, 'programme_curriculum/faculty/faculty_view_all_courses.html', {'courses': courses, 'coursefilter': coursefilter}) - - -def faculty_view_a_course(request, course_id): - """ views the details of a Course """ - - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student" : - return HttpResponseRedirect('/programme_curriculum/programmes/') - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - elif request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" : - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - course = get_object_or_404(Course, Q(id=course_id)) - return render(request, 'programme_curriculum/faculty/faculty_view_a_course.html', {'course': course}) - - -def view_a_course_proposal_form(request,CourseProposal_id): - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor": - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - else: - return HttpResponseRedirect('/programme_curriculum/programmes') - - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - proposalform = get_object_or_404(NewProposalFile, Q(id=CourseProposal_id)) - return render(request, 'programme_curriculum/faculty/view_a_course_proposal.html', {'proposal': proposalform}) - - -def new_course_proposal_file(request): - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor": - pass - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - else: - return HttpResponseRedirect('/programme_curriculum/programmes') - - uploader = request.user.extrainfo - design=request.session['currentDesignationSelected'] - form=NewCourseProposalFile(initial={'uploader':des.user,'designation':design}) - - submitbutton= request.POST.get('Submit') - - if submitbutton: - if request.method == 'POST': - form = NewCourseProposalFile(request.POST) - if form.is_valid(): - new_course=form.save(commit=False) - new_course.is_read=False - new_course.save() - messages.success(request, "Added successful") - - return HttpResponseRedirect('/programme_curriculum/view_course_proposal_forms/') - - return render(request,'programme_curriculum/faculty/course_proposal_form.html',{'form':form,'submitbutton': submitbutton}) - - - -def filetracking(request,proposal_id): - - - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" or request.session['currentDesignationSelected'] == "Dean Academic": - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "acadadmin": - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - uploader = request.user.extrainfo - design=request.session['currentDesignationSelected'] - file = get_object_or_404(NewProposalFile, Q(id=proposal_id)) - file_data=file.name+' '+file.code - form=CourseProposalTrackingFile(initial={'current_id':file.uploader,'current_design':file.designation,'file_id':int(proposal_id)}) - - submitbutton= request.POST.get('Submit') - - if submitbutton: - if request.method == 'POST': - form = CourseProposalTrackingFile(request.POST) - if form.is_valid(): - form.is_read=False - form.save() - receiver=request.POST.get('receive_id') - receiver_id = User.objects.get(id=receiver) - receiver_design=request.POST.get('receive_design') - receiver_des= Designation.objects.get(id=receiver_design) - uploader=request.POST.get('current_id') - uploader_design=request.POST.get('current_design') - - - data='Received as '+ str(receiver_id) +'-'+str(receiver_des) +' Course Proposal Form "'+file_data +'" By '+str(uploader)+' - '+str(uploader_design) - # data=file.subject - messages.success(request, "Submitted successful") - prog_and_curr_notif(request.user,receiver_id,data) - return HttpResponseRedirect('/programme_curriculum/outward_files/') - - - return render(request,'programme_curriculum/faculty/filetracking.html',{'form':form,'submitbutton': submitbutton,'file_info':file_data}) - - - -def inward_files(request): - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).last() - data='' - - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" : - data='As a "Professor or Assistant Professor or Associate Professor" you cannot receive any proposal requests' - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "Dean Academic": - pass - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes/') - else: - return HttpResponseRedirect('/programme_curriculum/programmes/') - - id=request.user - user_designation=HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - - designation = Designation.objects.get(name=request.session['currentDesignationSelected']) - des_id = designation.id - - courseProposal = Proposal_Tracking.objects.filter(receive_design = des_id,receive_id= id) - - - return render(request, 'programme_curriculum/faculty/inward_course_forms.html',{'courseProposals': courseProposal,'design':request.session['currentDesignationSelected'],'data':data}) - - - -def outward_files(request): - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).last() - data='' - if request.session['currentDesignationSelected'] == "Dean Academic" : - data='As a "Dean Academic" you cannot have any out going files' - pass - elif request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" : - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "acadadmin" or request.session['currentDesignationSelected'] == "student" : - return HttpResponseRedirect('/programme_curriculum/programmes/') - - id=request.user - user_designation=HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - design=request.session['currentDesignationSelected'] - - - designation = Designation.objects.get(name=request.session['currentDesignationSelected']) - des_id = designation.id - - courseProposal = Proposal_Tracking.objects.filter(current_design = design,current_id= des.user) - - - return render(request, 'programme_curriculum/faculty/outward_course_forms.html',{'courseProposals': courseProposal,'design':request.session['currentDesignationSelected'],'data':data}) - -def update_course_proposal_file(request,course_id): - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor": - pass - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - else: - return HttpResponseRedirect('/programme_curriculum/programmes') - - uploader = request.user.extrainfo - design=request.session['currentDesignationSelected'] - course = get_object_or_404(Course, Q(id=course_id)) - file_data=course.code+' - '+course.name - form = NewCourseProposalFile(initial={'uploader':des.user,'designation':design},instance=course) - submitbutton= request.POST.get('Submit') - - - if submitbutton: - if request.method == 'POST': - form = NewCourseProposalFile(request.POST) - if form.is_valid(): - new_course=form.save(commit=False) - new_course.is_read=False - new_course.is_update=True - new_course.save() - messages.success(request, "Added successful") - return HttpResponseRedirect('/programme_curriculum/view_course_proposal_forms/') - - - return render(request,'programme_curriculum/faculty/course_proposal_form.html',{'form':form,'submitbutton': submitbutton,'file_info':file_data}) - - - - -def forward_course_forms(request,ProposalId): - de= ProposalId - des = HoldsDesignation.objects.all().filter(user = request.user).first() - - courseform = Proposal_Tracking.objects.all().filter(id=ProposalId) - - uploader = request.user.extrainfo - design=request.session['currentDesignationSelected'] - file = get_object_or_404(Proposal_Tracking, Q(id=ProposalId)) - file_id = int(file.file_id) - file2 = get_object_or_404(NewProposalFile, Q(id=file_id)) - file_data=file2.code + ' ' + file2.name - Proposal_D = file.id - - if request.session['currentDesignationSelected'] == "Dean Academic" : - file = get_object_or_404(Proposal_Tracking, Q(id=ProposalId)) - file_id = int(file.file_id) - file2 = get_object_or_404(NewProposalFile, Q(id=file_id)) - course =Course.objects.all().filter(code=file2.code).last() - version_error='' - if(course): - previous = Course.objects.all().filter(code=course.code).order_by('version').last() - course.version=previous.version - form = CourseForm(instance=course) - submitbutton= request.POST.get('Submit') - if submitbutton: - if request.method == 'POST': - form = CourseForm(request.POST) - if form.is_valid() : - - new_course = form.save(commit=False) - if(new_course.version>previous.version): - previous.latest_version=False - previous.save() - file.is_added=True - file.is_submitted=True - file.save() - form.latest_version=True - form.save() - course = Course.objects.last() - - receiver=file2.uploader - receiver_id = User.objects.get(username=receiver) - data='The Course "'+ file2.code+ ' - '+ file2.name + '" Updated Successfully' - # data=file.subject - prog_and_curr_notif(request.user,receiver_id,data) - messages.success(request, data) - return HttpResponseRedirect("/programme_curriculum/course/" + str(course.id) + "/") - else: - version_error+=f'The version should be greater than {previous.version}' - - return render(request,'programme_curriculum/faculty/dean_view_a_course_proposal.html',{'course':course, 'form':form, 'submitbutton': submitbutton,'version_error':version_error,'id':Proposal_D}) - else: - form = CourseForm(instance=file2,initial={'disciplines':file.disciplines}) - # course1 =Course.objects.filter(code=file2.code,name=file2.name,credit=file2.credit,lecture_hours=file2.lecture_hours,tutorial_hours=file2.tutorial_hours,pratical_hours=file2.pratical_hours,discussion_hours=file2.discussion_hours,project_hours=file2.project_hours,pre_requisits=file2.pre_requisits,syllabus=file2.syllabus,percent_quiz_1=file2.percent_quiz_1,percent_midsem=file2.percent_midsem,percent_quiz_2=file2.percent_quiz_2,percent_project=file2.percent_project,percent_endsem=file2.percent_endsem,percent_lab_evaluation=file2.percent_lab_evaluation,percent_course_attendance=file2.percent_course_attendance,ref_books=file2.ref_books) - submitbutton= request.POST.get('Submit') - - if submitbutton: - if request.method == 'POST': - form = CourseForm(request.POST) - - if form.is_valid(): - file.is_added=True - file.is_submitted=True - file.save() - form.save() - receiver=file2.uploader - receiver_id = User.objects.get(username=receiver) - data='The Course "'+ file2.code+ ' - '+ file2.name + '" Added Successfully' - # data=file.subject - prog_and_curr_notif(request.user,receiver_id,data) - course =Course.objects.all().filter(code=file2.code).last() - messages.success(request, "Updated "+ file2.name +" successful") - return HttpResponseRedirect("/programme_curriculum/course/" + str(course.id) + "/") - - - - return render(request, 'programme_curriculum/faculty/dean_view_a_course_proposal.html', {'course': file2 ,'form':form,'submitbutton': submitbutton,'id':Proposal_D}) - - elif 'hod' in request.session['currentDesignationSelected'].lower(): - - form=CourseProposalTrackingFile(initial={'current_id':des.user,'current_design':request.session['currentDesignationSelected'],'file_id':file.file_id,'disciplines':file.disciplines}) - - # The above code is trying to retrieve the value of the 'Submit' key from the POST request - # data. It is using the `get` method on the `request.POST` dictionary to access the value - # associated with the 'Submit' key. - submitbutton= request.POST.get('Submit') - - if submitbutton: - if request.method == 'POST': - form = CourseProposalTrackingFile(request.POST) - if form.is_valid(): - file.is_submitted=True - file.save() - form.is_read=False - form.save() - - receiver=request.POST.get('receive_id') - - uploader=request.POST.get('current_id') - uploader_design=request.POST.get('current_design') - - - receiver_design=request.POST.get('receive_design') - receiver_des= Designation.objects.get(id=receiver_design) - receiver_id = User.objects.get(id=receiver) - messages.success(request, "Added successful") - data='Received as '+ str(receiver_id) +'-'+str(receiver_des) +' Course Proposal of Course '+file_data +' By '+str(uploader)+' - '+str(uploader_design) - - prog_and_curr_notif(request.user,receiver_id,data) - return HttpResponseRedirect('/programme_curriculum/outward_files/') - elif request.session['currentDesignationSelected'] == "acadadmin" : - return HttpResponseRedirect('/programme_curriculum/admin_programmes') - else: - return HttpResponseRedirect('/programme_curriculum/programmes') - - - - return render(request,'programme_curriculum/faculty/forward.html',{'form':form,'receive_date':file.receive_date,'proposal':file2,'submitbutton': submitbutton,'id':Proposal_D}) - - -def view_inward_files(request,ProposalId): - - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" or request.session['currentDesignationSelected'] == "Dean Academic": - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "acadadmin": - return HttpResponseRedirect('/programme_curriculum/admin_programmes/') - else: - return HttpResponseRedirect('/programme_curriculum/programmes/') - - des = HoldsDesignation.objects.all().filter(user = request.user).first() - - - uploader = request.user.extrainfo - design=request.session['currentDesignationSelected'] - file = get_object_or_404(Proposal_Tracking, Q(id=ProposalId)) - file_id = int(file.file_id) - file2 = get_object_or_404(NewProposalFile, Q(id=file_id)) - file_data='' - file_data2='' - - - if(file.is_rejected): - file_data='"'+str(file2.name) + '"'+' Course Rejected by ' + str(file.receive_id) + ' - ' +str(file.receive_design) - if(file.is_added and not file.is_rejected): - file_data2='"'+str(file2.code)+' - '+str(file2.name) +'" Course Added Succesfully' - - courseProposal = Proposal_Tracking.objects.filter(file_id=file.file_id,disciplines=file.disciplines) - form=CourseProposalTrackingFile(initial={'current_id':des.user,'current_design':request.session['currentDesignationSelected'],'file_id':file.file_id,'disciplines':file.disciplines}) - - return render(request,'programme_curriculum/faculty/view_file.html',{'form':form,'receive_date':file.receive_date,'proposal':file2,'trackings':courseProposal,'file_info':file_data,'file_sucess':file_data2}) - -def reject_form(request,ProposalId): - - if request.session['currentDesignationSelected'] == "Associate Professor" or request.session['currentDesignationSelected'] == "Professor" or request.session['currentDesignationSelected'] == "Assistant Professor" or request.session['currentDesignationSelected'] == "Dean Academic": - pass - elif 'hod' in request.session['currentDesignationSelected'].lower(): - pass - elif request.session['currentDesignationSelected'] == "acadadmin": - return HttpResponseRedirect('/programme_curriculum/admin_programmes/') - else: - return HttpResponseRedirect('/programme_curriculum/programmes/') - - track=get_object_or_404(Proposal_Tracking, Q(id=ProposalId)) - file2 = get_object_or_404(NewProposalFile,Q(id = track.file_id)) - if(not track.is_added and not track.is_submitted): - track.is_rejected=True - track.is_submitted=True - track.save() - messages.success(request, "Course Proposal Form Rejected") - receiver=file2.uploader - receiver_id = User.objects.get(username=receiver) - data='The Course "'+ file2.code+ ' - '+ file2.name + '" was Rejected by ' + str(request.user) + ' - ' +str(request.session['currentDesignationSelected']) - prog_and_curr_notif(request.user,receiver_id,data) - - - else: - messages.error(request, "course already forwarded or added can't be rejected") - return HttpResponseRedirect('/programme_curriculum/inward_files/') - \ No newline at end of file + return render(request, 'programme_curriculum/acad_admin/add_curriculum_form.html',{'form':form, 'submitbutton': submitbutton}) \ No newline at end of file diff --git a/FusionIIIT/applications/ps1/__init__.py b/FusionIIIT/applications/ps1/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/FusionIIIT/applications/ps1/admin.py b/FusionIIIT/applications/ps1/admin.py index ec612790d..8dd0ad5ee 100644 --- a/FusionIIIT/applications/ps1/admin.py +++ b/FusionIIIT/applications/ps1/admin.py @@ -2,8 +2,6 @@ # Register your models here. -from applications.ps1.models import StockEntry,IndentFile,StockItem,StockTransfer +from applications.ps1.models import StockEntry,IndentFile admin.site.register(StockEntry) -admin.site.register(IndentFile) -admin.site.register(StockItem) -admin.site.register(StockTransfer) \ No newline at end of file +admin.site.register(IndentFile) \ No newline at end of file diff --git a/FusionIIIT/applications/ps1/api/serializers.py b/FusionIIIT/applications/ps1/api/serializers.py deleted file mode 100644 index bdd05635c..000000000 --- a/FusionIIIT/applications/ps1/api/serializers.py +++ /dev/null @@ -1,45 +0,0 @@ -from rest_framework import serializers #type:ignore -from applications.ps1.models import IndentFile, File ,StockEntry,StockItem,StockTransfer -from applications.globals.models import ExtraInfo, HoldsDesignation -from applications.filetracking.models import Tracking - -class FileSerializer(serializers.ModelSerializer): - class Meta: - model = File - fields = '__all__' - -class IndentFileSerializer(serializers.ModelSerializer): - class Meta: - model = IndentFile - fields = '__all__' - -class ExtraInfoSerializer(serializers.ModelSerializer): - class Meta: - model = ExtraInfo - fields = '__all__' - -class HoldsDesignationSerializer(serializers.ModelSerializer): - class Meta: - model = HoldsDesignation - fields = '__all__' - -class TrackingSerializer(serializers.ModelSerializer): - class Meta: - model = Tracking - fields = '__all__' - -class StockEntrySerializer(serializers.ModelSerializer): - class Meta: - model = StockEntry - fields = '__all__' - -class StockItemSerializer(serializers.ModelSerializer): - class Meta: - model = StockItem - fields = '__all__' - -class StockTransferSerializer(serializers.ModelSerializer): - class Meta: - model = StockTransfer - fields = '__all__' - diff --git a/FusionIIIT/applications/ps1/api/urls.py b/FusionIIIT/applications/ps1/api/urls.py deleted file mode 100644 index df8ec1719..000000000 --- a/FusionIIIT/applications/ps1/api/urls.py +++ /dev/null @@ -1,53 +0,0 @@ -from django.conf.urls import url - -from . import views - -urlpatterns = [ - # to create a new indent file - url(r'^create_proposal/', views.createProposal, name='create-proposal'), - - # PENDING : TO CREATE A INDENT FILE DRAFT - - # GET DESIGNATIONS USING USER TOKEN - url(r'^getDesignations/', views.getDesignations, name='get-designations'), - - # to get the indent files created by the user - url(r'^indentview/(?P\d+)$', views.indentView, name='indent-view'), - - # to get the indent Files drafts by a user - url(r'^draftview/(?P\d+)$', views.draftView, name='draft-view'), - - # to get all the indent files inwarded to the user 'id' is holdsDesignation id. - url(r'^inwardIndents/(?P\d+)$', views.inwardIndents, name='inward-indents'), - - # to see the details of a specifc indent file - url(r'^indentFile/(?P\d+)$', views.indentFile, name='indent-file'), - - # to forward a indent File - url(r'^indentFile/forward/(?P\d+)$', views.ForwardIndentFile, name='forward-indent-file'), - - # STOCKS API - # to return all the indent files (GET) as well as to get the information of any specific indent file (POST) to further add stock to it (just info). - url(r'^entry/(?P\d+)$', views.entry, name='entry'), - - # To add stock corresponding to a Indent File - url(r'^stockEntry/(?P\d+)$', views.stockEntry, name='stock-entry'), - - # To view all the stock entry details - url(r'^stock_entry_view/(?P\d+)$', views.stockEntryView, name='stock-entry-view'), - - - # To view the current_stock_view based on filters - url(r'^current_stock_view/(?P\d+)$', views.currentStockView, name='current-stock-view'), - - # to view all the items present in any stock entry - url(r'^stock_entry_item_view/(?P\d+)$', views.stock_entry_item_view, name='stock-entry-item-view'), - - # to delete any stock entry - url(r'^stock_item_delete/(?P\d+)$', views.stockDelete, name='stock-delete'), - - url(r'^stock_transfer/(?P\d+)$', views.stockTransfer, name='stock-transfer'), - - - url(r'^perform_transfer/(?P\d+)$', views.performTransfer, name='perform-transfer'), -] diff --git a/FusionIIIT/applications/ps1/api/views.py b/FusionIIIT/applications/ps1/api/views.py deleted file mode 100644 index 37d6546e4..000000000 --- a/FusionIIIT/applications/ps1/api/views.py +++ /dev/null @@ -1,619 +0,0 @@ -from rest_framework.permissions import IsAuthenticated #type:ignore -from rest_framework.response import Response #type:ignore -from rest_framework import status #type:ignore -from rest_framework.decorators import api_view, permission_classes #type:ignore -from applications.ps1.models import IndentFile, File,StockTransfer,StockEntry,StockItem -from applications.globals.models import HoldsDesignation, Designation,ExtraInfo,DepartmentInfo -from applications.filetracking.models import Tracking -from .serializers import IndentFileSerializer ,FileSerializer,ExtraInfoSerializer,HoldsDesignationSerializer,TrackingSerializer,StockEntrySerializer,StockItemSerializer,StockTransferSerializer -from django.utils import timezone -from applications.filetracking.sdk.methods import * -from datetime import datetime -from django.http import HttpResponseForbidden -from django.db.models import Q,Count -from django.shortcuts import get_object_or_404 -from django.http import HttpResponse -import ast - -dept_admin_to_dept = { - "deptadmin_cse": "CSE", - "deptadmin_ece": "ECE", - "deptadmin_me": "ME", - "deptadmin_sm": "SM", - "deptadmin_design": "Design", - "deptadmin_liberalarts": "Liberal Arts", - "deptadmin_ns": "Natural Science", -} - -dept_admin_design = ["deptadmin_cse", "deptadmin_ece", "deptadmin_me","deptadmin_sm", "deptadmin_design", "deptadmin_liberalarts","deptadmin_ns" ] - - -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def getDesignations(request): - if request.method == 'GET': - designations = HoldsDesignation.objects.filter(user=request.user) - designations_serialized = HoldsDesignationSerializer(designations,many=True) - return Response(designations_serialized.data) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def createProposal(request): - if request.method == 'POST': - # print('our requested data :',request.data) - # Process the POST request data - uploader = request.user.extrainfo - subject = request.data.get('title') - description = request.data.get('desc') - design = request.data.get('design') - designation = Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=design).designation_id) - upload_file = request.FILES.get('myfile') - item_name = request.data.get('item_name') - grade = request.data.get('grade') - quantity = request.data.get('quantity') - present_stock = request.data.get('present_stock') - estimated_cost = request.data.get('estimated_cost') - purpose = request.data.get('purpose') - specification = request.data.get('specification') - item_type = request.data.get('item_type') - nature = request.data.get('nature') - indigenous = request.data.get('indigenous') - replaced = request.data.get('replaced') - budgetary_head = request.data.get('budgetary_head') - expected_delivery = request.data.get('expected_delivery') - sources_of_supply = request.data.get('sources_of_supply') - head_approval = False - director_approval = False - financial_approval = False - purchased = False - - # Create File object - file = File.objects.create( - uploader=uploader, - description=description, - subject=subject, - designation=designation, - upload_file=upload_file - ) - - # Create IndentFile object - indent_file = IndentFile.objects.create( - file_info=file, - item_name=item_name, - quantity=quantity, - present_stock=present_stock, - estimated_cost=estimated_cost, - purpose=purpose, - specification=specification, - grade=grade, - item_type=item_type, - nature=nature, - indigenous=indigenous, - replaced=replaced, - budgetary_head=budgetary_head, - expected_delivery=expected_delivery, - sources_of_supply=sources_of_supply, - head_approval=head_approval, - director_approval=director_approval, - financial_approval=financial_approval, - purchased=purchased, - ) - - # Serialize response data - file_serializer = FileSerializer(file) - indent_file_serializer = IndentFileSerializer(indent_file) - - # Return response - return Response({ - 'file': file_serializer.data, - 'indent_file': indent_file_serializer.data, - 'message': 'Indent Filed Successfully!' - }) - - -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def indentView(request, id): - if request.method == 'GET': - tracking_objects = Tracking.objects.all() - tracking_obj_ids = [obj.file_id for obj in tracking_objects] - draft_indent = IndentFile.objects.filter(file_info__in=tracking_obj_ids) - draft = [indent.file_info.id for indent in draft_indent] - draft_files = File.objects.filter(id__in=draft).order_by('-upload_date') - indents = [file.indentfile for file in draft_files] - abcd = HoldsDesignation.objects.get(pk=id) - s = str(abcd).split(" - ") - - serializer = IndentFileSerializer(indents, many=True) - return Response(serializer.data) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - -# TO GET ALL THE USER DRAFTS USING HOLDS DESIGNATION ID -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def draftView(request, id): - if request.method == 'GET': - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - if designation == "student": - return Response({"message": "Unauthorized"}, status=status.HTTP_401_UNAUTHORIZED) - - indents = IndentFile.objects.filter(file_info__in=request.user.extrainfo.uploaded_files.all()).select_related('file_info') - indent_ids = [indent.file_info for indent in indents] - filed_indents = Tracking.objects.filter(file_id__in=indent_ids) - filed_indent_ids = [indent.file_id for indent in filed_indents] - draft = list(set(indent_ids) - set(filed_indent_ids)) - draft_indent = IndentFile.objects.filter(file_info__in=draft).values("file_info") - draft_files = File.objects.filter(id__in=draft_indent).order_by('-upload_date') - abcd = HoldsDesignation.objects.get(pk=id) - s = str(abcd).split(" - ") - serializer = FileSerializer(draft_files, many=True) - return Response(serializer.data) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def inwardIndents(request, id): - if request.method == 'GET': - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - abcd = HoldsDesignation.objects.get(pk=id) - - data = view_inbox(request.user.username, designation, "ps1") - # outboxd = view_outbox(request.user.username, designations, "ps1") - - data = sorted(data, key=lambda x: datetime.fromisoformat(x['upload_date']), reverse=True) - for item in data: - item['upload_date'] = datetime.fromisoformat(item['upload_date']) - - response_data = { - 'receive_design': str(abcd), - 'in_file': data - } - - return Response(response_data) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def indentFile(request, id): - if request.method == 'GET': - try: - indent_file = IndentFile.objects.select_related('file_info').get(file_info=id) - except IndentFile.DoesNotExist: - return Response({"message": "Indent file does not exist"}, status=status.HTTP_404_NOT_FOUND) - - # Retrieve tracking details for the indent file - track = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department','current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id=indent_file.file_info) - - # Retrieve ExtraInfo, HoldsDesignation, and filtered designations - extrainfo = ExtraInfo.objects.select_related('user','department').all() - holdsdesignations = HoldsDesignation.objects.select_related('user','working','designation').all() - designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - - - # Serialize the data - indent_serializer = IndentFileSerializer(indent_file) - track_serializer = TrackingSerializer(track, many=True) - extrainfo_serializer = ExtraInfoSerializer(extrainfo, many=True) - holdsdesignations_serializer = HoldsDesignationSerializer(holdsdesignations, many=True) - designations_serializer = HoldsDesignationSerializer(designations, many=True) - - # Construct response data - response_data = { - 'indent_file': indent_serializer.data, - 'track': track_serializer.data, - 'extrainfo': extrainfo_serializer.data, - 'holdsdesignations': holdsdesignations_serializer.data, - 'designations': designations_serializer.data - } - - return Response(response_data) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - - -# Forwarding Indent -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def ForwardIndentFile(request, id): - - if request.method == 'POST': - # print('hdfjaldfalk' , request.data); - try: - indent = IndentFile.objects.select_related('file_info').get(file_info=id) - file = indent.file_info - track = Tracking.objects.select_related('file_id__uploader__user','file_id__uploader__department','file_id__designation','current_id__user','current_id__department','current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id=file) - except IndentFile.DoesNotExist: - return Response({"message": "Indent file does not exist"}, status=status.HTTP_404_NOT_FOUND) - - # Extracting data from request.POST - remarks = request.data.get('remarks') - sender_design_id = request.data.get('sender') - receiverHdid = request.data.get('receive') - upload_file = request.FILES.get('myfile') - - # Retrieving sender and receiver designations - sender_designationobj = HoldsDesignation.objects.get(id=sender_design_id).designation - sender_designation_name = sender_designationobj.name - receiverHdobj = HoldsDesignation.objects.get(id=receiverHdid) - receiver = receiverHdobj.user.username - receive_design = receiverHdobj.designation.name - - try: - receiver_id = User.objects.get(username=receiver) - except User.DoesNotExist: - return Response({"message": "Enter a valid destination"}, status=status.HTTP_400_BAD_REQUEST) - - try: - receive_design = Designation.objects.get(name=receive_design) - except Designation.DoesNotExist: - return Response({"message": "Enter a valid designation"}, status=status.HTTP_400_BAD_REQUEST) - - # Forwarding the file - forwarded_file_id = forward_file( - file_id=file.id, - receiver=receiver_id, - receiver_designation=receive_design, - file_extra_JSON={"key": 2}, - remarks=remarks, - file_attachment=upload_file - ) - - # Updating indent approvals if necessary - if (str(receive_design) in dept_admin_design): - indent.head_approval=True - elif (( - (sender_designation_name in dept_admin_design) - or - (sender_designation_name == "ps_admin") - ) - and (str(receive_design) == "Accounts Admin")): - indent.director_approval=True - indent.financial_approval=True - indent.head_approval=True - - indent.save() - - # Serializing the data - indent_serializer = IndentFileSerializer(indent) - track_serializer = TrackingSerializer(track, many=True) - - # Constructing response data - response_data = { - 'indent_file': indent_serializer.data, - 'track': track_serializer.data, - 'message': 'Indent File Forwarded successfully' - } - - return Response(response_data, status=status.HTTP_200_OK) - else: - return Response({"message": "Method not allowed"}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - -@api_view(['GET', 'POST']) -@permission_classes([IsAuthenticated]) -def entry(request,id): - - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - if request.method == 'GET': - - if designation not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - # Get department name - department = request.user.extrainfo.department.name - - # Filter indent files based on user's designation - if request.session.get('currentDesignationSelected') == "dept_admin": - indent_files = IndentFile.objects.filter(file_info__uploader__department__name=department) - else: - indent_files = IndentFile.objects.all() - - serializer = IndentFileSerializer(indent_files, many=True) - return Response(serializer.data) - - elif request.method == 'POST': - print(designation) - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - id = request.data.get('id') - if not id: - return Response({"message": "ID parameter is required"}, status=status.HTTP_400_BAD_REQUEST) - - try: - request_file = File.objects.select_related('uploader').get(id=id) - requester = request_file.uploader.user - # persons = ExtraInfo.objects.filter(user_type__in=["staff"]) - corresponding_indent_file = IndentFile.objects.get(file_info=request_file) - - serializer = { - 'request_file': FileSerializer(request_file).data, - 'requester': requester.username, - # 'persons': persons.values(), - 'corresponding_indent_file': IndentFileSerializer(corresponding_indent_file).data - } - return Response(serializer) - except File.DoesNotExist: - return Response({"message": "File with given ID does not exist"}, status=status.HTTP_404_NOT_FOUND) - except IndentFile.DoesNotExist: - return Response({"message": "Corresponding indent file does not exist"}, status=status.HTTP_404_NOT_FOUND) - - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def stockEntry(request,id): - - # print(request.data); - - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - # print(designation) - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - if request.method == 'POST': - - id = request.POST.get('id') - vendor = request.POST.get('vendor') - current_stock = request.POST.get('current_stock') - # received_date = request.POST.get('received_date') - bill = request.FILES.get('bill') - location = request.POST.get('location') - - try: - temp1 = File.objects.get(id=id) - temp = IndentFile.objects.get(file_info=temp1) - except (File.DoesNotExist, IndentFile.DoesNotExist): - return Response({"message": "File with given ID does not exist"}, status=status.HTTP_404_NOT_FOUND) - - item_id = temp - dealing_assistant_id = request.user.extrainfo - - print(request.data) - - stock_entry = StockEntry.objects.create( - item_id=item_id, - vendor=vendor, - current_stock=current_stock, - dealing_assistant_id=dealing_assistant_id, - bill=bill, - # received_date=received_date, - location=location - ) - - # Marking the indent file as done - temp.purchased = True - temp.save() - - serializer = StockEntrySerializer(stock_entry) - return Response(serializer.data, status=status.HTTP_201_CREATED) - - -@api_view(['GET']) -@permission_classes([IsAuthenticated]) -def stockEntryView(request,id): - # print(request.user.id); - - designation =str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - department = request.user.extrainfo.department - - if designation in dept_admin_design: - stocks = StockEntry.objects.filter(item_id__file_info__uploader__department=department) - elif designation == "ps_admin": - stocks = StockEntry.objects.all() - else: - return Response({"message": "Invalid designation"}, status=status.HTTP_400_BAD_REQUEST) - - serializer = StockEntrySerializer(stocks, many=True) - return Response(serializer.data) - - -# to check the current stock situation in the module -@api_view(['GET', 'POST']) -@permission_classes([IsAuthenticated]) -def currentStockView(request,id): - - designation =str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - - if request.method == 'GET': - # Check if the user is authorized - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - # Handle GET request - department = request.user.extrainfo.department - - if designation in dept_admin_design: - # Only show stocks of the department for department admin - stocks = StockItem.objects.filter(department=department) - elif designation == "ps_admin": - # Show all stocks for PS admin - stocks = StockItem.objects.all() - else: - return Response({"message": "Invalid designation"}, status=status.HTTP_403_FORBIDDEN) - - grouped_items = stocks.values('StockEntryId__item_id__item_type', 'StockEntryId__item_id__grade', 'department').annotate(total_quantity=Count('id')) - - grouped_items_list = [ - { - 'item_type': item['StockEntryId__item_id__item_type'], - 'grade': item['StockEntryId__item_id__grade'], - 'department': DepartmentInfo.objects.get(id=item['department']).name, - 'total_quantity': item['total_quantity'] - } - for item in grouped_items - ] - - return Response(grouped_items_list) - - elif request.method == 'POST': - # Handle POST request - department = request.data.get('department') - grade = request.data.get('grade') - item_type = request.data.get('item_type') - - if not department or not grade or not item_type: - return Response({"message": "Missing required parameters"}, status=status.HTTP_400_BAD_REQUEST) - - # Filter StockItem based on provided filters - StockItems = StockItem.objects.filter( - department=department, - StockEntryId__item_id__grade=grade, - StockEntryId__item_id__item_type=item_type - ) - - grouped_items = StockItems.values('StockEntryId__item_id__item_type', 'StockEntryId__item_id__grade', 'department').annotate(total_quantity=Count('id')) - - grouped_items_list = [ - { - 'item_type': item['StockEntryId__item_id__item_type'], - 'grade': item['StockEntryId__item_id__grade'], - 'department': DepartmentInfo.objects.get(id=department).name, - 'total_quantity': item['total_quantity'] - } - for item in grouped_items - ] - - # Serialize the data - # serializer = StockItemSerializer(grouped_items_list, many=True) - - firstStock = StockItemSerializer(StockItems.first()) - - return Response({'stocks': grouped_items_list, 'first_stock': firstStock.data}) - - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def stock_entry_item_view(request,id): - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - department = request.data.get('department') - file_id=request.data.get('file_id') - temp=File.objects.get(id=file_id) - temp1=IndentFile.objects.get(file_info=temp) - stock_entry=StockEntry.objects.get(item_id=temp1) - - stocks=StockItem.objects.filter(StockEntryId=stock_entry) - serializer = StockItemSerializer(stocks, many=True) - return Response(serializer.data) - - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def stockDelete(request,id): - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - - id = request.POST.get('id') - try: - stock = StockItem.objects.get(id=id) - except StockItem.DoesNotExist: - return Response({"message": 'Stock item with given ID does not exist',"id":id}, status=status.HTTP_404_NOT_FOUND) - - stock.delete() - return Response({"message": "Stock item deleted successfully"}, status=status.HTTP_200_OK) - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def stockTransfer(request,id): - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - id=request.POST.get('id') - temp=File.objects.get(id=id) - temp1=IndentFile.objects.get(file_info=temp) - - item_type_required =temp1.item_type - item_grade_required = temp1.grade - - available_items=StockItem.objects.filter( - StockEntryId__item_id__item_type=item_type_required, - StockEntryId__item_id__grade=item_grade_required, - inUse=False - ) - - print(available_items) - serializer = StockItemSerializer(available_items, many=True) - return Response(serializer.data) - - - -@api_view(['POST']) -@permission_classes([IsAuthenticated]) -def performTransfer(request,id): - designation = str(Designation.objects.get(id=HoldsDesignation.objects.select_related('user', 'working', 'designation').get(id=id).designation_id)) - - if str(designation) not in dept_admin_design + ["ps_admin"]: - return Response({"message": "Not authorized"}, status=status.HTTP_403_FORBIDDEN) - - selected_stock_items = request.data.getlist('selected_stock_items[]') - indentId = request.data.get('indentId') - dest_location = request.data.get('dest_location') - - list = selected_stock_items[0]; - stock_items_list = ast.literal_eval(list) - - myIndent = IndentFile.objects.get(file_info=indentId) - - moreStocksRequired = myIndent.quantity - len(stock_items_list) - # print('dest_destination : ', myIndent.file_info.uploader.department) - - stock_transfers = [] - for item in stock_items_list: - stock_item = StockItem.objects.get(id=item) - # print('src dest : ', stock_item.department) - - store_cur_dept = stock_item.department; - store_cur_location = stock_item.location; - - # changing the attributes for this stock item as being transferred. - stock_item.department=myIndent.file_info.uploader.department; - stock_item.location=dest_location; - stock_item.inUse= True - stock_item.isTransferred= True - # if a stock_item is been transferred then obviously it will be put into use. - stock_item.save(); - - - stock_transfer = StockTransfer.objects.create( - indent_file=myIndent, - src_dept=store_cur_dept, - dest_dept=myIndent.file_info.uploader.department, - stockItem=stock_item, - src_location=store_cur_location, - dest_location=dest_location - ) - - stock_transfers.append(stock_transfer) - - - if(moreStocksRequired==0): - myIndent.purchased=True - else: - myIndent.quantity=moreStocksRequired; - - myIndent.save(); - - - serializer = StockTransferSerializer(stock_transfers,many=True) - return Response(serializer.data, status=status.HTTP_201_CREATED) diff --git a/FusionIIIT/applications/ps1/migrations/0001_initial.py b/FusionIIIT/applications/ps1/migrations/0001_initial.py index 4d5674c39..4cd74fe33 100644 --- a/FusionIIIT/applications/ps1/migrations/0001_initial.py +++ b/FusionIIIT/applications/ps1/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.db import migrations, models import django.db.models.deletion @@ -55,4 +55,4 @@ class Migration(migrations.Migration): 'db_table': 'StockEntry', }, ), - ] \ No newline at end of file + ] diff --git a/FusionIIIT/applications/ps1/models.py b/FusionIIIT/applications/ps1/models.py index d5aa60d93..bee76f36e 100644 --- a/FusionIIIT/applications/ps1/models.py +++ b/FusionIIIT/applications/ps1/models.py @@ -1,22 +1,18 @@ from django.db import models from django.contrib.auth.models import User -from applications.globals.models import Staff,ExtraInfo,DepartmentInfo +from applications.globals.models import Staff,ExtraInfo from applications.filetracking.models import File -from django.db.models.signals import post_save -from django.dispatch import receiver -from django.utils import timezone class IndentFile(models.Model): file_info=models.OneToOneField(File, on_delete=models.CASCADE,primary_key=True) - item_name=models.CharField(max_length=250,blank=False) # Apple pro vision 3.0 + item_name=models.CharField(max_length=250,blank=False) quantity= models.IntegerField(blank=False) present_stock=models.IntegerField(blank=False) estimated_cost=models.IntegerField(null=True, blank=False) purpose=models.CharField(max_length=250,blank=False ) specification=models.CharField(max_length=250) - grade = models.CharField(max_length=1, choices=[('A', 'A'), ('B', 'B'), ('C', 'C')],default='A') - item_type=models.CharField(max_length=250) + indent_type=models.CharField(max_length=250) nature=models.BooleanField(default = False) indigenous= models.BooleanField(default = False) replaced =models.BooleanField(default = False) @@ -31,85 +27,15 @@ class IndentFile(models.Model): class Meta: db_table = 'IndentFile' - -class Constants: - Locations = ( - ('H1', 'Vashistha Hostel'), - ('H4', 'Vivekananda Hostel'), - ('H3', 'AryaBhatta Hostel'), - ('SR1', 'Storage Room 1'), - ('SR2', 'Storage Room 2'), - ('SR3', 'Storage Room 3'), - ('SR4', 'Storage Room 4'), - ('SR5', 'Storage Room 5'), - ) - class StockEntry(models.Model): item_id=models.OneToOneField(IndentFile, on_delete=models.CASCADE,primary_key=True) dealing_assistant_id=models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) vendor=models.CharField(max_length=250, blank=False) + item_name=models.CharField(max_length=250, blank=False) current_stock=models.IntegerField(blank=False) - recieved_date = models.DateField(blank=False) + recieved_date=models.DateField(blank=False) bill=models.FileField(blank=False) - location = models.CharField(max_length=100 ,choices=Constants.Locations,default='SR1') - class Meta: - db_table = 'StockEntry' - -# Individual Stock Item -class StockItem(models.Model): - # this represents the id of the StockEntry instance (StockEntryId_id) - - # this StockEntryId will never ever change onces StockItem instance is created and will therefore be used for obtaining the grade,indentfile etc. details. - - StockEntryId = models.ForeignKey(StockEntry,on_delete=models.CASCADE) - nomenclature = models.CharField(max_length=100, unique=True) # Unique identifier for each StockItem - inUse = models.BooleanField(default=True) - - # as department is going to be a variable field here I have to add a Department fiedl for making our job a bit easir and same goes for location as well. Redundancy Hurts :). - - department = models.ForeignKey( - DepartmentInfo, on_delete=models.CASCADE, null=True, blank=True) - location = models.CharField(max_length=100,choices=Constants.Locations,default='SR1') - isTransferred = models.BooleanField(default=False) - - class Meta: - db_table = 'StockItem' - - def save(self, *args, **kwargs): - # Generate nomenclature when saving the StockItem instance - if not self.nomenclature: - # Construct nomenclature using StockEntry primary key and a sequential number - max_existing_number = StockItem.objects.filter(StockEntryId=self.StockEntryId_id).count() - new_number = max_existing_number + 1 - self.nomenclature = f"{self.StockEntryId.item_id}_{new_number}" - super().save(*args, **kwargs) - - -# this table will be used to keep a track of all the stockTransfer things. -class StockTransfer(models.Model): - indent_file=models.ForeignKey(IndentFile, on_delete=models.CASCADE) - - src_dept= models.ForeignKey( - DepartmentInfo, on_delete=models.CASCADE, null=True, blank=True, related_name='dept_src_transfers') - dest_dept= models.ForeignKey( - DepartmentInfo, on_delete=models.CASCADE, null=True, blank=True, related_name='dept_dest_transfers') - - stockItem= models.ForeignKey(StockItem,on_delete=models.CASCADE) - src_location = models.CharField(max_length=100,choices=Constants.Locations,default='SR1') - dest_location = models.CharField(max_length=100,choices=Constants.Locations,default='SR2') - dateTime = models.DateTimeField(default=timezone.now) - - class Meta : - db_table = 'StockTransfer' - - -@receiver(post_save, sender=StockEntry) -def create_stock_items(sender, instance, created, **kwargs): - if created: - # Automatically create 'n' number of StockItem instances based on current_stock of StockEntry - # instance is stockEntry - current_stock = int(instance.current_stock) - for _ in range(current_stock): - StockItem.objects.create(StockEntryId=instance,location=instance.location,department=instance.item_id.file_info.uploader.department) + class Meta: + db_table = 'StockEntry' \ No newline at end of file diff --git a/FusionIIIT/applications/ps1/urls.py b/FusionIIIT/applications/ps1/urls.py index 793d34ec5..e8b3ad417 100644 --- a/FusionIIIT/applications/ps1/urls.py +++ b/FusionIIIT/applications/ps1/urls.py @@ -1,4 +1,4 @@ -from django.conf.urls import url,include +from django.conf.urls import url from . import views @@ -7,68 +7,22 @@ urlpatterns = [ url(r'^$', views.ps1, name='ps1'), - url(r'^create_proposal/$', views.create_proposal, name='create_proposal'), # url(r'^compose_indent/$', views.compose_indent, name='compose_indent'), url(r'^composed_indents/$', views.composed_indents, name='composed_indents'), - - # here id is the Holdsdesignation id. url(r'^indentview/(?P\d+)$', views.indentview, name='indentview'), - url(r'^drafts/$', views.drafts, name='drafts'), url(r'^draftview/(?P\d+)$', views.draftview, name='draftview'), url(r'^inwardIndent/$', views.inward, name='inward'), - - # indentview2 is to get all the indentFiles inwarded towards the request.user. - url(r'^indentview2/(?P\d+)$', views.indentview2, name='indentview2'), url(r'^confirmdelete/(?P\d+)$', views.confirmdelete, name='confirm_delete'), url(r'^delete/(?P\d+)$',views.delete, name='delete'), - # forward Indent is to see a specific forwarded indent to ourselves url(r'^forwardindent/(?P\d+)/$', views.forwardindent, name='forwardindent'), url(r'^createdindent/(?P\d+)/$', views.createdindent, name='createdindent'), - - - url(r'^entry/$', views.entry, name='entry'), url(r'^StockEntry/$', views.Stock_Entry, name='Stock_Entry'), - - # stock_view is now stock_entry_view which will tell us about the new stock that is entered in any department via a new StockEntry - url(r'^stock_entry_view/$', views.stock_entry_view, name='stock_view'), - - # current_stock_view will tell us about the current situation of stocks present in any department (both transferred to the department and new stocks added in the department) - url(r'^current_stock_view/$', views.current_stock_view, name='current_stock_view'), - - # to display individual items belonging to a certain stock entry record. - url(r'^stock_entry_item_view/$', views.stock_entry_item_view, name='stock_entry_item_view'), - - # to display stock items which are having similar item_type ,grade and department.(used in current_stock_view) - url(r'^stock_item_view/$', views.stock_item_view, name='stock_item_view'), - - - - - + url(r'^stock_view/$', views.stock_view, name='stock_view'), url(r'^stock_delete/$', views.stock_delete, name='stock_delete'), url(r'^stock_edit/$', views.stock_edit, name='stock_edit'), url(r'^stock_update/$', views.stock_update, name='stock_update'), - url(r'^stock_login/$', views.dealing_assistant, name='dealing_assistant'), - - - url(r'^generate_report/$', views.generate_report, name='generate_report'), - url(r'^report/$', views.report, name='report'), # !not clear - url(r'view-bill//$', views.view_bill, name='view_bill'), - - - url(r'^perform_transfer/$', views.perform_transfer, name='perform_transfer'), - url(r'^stock_transfer/$', views.stock_transfer, name='stock_transfer'), - url(r'^view_transfer/$', views.view_transfer, name='view_transfer'), - - url(r'^outboxview2/$', views.outboxview2, name='outboxview2'), - url(r'^outboxview/$', views.outboxview, name='outboxview'), - - - url(r'^update_stock_item_inUse/$', views.updateStockItemInUse, name='outboxview'), - - # BASE API - url(r'^api/',include('applications.ps1.api.urls')), - + url(r'^entry/$', views.entry, name='entry'), + url(r'^stock_login/$', views.dealing_assistant, name='dealing_assistant') ] diff --git a/FusionIIIT/applications/ps1/views.py b/FusionIIIT/applications/ps1/views.py index f3e603ec5..15168a6b9 100644 --- a/FusionIIIT/applications/ps1/views.py +++ b/FusionIIIT/applications/ps1/views.py @@ -1,7 +1,7 @@ from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect -from applications.filetracking.sdk.methods import * -from applications.ps1.models import IndentFile,StockEntry,StockItem,StockTransfer +from applications.filetracking.models import File, Tracking +from applications.ps1.models import IndentFile,StockEntry from applications.globals.models import ExtraInfo, HoldsDesignation, Designation from django.template.defaulttags import csrf_token from django.http import HttpResponse, HttpResponseRedirect, JsonResponse @@ -11,51 +11,9 @@ from django.contrib.auth.models import User from timeit import default_timer as time from notification.views import office_module_notif -from django.utils import timezone -from datetime import datetime -from applications.globals.models import DepartmentInfo -import re -import json - -from django.db.models import Q,Count - -dept_admin_to_dept = { - "deptadmin_cse": "CSE", - "deptadmin_ece": "ECE", - "deptadmin_me": "ME", - "deptadmin_sm": "SM", - "deptadmin_design": "Design", - "deptadmin_liberalarts": "Liberal Arts", - "deptadmin_ns": "Natural Science", -} - -dept_admin_design = ["deptadmin_cse", "deptadmin_ece", "deptadmin_me","deptadmin_sm", "deptadmin_design", "deptadmin_liberalarts","deptadmin_ns" ] - @login_required(login_url = "/accounts/login/") def ps1(request): - des_obj = HoldsDesignation.objects.filter(user=request.user) - - if des_obj: - designations = [des.designation.name for des in des_obj] - - # request.session['currentDesignationSelected'] - currentDes = request.session['currentDesignationSelected'] - - print('currentDes : ',currentDes); - - isdept_admin = any(designation in dept_admin_to_dept for designation in designations) - - if(isdept_admin or currentDes=="ps_admin"): - return redirect('/purchase-and-store/entry/') - elif not("student" in designations) and str((request.user.extrainfo.department.name)): - return redirect('/purchase-and-store/create_proposal/') - else: - return redirect('/dashboard') - - -@login_required(login_url = "/accounts/login/") -def create_proposal(request): """ The function is used to create indents by faculty. It adds the indent datails to the indet_table of Purchase and Store module @@ -76,7 +34,7 @@ def create_proposal(request): estimated_cost=request.POST.get('estimated_cost') purpose=request.POST.get('purpose') specification=request.POST.get('specification') - item_type=request.POST.get('item_type') + indent_type=request.POST.get('indent_type') nature=request.POST.get('nature') indigenous=request.POST.get('indigenous') replaced =request.POST.get('replaced') @@ -88,8 +46,11 @@ def create_proposal(request): financial_approval=False purchased =request.POST.get('purchased') """ - print("request.user.id : ", request.user.id) - + des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() + if str(des.designation) == "student": + return redirect('/dashboard') + if request.user.extrainfo.id == '132': + return redirect("/purchase-and-store/entry/") if request.method =="POST": try: if 'save' in request.POST: @@ -99,13 +60,15 @@ def create_proposal(request): design = request.POST.get('design') designation = Designation.objects.get(id = HoldsDesignation.objects.select_related('user','working','designation').get(id = design).designation_id) upload_file = request.FILES.get('myfile') + + item_name=request.POST.get('item_name') quantity= request.POST.get('quantity') present_stock=request.POST.get('present_stock') estimated_cost=request.POST.get('estimated_cost') purpose=request.POST.get('purpose') specification=request.POST.get('specification') - item_type=request.POST.get('item_type') + indent_type=request.POST.get('indent_type') nature=request.POST.get('nature') indigenous=request.POST.get('indigenous') replaced =request.POST.get('replaced') @@ -133,7 +96,7 @@ def create_proposal(request): estimated_cost=estimated_cost, purpose=purpose, specification=specification, - item_type=item_type, + indent_type=indent_type, nature=nature, indigenous=indigenous, replaced = replaced , @@ -147,24 +110,21 @@ def create_proposal(request): ) if 'send' in request.POST: - - - print('request.POST : ',request.POST); - uploader = request.user.extrainfo subject = request.POST.get('title') description = request.POST.get('desc') design = request.POST.get('design') designation = Designation.objects.get(id = HoldsDesignation.objects.select_related('user','working','designation').get(id = design).designation_id) + upload_file = request.FILES.get('myfile') + item_name=request.POST.get('item_name') quantity= request.POST.get('quantity') present_stock=request.POST.get('present_stock') estimated_cost=request.POST.get('estimated_cost') purpose=request.POST.get('purpose') specification=request.POST.get('specification') - item_type=request.POST.get('item_type') - grade=request.POST.get('grade') + indent_type=request.POST.get('indent_type') nature=request.POST.get('nature') indigenous=request.POST.get('indigenous') replaced =request.POST.get('replaced') @@ -175,62 +135,26 @@ def create_proposal(request): director_approval=False financial_approval=False purchased = False - designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user = request.user) - - for des in designations: - if request.session['currentDesignationSelected'] == "Director": - head_approval=True - director_approval=True - financial_approval=True - break - - - - # current_id = request.user.extrainfo - # remarks = request.POST.get('remarks') - - sender = request.POST.get('design') - current_design = HoldsDesignation.objects.select_related('user','working','designation').get(id=sender) - - - receiver = request.POST.get('receiver') - try: - receiver_id = User.objects.get(username=receiver) - except Exception as e: - messages.error(request, 'Enter a valid Username') - return redirect('/filetracking/') - recieve = request.POST.get('recieve') - try: - receive_design = Designation.objects.get(name=recieve) - except Exception as e: - receive_design = Designation.objects.get(name=recieve) - messages.error(request, 'Enter a valid Designation') - return redirect('/purchase-and-store/create_proposal/') - - - file_id = create_file( - uploader=request.user, - uploader_designation=designation, - receiver= receiver_id, - receiver_designation=receive_design, - src_module="ps1", - src_object_id="", - file_extra_JSON={"value": 2}, - attached_file=upload_file + file = File.objects.create( + uploader=uploader, + description=description, + subject=subject, + designation=designation, + upload_file=upload_file ) + IndentFile.objects.create( - file_info=get_object_or_404(File, pk=file_id), + file_info=file, item_name= item_name, quantity=quantity, present_stock=present_stock, estimated_cost=estimated_cost, purpose=purpose, specification=specification, - item_type=item_type, + indent_type=indent_type, nature=nature, - grade=grade, indigenous=indigenous, replaced = replaced , budgetary_head=budgetary_head, @@ -242,6 +166,37 @@ def create_proposal(request): purchased =purchased, ) + + current_id = request.user.extrainfo + remarks = request.POST.get('remarks') + + sender = request.POST.get('design') + current_design = HoldsDesignation.objects.select_related('user','working','designation').get(id=sender) + + receiver = request.POST.get('receiver') + try: + receiver_id = User.objects.get(username=receiver) + except Exception as e: + messages.error(request, 'Enter a valid Username') + return redirect('/filetracking/') + receive = request.POST.get('recieve') + try: + receive_design = Designation.objects.get(name=receive) + except Exception as e: + messages.error(request, 'Enter a valid Designation') + return redirect('/ps1/') + + upload_file = request.FILES.get('myfile') + + Tracking.objects.create( + file_id=file, + current_id=current_id, + current_design=current_design, + receive_design=receive_design, + receiver_id=receiver_id, + remarks=remarks, + upload_file=upload_file, + ) office_module_notif(request.user, receiver_id) messages.success(request,'Indent Filed Successfully!') @@ -252,19 +207,12 @@ def create_proposal(request): extrainfo = ExtraInfo.objects.select_related('user','department').all() holdsdesignations = HoldsDesignation.objects.select_related('user','working','designation').all() designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user = request.user) - today = timezone.now().strftime('%Y-%m-%d') - - currDesig = request.session['currentDesignationSelected'] - dept_admin_design = ['dept_admin1', 'dept_admin2', 'dept_admin3'] # Replace with actual department admin designations - isAdmin = currDesig == 'ps_admin' or currDesig in dept_admin_design context = { 'file': file, 'extrainfo': extrainfo, 'holdsdesignations': holdsdesignations, 'designations': designations, - 'today': today, - 'isAdmin': isAdmin, } return render(request, 'ps1/composeIndent.html', context) @@ -283,9 +231,6 @@ def create_proposal(request): # } # return render(request, 'ps1/composeIndent.html', context) - - - @login_required(login_url = "/accounts/login") def composed_indents(request): @@ -310,9 +255,6 @@ def composed_indents(request): # print(File.objects) # extrainfo = ExtraInfo.objects.all() # designation = Designation.objects.get(id=HoldsDesignation.objects.get(user=request.user).designation_id) - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') designation = HoldsDesignation.objects.filter(user=request.user) context = { # 'draft': draft, @@ -321,29 +263,6 @@ def composed_indents(request): } return render(request, 'ps1/composed_indents.html', context) - - -@login_required(login_url = "/accounts/login") -def drafts_for_multiple_item(request): - """ - The function is used to get all the designations hold by the user. - - @param: - request - trivial. - - @variables: - context - Holds data needed to make necessary changes in the template. - """ - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') - designation = HoldsDesignation.objects.filter(user=request.user) - context = { - 'designation': designation, - } - return render(request, 'ps1/drafts1.html', context) - - def drafts(request): """ The function is used to get all the files created by user(employee). @@ -366,9 +285,6 @@ def drafts(request): # print(File.objects) # extrainfo = ExtraInfo.objects.all() # designation = Designation.objects.get(id=HoldsDesignation.objects.get(user=request.user).designation_id) - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') designation = HoldsDesignation.objects.filter(user=request.user) context = { # 'draft': draft, @@ -379,7 +295,7 @@ def drafts(request): @login_required(login_url = "/accounts/login") def indentview(request,id): - print("id : ",id); + tracking_objects=Tracking.objects.all() tracking_obj_ids=[obj.file_id for obj in tracking_objects] @@ -399,57 +315,9 @@ def indentview(request,id): } return render(request, 'ps1/indentview.html', context) - -# @login_required(login_url = "/accounts/login") -# def draftview_multiple_items_indent(request,id): -# """ -# The function is used to get all the files created by user(employee). -# It gets all files created by user by filtering file(table) object by user i.e, uploader. -# It displays user and file details of a file(table) of filetracking(model) in the -# template of 'Saved files (new)' tab for indentfile with multiple items. - -# @param: -# request - trivial. - -# @variables: -# draft - The File object filtered by uploader(user). -# extrainfo - The Extrainfo object. -# context - Holds data needed to make necessary changes in the template. -# """ - - -# des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() -# if request.session['currentDesignationSelected'] == "student": -# return redirect('/dashboard') - -# indents= IndentFile2.objects.filter(file_info__in=request.user.extrainfo.uploaded_files.all()).select_related('file_info') -# indent_ids=[indent.file_info for indent in indents] -# filed_indents=Tracking.objects.filter(file_id__in=indent_ids) -# filed_indent_ids=[indent.file_id for indent in filed_indents] -# draft = list(set(indent_ids) - set(filed_indent_ids)) -# draft_indent=IndentFile2.objects.filter(file_info__in=draft).values("file_info") -# draft_files=File.objects.filter(id__in=draft_indent).order_by('-upload_date') -# extrainfo = ExtraInfo.objects.all() -# abcd = HoldsDesignation.objects.get(pk=id) -# s = str(abcd).split(" - ") -# designations = s[1] - -# context = { -# 'draft':draft_files, -# 'extrainfo': extrainfo, -# 'designations': designations, -# } -# return render(request, 'ps1/draftview1.html', context) - - - @login_required(login_url = "/accounts/login") def draftview(request,id): - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') - indents= IndentFile.objects.filter(file_info__in=request.user.extrainfo.uploaded_files.all()).select_related('file_info') indent_ids=[indent.file_info for indent in indents] filed_indents=Tracking.objects.filter(file_id__in=indent_ids) @@ -471,33 +339,26 @@ def draftview(request,id): @login_required(login_url = "/accounts/login") def indentview2(request,id): + + + + indent_files = IndentFile.objects.all().values('file_info') + print(indent_files) + in_file = Tracking.objects.filter(file_id__in=indent_files,receiver_id=request.user).order_by("-receive_date") + + #print (File.designation) abcd = HoldsDesignation.objects.get(pk=id) s = str(abcd).split(" - ") designations = s[1] - data = view_inbox(request.user.username, designations, "ps1") - - outboxd = view_outbox(request.user.username, designations, "ps1") - data = sorted(data, key=lambda x: datetime.fromisoformat(x['upload_date']), reverse=True) - - for item in data: - item['upload_date'] = datetime.fromisoformat(item['upload_date']) - context = { - 'receive_design':abcd, - 'in_file': data, + + 'in_file': in_file, + 'designations': designations, } return render(request, 'ps1/indentview2.html', context) - - - - - - - - @login_required(login_url = "/accounts/login") def inward(request): """ @@ -511,27 +372,18 @@ def inward(request): in_file - The Tracking object filtered by receiver_id i.e, present working user. context - Holds data needed to make necessary changes in the template. """ - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if str(des.designation) == "student": - return redirect('/dashboard') - designation = HoldsDesignation.objects.filter(user=request.user) + in_file=Tracking.objects.filter(receiver_id=request.user).order_by('-receive_date') + + context = { + 'in_file': in_file, 'designation': designation, } return render(request, 'ps1/inwardIndent.html', context) - - - - - - @login_required(login_url = "/accounts/login") def confirmdelete(request,id): - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') file = File.objects.get(pk = id) context = { @@ -567,8 +419,6 @@ def forwardindent(request, id): # start = timer() # end = timer() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') indent=IndentFile.objects.select_related('file_info').get(file_info=id) file=indent.file_info # start = timer() @@ -576,9 +426,10 @@ def forwardindent(request, id): 'current_design__user','current_design__working','current_design__designation','receiver_id','receive_design').filter(file_id=file) # end = timer() - if request.method == "POST": - # print('Mohit Will Win : ' , request.POST); + + + if request.method == "POST": if 'finish' in request.POST: file.complete_flag = True file.save() @@ -586,15 +437,11 @@ def forwardindent(request, id): if 'send' in request.POST: current_id = request.user.extrainfo remarks = request.POST.get('remarks') - sender_design_id = request.POST.get('sender') - sender_designationobj = HoldsDesignation.objects.get(id=sender_design_id).designation - sender_designation_name = sender_designationobj.name - receiverHdid = request.POST.get('receive') - receiverHdobj = HoldsDesignation.objects.get(id=receiverHdid) - receiver = receiverHdobj.user.username - receive_design = receiverHdobj.designation.name + sender = request.POST.get('sender') + current_design = HoldsDesignation.objects.select_related('user','working','designation').get(id=sender) + receiver = request.POST.get('receiver') try: receiver_id = User.objects.get(username=receiver) except Exception as e: @@ -602,73 +449,102 @@ def forwardindent(request, id): designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) context = { + # 'extrainfo': extrainfo, + # 'holdsdesignations': holdsdesignations, 'designations': designations, 'file': file, 'track': track, } return render(request, 'ps1/forwardindent.html', context) + receive = request.POST.get('recieve') try: - receive_design = Designation.objects.get(name=receive_design) + receive_design = Designation.objects.get(name=receive) except Exception as e: messages.error(request, 'Enter a valid Designation') designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) context = { + # 'extrainfo': extrainfo, + # 'holdsdesignations': holdsdesignations, 'designations': designations, 'file': file, 'track': track, } return render(request, 'ps1/forwardindent.html', context) - + # receive_design = receive_designation[0] upload_file = request.FILES.get('myfile') - forwarded_file_id = forward_file( - file_id=file.id, - receiver=receiver_id, - receiver_designation=receive_design, - file_extra_JSON={"key": 2}, + # return HttpResponse ("success") + Tracking.objects.create( + file_id=file, + current_id=current_id, + current_design=current_design, + receive_design=receive_design, + receiver_id=receiver_id, remarks=remarks, - file_attachment=upload_file + upload_file=upload_file, ) - - - if (str(receive_design) in dept_admin_design): - indent.head_approval=True - elif (( - (sender_designation_name in dept_admin_design) - or - (sender_designation_name == "ps_admin") - ) - and (str(receive_design) == "Accounts Admin")): - indent.director_approval=True - indent.financial_approval=True - indent.head_approval=True - + check=str(request.user) + val=str(request.POST.get('approval')) + + + # if val=="accept": + # print("correct") + # if check=="ptandon" or check=="atul" or check=="prabin16" or check=="subirs" or check=="prabir": + # indent.head_approval=True + # elif check=="director": + # indent.director_approval=True + # elif check=="rizwan": + # indent.financial_approval=True + + # else: + # if check=="ptandon" or check=="atul" or check=="prabin16" or check=="subirs" or check=="prabir": + # indent.head_approval=False + # elif check=="director": + # indent.director_approval=False + # elif check=="rizwan": + # indent.financial_approval=False + + designs =[] designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) for designation in designations : s = str(designation).split(" - ") designs.append(s[1]) + + if val=="accept": + if any(d in designs for d in ("HOD (ME)", "HOD (ECE)", "CSE HOD", "HOD (Design)", "HOD (NS)")): + indent.head_approval=True + elif "Director" in designs: + indent.director_approval=True + indent.financial_approval=True + + else: + if any(d in designs for d in ("HOD (ME)", "HOD (ECE)", "CSE HOD", "HOD (Design)", "HOD (NS)")): + indent.head_approval=False + elif "Director" in designs: + indent.director_approval=False + indent.financial_approval=False + + indent.save() - messages.success(request, 'Indent File Forwarded successfully') + messages.success(request, 'Indent File sent successfully') + # start = timer() extrainfo = ExtraInfo.objects.select_related('user','department').all() holdsdesignations = HoldsDesignation.objects.select_related('user','working','designation').all() designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - - - context = { - 'extrainfo': extrainfo, - 'holdsdesignations': holdsdesignations, + # 'extrainfo': extrainfo, + # 'holdsdesignations': holdsdesignations, 'designations':designations, 'file': file, 'track': track, - 'indent':indent + 'indent':indent, } return render(request, 'ps1/forwardindent.html', context) @@ -691,9 +567,6 @@ def createdindent(request, id): holdsdesignations = HoldsDesignation objects. context - Holds data needed to make necessary changes in the template. """ - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') # start = timer() # end = timer() @@ -749,6 +622,8 @@ def createdindent(request, id): 'track': track, } return render(request, 'ps1/createdindent.html', context) + + # receive_design = receive_designation[0] upload_file = request.FILES.get('myfile') # return HttpResponse ("success") Tracking.objects.create( @@ -763,9 +638,14 @@ def createdindent(request, id): messages.success(request, 'Indent File sent successfully') + # start = timer() + extrainfo = ExtraInfo.objects.select_related('user','department').all() + holdsdesignations = HoldsDesignation.objects.select_related('user','working','designation').all() designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) context = { + # 'extrainfo': extrainfo, + # 'holdsdesignations': holdsdesignations, 'designations':designations, 'file': file, 'track': track, @@ -776,10 +656,9 @@ def createdindent(request, id): + def AjaxDropdown1(request): - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') + print('brefore post') if request.method == 'POST': value = request.POST.get('value') # print(value) @@ -797,6 +676,7 @@ def AjaxDropdown1(request): def AjaxDropdown(request): + print('asdasdasdasdasdasdasdas---------------\n\n') # Name = ['student','co-ordinator','co co-ordinator'] # design = Designation.objects.filter(~Q(name__in=(Name))) # hold = HoldsDesignation.objects.filter(Q(designation__in=(design))) @@ -805,9 +685,6 @@ def AjaxDropdown(request): # for h in hold: # arr.append(ExtraInfo.objects.filter(user=h.user)) - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') if request.method == 'POST': value = request.POST.get('value') @@ -826,9 +703,6 @@ def test(request): @login_required(login_url = "/accounts/login") def delete(request,id): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') file = File.objects.get(pk = id) file.delete() @@ -847,40 +721,76 @@ def delete(request,id): return redirect('/ps1/composed_indents/') +@login_required(login_url = "/accounts/login") +def Stock_Entry(request): + + + if request.method=='GET' : + + return HttpResponseRedirect('../stock_view') -# stock Edit will provide the prepoulated form for updation of information. + if request.method =="POST": + + + #dealing_assistant_id=request.POST.get('dealing_assistant_id') + id=request.POST.get('id') + + + temp1=File.objects.get(id=id) + temp=IndentFile.objects.get(file_info=temp1) + + + + dealing_assistant_id=request.user.extrainfo + + item_id=temp + item_name=request.POST.get('item_name') + vendor=request.POST.get('vendor') + current_stock=request.POST.get('current_stock') + recieved_date=request.POST.get('recieved_date') + bill=request.FILES.get('bill') + + + # staff=Staff.objects.get(id=request.user.extrainfo) + + StockEntry.objects.create(item_id=item_id,item_name= item_name,vendor=vendor,current_stock=current_stock,dealing_assistant_id=dealing_assistant_id,bill=bill,recieved_date=recieved_date,) + IndentFile.objects.filter(file_info=temp).update(purchased=True) + + return HttpResponseRedirect('../stock_view') + + + + + + @login_required(login_url = "/accounts/login") def stock_edit(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') + # stocks=StockEntry.objects.get(pk=id) + # return render(request,'ps1/stock_edit.html',{'StockEntry':stocks}) + if request.method =="POST": id=request.POST.get('id') temp=File.objects.get(id=id) temp1=IndentFile.objects.get(file_info=temp) - Stock_Entry=StockEntry.objects.get(item_id=temp1) - - print(Stock_Entry.recieved_date); - formatted_received_date = Stock_Entry.recieved_date.strftime("%Y-%m-%d") - - persons = ExtraInfo.objects.filter(user_type__in=["staff"]) - return render(request,'ps1/stock_edit.html',{'StockEntry':Stock_Entry,'persons':persons,'formatted_received_date': formatted_received_date}) - - return HttpResponseRedirect('../stock_entry_view') + stocks=StockEntry.objects.get(item_id=temp1) + return render(request,'ps1/stock_edit.html',{'StockEntry':stocks}) + + # if 'save' in request.POST: + # stocks.item_name=request.POST.get('item_name') + # stocks.vendor=request.POST.get('vendor') + # stocks.current_stock=request.POST.get('current_stock') + # stocks.recieved_date=request.POST.get('recieved_date') + # stocks.bill=request.FILES.get('bill') + # stocks.save() + + return HttpResponseRedirect('../stock_view') #else: # print("ELSE") # return render(request,'ps1/stock_edit.html',{'StockEntry':stocks}) - - -# This view defines the logic for stock -@login_required(login_url = "/accounts/login") + def stock_update(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - if request.method =="POST": if 'save' in request.POST: id=request.POST.get('id') @@ -888,179 +798,36 @@ def stock_update(request): temp1=IndentFile.objects.get(file_info=temp) stocks=StockEntry.objects.get(item_id=temp1) - # Retrieve the ExtraInfo instance based on the provided string value - - print(request.POST); - - dealing_assistant_id_str = request.POST.get('dealing_assistant_id').split('-')[0].strip(); - print({dealing_assistant_id_str}) - - dealing_assistant_instance = ExtraInfo.objects.get(id=dealing_assistant_id_str) - - stocks.dealing_assistant_id = dealing_assistant_instance - + stocks.item_name=request.POST.get('item_name') stocks.vendor=request.POST.get('vendor') stocks.current_stock=request.POST.get('current_stock') - # stocks.recieved_date=request.POST.get('recieved_date') + #stocks.recieved_date=request.POST.get('recieved_date') stocks.bill=request.FILES.get('bill') - stocks.location = request.POST.get('location') - stocks.recieved_date = request.POST.get('recieved_date') - stocks.save() - return HttpResponseRedirect('../stock_entry_view') - - -# this is know the current situation of stocks present in any department. - -@login_required(login_url = "/accounts/login") -def current_stock_view(request): + return HttpResponseRedirect('../stock_view') + - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - # for handling the search after submission of filters form - if request.method=="POST": - print('the requested data : ', request.POST) - department = request.POST.get('department') - grade = request.POST.get('grade') - type = request.POST.get('type') - - # StockEntryId__item_id__file_info_grade - StockItems = StockItem.objects.filter( - department=department, - StockEntryId__item_id__grade=grade, - StockEntryId__item_id__item_type=type - ) - - grouped_items = StockItems.values('StockEntryId__item_id__item_type', 'StockEntryId__item_id__grade','department').annotate(total_quantity=Count('id')) - - grouped_items_list = [ - { - 'item_type': item['StockEntryId__item_id__item_type'], - 'grade': item['StockEntryId__item_id__grade'], - 'department': DepartmentInfo.objects.get(id=department), - 'total_quantity': item['total_quantity'] - } - for item in grouped_items - ] - - - firstStock=StockItems.first() - - return render(request,'ps1/current_stock_view.html',{'stocks':grouped_items_list,'first_stock':firstStock, - 'stockItems':StockItems}) - # return render(request,'ps1/current_stock_view.html',{'stocks':StockItems,'quantity':StockItems.count()}) - - - # THIS IS HARDCODED FOR NOW . - itemsTypes=['Equipment','Machinery','Furniture','Fixture'] - grades=['A','B','C'] - departmentUser=request.user.extrainfo.department - - if request.session['currentDesignationSelected'] in dept_admin_design: - # if department admin then only show the stocks of that department to them - - print(dept_admin_to_dept[request.session['currentDesignationSelected']]); - deptId = DepartmentInfo.objects.get(name=dept_admin_to_dept[request.session['currentDesignationSelected']]) - - departments=[deptId] - - StockItems = StockItem.objects.filter(department=deptId) - - elif request.session['currentDesignationSelected'] == "ps_admin": - departments=DepartmentInfo.objects.all() - StockItems = StockItem.objects.all() - else : - return redirect('/dashboard') - - - grouped_items = StockItems.values('StockEntryId__item_id__item_type', 'StockEntryId__item_id__grade','department').annotate(total_quantity=Count('id')) - - grouped_items_list = [ - { - 'item_type': item['StockEntryId__item_id__item_type'], - 'grade': item['StockEntryId__item_id__grade'], - 'department': DepartmentInfo.objects.get(id=item['department']), - 'departmentId': item['department'], - 'total_quantity': item['total_quantity'] - } - for item in grouped_items - ] - - return render(request,'ps1/current_stock_view_filter.html',{'itemsTypes':itemsTypes,'grades':grades,'departments':departments,'stocks':grouped_items_list}) -# to display stock items which are having similar item_type ,grade and department.(used in current_stock_view) - -@login_required(login_url = "/accounts/login") -def stock_item_view(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - if request.method=="POST": - departmentId = request.POST.get('departmentId') - grade = request.POST.get('grade') - type = request.POST.get('item_type') - - # StockEntryId__item_id__file_info_grade - StockItems = StockItem.objects.filter( - department=departmentId, - StockEntryId__item_id__grade=grade, - StockEntryId__item_id__item_type=type - ) - - return render(request,'ps1/stock_item_view.html',{'stocks':StockItems}) - - -@login_required(login_url = "/accounts/login") -def stock_entry_view(request): - - # ! CHALLENGE HERE IS HOW TO SHOW THE TRANSFERRED STOCKS AND CURRENTLY PRESENT. - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - department = request.user.extrainfo.department - - if request.session['currentDesignationSelected'] in dept_admin_design: - # if department admin then only show the stocks of that department to them - print("I am a department admin "); - deptId = DepartmentInfo.objects.get(name=dept_admin_to_dept[request.session['currentDesignationSelected']]) - stocks=StockEntry.objects.filter(item_id__file_info__uploader__department=deptId) - elif request.session['currentDesignationSelected'] == "ps_admin": - print("I am a PS admin "); - stocks=StockEntry.objects.all() - else : - return redirect('/dashboard') - - print('stocks : ',stocks) +# def stock_view(request): +# sto=StockEntry.objects.all() +# return render(request,'ps1/stock_view.html',{'StockEntry':sto}) +# @login_required(login_url = "/accounts/login") +def stock_view(request): - return render(request,'ps1/stock_entry_view.html',{'stocks':stocks}) - -@login_required(login_url = "/accounts/login") -def stock_entry_item_view(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - department = request.user.extrainfo.department - file_id = request.POST.get('id') - temp=File.objects.get(id=file_id) - temp1=IndentFile.objects.get(file_info=temp) - Stock_Entry=StockEntry.objects.get(item_id=temp1) - - - stocks=StockItem.objects.filter(StockEntryId=Stock_Entry) - - return render(request,'ps1/stock_entry_item_view.html',{'stocks':stocks,'first_stock':stocks.first()}) - - - - + sto=StockEntry.objects.all() + if sto: + temp=sto.first() + + if temp.item_id.purchased: + print("Purchase Succesful") + print() + print() + + return render(request,'ps1/stock_view.html',{'sto':sto}) @login_required(login_url = "/accounts/login") def stock_delete(request): - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') if request.method=='POST': @@ -1071,323 +838,26 @@ def stock_delete(request): temp1=IndentFile.objects.get(file_info=temp) stocks=StockEntry.objects.get(item_id=temp1) stocks.delete() - return HttpResponseRedirect('../stock_entry_view') - - - - - + return HttpResponseRedirect('../stock_view') @login_required(login_url = "/accounts/login") def entry(request): - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - # To Add stock corresponding to 'id' indent File. + if request.method=='POST': - # id is the id of the File Object here id=request.POST.get('id') - RequestFile = File.objects.select_related('uploader').get(id=id) - - # Requester is the person who uploaded the IndentFile Initially and you can access all of the requesters info available in User model (AbstractUser) like username ,email etc. - Requester = RequestFile.uploader.user - - # RequestFile.uploader contains the Extra information about the uploader of the RequestFile (using ExtraInfo Foreign key) - - - persons = ExtraInfo.objects.filter(user_type__in=["staff"]) - - CorrespondingIndentFile=IndentFile.objects.get(file_info=RequestFile) - return render(request,'ps1/StockEntry.html',{'id':id, 'indent':CorrespondingIndentFile,'RequestFile':RequestFile,'persons':persons}) - - - - # ent=IndentFile.objects.all() - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - department = request.user.extrainfo.department.name - - # this is to filter out the indent files only specific to a department like if A is a department Admin then he should only see the indent files corresponding to his department. - if request.session['currentDesignationSelected'] in dept_admin_design: - IndentFiles=IndentFile.objects.filter(file_info__uploader__department__name=dept_admin_to_dept[request.session['currentDesignationSelected']]) - else : - # otherwise all the indent files will be shown. - IndentFiles=IndentFile.objects.all() - return render(request,'ps1/entry.html',{'IndentFiles':IndentFiles}) - - -@login_required(login_url = "/accounts/login") -def Stock_Entry(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - else : - if request.method=='GET' : - return HttpResponseRedirect('../stock_entry_view') + temp=File.objects.get(id=id) + temp1=IndentFile.objects.get(file_info=temp) + return render(request,'ps1/StockEntry.html',{'id':id, 'indent':temp1}) - if request.method =="POST": - - id=request.POST.get('id') - temp1=File.objects.get(id=id) - temp=IndentFile.objects.get(file_info=temp1) - - item_id=temp - dealing_assistant_id=request.user.extrainfo - vendor=request.POST.get('vendor') - current_stock=request.POST.get('current_stock') - recieved_date=request.POST.get('recieved_date') - bill=request.FILES.get('bill') - location= request.POST.get('location') - - StockEntry.objects.create( - item_id=item_id, - vendor=vendor, - current_stock=current_stock, - dealing_assistant_id=dealing_assistant_id, - bill=bill, - recieved_date=recieved_date, - location=location - ) - - # marking the indent file as done - IndentFile.objects.filter(file_info=temp).update(purchased=True) - return HttpResponseRedirect('../stock_entry_view') - + + ent=IndentFile.objects.all() + return render(request,'ps1/entry.html',{'ent':ent}) + def dealing_assistant(request): - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - if request.session['currentDesignationSelected'] == "student": - return redirect('/dashboard') print(request.user.extrainfo.id) print(type(request.user.extrainfo.id)) if request.user.extrainfo.id=='132' : - return redirect('/purchase-and-store/entry/') + return redirect('/ps1/entry/') else: return redirect('/ps1') - - -@login_required(login_url = "/accounts/login") -def generate_report(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - des = HoldsDesignation.objects.all().select_related().filter(user = request.user).first() - department = request.user.extrainfo.department.name - - if request.session['currentDesignationSelected'] in dept_admin_design: - sto=StockEntry.objects.filter(item_id__file_info__uploader__department__name=dept_admin_to_dept[request.session['currentDesignationSelected']]) - else: - sto=StockEntry.objects.all() - - return render(request,'ps1/generate_report.html',{'sto':sto}) - - -@login_required(login_url = "/accounts/login") -def report(request): - id=request.POST.get('id') - designations = HoldsDesignation.objects.select_related('user','working','designation').filter(user=request.user) - indent=IndentFile.objects.select_related('file_info').get(file_info=id) - sto=StockEntry.objects.select_related('item_id').get(item_id=indent) - file=indent.file_info - total_stock = indent.quantity + indent.present_stock - - print(sto.recieved_date) - - context = { - 'designations':designations, - 'file': file, - 'indent':indent, - 'sto' : sto, - 'total_stock': total_stock - } - - return render(request,'ps1/report.html',context) - - -def view_bill(request, stock_entry_id): - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - print('Hello I am here ' , stock_entry_id) - stock_entry = get_object_or_404(StockEntry, pk=stock_entry_id) - - print(stock_entry); - - # Check if the bill file exists - if stock_entry.bill: - # Read the contents of the bill file - bill_content = stock_entry.bill.read() - - # Return the bill file as a response - response = HttpResponse(bill_content, content_type='application/pdf') - response['Content-Disposition'] = f'attachment; filename="{stock_entry.bill.name}"' - return response - else: - # If the bill file does not exist, return a 404 response - return HttpResponse("Bill not found", status=404) - - - -# This is to return a list of stocks available for transfer. -@login_required(login_url = "/accounts/login") -def perform_transfer(request): - - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - if request.method == "POST": - - selected_stock_items = request.POST.getlist('selected_stock_items[]') - indentId = request.POST.get('indentId') - dest_location = request.POST.get('dest_location') - - # print(selected_stock_items) - # print('dest_location : ',dest_location); - - # Use regular expression to extract the number - match = re.search(r'\((\d+)\)', indentId) - - number = match.group(1) # Extract the number from the match - - myIndent = IndentFile.objects.get(file_info=number) - - moreStocksRequired = myIndent.quantity - len(selected_stock_items) - # print('dest_destination : ', myIndent.file_info.uploader.department) - - for item in selected_stock_items: - stock_item = StockItem.objects.get(id=item) - # print('src dest : ', stock_item.department) - - store_cur_dept = stock_item.department; - store_cur_location = stock_item.location; - - # changing the attributes for this stock item as being transferred. - stock_item.department=myIndent.file_info.uploader.department; - stock_item.location=dest_location; - stock_item.inUse= True - stock_item.isTransferred= True - # if a stock_item is been transferred then obviously it will be put into use. - stock_item.save(); - - StockTransfer.objects.create( - indent_file = myIndent, - src_dept=store_cur_dept, - dest_dept=myIndent.file_info.uploader.department, - stockItem=stock_item, - src_location=store_cur_location, - dest_location=dest_location - ) - - messages.success(request,'Stock Transfer Done Successfully.!') - # if the quantity required for this indent file is fulfilled we should mark this indentfile as done. - if(moreStocksRequired<=0): - myIndent.purchased=True - else : - myIndent.quantity=moreStocksRequired; - - myIndent.save(); - - department = request.user.extrainfo.department.name - - return HttpResponseRedirect('../view_transfer') - -# This is to get the list of all the available stock items for transfer. -@login_required(login_url = "/accounts/login") -def stock_transfer(request): - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - if request.method =="POST": - # id is the of File instance id in db. - id=request.POST.get('id') - - temp=File.objects.get(id=id) - temp1=IndentFile.objects.get(file_info=temp) - - item_type_required =temp1.item_type - item_grade_required = temp1.grade - - available_items = StockItem.objects.filter( - StockEntryId__item_id__item_type=item_type_required, # Foreign key traversal to IndentFile model - StockEntryId__item_id__grade=item_grade_required, # Foreign key traversal to IndentFile model - inUse=False # Filter for inUse=False - ) - - print(available_items) - return render(request,'ps1/stock_transfer.html',{'indentFile': temp1,'available_items':available_items}) - - return HttpResponseRedirect('../stock_transfer') - - -# to view the transfers -@login_required(login_url = "/accounts/login") -def view_transfer(request): - curr_desg = request.session['currentDesignationSelected'] - if curr_desg not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - if curr_desg=="ps_admin": - stockTransfers = StockTransfer.objects.all(); - - elif curr_desg in dept_admin_design: - user_dept = DepartmentInfo.objects.get(name=dept_admin_to_dept[curr_desg]) - stockTransfers = StockTransfer.objects.filter( - Q(src_dept=user_dept) | Q(dest_dept=user_dept) - ) - - # print('stock Transfers : ',stockTransfers); - - return render(request,'ps1/view_transfer.html',{'stockTransfers': stockTransfers}) - - -@login_required(login_url = "/accounts/login") -def outboxview2(request,id): - abcd = HoldsDesignation.objects.get(pk=id) - s = str(abcd).split(" - ") - designations = s[1] - data = view_outbox(request.user.username, designations, "ps1") - data = sorted(data, key=lambda x: datetime.fromisoformat(x['upload_date']), reverse=True) - - for item in data: - item['upload_date'] = datetime.fromisoformat(item['upload_date']) - - context = { - 'receive_design':abcd, - 'in_file': data, - } - return render(request, 'ps1/outboxview2.html', context) - -@login_required(login_url = "/accounts/login") -def outboxview(request): - - designation = HoldsDesignation.objects.filter(user=request.user) - context = { - 'designation': designation, - } - - return render(request, 'ps1/outboxview.html', context) - - -@login_required(login_url="/accounts/login") -def updateStockItemInUse(request): - if request.session['currentDesignationSelected'] not in dept_admin_design + ["ps_admin"]: - return redirect('/dashboard') - - if request.method == "POST": - - # print(request.POST); - - # Get the JSON data from the request body - json_data = json.loads(request.POST.get('selected_stock_items')) - - - # print('jsondata : ', json_data) - - for item in json_data: - item_id = item['id'] - checked = item['checked'] - stock_item = StockItem.objects.get(id=item_id) - stock_item.inUse = checked - stock_item.save() - - return redirect('/purchase-and-store/current_stock_view') \ No newline at end of file diff --git a/FusionIIIT/applications/recruitment/migrations/0001_initial.py b/FusionIIIT/applications/recruitment/migrations/0001_initial.py index 386d6d6fb..9cf2d3a77 100644 --- a/FusionIIIT/applications/recruitment/migrations/0001_initial.py +++ b/FusionIIIT/applications/recruitment/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.conf import settings diff --git a/FusionIIIT/applications/research_procedures/migrations/0001_initial.py b/FusionIIIT/applications/research_procedures/migrations/0001_initial.py index 2befdff1a..ec4b77a48 100644 --- a/FusionIIIT/applications/research_procedures/migrations/0001_initial.py +++ b/FusionIIIT/applications/research_procedures/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.conf import settings diff --git a/FusionIIIT/applications/scholarships/helpers.py b/FusionIIIT/applications/scholarships/helpers.py deleted file mode 100644 index 489f340a4..000000000 --- a/FusionIIIT/applications/scholarships/helpers.py +++ /dev/null @@ -1,14 +0,0 @@ -import subprocess -from datetime import datetime - -from django.conf import settings - - -def getBatch(roll): - batch = "20" - if(str(roll)[2].isdigit()): - return str(roll)[0:4] - - else: - batch+=str(roll)[0:2] - return batch \ No newline at end of file diff --git a/FusionIIIT/applications/scholarships/migrations/0001_initial.py b/FusionIIIT/applications/scholarships/migrations/0001_initial.py index 13627011e..176422fd9 100644 --- a/FusionIIIT/applications/scholarships/migrations/0001_initial.py +++ b/FusionIIIT/applications/scholarships/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 import datetime from django.db import migrations, models @@ -10,8 +10,8 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('globals', '0001_initial'), ('academic_information', '0001_initial'), + ('globals', '0001_initial'), ] operations = [ @@ -85,7 +85,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('programme', models.CharField(default='B.Tech', max_length=10)), - ('year', models.IntegerField(default=2024)), + ('year', models.IntegerField(default=2023)), ('award_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scholarships.award_and_scholarship')), ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), ], diff --git a/FusionIIIT/applications/scholarships/migrations/0002_auto_20240420_1925.py b/FusionIIIT/applications/scholarships/migrations/0002_auto_20240420_1925.py new file mode 100644 index 000000000..4980445b7 --- /dev/null +++ b/FusionIIIT/applications/scholarships/migrations/0002_auto_20240420_1925.py @@ -0,0 +1,18 @@ +# Generated by Django 3.1.5 on 2024-04-20 19:25 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('scholarships', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='previous_winner', + name='year', + field=models.IntegerField(default=2024), + ), + ] diff --git a/FusionIIIT/applications/scholarships/urls.py b/FusionIIIT/applications/scholarships/urls.py index 77a292977..fd5a3516f 100755 --- a/FusionIIIT/applications/scholarships/urls.py +++ b/FusionIIIT/applications/scholarships/urls.py @@ -17,6 +17,5 @@ url(r'^getConvocationFlag/$', views.getConvocationFlag, name='getConvocationFlag'), url(r'^getContent/$', views.getContent, name='getContent'), url(r'^updateEndDate/$', views.updateEndDate, name='updateEndDate'), - url(r'^deleteRelease/$', views.deleteRelease, name='deleteRelease'), ] diff --git a/FusionIIIT/applications/scholarships/views.py b/FusionIIIT/applications/scholarships/views.py index 0d95daa96..5f547149f 100755 --- a/FusionIIIT/applications/scholarships/views.py +++ b/FusionIIIT/applications/scholarships/views.py @@ -3,7 +3,6 @@ from operator import or_ from functools import reduce -from django.http import JsonResponse from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect @@ -24,13 +23,9 @@ from .validations import MCM_list, MCM_schema, gold_list, gold_schema, silver_list, silver_schema, proficiency_list,proficiency_schema from jsonschema import validate from jsonschema.exceptions import ValidationError -from .helpers import getBatch # Create your views here. - - - @login_required(login_url='/accounts/login') def spacs(request): convener = Designation.objects.get(name='spacsconvenor') @@ -75,8 +70,6 @@ def spacs(request): @login_required(login_url='/accounts/login') def convener_view(request): - print(request) - try: convener = Designation.objects.get(name='spacsconvenor') hd = HoldsDesignation.objects.get( @@ -84,11 +77,8 @@ def convener_view(request): except: return HttpResponseRedirect('/logout') if request.method == 'POST': - print("this is a check for post request") if 'Submit' in request.POST: - print("this is a check for post xfhjgisdfkhlsjk request") award = request.POST.get('type') - print("award " + award) programme = request.POST.get('programme') batch = request.POST.get('batch') from_date = request.POST.get('From') @@ -108,27 +98,14 @@ def convener_view(request): ) # It updates the student Notification table on the spacs head sending the mcm invitation - if batch == 'All': + if batch == 'all': active_batches = range(datetime.datetime.now().year - 4 , datetime.datetime.now().year + 1) - # active_batches=str(active_batches) - # active_batches.split(',') - print(active_batches) - querybatch = [] - for curbatch in active_batches: - if curbatch > 2019: - curbatch=curbatch%2000 - querybatch.append(curbatch) - print( active_batches) - query = reduce(or_, (Q(id__id__startswith=batch) for batch in querybatch)) - print(query) + query = reduce(or_, (Q(id__id__startswith=batch) for batch in active_batches)) recipient = Student.objects.filter(programme=programme).filter(query) else: - if(int(batch)>2019): - curbatch=int(batch)%2000 - recipient = Student.objects.filter(programme=programme, id__id__startswith=curbatch) + recipient = Student.objects.filter(programme=programme, id__id__startswith=batch) # Notification starts - print(recipient) convenor = request.user for student in recipient: scholarship_portal_notif(convenor, student.id.user, 'award_' + award) # Notification @@ -147,9 +124,9 @@ def convener_view(request): notification_convocation_flag=True, invite_convocation_accept_flag=False) for student in recipient]) # Notification ends - print(batch) + messages.success(request, - award + ' applications are invited successfully for ' + str(batch) + ' batch(es)') + award + ' applications are invited successfully for ' + batch + ' batch(es)') return HttpResponseRedirect('/spacs/convener_view') elif 'Email' in request.POST: @@ -280,7 +257,6 @@ def convener_view(request): @login_required(login_url='/accounts/login') def student_view(request): - if request.method == 'POST': if 'Submit_MCM' in request.POST: return submitMCM(request) @@ -406,52 +382,37 @@ def convenerCatalogue(request): context['result'] = 'Failure' return HttpResponse(json.dumps(context), content_type='convenerCatalogue/json') - - -#below function is refactored and changed as it is not used by the user interface -#it will be changed later for other testing and download of winners def getWinners(request): - # Extract parameters from the request award_name = request.GET.get('award_name') batch_year = int(request.GET.get('batch')) programme_name = request.GET.get('programme') - - # Get the Award_and_scholarship object based on the provided award name - try: - award = Award_and_scholarship.objects.get(award_name=award_name) - except Award_and_scholarship.DoesNotExist: - return JsonResponse({'result': 'Failure', 'message': 'Award not found'}) - - # Query for previous winners based on the provided criteria - winners = Previous_winner.objects.select_related('student__extra_info').filter( + award = Award_and_scholarship.objects.get(award_name=award_name) + winners = Previous_winner.objects.select_related('student','award_id').filter( year=batch_year, award_id=award, programme=programme_name) + context = {} + context['student_name'] = [] + context['student_program'] = [] + context['roll'] = [] - context = { - 'result': 'Success', - 'winners': [], - } - - # Process the winners if any found +# If-Else Condition for previous winner if there is or no data in the winner table if winners: for winner in winners: - # Fetch extra information for the student - extra_info = winner.student.extra_info + + extra_info = ExtraInfo.objects.get(id=winner.student_id) + student_id = Student.objects.get(id=extra_info) student_name = extra_info.user.first_name student_roll = winner.student_id - student_program = winner.student.programme - - # Append student details to the context - context['winners'].append({ - 'student_name': student_name, - 'roll': student_roll, - 'student_program': student_program, - }) + student_program = student_id.programme + context['student_name'].append(student_name) + context['roll'].append(student_roll) + context['student_program'].append(student_program) + + context['result'] = 'Success' else: context['result'] = 'Failure' - context['message'] = 'No winners found for the provided criteria' - return JsonResponse(context) + return HttpResponse(json.dumps(context), content_type='getWinners/json') def get_MCM_Flag(request): # Here we are extracting mcm_flag x = Notification.objects.select_related('student_id','release_id').filter(student_id=request.user.extrainfo.id) @@ -470,7 +431,7 @@ def get_MCM_Flag(request): # Here we are extracting mcm_flag # return HttpResponseRedirect('/spacs/student_view') def getConvocationFlag(request): # Here we are extracting convocation_flag - x = Notification.objects.select_related('student_id', 'release_id').filter(student_id=request.user.extrainfo.id) + x = Notification.objects.filter(student_id=request.user.extrainfo.id) for i in x: i.invite_convocation_accept_flag = True i.save() @@ -520,18 +481,6 @@ def updateEndDate(request): context['result'] = 'Failure' return HttpResponse(json.dumps(context), content_type='updateEndDate/json') -def deleteRelease(request): - print("deleteRelease") - id = request.GET.get('id') - is_deleted = Release.objects.filter(pk=id).delete() - request.session['last_clicked'] = "Release_deleted" - context = {} - if is_deleted: - context['result'] = 'Success' - else: - context['result'] = 'Failure' - return HttpResponse(json.dumps(context), content_type='deleteRelease/json') - def getAwardId(request): award = request.POST.get('award') a = Award_and_scholarship.objects.get(award_name=award).id @@ -1063,6 +1012,7 @@ def sendConvenerRenderRequest(request, additionalParams={}): source = Constants.FATHER_OCC_CHOICE time = Constants.TIME release = Release.objects.all() + notification = Notification.objects.select_related('student_id','release_id').all() spi = Spi.objects.all() context.update({ 'source': source, 'time': time, 'ch': ch, 'spi': spi, 'release': release}) context.update(additionalParams) @@ -1070,7 +1020,6 @@ def sendConvenerRenderRequest(request, additionalParams={}): def sendStudentRenderRequest(request, additionalParams={}): context = getCommonParams(request) - ch = Constants.BATCH time = Constants.TIME mother_occ = Constants.MOTHER_OCC_CHOICES @@ -1090,48 +1039,24 @@ def sendStudentRenderRequest(request, additionalParams={}): update_con_flag = False x_notif_mcm_flag = False x_notif_con_flag = False - student_batch = getBatch(request.user.extrainfo.student) for dates in release: if checkDate(dates.startdate, dates.enddate): - curBatch = dates.batch - checkBatch = str(request.user.extrainfo.student)[0:4] - batchCondition = False - if checkBatch[2] >= "A" and checkBatch[2] <= "Z": - if(curBatch == 'All'): - batchRange = range(datetime.datetime.now().year - 4, datetime.datetime.now().year + 1) - for batches in batchRange : - if int(checkBatch[0:2]) == batches % 2000: - batchCondition = True - elif curBatch == checkBatch: - batchCondition = True - else: - if(curBatch == 'All'): - batchRange = range(datetime.datetime.now().year - 4, datetime.datetime.now().year + 1) - for batch in batchRange: - if str(checkBatch) == batch: - batchCondition = True - elif curBatch == checkBatch: - True - print("bye") - - - print(curBatch, checkBatch) - if dates.award == 'Merit-cum-Means Scholarship' and batchCondition and dates.programme == request.user.extrainfo.student.programme: + if dates.award == 'Merit-cum-Means Scholarship' and dates.batch == str(request.user.extrainfo.student)[0:4] and dates.programme == request.user.extrainfo.student.programme: x_notif_mcm_flag = True if no_of_mcm_filled > 0: update_mcm_flag = True - elif dates.award == 'Convocation Medals' and dates.batch == student_batch and dates.programme == request.user.extrainfo.student.programme: + elif dates.award == 'Convocation Medals' and dates.batch == str(request.user.extrainfo.student)[0:4] and dates.programme == request.user.extrainfo.student.programme: x_notif_con_flag = True if no_of_con_filled > 0: update_con_flag = True else: - if dates.award == "Merit-cum-Means Scholarship" and dates.batch == student_batch: + if dates.award == "Merit-cum-Means Scholarship" and dates.batch == str(request.user.extrainfo.student)[0:4]: try: x = Notification.objects.select_related('student_id','release_id').get( student_id=request.user.extrainfo.id, release_id=dates.id).delete() except: pass - elif dates.award == 'Convocation Medals' and dates.batch == student_batch: + elif dates.award == 'Convocation Medals' and dates.batch == str(request.user.extrainfo.student)[0:4]: try: x = Notification.objects.select_related('student_id','release_id').get( student_id=request.user.extrainfo.id, release_id=dates.id).delete() @@ -1156,7 +1081,7 @@ def sendStudentRenderRequest(request, additionalParams={}): context.update(additionalParams) return render(request, 'scholarshipsModule/scholarships_student.html',context) -def sendStaffRenderRequest(request, additionalParams={}): +def sendStaffRenderRequest(request, additionalParams={}): context = getCommonParams(request) context.update(additionalParams) return render(request, 'scholarshipsModule/scholarships_staff.html', context) diff --git a/FusionIIIT/applications/visitor_hostel/forms.py b/FusionIIIT/applications/visitor_hostel/forms.py index c506bc932..32b915407 100644 --- a/FusionIIIT/applications/visitor_hostel/forms.py +++ b/FusionIIIT/applications/visitor_hostel/forms.py @@ -5,37 +5,41 @@ from applications.visitor_hostel.models import * +from .models import Inventory + #class booking_request(forms.Form): CHOICES = (('A', 'A',), ('B', 'B',), ('C', 'C',), ('D', 'D',)) class ViewBooking(forms.Form): - date_from = forms.DateField(initial=datetime.date.today) - date_to = forms.DateField(initial=datetime.date.today) + date_from = forms.DateField(initial=datetime.date.today) + date_to = forms.DateField(initial=datetime.date.today) +class MealBooking(ModelForm): + date = forms.DateField(initial=datetime.date.today) + class Meta: + model = MealRecord + exclude = ['meal_date'] class RoomAvailability(forms.Form): - date_from = forms.DateField(initial=datetime.date.today) - date_to = forms.DateField(initial=datetime.date.today) + date_from = forms.DateField(initial=datetime.date.today) + date_to = forms.DateField(initial=datetime.date.today) -# class InventoryForm(forms.Form): -# # class Meta: -# # model = Inventory -# # fields = ["item_name", "quantity"] -# item_name = forms.CharField(max_length=20) -# quantity = forms.IntegerField(min_value=0) -# consumable = forms.BooleanField(initial=False) -# # checkbox = ["consumable"] +class InventoryForm(forms.ModelForm): + class Meta: + model = Inventory + fields = ["item_name", "quantity", "consumable"] class Room_booking(forms.Form): - name = forms.CharField(max_length=100) - mob = forms.CharField(max_length=12) - email = forms.CharField(max_length=40) - address = forms.CharField(max_length=200) - country = forms.CharField(max_length=25) - category = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) - total_persons = forms.IntegerField() - purpose = forms.CharField(widget=forms.Textarea) - date_from = forms.DateField(initial=datetime.date.today) - date_to = forms.DateField(initial=datetime.date.today) + name = forms.CharField(max_length=100) + mob = forms.CharField(max_length=12) + email = forms.CharField(max_length=40) + address = forms.CharField(max_length=200) + country = forms.CharField(max_length=25) + category = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) + total_persons = forms.IntegerField() + purpose = forms.CharField(widget=forms.Textarea) + date_from = forms.DateField(initial=datetime.date.today) + date_to = forms.DateField(initial=datetime.date.today) + \ No newline at end of file diff --git a/FusionIIIT/applications/visitor_hostel/migrations/0001_initial.py b/FusionIIIT/applications/visitor_hostel/migrations/0001_initial.py index 96df7d704..f4229feb2 100644 --- a/FusionIIIT/applications/visitor_hostel/migrations/0001_initial.py +++ b/FusionIIIT/applications/visitor_hostel/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 3.1.5 on 2024-04-15 23:58 +# Generated by Django 3.1.5 on 2023-03-15 18:53 from django.conf import settings from django.db import migrations, models @@ -89,13 +89,14 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('meal_date', models.DateField()), - ('morning_tea', models.IntegerField(default=0)), - ('eve_tea', models.IntegerField(default=0)), - ('breakfast', models.IntegerField(default=0)), - ('lunch', models.IntegerField(default=0)), - ('dinner', models.IntegerField(default=0)), + ('morning_tea', models.BooleanField(default=False)), + ('eve_tea', models.BooleanField(default=False)), + ('breakfast', models.BooleanField(default=False)), + ('lunch', models.BooleanField(default=False)), + ('dinner', models.BooleanField(default=False)), ('persons', models.IntegerField(default=0)), ('booking', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='visitor_hostel.bookingdetail')), + ('room', models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='visitor_hostel.roomdetail')), ('visitor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='visitor_hostel.visitordetail')), ], ), @@ -125,7 +126,6 @@ class Migration(migrations.Migration): ('meal_bill', models.IntegerField(default=0)), ('room_bill', models.IntegerField(default=0)), ('payment_status', models.BooleanField(default=False)), - ('bill_date', models.DateField(blank=True, default=django.utils.timezone.now)), ('booking', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='visitor_hostel.bookingdetail')), ('caretaker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('room', models.ManyToManyField(to='visitor_hostel.RoomDetail')), diff --git a/FusionIIIT/applications/visitor_hostel/models.py b/FusionIIIT/applications/visitor_hostel/models.py index ffd49a1be..508b2fa63 100644 --- a/FusionIIIT/applications/visitor_hostel/models.py +++ b/FusionIIIT/applications/visitor_hostel/models.py @@ -58,6 +58,7 @@ class VisitorDetail(models.Model): visitor_address = models.TextField(blank=True) nationality = models.CharField(max_length=20, blank=True) + def __str__(self): return '{} - {}'.format(self.id, self.visitor_name, self.visitor_email, self.visitor_organization, self.visitor_address, self.visitor_phone) @@ -70,7 +71,7 @@ class RoomDetail(models.Model): room_status = models.CharField(max_length=20, choices=ROOM_STATUS, default='Available') def __str__(self): - return '{} - {}'.format(self.id, self.room_number , self.room_type, self.room_status, self.room_floor) + return self.room_number class BookingDetail(models.Model): @@ -99,7 +100,7 @@ class BookingDetail(models.Model): number_of_rooms_alloted = models.IntegerField(default=1,null=True,blank=True) booking_date = models.DateField(auto_now_add=False, auto_now=False, default=timezone.now) bill_to_be_settled_by = models.CharField(max_length=15, choices=BILL_TO_BE_SETTLED_BY ,default ="Intender") - + def __str__(self): return '%s ----> %s - %s id is %s and category is %s' % (self.id, self.visitor, self.status, self.id, self.visitor_category) @@ -107,12 +108,13 @@ def __str__(self): class MealRecord(models.Model): booking = models.ForeignKey(BookingDetail, on_delete=models.CASCADE) visitor = models.ForeignKey(VisitorDetail, on_delete=models.CASCADE) + room = models.ForeignKey(RoomDetail, on_delete=models.CASCADE, default=0) meal_date = models.DateField() - morning_tea = models.IntegerField(default=0) - eve_tea = models.IntegerField(default=0) - breakfast = models.IntegerField(default=0) - lunch = models.IntegerField(default=0) - dinner = models.IntegerField(default=0) + morning_tea = models.BooleanField(default=False) + eve_tea = models.BooleanField(default=False) + breakfast = models.BooleanField(default=False) + lunch = models.BooleanField(default=False) + dinner = models.BooleanField(default=False) persons=models.IntegerField(default=0) @@ -123,7 +125,6 @@ class Bill(models.Model): meal_bill = models.IntegerField(default=0) room_bill = models.IntegerField(default=0) payment_status = models.BooleanField(default=False) - bill_date = models.DateField(default=timezone.now, blank=True) def __str__(self): return '%s ----> %s - %s id is %s' % (self.booking.id, self.meal_bill, self.room_bill, self.payment_status) @@ -153,3 +154,5 @@ class InventoryBill(models.Model): def __str__(self): return str(self.bill_number) + + diff --git a/FusionIIIT/applications/visitor_hostel/static/visitor_hostel/visitor-hostel.js b/FusionIIIT/applications/visitor_hostel/static/visitor_hostel/visitor-hostel.js index 5338efcbc..3ecb7a431 100644 --- a/FusionIIIT/applications/visitor_hostel/static/visitor_hostel/visitor-hostel.js +++ b/FusionIIIT/applications/visitor_hostel/static/visitor_hostel/visitor-hostel.js @@ -294,41 +294,31 @@ function request_booking (event) { // Meal Record -function bookameal_submit(event, htmlElement){ - console.log('hii') +$('.bookameal-submit').click(function(event){ event.preventDefault(); - var pk = $(htmlElement).attr('data-pk'); - var booking_id = $(htmlElement).attr('booking_id') - // 'numberofpeople': $('input[name="numberofpeople-meal"]').val(), - console.log(pk); - var jsondata = { - 'pk' : pk, - 'booking' : booking_id, - 'm_tea': $(`input[name="m_tea${booking_id}"]`).val(), - 'breakfast': $(`input[name="breakfast${booking_id}"]`).val(), - 'lunch': $(`input[name="lunch${booking_id}"]`).val(), - 'eve_tea': $(`input[name="eve_tea${booking_id}"]`).val(), - 'dinner': $(`input[name="dinner${booking_id}"]`).val(), - - 'csrfmiddlewaretoken': $('input[name="csrf"]').val(), - } - console.log(jsondata) + var pk = $(this).attr('data-pk'); + var food = [] + $('input[name=food'+pk+']:checked').each(function(){ + food.push($(this).val()); + }); $.ajax({ type: 'POST', url: '/visitorhostel/record-meal/', - data: jsondata, + data: { + 'pk' : pk, + 'booking' : $('input[name="meal-booking-id"]').val(), + 'numberofpeople': $('input[name="numberofpeople-meal"]').val(), + 'food':food, + 'csrfmiddlewaretoken': $('input[name="csrf"]').val(), + }, success: function(data) { alertModal('Great! Meals recorded successfully'); - setTimeout(function() { - location.reload(); - }, 1500); - }, - error: function (data, err) { - alertModal('Something missing! Please refill the form '); + error: function(data, err) { + alertModal('Something missing! Please refill the form'); } }); -}; +}); // Update Inventory @@ -366,75 +356,49 @@ function submit_inventory_form(id){ // Adding more items to inventory -// $('#add-more-items-inventory').click(function(event){ +$('#add-more-items-inventory').click(function(event){ -// $.ajax({ -// type: 'POST', -// url: '/visitorhostel/add-to-inventory/', -// data: { -// 'item' : $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value, -// 'quantity' : $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value, -// 'amount' : $('.reset-this-form')[0].children[2].children[2].children[1].children[0].value, -// 'consumable' : $('.reset-this-form')[0].children[2].children[3].children[1].children[0].value, -// 'csrfmiddlewaretoken': '{{csrf_token}}' -// }, -// success: function(data) { -// $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value = ""; -// $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value = ""; -// $('.reset-this-form')[0].children[2].children[2].children[1].children[0].value = ""; -// }, -// error: function(data, err) { -// alertModal('Something missing! Please refill the form'); -// } -// }); - -// }); - -function add_inventory_item(event) { - event.preventDefault(); - jsondata = { - 'csrfmiddlewaretoken': $('input[name="csrf"]').val(), - 'item_name' : $('input[name="item_name"]').val(), - 'quantity' : $('input[name="quantity_add"]').val(), - 'cost' : $('input[name="cost"]').val(), - 'consumable': ($('input[name="consumable"]:checked').val())?true:false, - 'bill_number' : $('input[name="bill_number"]').val() - } - console.log(jsondata) $.ajax({ type: 'POST', url: '/visitorhostel/add-to-inventory/', - data: jsondata, + data: { + 'item' : $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value, + 'quantity' : $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value, + 'amount' : $('.reset-this-form')[0].children[2].children[2].children[1].children[0].value, + 'consumable' : $('.reset-this-form')[0].children[2].children[3].children[1].children[0].value, + 'csrfmiddlewaretoken': '{{csrf_token}}' + }, success: function(data) { - // $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value = ""; - // $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value = ""; - // $('.reset-this-form')[0].children[2].children[2].children[1].children[0].value = ""; - alertModal('Great! Item added successfully'); - setTimeout(function() { - location.reload(); - }, 1500); + $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value = ""; + $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value = ""; + $('.reset-this-form')[0].children[2].children[2].children[1].children[0].value = ""; }, - error: function(xhr, data, err) { + error: function(data, err) { alertModal('Something missing! Please refill the form'); } - }); -} -$('.add-item-form-submit').click(function(event){ + +}); + +$('#add-item-form-submit').click(function(event){ event.preventDefault(); - jsondata = { - 'csrfmiddlewaretoken': $('input[name="csrf"]').val(), - 'item_name' : $('input[name="item_name"]').val(), - 'quantity' : $('input[name="quantity_add"]').val(), - 'cost' : $('input[name="cost"]').val(), - 'consumable': ($('input[name="consumable"]:checked').val())?true:false, - 'bill_number' : $('input[name="bill_number"]').val() - } - console.log(jsondata) + if($('input[name="consumable"]:checked')){ + consumable = 'True'; + } + else{ + consumable = 'False'; + } $.ajax({ type: 'POST', url: '/visitorhostel/add-to-inventory/', - data: jsondata, + data: { + 'csrfmiddlewaretoken': $('input[name="csrf"]').val(), + 'item_name' : $('input[name="item-name"]').val(), + 'quantity' : $('input[name="quantity_add"]').val(), + 'cost' : $('input[name="cost"]').val(), + 'consumable' : consumable, + 'bill_number' : $('input[name="bill_number"]').val() + }, success: function(data) { $('.reset-this-form')[0].children[2].children[0].children[1].children[0].value = ""; $('.reset-this-form')[0].children[2].children[1].children[1].children[0].value = ""; @@ -650,20 +614,12 @@ function forward_booking (id) { previous_category = $('input[name=category-'+id+']').val(); modified_category = $('input[name=modified-category-'+id+']').val(); rooms = $('select[name=alloted-rooms-'+id+']').val(); - rem = $('input[name=cancellation-remarks-' + id + ']').val(); - console.log("TExt rem: ", rem); + // if (previous_category == 0) { // alertModal("Please fill the category to confirm."); // return; // } - console.log("Rooms: ", rooms); - remark = ""; - for (x in rooms) { - remark += rooms[x] + " "; - } - remark += "can be alloted"; - console.log("remarks: ", remark); if (modified_category == 0) { modified_category = previous_category; } @@ -681,8 +637,7 @@ function forward_booking (id) { 'csrfmiddlewaretoken': csrfmiddlewaretoken, 'previous_category' : previous_category, 'modified_category' : modified_category, - 'rooms': rooms, - 'remark': remark, + 'rooms' : rooms, }, success: function(data) { alertModal("This booking has been forwarded"); @@ -729,28 +684,28 @@ function cancel_active_booking (id, booking_from) { // Edit Inventory -// $("#edit-inventory").click(function(e){ -// $(".inventory-item").slideToggle(); -// $(".inventory-form").slideToggle(); -// $("#update-inventory-submit").slideToggle(); -// }); -// $("#update-inventory-submit").click(function(e){ -// event.preventDefault(); -// $.ajax({ -// type: 'POST', -// url: '/visitorhostel/bookaroom/', -// data: { -// 'csrfmiddlewaretoken' : '{{csrf_token}}', -// 'data' : data -// }, -// success: function(data) { -// alertModal("Congratulations! Inventory is updated successfully"); -// }, -// error: function(data, err) { -// alertModal('Something missing! PLease refill the form'); -// } -// }); -// }); +$("#edit-inventory").click(function(e){ + $(".inventory-item").slideToggle(); + $(".inventory-form").slideToggle(); + $("#update-inventory-submit").slideToggle(); +}); +$("#update-inventory-submit").click(function(e){ + event.preventDefault(); + $.ajax({ + type: 'POST', + url: '/visitorhostel/bookaroom/', + data: { + 'csrfmiddlewaretoken' : '{{csrf_token}}', + 'data' : data + }, + success: function(data) { + alertModal("Congratulations! Inventory is updated successfully"); + }, + error: function(data, err) { + alertModal('Something missing! PLease refill the form'); + } + }); +}); // Submit Visitor Details @@ -832,7 +787,7 @@ function submit_visitor_details (id) { // Check Out -function check_out(id, mess_bill, room_bill) { +function check_out (id , mess_bill , room_bill) { $.ajax({ type: 'POST', url: '/visitorhostel/check-out/', @@ -858,10 +813,10 @@ function check_out(id, mess_bill, room_bill) { function bill_between_date_range() { - start = $('input[name=start]').val(); - end = $('input[name=end]').val(); - - if(new Date(start)>new Date(end)) + start_date = $('input[name=start').val(); + end_date = $('input[name=end]').val(); + + if(new Date(start_date)>new Date(end_date)) { alertModal('Please check start date and end date.') return; @@ -869,21 +824,24 @@ function bill_between_date_range() { $.ajax({ type: 'POST', - url: '/visitorhostel/bill_between_dates/', + url: '/visitorhostel/bill_between_date_range/', data: { 'csrfmiddlewaretoken' : $('input[name="csrf"]').val(), - 'start_date' : start, - 'end_date' : end, + 'start_date' : start_date, + 'end_date' : end_date, }, success: function(data) { $('#replace-this-div-booking-bw-dates').html(data); console.log("winning"); + console.log(start_date); // alert('Bookings Between range are ..'); }, error: function(data, err) { - alertModal ('Error !', data, err); + alertModal ('Error !'); + console.log(start_date); + console.log(end_date); // alertModal('Something missing! Please refill the form'); } }); @@ -892,12 +850,14 @@ function bill_between_date_range() { // finding available room's list between date range function find_available_rooms ( available_rooms ) { - start_date = $('input[name=start-date]').val(); + start_date = $('input[name=start-date').val(); end_date = $('input[name=end-date]').val(); if (new Date(start_date) > new Date(end_date)) { alertModal ('Please check start date and end date!'); return; } + console.log(start_date); + console.log(end_date); $.ajax({ type: 'POST', diff --git a/FusionIIIT/applications/visitor_hostel/urls.py b/FusionIIIT/applications/visitor_hostel/urls.py index 1153e0d88..fc352d646 100644 --- a/FusionIIIT/applications/visitor_hostel/urls.py +++ b/FusionIIIT/applications/visitor_hostel/urls.py @@ -12,9 +12,9 @@ url(r'^get-booking-form/', views.get_booking_form, name='get_booking_form'), url(r'^request-booking/' , views.request_booking , name ='request_booking'), url(r'^confirm-booking/' , views.confirm_booking , name ='confirm_booking'), - url(r'^cancel-booking/', views.cancel_booking, name='cancel_booking'), - url(r'^cancel-booking-request/', views.cancel_booking_request,name='cancel_booking_request'), - url(r'^reject-booking/', views.reject_booking, name='reject_booking'), + url(r'^cancel-booking/', views.cancel_booking, name = 'cancel_booking'), + url(r'^cancel-booking-request/', views.cancel_booking_request, name = 'cancel_booking_request'), + url(r'^reject-booking/', views.reject_booking, name = 'reject_booking'), url(r'^check-in/', views.check_in, name = 'check_in'), url(r'^check-out/', views.check_out, name = 'check_out'), url(r'^record-meal/', views.record_meal, name = 'record_meal'), @@ -29,3 +29,4 @@ url(r'^booking-details/', views.booking_details, name = 'booking_details'), url(r'^forward-booking/', views.forward_booking, name = 'forward_booking'), ] + \ No newline at end of file diff --git a/FusionIIIT/applications/visitor_hostel/views.py b/FusionIIIT/applications/visitor_hostel/views.py index 3419a7d14..ab0711153 100644 --- a/FusionIIIT/applications/visitor_hostel/views.py +++ b/FusionIIIT/applications/visitor_hostel/views.py @@ -25,7 +25,7 @@ import numpy as np from django.contrib.auth.models import User -# from .forms import InventoryForm +from .forms import InventoryForm # for notifications from notification.views import visitors_hostel_notif @@ -61,14 +61,10 @@ def visitorhostel(request): # bookings for intender view if (user_designation == "Intender"): - all_bookings = BookingDetail.objects.select_related( - 'intender', 'caretaker').all().order_by('booking_from') - pending_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(status="Pending") | Q( - status="Forward"), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') - active_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status="CheckedIn", booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') - dashboard_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(status="Pending") | Q(status="Forward") | Q( - status="Confirmed") | Q(status='Rejected'), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') + all_bookings = BookingDetail.objects.select_related('intender','caretaker').all().order_by('booking_from') + pending_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status="Pending") | Q(status="Forward"), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') + active_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status="CheckedIn", booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') + dashboard_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status = "Pending") | Q(status="Forward") | Q(status = "Confirmed") | Q(status = 'Rejected'), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') # print(dashboard_bookings.booking_from) visitors = {} @@ -82,55 +78,43 @@ def visitorhostel(request): temp2 = range(1, booking.number_of_rooms_alloted) rooms[booking.id] = temp2 - complete_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - check_out__lt=datetime.datetime.today(), intender=user).order_by('booking_from').reverse() - canceled_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status="Canceled", intender=user).order_by('booking_from') - rejected_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status='Rejected', intender=user).order_by('booking_from') - cancel_booking_requested = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status='CancelRequested', intender=user).order_by('booking_from') + complete_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(booking_to__lt=datetime.datetime.today(), intender=user).order_by('booking_from') + canceled_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status="Canceled", intender=user).order_by('booking_from') + rejected_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status='Rejected', intender=user).order_by('booking_from') + cancel_booking_requested = BookingDetail.objects.select_related('intender','caretaker').filter(status='CancelRequested', intender=user).order_by('booking_from') + else: # booking for caretaker and incharge view - all_bookings = BookingDetail.objects.select_related( - 'intender', 'caretaker').all().order_by('booking_from') - pending_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - Q(status="Pending") | Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') - active_bookings = BookingDetail.objects.filter(Q(status="Confirmed") | Q( - status="CheckedIn"), booking_to__gte=datetime.datetime.today()).select_related('intender', 'caretaker').order_by('booking_from') - cancel_booking_request = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status="CancelRequested", booking_to__gte=datetime.datetime.today()).order_by('booking_from') - dashboard_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(status="Pending") | Q( - status="Forward") | Q(status="Confirmed"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') - print(dashboard_bookings) + all_bookings = BookingDetail.objects.select_related('intender','caretaker').all().order_by('booking_from') + pending_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status="Pending") | Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') + active_bookings = BookingDetail.objects.filter(Q(status="Confirmed") | Q(status="CheckedIn"), booking_to__gte=datetime.datetime.today()).select_related('intender','caretaker').order_by('booking_from') + cancel_booking_request = BookingDetail.objects.select_related('intender','caretaker').filter(status="CancelRequested", booking_to__gte=datetime.datetime.today()).order_by('booking_from') + dashboard_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status = "Pending") | Q(status="Forward") | Q(status = "Confirmed"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') visitors = {} rooms = {} # x = BookingDetail.objects.all().annotate(rooms_count=Count('rooms')) - c_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') - + c_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') + # number of visitors for booking in active_bookings: temp = range(2, booking.person_count + 1) visitors[booking.id] = temp + # rooms alloted to booking for booking in active_bookings: for room_no in booking.rooms.all(): temp2 = range(2, booking.number_of_rooms_alloted + 1) rooms[booking.id] = temp2 - # print(booking.rooms.all()) + #print(booking.rooms.all()) + - complete_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(status="Canceled") | Q( - status="Complete"), check_out__lt=datetime.datetime.today()).select_related().order_by('booking_from').reverse() - canceled_bookings = BookingDetail.objects.filter(status="Canceled").select_related( - 'intender', 'caretaker').order_by('booking_from') - cancel_booking_requested = BookingDetail.objects.select_related('intender', 'caretaker').filter( - status='CancelRequested', booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') - rejected_bookings = BookingDetail.objects.select_related( - 'intender', 'caretaker').filter(status='Rejected').order_by('booking_from') + complete_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status="Canceled") | Q(status="Complete"), booking_to__lt=datetime.datetime.today()).select_related().order_by('booking_from') + canceled_bookings = BookingDetail.objects.filter(status="Canceled").select_related('intender','caretaker').order_by('booking_from') + cancel_booking_requested = BookingDetail.objects.select_related('intender','caretaker').filter(status='CancelRequested', booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') + rejected_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status='Rejected').order_by('booking_from') # finding available room list for alloting rooms for booking in pending_bookings: @@ -138,18 +122,17 @@ def visitorhostel(request): booking_to = booking.booking_to temp1 = booking_details(booking_from, booking_to) available_rooms[booking.id] = temp1 - + # forwarded rooms details for booking in c_bookings: booking_from = booking.booking_from booking_to = booking.booking_to temp2 = forwarded_booking_details(booking_from, booking_to) forwarded_rooms[booking.id] = temp2 - # print(available_rooms) - # print(forwarded_rooms) # inventory data inventory = Inventory.objects.all() inventory_bill = InventoryBill.objects.select_related('item_name').all() + # completed booking bills completed_booking_bills = {} @@ -157,8 +140,7 @@ def visitorhostel(request): current_balance = 0 for bill in all_bills: - completed_booking_bills[bill.id] = {'intender': str(bill.booking.intender), 'booking_from': str( - bill.booking.booking_from), 'booking_to': str(bill.booking.booking_to), 'total_bill': str(bill.meal_bill + bill.room_bill), 'bill_date': str(bill.bill_date)} + completed_booking_bills[bill.id] = {'intender': str(bill.booking.intender), 'booking_from': str(bill.booking.booking_from), 'booking_to': str(bill.booking.booking_to), 'total_bill': str(bill.meal_bill + bill.room_bill)} current_balance = current_balance+bill.meal_bill + bill.room_bill for inv_bill in inventory_bill: @@ -184,7 +166,7 @@ def visitorhostel(request): category = booking.visitor_category person = booking.person_count - room_bill = 100 + room_bill = 0 if days == 0: days = 1 @@ -211,23 +193,25 @@ def visitorhostel(request): mess_bill = 0 for visitor in booking.visitor.all(): - meal = MealRecord.objects.select_related( - 'booking__intender', 'booking__caretaker', 'visitor').filter(booking_id=booking.id) + meal = MealRecord.objects.select_related('booking__intender','booking__caretaker','visitor','room').filter(visitor=visitor) mess_bill1 = 0 for m in meal: - if m.morning_tea != 0: - mess_bill1 = mess_bill1+m.morning_tea*10 - if m.eve_tea != 0: - mess_bill1 = mess_bill1+m.eve_tea*10 - if m.breakfast != 0: - mess_bill1 = mess_bill1+m.breakfast*50 - if m.lunch != 0: - mess_bill1 = mess_bill1+m.lunch*100 - if m.dinner != 0: - mess_bill1 = mess_bill1+m.dinner*100 - - mess_bill = mess_bill + mess_bill1 + if m.morning_tea == True: + mess_bill1 = mess_bill1+10 + if m.eve_tea == True: + mess_bill1 = mess_bill1+10 + if m.breakfast == True: + mess_bill1 = mess_bill1+50 + if m.lunch == True: + mess_bill1 = mess_bill1+100 + if m.dinner == True: + mess_bill1 = mess_bill1+100 + + if mess_bill1 == 270: + mess_bill = mess_bill+225 + else: + mess_bill = mess_bill + mess_bill1 total_bill = mess_bill + room_bill @@ -239,7 +223,7 @@ def visitorhostel(request): visitor_list = [] for b in dashboard_bookings: - count = 1 + count=1 b_visitor_list = b.visitor.all() for v in b_visitor_list: if count == 1: @@ -252,7 +236,7 @@ def visitorhostel(request): 'pending_bookings': pending_bookings, 'active_bookings': active_bookings, 'canceled_bookings': canceled_bookings, - 'dashboard_bookings': dashboard_bookings, + 'dashboard_bookings' : dashboard_bookings, 'bills': bills, # 'all_rooms_status' : all_rooms_status, @@ -267,7 +251,7 @@ def visitorhostel(request): 'intenders': intenders, 'user': user, 'visitors': visitors, - 'rooms': rooms, + 'rooms' : rooms, # 'num_rooms' : list(range(1, booking.number_of_rooms_alloted+1)), # 'num_rooms' :list(range(1, booking.number_of_rooms_alloted+1)), 'previous_visitors': previous_visitors, @@ -275,17 +259,15 @@ def visitorhostel(request): 'current_balance': current_balance, 'rejected_bookings': rejected_bookings, 'cancel_booking_request': cancel_booking_request, - 'cancel_booking_requested': cancel_booking_requested, + 'cancel_booking_requested' : cancel_booking_requested, 'user_designation': user_designation}) # Get methods for bookings - @login_required(login_url='/accounts/login/') def get_booking_requests(request): if request.method == 'POST': - pending_bookings = BookingDetail.objects.select_related( - 'intender', 'caretaker').filter(status="Pending") + pending_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status="Pending") return render(request, "vhModule/visitorhostel.html", {'pending_bookings': pending_bookings}) else: @@ -293,12 +275,10 @@ def get_booking_requests(request): # getting active bookings - @login_required(login_url='/accounts/login/') def get_active_bookings(request): if request.method == 'POST': - active_bookings = BookingDetail.objects.select_related( - 'intender', 'caretaker').filter(status="Confirmed") + active_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(status="Confirmed") return render(request, "vhModule/visitorhostel.html", {'active_bookings': active_bookings}) else: @@ -307,8 +287,8 @@ def get_active_bookings(request): @login_required(login_url='/accounts/login/') def get_inactive_bookings(request): - if request.method == 'POST': - inactive_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( + if request.method == 'POST' : + inactive_bookings = BookingDetail.objects.select_related('intender','caretaker').filter( Q(status="Cancelled") | Q(status="Rejected") | Q(status="Complete")) return render(request, "vhModule/visitorhostel.html", {'inactive_bookings': inactive_bookings}) @@ -328,27 +308,26 @@ def get_booking_form(request): # request booking form action view starts here - @login_required(login_url='/accounts/login/') def request_booking(request): if request.method == 'POST': - flag = 0 + flag=0 # getting details from request form intender = request.POST.get('intender') user = User.objects.get(id=intender) print("jiihuhhih") print(user) - booking_id = request.POST.get('booking-id') + booking_id = request.POST.get('booking-id') category = request.POST.get('category') person_count = request.POST.get('number-of-people') bookingObject = [] - # if person_count and (int(person_count)<20): - # person_count = person_count + #if person_count and (int(person_count)<20): + # person_count = person_count - # else: - # flag = 1 # for error + #else: + # flag = 1 # for error # person_count = 1 purpose_of_visit = request.POST.get('purpose-of-visit') @@ -356,8 +335,7 @@ def request_booking(request): booking_to = request.POST.get('booking_to') booking_from_time = request.POST.get('booking_from_time') booking_to_time = request.POST.get('booking_to_time') - remarks_during_booking_request = request.POST.get( - 'remarks_during_booking_request') + remarks_during_booking_request = request.POST.get('remarks_during_booking_request') bill_to_be_settled_by = request.POST.get('bill_settlement') number_of_rooms = request.POST.get('number-of-rooms') caretaker = 'shailesh' @@ -366,28 +344,27 @@ def request_booking(request): # flag=1 # if flag ==0: - # print(sys.getsizeof(booking_from_time)) - # print(sys.getsizeof(booking_from)) - # print(sys.getsizeof(purpose_of_visit)) - # print(sys.getsizeof(bill_to_be_settled_by)) - # print("gfcfhcghv") + print(sys.getsizeof(booking_from_time)) + print(sys.getsizeof(booking_from)) + print(sys.getsizeof(purpose_of_visit)) + print(sys.getsizeof(bill_to_be_settled_by)) + care_taker = HoldsDesignation.objects.select_related('user','working','designation').filter(designation__name = "VhCaretaker") - care_taker = care_taker[0] - # print(care_taker,"care_taker") + care_taker = care_taker[1] care_taker = care_taker.user bookingObject = BookingDetail.objects.create( - caretaker=care_taker, - purpose=purpose_of_visit, - intender=user, - booking_from=booking_from, - booking_to=booking_to, - visitor_category=category, - person_count=person_count, - arrival_time=booking_from_time, - departure_time=booking_to_time, - # remark=remarks_during_booking_request, - number_of_rooms=number_of_rooms, - bill_to_be_settled_by=bill_to_be_settled_by) + caretaker = care_taker, + purpose=purpose_of_visit, + intender=user, + booking_from=booking_from, + booking_to=booking_to, + visitor_category=category, + person_count=person_count, + arrival_time=booking_from_time, + departure_time=booking_to_time, + #remark=remarks_during_booking_request, + number_of_rooms=number_of_rooms, + bill_to_be_settled_by=bill_to_be_settled_by) # visitor_hostel_caretaker_notif(request.user,care_taker,"Submitted") # print (bookingObject) # print("Hello") @@ -405,11 +382,10 @@ def request_booking(request): # in case of any attachment doc = request.FILES.get('files-during-booking-request') - remark = remarks_during_booking_request, + remark=remarks_during_booking_request, if doc: print("hello") - filename, file_extenstion = os.path.splitext( - request.FILES.get('files-during-booking-request').booking_id) + filename, file_extenstion = os.path.splitext(request.FILES.get('files-during-booking-request').booking_id) filename = booking_id full_path = settings.MEDIA_ROOT + "/VhImage/" url = settings.MEDIA_URL + filename + file_extenstion @@ -423,7 +399,7 @@ def request_booking(request): bookingObject.image = uploaded_file_url bookingObject.save() - # visitor datails from place request form + # visitor datails from place request form visitor_name = request.POST.get('name') visitor_phone = request.POST.get('phone') @@ -436,8 +412,9 @@ def request_booking(request): visitor_organization = ' ' visitor = VisitorDetail.objects.create( - visitor_phone=visitor_phone, visitor_name=visitor_name, visitor_email=visitor_email, visitor_address=visitor_address, visitor_organization=visitor_organization, nationality=visitor_nationality - ) + visitor_phone=visitor_phone, visitor_name=visitor_name, visitor_email=visitor_email, visitor_address=visitor_address, visitor_organization=visitor_organization + , nationality=visitor_nationality + ) # try: # bd = BookingDetail.objects.get(id=booking_id) @@ -446,13 +423,13 @@ def request_booking(request): bookingObject.save() # except: - # print("exception occured") - # return HttpResponse('/visitorhostel/') + #print("exception occured") + # return HttpResponse('/visitorhostel/') # for sending notification of booking request to caretaker - # caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = "VhCaretaker") - # visitors_hostel_notif(request.user, care_taker.user, 'booking_request') + #caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = "VhCaretaker") + #visitors_hostel_notif(request.user, care_taker.user, 'booking_request') return HttpResponseRedirect('/visitorhostel/') else: @@ -482,33 +459,30 @@ def update_booking(request): number_of_rooms = request.POST.get('number-of-rooms') # remark = request.POST.get('remark') - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) booking.person_count = person_count booking.number_of_rooms = number_of_rooms booking.booking_from = booking_from booking.booking_to = booking_to booking.purpose = purpose_of_visit booking.save() - forwarded_rooms = {} + # BookingDetail.objects.filter(id=booking_id).update(person_count=person_count, # purpose=purpose_of_visit, # booking_from=booking_from, # booking_to=booking_to, # number_of_rooms=number_of_rooms) - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) - c_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter( - Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) + c_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status="Forward"), booking_to__gte=datetime.datetime.today()).order_by('booking_from') for booking in c_bookings: booking_from = booking.booking_from booking_to = booking.booking_to temp2 = forwarded_booking_details(booking_from, booking_to) forwarded_rooms[booking.id] = temp2 return render(request, "visitorhostel/", - { - 'forwarded_rooms': forwarded_rooms}) - + { + 'forwarded_rooms': forwarded_rooms}) + else: return HttpResponseRedirect('/visitorhostel/') @@ -528,11 +502,9 @@ def confirm_booking(request): # rooms list rooms = request.POST.getlist('rooms[]') - # print(rooms) - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) - bd = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + #print(rooms) + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) + bd = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) bd.status = 'Confirmed' bd.category = category @@ -541,9 +513,8 @@ def confirm_booking(request): bd.rooms.add(room_object) bd.save() - # notification of booking confirmation - visitors_hostel_notif(request.user, bd.intender, - 'booking_confirmation') + # notification of booking confirmation + visitors_hostel_notif(request.user, bd.intender, 'booking_confirmation') return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') @@ -557,51 +528,42 @@ def cancel_booking(request): booking_id = request.POST.get('booking-id') remark = request.POST.get('remark') charges = request.POST.get('charges') - BookingDetail.objects.select_related('intender', 'caretaker').filter(id=booking_id).update( + BookingDetail.objects.select_related('intender','caretaker').filter(id=booking_id).update( status='Canceled', remark=remark) - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) # if no applicable charges then set charges to zero x = 0 if charges: - Bill.objects.create(booking=booking, meal_bill=x, room_bill=int( - charges), caretaker=user, payment_status=True) + Bill.objects.create(booking=booking, meal_bill=x, room_bill=int(charges), caretaker=user, payment_status=True) else: - Bill.objects.create(booking=booking, meal_bill=x, - room_bill=x, caretaker=user, payment_status=True) - - complete_bookings = BookingDetail.objects.filter(Q(status="Canceled") | Q( - status="Complete"), booking_to__lt=datetime.datetime.today()).select_related('intender', 'caretaker').order_by('booking_from') + Bill.objects.create(booking=booking, meal_bill=x, room_bill=x, caretaker=user, payment_status=True) + complete_bookings = BookingDetail.objects.filter(Q(status="Canceled") | Q(status="Complete"), booking_to__lt=datetime.datetime.today()).select_related('intender','caretaker').order_by('booking_from') + + # to notify the intender that his cancellation request has been confirmed - visitors_hostel_notif(request.user, booking.intender, - 'booking_cancellation_request_accepted') + visitors_hostel_notif(request.user, booking.intender, 'booking_cancellation_request_accepted') return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') # cancel confirmed booing by intender - @login_required(login_url='/accounts/login/') def cancel_booking_request(request): if request.method == 'POST': - intender = request.user.holds_designations.filter( - designation__name='VhIncharge') + intender = request.user.holds_designations.filter(designation__name = 'VhIncharge') booking_id = request.POST.get('booking-id') remark = request.POST.get('remark') - BookingDetail.objects.select_related('intender', 'caretaker').filter( - id=booking_id).update(status='CancelRequested', remark=remark) + BookingDetail.objects.select_related('intender','caretaker').filter(id=booking_id).update(status='CancelRequested', remark=remark) - incharge_name = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').filter(designation__name="VhIncharge")[1] + incharge_name = HoldsDesignation.objects.select_related('user','working','designation').filter(designation__name = "VhIncharge")[1] # to notify the VhIncharge about a new cancelltaion request - visitors_hostel_notif( - request.user, incharge_name.user, 'cancellation_request_placed') + visitors_hostel_notif(request.user, incharge_name.user, 'cancellation_request_placed') return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') @@ -614,19 +576,18 @@ def reject_booking(request): if request.method == 'POST': booking_id = request.POST.get('booking-id') remark = request.POST.get('remark') - BookingDetail.objects.select_related('intender', 'caretaker').filter(id=booking_id).update( + BookingDetail.objects.select_related('intender','caretaker').filter(id=booking_id).update( status="Rejected", remark=remark) # to notify the intender that his request has been rejected - # visitors_hostel_notif(request.user, booking.intender, 'booking_rejected') + #visitors_hostel_notif(request.user, booking.intender, 'booking_rejected') return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') # Guest check in view - @login_required(login_url='/accounts/login/') def check_in(request): if request.method == 'POST': @@ -641,8 +602,7 @@ def check_in(request): visitor = VisitorDetail.objects.create( visitor_phone=visitor_phone, visitor_name=visitor_name, visitor_email=visitor_email, visitor_address=visitor_address) try: - bd = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + bd = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) bd.status = "CheckedIn" bd.check_in = check_in_date bd.visitor.add(visitor) @@ -656,7 +616,6 @@ def check_in(request): # guest check out view - @login_required(login_url='/accounts/login/') def check_out(request): user = get_object_or_404(User, username=request.user.username) @@ -667,14 +626,11 @@ def check_out(request): id = request.POST.get('id') meal_bill = request.POST.get('mess_bill') room_bill = request.POST.get('room_bill') - checkout_date = datetime.date.today() - total_bill = int(meal_bill)+int(room_bill) - BookingDetail.objects.select_related('intender', 'caretaker').filter(id=id).update( + BookingDetail.objects.select_related('intender','caretaker').filter(id=id).update( check_out=datetime.datetime.today(), status="Complete") - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=id) + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=id) Bill.objects.create(booking=booking, meal_bill=int(meal_bill), room_bill=int( - room_bill), caretaker=user, payment_status=True, bill_date=checkout_date) + room_bill), caretaker=user, payment_status=True) # for visitors in visitor_info: @@ -706,6 +662,7 @@ def check_out(request): return HttpResponseRedirect('/visitorhostel/') + @login_required(login_url='/accounts/login/') def record_meal(request): user = get_object_or_404(User, username=request.user.username) @@ -716,40 +673,58 @@ def record_meal(request): id = request.POST.get('pk') booking_id = request.POST.get('booking') - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) visitor = VisitorDetail.objects.get(id=id) date_1 = datetime.datetime.today() - print(id, booking_id, booking, visitor, date_1) - m_tea = request.POST.get("m_tea") - breakfast = request.POST.get("breakfast") - lunch = request.POST.get("lunch") - eve_tea = request.POST.get("eve_tea") - dinner = request.POST.get("dinner") - - person = 1 - print("bid: ", id) - + food = request.POST.getlist('food[]') + if '1' in food: + m_tea = True + else: + m_tea = False + + if '4' in food: + e_tea = True + else: + e_tea = False + + if '2' in food: + breakfast = True + else: + breakfast = False + + if '3' in food: + lunch = True + else: + lunch = False + + if '5' in food: + dinner = True + else: + dinner = False + + if request.POST.get('numberofpeople'): + person = request.POST.get('numberofpeople') + else: + person = 1 + try: - meal = MealRecord.objects.select_related('booking__intender', 'booking__caretaker', 'visitor').get( + meal = MealRecord.objects.select_related('booking__intender','booking__caretaker','visitor','room').get( visitor=visitor, booking=booking, meal_date=date_1) except: meal = False if meal: - meal.morning_tea += int(m_tea) - meal.eve_tea += int(eve_tea) - meal.breakfast += int(breakfast) - meal.lunch += int(lunch) - meal.dinner += int(dinner) + meal.morning_tea = m_tea + meal.eve_tea = e_tea + meal.breakfast = breakfast + meal.lunch = lunch + meal.dinner = dinner meal.save() - return HttpResponseRedirect('/visitorhostel/') - else: MealRecord.objects.create(visitor=visitor, booking=booking, morning_tea=m_tea, - eve_tea=eve_tea, + eve_tea=e_tea, meal_date=date_1, breakfast=breakfast, lunch=lunch, @@ -762,7 +737,6 @@ def record_meal(request): # generate bill records between date range - @login_required(login_url='/accounts/login/') def bill_generation(request): user = get_object_or_404(User, username=request.user.username) @@ -781,8 +755,7 @@ def bill_generation(request): st = False user = get_object_or_404(User, username=request.user.username) - c = ExtraInfo.objects.select_related( - 'department').filter(user=user) + c = ExtraInfo.objects.select_related('department').filter(user=user) visitor = Visitor.objects.filter(visitor_phone=v_id) visitor = visitor[0] visitor_bill = Visitor_bill.objects.create( @@ -795,7 +768,6 @@ def bill_generation(request): # get available rooms list between date range - @login_required(login_url='/accounts/login/') def room_availabity(request): if request.method == 'POST': @@ -803,7 +775,7 @@ def room_availabity(request): date_2 = request.POST.get('end_date') available_rooms_list = [] available_rooms_bw_dates = booking_details(date_1, date_2) - # print("Available rooms are ") + #print("Available rooms are ") for room in available_rooms_bw_dates: available_rooms_list.append(room.room_number) @@ -819,21 +791,18 @@ def add_to_inventory(request): if request.method == 'POST': item_name = request.POST.get('item_name') bill_number = request.POST.get('bill_number') - quantity = int((request.POST.get('quantity'))) - cost = int(request.POST.get('cost')) + quantity = (request.POST.get('quantity')) + cost = request.POST.get('cost') consumable = request.POST.get('consumable') - if consumable == 'false': - isConsumable = False - else: - isConsumable = True - print(isConsumable) - x = Inventory.objects.create( - item_name=item_name, quantity=quantity, consumable=isConsumable) - print(x.pk) - item = Inventory.objects.get(pk=x.pk) - item_id = item.pk + # if(Inventory.objects.get(item_name = item_name)): + # Inventory.objects.filter(item_name=item_name).update(quantity=quantity,consumable=consumable) + # else: + Inventory.objects.create( + item_name=item_name, quantity=quantity, consumable=consumable) + + item_name_key = Inventory.objects.get(item_name=item_name) InventoryBill.objects.create( - bill_number=bill_number, cost=cost, item_name_id=item_id) + item_name=item_name_key, bill_number=bill_number, cost=cost) return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') @@ -843,13 +812,9 @@ def add_to_inventory(request): def update_inventory(request): if request.method == 'POST': id = request.POST.get('id') - quantity = int(request.POST.get('quantity')) - if quantity < 0: - quantity = 1 - if quantity == 0: - Inventory.objects.filter(id=id).delete() - else: - Inventory.objects.filter(id=id).update(quantity=quantity) + quantity = request.POST.get('quantity') + + Inventory.objects.filter(id=id).update(quantity=quantity) return HttpResponseRedirect('/visitorhostel/') else: return HttpResponseRedirect('/visitorhostel/') @@ -867,6 +832,7 @@ def edit_room_status(request): return HttpResponseRedirect('/visitorhostel/') + @login_required(login_url='/accounts/login/') def bill_between_dates(request): if request.method == 'POST': @@ -875,7 +841,7 @@ def bill_between_dates(request): bill_range_bw_dates = bill_range(date_1, date_2) meal_total = 0 room_total = 0 - individual_total = [] + individual_total =[] # calculating room and mess bill booking wise for i in bill_range_bw_dates: @@ -885,22 +851,24 @@ def bill_between_dates(request): total_bill = meal_total + room_total # zip(bill_range_bw_dates, individual_total) return render(request, "vhModule/booking_bw_dates.html", { - # 'booking_bw_dates': bill_range_bw_dates, - 'booking_bw_dates_length': bill_range_bw_dates, - 'meal_total': meal_total, - 'room_total': room_total, - 'total_bill': total_bill, - 'individual_total': individual_total, - 'booking_bw_dates': zip(bill_range_bw_dates, individual_total) - }) + # 'booking_bw_dates': bill_range_bw_dates, + 'booking_bw_dates_length': bill_range_bw_dates, + 'meal_total' : meal_total, + 'room_total' :room_total, + 'total_bill' : total_bill, + 'individual_total' : individual_total, + 'booking_bw_dates': zip(bill_range_bw_dates, individual_total) + }) else: return HttpResponseRedirect('/visitorhostel/') -def bill_range(date1, date2): - bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1) | Q(booking_from__gte=date1, - booking_to__lte=date2) | Q(booking_from__lte=date2, booking_to__gte=date2) | Q(booking_from__lte=date1, booking_to__gte=date1) | Q(booking_from__gte=date1, booking_to__lte=date2) | Q(booking_from__lte=date2, booking_to__gte=date2)) +def bill_range(date1,date2): + + + bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1) | Q(booking_from__gte=date1, + booking_to__lte=date2) | Q(booking_from__lte=date2, booking_to__gte=date2) | Q(booking_from__lte=date1, booking_to__gte=date1) | Q(booking_from__gte=date1, booking_to__lte=date2) | Q(booking_from__lte=date2, booking_to__gte=date2)) # bill_details = Bill.objects.filter(Q(booking__booking_from__lte=date1, booking__booking_to__gte=date1, booking__status="Confirmed") | Q(booking__booking_from__gte=date1, # booking__booking_to__lte=date2, booking__status="Confirmed") | Q(booking__booking_from__lte=date2, booking__booking_to__gte=date2, status="Confirmed") | Q(booking_from__lte=date1, booking__booking_to__gte=date1, status="CheckedIn") | Q(booking__booking_from__gte=date1, booking__booking_to__lte=date2, booking__status="CheckedIn") | Q(booking__booking_from__lte=date2, booking__booking_to__gte=date2, booking__status="CheckedIn")) bookings_bw_dates = [] @@ -911,9 +879,8 @@ def bill_range(date1, date2): all_bill = Bill.objects.select_related('caretaker').all().order_by('-id') for b_id in booking_ids: - if Bill.objects.select_related('caretaker').filter(booking__pk=b_id).exists(): - bill_id = Bill.objects.select_related( - 'caretaker').get(booking__pk=b_id) + if Bill.objects.select_related('caretaker').filter(booking__pk=b_id).exists() : + bill_id = Bill.objects.select_related('caretaker').get(booking__pk=b_id) bookings_bw_dates.append(bill_id) return bookings_bw_dates @@ -921,9 +888,9 @@ def bill_range(date1, date2): def booking_details(date1, date2): - bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Confirmed") | Q(booking_from__gte=date1, - booking_to__lte=date2, status="Confirmed") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Confirmed") | Q(booking_from__lte=date1, booking_to__gte=date1, status="Forward") | Q(booking_from__gte=date1, - booking_to__lte=date2, status="Forward") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Forward") | Q(booking_from__lte=date1, booking_to__gte=date1, status="CheckedIn") | Q(booking_from__gte=date1, booking_to__lte=date2, status="CheckedIn") | Q(booking_from__lte=date2, booking_to__gte=date2, status="CheckedIn")) + bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Confirmed") | Q(booking_from__gte=date1, + booking_to__lte=date2, status="Confirmed") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Confirmed") | Q(booking_from__lte=date1, booking_to__gte=date1, status="Forward") | Q(booking_from__gte=date1, + booking_to__lte=date2, status="Forward") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Forward") | Q(booking_from__lte=date1, booking_to__gte=date1, status="CheckedIn") | Q(booking_from__gte=date1, booking_to__lte=date2, status="CheckedIn") | Q(booking_from__lte=date2, booking_to__gte=date2, status="CheckedIn")) booked_rooms = [] for booking in bookings: @@ -940,13 +907,12 @@ def booking_details(date1, date2): # function for finding forwarded booking rooms - def forwarded_booking_details(date1, date2): - bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Confirmed") | Q(booking_from__gte=date1, - booking_to__lte=date2, status="Confirmed") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Confirmed") | Q(booking_from__lte=date1, booking_to__gte=date1, status="CheckedIn") | Q(booking_from__gte=date1, booking_to__lte=date2, status="CheckedIn") | Q(booking_from__lte=date2, booking_to__gte=date2, status="CheckedIn")) - forwarded_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Forward") | Q(booking_from__gte=date1, - booking_to__lte=date2, status="Forward") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Forward")) + bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Confirmed") | Q(booking_from__gte=date1, + booking_to__lte=date2, status="Confirmed") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Confirmed") | Q(booking_from__lte=date1, booking_to__gte=date1, status="CheckedIn") | Q(booking_from__gte=date1, booking_to__lte=date2, status="CheckedIn") | Q(booking_from__lte=date2, booking_to__gte=date2, status="CheckedIn")) + forwarded_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(booking_from__lte=date1, booking_to__gte=date1, status="Forward") | Q(booking_from__gte=date1, + booking_to__lte=date2, status="Forward") | Q(booking_from__lte=date2, booking_to__gte=date2, status="Forward") ) booked_rooms = [] # Bookings for rooms which are forwarded but not yet approved @@ -969,14 +935,10 @@ def forward_booking(request): previous_category = request.POST.get('previous_category') modified_category = request.POST.get('modified_category') rooms = request.POST.getlist('rooms[]') - remark = request.POST.get('remark') print(rooms) - BookingDetail.objects.select_related('intender', 'caretaker').filter( - id=booking_id).update(status="Forward", remark=remark) - booking = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) - bd = BookingDetail.objects.select_related( - 'intender', 'caretaker').get(id=booking_id) + BookingDetail.objects.select_related('intender','caretaker').filter(id=booking_id).update(status="Forward") + booking = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) + bd = BookingDetail.objects.select_related('intender','caretaker').get(id=booking_id) bd.modified_visitor_category = modified_category count_rooms = 0 @@ -987,17 +949,14 @@ def forward_booking(request): bd.number_of_rooms_alloted = count_rooms bd.save() - dashboard_bookings = BookingDetail.objects.select_related('intender', 'caretaker').filter(Q(status="Pending") | Q(status="Forward") | Q( - status="Confirmed") | Q(status='Rejected'), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') + dashboard_bookings = BookingDetail.objects.select_related('intender','caretaker').filter(Q(status = "Pending") | Q(status="Forward") | Q(status = "Confirmed") | Q(status = 'Rejected'), booking_to__gte=datetime.datetime.today(), intender=user).order_by('booking_from') # return render(request, "vhModule/visitorhostel.html", # {'dashboard_bookings' : dashboard_bookings}) - incharge_name = HoldsDesignation.objects.select_related( - 'user', 'working', 'designation').filter(designation__name="VhIncharge")[1] + incharge_name = HoldsDesignation.objects.select_related('user','working','designation').filter(designation__name = "VhIncharge")[1] # notify incharge about forwarded booking - visitors_hostel_notif( - request.user, incharge_name.user, 'booking_forwarded') + visitors_hostel_notif(request.user, incharge_name.user, 'booking_forwarded') return HttpResponseRedirect('/visitorhostel/') else: - return HttpResponseRedirect('/visitorhostel/') + return HttpResponseRedirect('/visitorhostel/') \ No newline at end of file diff --git a/FusionIIIT/media/Administrator/academic_information/sheet.xlsx b/FusionIIIT/media/Administrator/academic_information/sheet.xlsx deleted file mode 100644 index 274ab022fa5868f15fcb040c333db7988f25f366..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8786 zcmaJ{1z40_)22ak>6Y$Xq*-U%I;5qfTS;jI1Ox#o32CIeLzI8f?=8Of z|IT&oK6~xXoH^&7XXeZ^_o~RlBcQ_Ej|inz(fjKk;}P_Og|oSetFwz6hYC~-5Bdel zFEPs4FF9PWFff8}Fff3>iv@nr zah~f^z&Xj0*ll_Trn*9|z9mHz>G_1PqhZk8%5e#Hb4p@sR2 zyZdUXlKq+WD=H@a@;TjsYs>_WZ^x=y2%A(1uol2>vk^YYKz4*33~to^vBt470~@># zz{=+p%mpjm+Yv~tFJ>)VnN8$Py8H@g{f6Fb>Kk>EAc+4OI#aADSFZSQ@HFtKkyazZoNmV(N6Yu$w z;w@I;;b*uB8+carx~pXzTx;$Qp8W;s!XjHC;=4sS(%P-i`1Z~D!yLZ}hrk5QBgDSc zhCx*_Y&^(n1LG9$vzlE??@+kibezg^{BNa*(HkGurTTc*8-lIX?K!IvNWGJ4U+$9a zznZ`^AM&Eih;5Vb0jraKd=-?*_9Z5$mTfsK!JhR!@I6@%Ip-t|HhE%5yi7ZvCKiB9 z0ukqB9eQ0d6IlOp#g~)^b7t7AlTUj(5tVmBvG@VO@!}E7 z4C`#|K{_0&i3zkAvN(NpJk3QG(vPmUHge9r#==8DN_TufrR_aCaS&|O)5~iw#tztj zqK!|lQ_BcN8xx8)?my7>aC3KdyvMsJ(NMmJ6EFM_@lIkOAS?ddoZPX0yqeO8k>AgF z&Ygu@R(5So8bj_$i+Pi5auA&B)TSfrV{lo*nq z8VQk)X6(bZvo=pTD&`<-JJNdgUE88$t}eUGtK{SM#x}z(g0E==d#JOe&P&TkiFl{v zZklvX4qe)}5otu~($UPb4og(&BSUy_vnbj>s!PdtZM4_U%qmBYx#G$><#=IfU>_wZ zen8aIp`F8=#-vVCFuJ&#=mX_`hbIzECApbPfLux26Fhu_) z`%49Q@2V6nL+3e8ynx*LJHU0jELk3&WT_yLeUoST#kB)YgpT6sC*H81-wlO;{QJF8 z6n6dnn^%F?c=`SW-*!<5_i{x;KM*`ijVuiEw>18U^PX<> zW$qD|jiTTFI&J#dEo-v2_#KLtZ0|&42h0k|EB(5VGV8T!p2+e7r3vmpb$O98L6%oA zD`3$nGZuV~G)Zjk+zfP3l*vm|}g?Qew;NW~l+6Af;~H%r#6L@m2Sv^HK=Da?XUIf{s9 z3GCiSFR^O+#Ly2M1gs6SS!Njo10{k=rErZPaJT1jNb6)&HMD+D_}EA>&Acc%fQj3^ zv8Tv4c?CTV+cZI2ami<<&mx)&u#kSv5Fgbm%|G4Q;`BO8q&V-By|H{2F-t;`y(08& zC=Am|UWCDYIWxbjH+}WI6WQ-A#d9*6gq}gBIBIzCtxQye_IrdaWnIbko4khN_6ba z3eqYvjsm z$)Na2ntq3PpR)cvaPH4(Xk@wDSUOrhIHy0SW_2wi!obiI|ITcGiv1G)6)yX_iq52b zfOf*IAf3JTM2lS-E^6e)r>pdyIFfQvWMzhSY1m%PluSY`_#fYj2EVo)lMi0>Wt>Bj zff$V&uklJ{!Cj+~yK1wjy|(KgpkgyKZky-p>Cadpbq!eG=?U}gPek27x7I2V3} z#7b*Bd3+d$L}7R#Or=UfJ*YN+ys2}g?Im)%j5?PHRCxVH0e^4Do&Ih3CEni}Nf$>|s)N-vw4I?eWP6kw8LVv@+d*0lXJqzqd;V^N3#O zVlK67Ik#G^VBCGRe|1T+Gu>^ka?sfkPJ!M6kV2~w6X`y%mhR=roC3Rn>isgE*z4m6mDNt=3%j1?LQM3=4yo zKrO4LJn{r22CD%kROQ;}6{1yTo#M7ZrdbPkiWk{H#Z$llr^GdTTw{%L@nL*-mr$f5 z@c5J8kJat%g3XfnK!JeUtFy7uW{#mFn4(16tDWy0KYw1RAJ$kewfml=ka8&89*P89 ze62BV34Rlw8eI7~C}d1yy#=sm>63l2r~QF65Fxbx%sppD zhW+E@`Y8ZtMeXM>7pt1o{6-?FkN(0O_#8)S(UIQph{oy=aE|UHy4~l#L^C6IIVwlKaMR%jjN^|Z%t_Tb9z6+hqT`zRgf?jOi> zEfH4Rj_9ps?NaU9TbHQ&cZc}C6GnmGTiRZlsn~iDeNvvkxy^O}1uCNyNeGl&schlC zgCOBynyAcfS1_>GnCqekm1m>l>b#4jaa;q_i%@Yr?qdv{@Eg`vqE>wu7nTNuZITw= zJF7Z!PbGWH+3E4cZYMk=IzrS{z{v6Cnu~dYK+CM&Vxin+remRV8yei;g`x~m@+@s5 zIjvr_7(Q)4XLz1~%vMS}K7k{0^w8iBYE64qh+YOhKb4P5_0CnSU^)cbAPevze^5PV zN6OQKYsspZ4{@R#!t6iC$ZV3a-MHEU_ObKuDa)prAb3u7)e`Z7==r-+B_7|$ zB+i+;7hFXI!uV0t1W2)8)`QH!V+NrM<-DIKHBd8s8OS@E7a&QGRK6TDxcEhgB%|9s zD@|s5jqMMIMmx%PEA^6YP5dGu@)Tk}_Hl}m3db!zsc@}gJJdylwFUk!s=yh1iN)l}pFe1|c$wJa4Ew*4j}o=>&0SXkIT#RVJ#5 z41)h^+4>mzBmWfE=MK6-EU{$?hNpFT)%pHpW319r&ww955%x?R+gl}ENPX&Wtx!s_ zlU`%T(M*{P=jkof?~w>Z#2Q{Y(BKP5aHk1RsNqlXEHGOQzp;U5dE2Iw%%{U9j=n#> zchu}&Bj@Co@4>PeRx2;sHFPD=av(qwBIYQNA*Bd3N;55*{ZP6fM1Tego%6{I%fA_Z z{x#)Yig338Il58lY3PF8RQG2KaP?&3m%9$myPmE-EK!i}5u2BE(Ey@&sOQ~-Qn$I# z5HA3FV5G~#z+n77H{9HP94y`LE2k-g-MB0*z)$0{LrCNtg=+i82HHp8iApb9>LS}h zhbcM7hHldOSG zf~tpg4(F9i%A1!)TgBGLgVD=rmaoE`kc^XC16$-kUWqvQoLi)syn7MV6lH{)V}kD8 zteP9gf`jzsnmKAS95sY4<0|-`O}1??j7{w|cRKyEr*}UsbCpvVmOwtQ7cO${T29j( ziRrV@AbXC7U%%$eaZsB6xG4^-Or%)4$YG`cYrFLuj&fVc1)5)Y>@IQ`X_zG{g^LGjoN@HFNl?H1bIPha3#kQ(PE_&Ke z+s%n(JawSn<6>8KPx9R`ZLXDH>-Ttk!CPOCoG9-60V||d-!8N84$hi=MB6FVNA_D6 zA)QEvkAc`BU5FFcibk$s)8WrE!h=X$f{G+cLfQ}kN)FsUq+-G9plee zyg`j@>Lme%x`A&g*xHb>TE-=OTjFC%(YzymrcTbxe}YZ7%`*41fi#euo19wB(bf)E zh>dZ-9~?8`e7x0Yy3Mv7Atv#@xZqvJm(q=em>Kt%g~9nAD;ot{6yP8Gn%o@1I9uvWTCeWg=o_B6Sh4qCyn^W=ZyZ~SG)49bo#1~Kyps6>6aPlh^G2z zKKKeY=-VAg?-!0j(!P31WTuHS;uZ7_IT|r%R@XO^ye!(Ut*?x%Izv{KSYUS>v`HmT zDR@V0IieZ`w7ZI14Z^z{tF{&uS*ksE}!8c+J=hj1Xx!npE00jR0*7 zmKU3ry6@T4x+zj^nn|=yKHf0s3NS=)s%B8sx(;_hgj>S~?7Y|!_OS@m=BJpw{aZ1u zjaEOe2b728v=?Ha-TmY`I(+@PKs}im*FUW{gKu;z9KMzkeYbTFrxuIqbkjoD8x!ZT z{$PNPlS%zn)b-P$barG=*L!{wth+Br8ZDN~+36SZYn{Z`O5XX=7phR?r@9M{Q6ou!ZXvRh|M`Yw5 z0>XBoD#WSWWJ$?%5jce9vqYevmxeIbYYvM`#tN}AQ$<4B;mpt!>7%%1*SizNODn{p z@|}peo;jcpt79}VjBD2`K|7wzpU<&Ucd6Gp;pvXn#8O)v<{4FMIna$z&B zzOePwN8z7IgWD=x?Catr1+dt&$4vE}QdV|NR&T2GZ9$r{C_N@&gZFt*=+Ki{3}zj? zRn=u-JSRMs^QeK6qvTJ3C`oWBDhR=`_$zoU3O(=XdSqrl!%{EcM=~~sC*V&#Z&`o~ zy)E^!SBtJEzIGrlpIq1%cNO0eA9rV(8%UJ4{t7}@BVzUZm|W@s6e4v(sI8OGBimPp znVqdhK;^xv&srcS+ZzdyjN?{@EgaL8TXpejbPMjm=+9Oroz&soG zoK3d^>od8vy$FN>Am^S1mwJ&hu5L8)(GG-%79OU7!ERm4Fc(GssJYmdEZm7oR1cq4 zl=swu`SmnQr%fk5m&J0A<<=>sKG!a7ur@x(3@Gl(E`51^fWyL_IKNJPCQz)H=w&1h zQjtlB>ZRLKnpS+FeZ;7Pb2WDO9NiY{9lBq*TaUHGH-|T&0$JRi1|vz`ZmX1$cV`5H zsaoSb-^Shf&gsXu+xhMcGvHFi>BvXHOgeoD2z&T#{jf&Z`JxVPT9NgTu?EQ8tx}=_$bLYufk_gMOmnukcBLd)|6KyPqFxZN3UtX{Ri^MvQpUfQV zK=5?oqG54Pi>I+Fx?<;9l^#nKQX3 z7S3ptt)3pUGxW_>dhT}EgF)--g7XpuBat~(ekJmmx55A;i2KXb&cV%ZNRl05roUJK{8F@vo)i zcxEID6&kd;H-DFuhKRoiZ(03l*TsyrNnE1HxidSPWZfonFkh(eij z`g6V?}Ws--Wn+j3uFtr8<@S z$W=QAm_m@x z%c1^;GPnLMlZXk%V|h2UpvYaa?ZF+41G)N^PG(hjkcr@HWB9{W5!XjC0Sezw`XZ>} z)o*X7U+?1Jq^z@$QN8W&Dw>U%(Q~=L;IDa8&$m3^gqLz@wfLZ-y^OhRrH7(44}D?% zM(VzWXy)u}|Ep1+IHc6W36Q#!xeev<+u^olDb3UnhioBf!VS*#Cij(7B{08ELk{y=(7bvCD!Y;;U2AXcps}mAl*HF7qOBl zJ$1FbQy@nAEb0=S@nSH^3-9HzOvMuXUQ9^v_NLvno9Q{5lL^^s79j^b$KsxRQJE8yL(&>`|WZ_&lNOQJ+u19Q>iCy2|G&2pE~R%ipcCW4 z8oOFLJnY8$@q4!2L4R9*WOW9flkNHaZl&@UdszIjHv(Edn6v z3U{CBag%iSJKDumStnbN<1?-|vX=ZUT1giujex~*Z6O}2A)?L$o*k-3{@ywZAu^Ti zQ}8|-F5L*NJ11t}!$LPeFXz~46Ak^|a%8Cs`%HVmrder>7K_{3squ)S@B8o0=_*!&gVzc{w;+TH@kc?m$ z-Rs>uTCV=yZ>c^{d5mRTPuMEF{(mh0)2RD5IM(T?>h`_4;>2tkH-R~vyJ-lrmOs5%vpkL%#h{vvzl@T@^$mv(+tpa!#WQchQ2N| zA5LP?+nIB!SO_qpv)}MeB6VOMVsYd}IvzDf!(zn9ykR*!Y^0dcO_iUlhi3vmvdA-i zY}7zMZQ{%n4Ue>~0X$EYD%QjLLhcyro4h$H_~RVnx>9zrC_49@K_vp5@a?YMT(bdl z>Gk&m;86;SVyxnph`>j0+CJW?0VINTg-9{u2p2Z^kC!fGfi4O9DghcIE;PnUH%+g~$H*08^V?aBa_dJchgtL>orIWj{ zhL4M-o8f)9SG^okf&=1(U($E<6zV@wcQK7IHCeGNqg{ocyy)USOU(&6y2xQNffEak z$&wY^zwW%dZAX`8v5%sYoLro$G(OjXRq`!bsI;O;PCLoLPY+Y?_D1H>hp!zwy0PQb zMeYhIC;w6@%LHT>pL7h-RhUslV|!{8+Yz1Lt> zV9wD#^IM}05z_)W5j0k2z5v9eQYWf+xbHyJoF3t8Zt%=(LHH~}j|;*)H@vzU4`N@x z&=Ug^0NYXJdEcG5k_Ct=g_n0~#?72fl%D=iCqq~7{G}M1xa(O!Prl+3id=PbiWOtOoL2S4--)HyJ)FqF{uY_fm#)9(rXy`O!ba(<6{Y8eq44u3?{z#l^Nkkb82I|6!3 z|7r9Og7=~NLyqz<^>b*-_)Gmy#`1q{`kssXJ?=NHgzz6`?tZ)f?vj6^q)Pg?1od#C z4>Q@lo!=;V|6T3B^4i0B9#%kq%@axZ@Ac5b86Nh!{+eMK+WNY$sQ&DH{V%Zox%X1! zU#fqQE&sej9?~s;SseYl+F#_$!zDi~X8xL>7D{n2`3dm47p2zok{|8~)?a}}M diff --git a/FusionIIIT/notification/views.py b/FusionIIIT/notification/views.py index 7cde647a8..1ef9f7220 100644 --- a/FusionIIIT/notification/views.py +++ b/FusionIIIT/notification/views.py @@ -1,6 +1,6 @@ from django.shortcuts import render -from requests import Response from notifications.signals import notify + # Create your views here. @@ -76,7 +76,6 @@ def central_mess_notif(sender, recipient, type, message=None): sender = sender recipient = recipient verb = '' - if type == 'feedback_submitted': verb = 'Your feedback has been successfully submitted.' elif type == 'menu_change_accepted': @@ -92,37 +91,9 @@ def central_mess_notif(sender, recipient, type, message=None): elif type == 'added_committee': verb = "You have been added to the mess committee. " - notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb) - -def placement_cellNotif(sender, recipient, type): - url = 'placement:placement' - module = 'Placement Cell' - sender = sender - recipient = recipient - verb = '' + notify.send(sender=sender, recipient=recipient, + url=url, module=module, verb=verb) - notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb) - -def visitors_hostel_notif(sender, recipient, type): - url='visitorhostel:visitorhostel' - module="Visitor's Hostel" - sender = sender - recipient = recipient - verb = '' - if type =='booking_confirmation': - verb='Your booking has been confirmed ' - elif type =='booking_cancellation_request_accepted': - verb='Your Booking Cancellation Request has been accepted ' - elif type =='booking_request': - verb='New Booking Request ' - elif type =='cancellation_request_placed': - verb='New Booking Cancellation Request ' - elif type =='booking_forwarded': - verb='New Forwarded Booking Request ' - elif type =='booking_rejected': - verb='Your Booking Request has been rejected ' - - notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb) def visitors_hostel_notif(sender, recipient, type): url = 'visitorhostel:visitorhostel' @@ -153,23 +124,20 @@ def healthcare_center_notif(sender, recipient, type): sender = sender recipient = recipient verb = '' - if type == 'appoint': verb = "Your Appointment has been booked" - elif type == 'amb_request': + if type == 'amb_request': verb = "Your Ambulance request has been placed" - elif type == 'Presc': + if type == 'Presc': verb = "You have been prescribed some medicine" - elif type == 'appoint_req': + if type == 'appoint_req': verb = "You have a new appointment request" - elif type == 'amb_req': + if type == 'amb_req': verb = "You have a new ambulance request" - elif type == 'rel_forward': - verb = "You have a new medical relief forward request" - elif type == 'rel_approve': - verb = "You have a new medical relief approval request" - elif type == 'rel_approved': - verb = 'Your medical relief request has been approved' + + notify.send(sender=sender, recipient=recipient, + url=url, module=module, verb=verb) + def file_tracking_notif(sender, recipient, title): url = 'filetracking:inward' @@ -191,8 +159,6 @@ def scholarship_portal_notif(sender, recipient, type): if type.startswith('award'): s = type.split('_') - # print("psss") - # print(type, s) verb = "Invitation to apply for " + s[1] elif type == 'Accept_MCM': verb = "Your Mcm form has been accepted " @@ -401,38 +367,20 @@ def department_notif(sender, recipient, type): module=module, verb=verb, flag=flag) + def examination_notif(sender, recipient, type): - url='examination:examination' - module='examination' + url = 'examination:updateGrades' + module = 'examination' sender = sender recipient = recipient verb = type flag = "announcement" - notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb, flag=flag) -def examination_notif(sender, recipient, type,request): - url='examination:examination' - module='examination' - sender = sender - recipient = recipient - verb = type - flag = "examination" - - notify.send(sender=sender, - recipient=recipient, - url=url, - module=module, - verb=verb, - flag=flag) - print("test3") - # return render(request, 'examination/announcement_req.html') - - def office_module_DeanRSPC_notif(sender, recipient, type): @@ -471,36 +419,5 @@ def research_procedures_notif(sender, recipient, type): elif type == "created": verb = "A new Patent has been Created" - notify.send(sender=sender,recipient=recipient,url=url,module=module,verb=verb) - -def hostel_notifications(sender, recipient, type): - url = 'hostelmanagement:hostel_view' - module = 'Hostel Management' - - sender = sender - recipient = recipient - verb = "" - if type == "leave_accept": - verb = "Your leave request has been Accepted." - elif type == "leave_reject": - verb = "Your leave request has been Rejected." - elif type == "guestRoom_accept": - verb = "Your Guest Room request has been Accepted." - elif type == "guestRoom_reject": - verb = "Your Guest Room request has been Rejected." - elif type == "leave_request": - verb = "You have a new Leave Request." - elif type == "guestRoom_request": - verb = "You have a new Guest Room Request." - elif type == "fine_imposed": - verb = "A fine has been imposed on you." - - notify.send(sender=sender,recipient=recipient,url=url,module=module,verb=verb) - -def prog_and_curr_notif(sender, recipient,title): - url='programme_curriculum:inward_files' - module='Programme and Curriculum' - sender = sender - recipient = recipient - verb = title - notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb) \ No newline at end of file + notify.send(sender=sender, recipient=recipient, + url=url, module=module, verb=verb) diff --git a/FusionIIIT/templates/academic_procedures/academic.html b/FusionIIIT/templates/academic_procedures/academic.html index 217e011b5..35eebf446 100644 --- a/FusionIIIT/templates/academic_procedures/academic.html +++ b/FusionIIIT/templates/academic_procedures/academic.html @@ -183,10 +183,10 @@ {% include 'academic_procedures/registeredCourse.html' %}
- {% include 'academic_procedures/auto_pre_registration.html' %} + {% include 'academic_procedures/register.html' %}
- {% include 'academic_procedures/auto_finalregister.html' %} + {% include 'academic_procedures/finalregister.html' %}
@@ -204,12 +204,7 @@ Add/drop courses - - Backlogs - - - Replace - +
-
- {% include 'academic_procedures/backlog.html' %} -
-
- {% include 'academic_procedures/replace.html' %} -
+ @@ -335,9 +325,6 @@ {% comment %} TODO: the right rail! {% endcomment %} - {% block sidepanel%} - {% include 'notifications/academic_procedures_sidepanel.html' %} - {% endblock %} {% comment %}The right-rail segment ends here!{% endcomment %} diff --git a/FusionIIIT/templates/academic_procedures/academicfac.html b/FusionIIIT/templates/academic_procedures/academicfac.html index 8789d7cbc..dd74efff5 100644 --- a/FusionIIIT/templates/academic_procedures/academicfac.html +++ b/FusionIIIT/templates/academic_procedures/academicfac.html @@ -25,13 +25,7 @@ style="max-width: 320px;"> {% if fac_flag %} - {% if request.user.extrainfo.user_type == 'fx' or request.user.extrainfo.user_type == 'faculty' %} - - Assigned Course - - - {% endif %} - + Course Management @@ -67,60 +61,9 @@ Kartik {% endcomment %} -
-
-
-
- - - - - - - - - - - - - - - - - - - {% for course in assigned_courses %} - - - - - - - - - - - - - {%endfor%} - -

Course Name

Course Code

Course Version

Programme

Branch

Year

Download Roll List

{{course.course_id.name }} {{course.course_id.code }} {{course.course_id.version }} {{course.batch_id.name }} {{course.batch_id.discipline.name }} {{course.batch_id.year }} -
- {% csrf_token %} - - - -
-
- - - -
+


@@ -135,7 +78,7 @@ - + diff --git a/FusionIIIT/templates/academic_procedures/studentSwayam.html b/FusionIIIT/templates/academic_procedures/studentSwayam.html deleted file mode 100644 index 6a912f3e9..000000000 --- a/FusionIIIT/templates/academic_procedures/studentSwayam.html +++ /dev/null @@ -1,322 +0,0 @@ -{% load static %} - - - - -
-
- {% if dict2 %} - -           -           -           -           - Name = {{ dict2.firstname }} {{ dict2.lastname }} -           -           -           - Roll No = {{ dict2.roll_no }} - - {% endif %} - {% if details %} -
{{obj.course_id.code}} {{obj.course_id.name}}{{ obj.batch_id.name}} {{obj.batch_id.year}}-{{obj.batch_id.discipline.name}}{{ obj.batch_id }} {% comment %}The right-rail segment ends here!{% endcomment %} diff --git a/FusionIIIT/templates/academic_procedures/addCourse.html b/FusionIIIT/templates/academic_procedures/addCourse.html index 42f38a05d..c58b1ac45 100755 --- a/FusionIIIT/templates/academic_procedures/addCourse.html +++ b/FusionIIIT/templates/academic_procedures/addCourse.html @@ -11,7 +11,7 @@
{% if adc_date_flag %} - {% if details.cpi >= 0.0 %} + {% if details.cpi >= 6.0 %} {% if add_courses_options %}
{% csrf_token %} diff --git a/FusionIIIT/templates/academic_procedures/allot_courses.html b/FusionIIIT/templates/academic_procedures/allot_courses.html index f5ac54c7e..5d4fc0e45 100644 --- a/FusionIIIT/templates/academic_procedures/allot_courses.html +++ b/FusionIIIT/templates/academic_procedures/allot_courses.html @@ -27,7 +27,7 @@

diff --git a/FusionIIIT/templates/academic_procedures/auto_finalregister.html b/FusionIIIT/templates/academic_procedures/auto_finalregister.html deleted file mode 100644 index 95788c24d..000000000 --- a/FusionIIIT/templates/academic_procedures/auto_finalregister.html +++ /dev/null @@ -1,251 +0,0 @@ -{% load static %} -{% block finalregister %} - - - - -
Final Registration
- -
- {% if curr_sem.semester_no != 8 %} - {% if frd %} - {% if final_registration_flag == True %} -

-

You have already registered for this semester!!!
-

- - - {% else %} -
- - {% csrf_token %} -
- - - - - -
- -
-
- - -
-
- -
-
-
- - -
- -
- -
-
- -
-
-
- - -
-
- - -
-
-
- - -
- -
-
- - -
-
-
-
-
-
-
- - - -
-
- -
-
- -
- -
- - - {% comment %}
- {% csrf_token %} - -

Fee Payment

- - - - - -
{% endcomment %} - {% endif %} - {% else %} -
-

Final Registration Date is yet to come

-
- {% endif %} - {% else %} -
-

You are not Eligible for Registration !!

-
- {% endif %} -
-{% endblock %} - - - - - - - - \ No newline at end of file diff --git a/FusionIIIT/templates/academic_procedures/auto_pre_registration.html b/FusionIIIT/templates/academic_procedures/auto_pre_registration.html deleted file mode 100644 index b9129ca23..000000000 --- a/FusionIIIT/templates/academic_procedures/auto_pre_registration.html +++ /dev/null @@ -1,437 +0,0 @@ - - - - -{% load static %} -{% block resiterstudent %} - - -
Pre-Registration for Next Semester Courses
-
- {% if curr_sem.semester_no != 8 %} - {% if prd %} - {% if pre_registration_flag %} - -
You have already registered at - {% if pre_registration_timestamp is not None %} - {{pre_registration_timestamp}} - {% endif %} - !!! -
-
View Courses
-
Hide courses
-
-
-
- - - - - - - - - - - - {% for course_slot,courses in pre_registered_course_show.items %} - - - - - - - - - - {% endfor %} - - -
-
-
- {% else %} -
- {% csrf_token %} - - - - - - - - - - - - - - - {% for course_slot in next_sem_registration_courses %} - {% if course_slot.type == "Swayam" %} - {% with "x"|ljust:swayam_courses_count as dummy_range %} - {% for _ in dummy_range %} - - - - - - - - - - - {% endfor %} - {% endwith %} - {% else %} - - - - - - - - - - - - - {% endif %} - {% endfor %} - - - - -
#Slot nameSlot typeSemesterCreditsSelect
{{ forloop.counter0|add:forloop.parentloop.counter0|add:"+1" }}.{{course_slot.name}}{{course_slot.type}}{{next_sem.semester_no}} - - {{course_slot.courses.all.0.credit}} -
- -
-
{{forloop.counter}}.{{course_slot.name}}{{course_slot.type}}{{next_sem.semester_no}} - - {{course_slot.courses.all.0.credit}} -
- -
-
-
-
- -
-
-
- -
-
-
-

You need minimum {{curr_sem.curriculum.min_credit}} credits for semester {{next_sem.semester_no}}

-
- - {% endif %} - {% else %} - {% if prd_start_date%} - -
Pre Registration will start on {{prd_start_date}}. -
- {% else %} - -
Pre Registration date hasn't come yet -
- {% endif %} - {% endif %} - {% else %} -
-

You are not Eligible for Registration !!

-
- {% endif %} - -
- - - -{% endblock %} - - - - diff --git a/FusionIIIT/templates/academic_procedures/backlog.html b/FusionIIIT/templates/academic_procedures/backlog.html deleted file mode 100644 index c2e7897da..000000000 --- a/FusionIIIT/templates/academic_procedures/backlog.html +++ /dev/null @@ -1,76 +0,0 @@ -{% load static %} -
Backlog Courses
-
- - - - - - - - - - - - - {% for i in auto_backlog_courses_list %} - - {% for j in i %} - - {% endfor %} - - - {% endfor %} -
Course NameCourse CodeVersionCreditGrade
Apply For Registration
{{ j }}
- {%if adc_date_flag%} - - {%else %} - - {%endif%} -
-
- - diff --git a/FusionIIIT/templates/academic_procedures/dropCourse.html b/FusionIIIT/templates/academic_procedures/dropCourse.html index e310ec14e..a44f365a6 100755 --- a/FusionIIIT/templates/academic_procedures/dropCourse.html +++ b/FusionIIIT/templates/academic_procedures/dropCourse.html @@ -1,7 +1,7 @@ {% load static %} {% block complainthistory %} -
Drop Course(s)
+
Drop Couse(s)
@@ -52,7 +52,7 @@
{% else %} -
No Courses to drop
+ No Courses to drop {% endif %} {% else %}
You have to wait for the date
diff --git a/FusionIIIT/templates/academic_procedures/finalregister.html b/FusionIIIT/templates/academic_procedures/finalregister.html index 387aa659f..2349c5f01 100755 --- a/FusionIIIT/templates/academic_procedures/finalregister.html +++ b/FusionIIIT/templates/academic_procedures/finalregister.html @@ -212,6 +212,10 @@

Fee Payment

+ + + + - - - diff --git a/FusionIIIT/templates/academic_procedures/studentCourses.html b/FusionIIIT/templates/academic_procedures/studentCourses.html index 1a15c3d1a..7c1a9152c 100644 --- a/FusionIIIT/templates/academic_procedures/studentCourses.html +++ b/FusionIIIT/templates/academic_procedures/studentCourses.html @@ -8,27 +8,6 @@ .modal('show') ; }); - function courseDropCalled(event) { - // Prevent the default action of the link - event.preventDefault(); - - // Get the URL from the link's href attribute - let url = event.target.href; - - // Perform AJAX request - $.ajax({ - url: url, - type: 'GET', - success: function(data) { - // Reload the page after successful deletion - location.reload(); - }, - error: function(xhr, status, error) { - // Handle errors if needed - console.error(error); - } - }); - } @@ -102,7 +81,7 @@

+ href="/academic-procedures/acad_person/verifyCourse/drop/?id={{ items.reg_id|urlencode }}"> DROP
- - - - - - - - - - - - - - - - - - - - {% for items in details %} - - - - - - - - - - - - - - {% endfor %} - - -
- Reg ID# - - Course ID - - Course Name - - Credits - - Semester - - Replace Course -
- {{ items.rid }} - - {{ items.course_id }} - - {{ items.course_name }} - - {{ items.credits }} - - {{ items.sem }} - - -
- - - - - - -
- -
- {% else %} -
-


-
- NO RECORDS FOUND -
- {% endif %} - -
- {% comment %} {% endcomment %} - - - - -
- - - - \ No newline at end of file diff --git a/FusionIIIT/templates/academic_procedures/student_table.html b/FusionIIIT/templates/academic_procedures/student_table.html index 696f06cc7..cf74029d7 100755 --- a/FusionIIIT/templates/academic_procedures/student_table.html +++ b/FusionIIIT/templates/academic_procedures/student_table.html @@ -101,8 +101,7 @@ var student_id = $(this).attr('data'); $.ajax({ type: 'post', - // url: '/academic-procedures/process_verification_request/', - url: '/academic-procedures/auto_process_verification_request/', + url: '/academic-procedures/process_verification_request/', data: { student_id: student_id, status_req: 'accept', @@ -130,12 +129,10 @@ $('.reg-disapprove').on('click', function(e){ var id = $(this).attr('data-two'); var student_id = $(this).attr('data'); - // var reason = $('#fname').val(); - var reason = $(this).closest('.verify').find('.reason').val(); + var reason = $('#fname').val(); $.ajax({ type: 'post', - // url: '/academic-procedures/process_verification_request/', - url: '/academic-procedures/auto_process_verification_request/', + url: '/academic-procedures/process_verification_request/', data: { student_id: student_id, status_req: 'reject', diff --git a/FusionIIIT/templates/academic_procedures/studentlist.html b/FusionIIIT/templates/academic_procedures/studentlist.html index b3c3ea209..8f43ce3d5 100755 --- a/FusionIIIT/templates/academic_procedures/studentlist.html +++ b/FusionIIIT/templates/academic_procedures/studentlist.html @@ -61,7 +61,7 @@ Verify Student Registration for Semester {{ date.semflag }} : {{ date.year }} - +
{% if course_verification_date %}
diff --git a/FusionIIIT/templates/academic_procedures/swayam_list.html b/FusionIIIT/templates/academic_procedures/swayam_list.html deleted file mode 100644 index 12c50c1de..000000000 --- a/FusionIIIT/templates/academic_procedures/swayam_list.html +++ /dev/null @@ -1,57 +0,0 @@ -{% comment %} ACAD ADMIN WILL REPLACE COURSES WITH SWAYAM COURSES HERE {% endcomment%} -{% load static %} -{% block allot_swayam %} - - - - - -{% comment %}The tab menu starts here!{% endcomment %} - -
-
- - {% csrf_token %} -
- - -
-
- -
- - -
-
- -
-
- -{% endblock %} \ No newline at end of file diff --git a/FusionIIIT/templates/ais/ais.html b/FusionIIIT/templates/ais/ais.html index d749b0270..e9d3fea7d 100755 --- a/FusionIIIT/templates/ais/ais.html +++ b/FusionIIIT/templates/ais/ais.html @@ -47,7 +47,7 @@

@@ -146,7 +135,7 @@
-
+
{% block generateSheet %} {% include 'ais/generateSheet.html' %} {% endblock %} @@ -181,26 +170,18 @@ {% endblock %}
- - - - - - - -
- {% block config_pre_registration %} - {% include 'ais/pre_registration_courses.html' %} +
+ {% block min_credfloat_courses %} + {% include 'ais/new.html' %} {% endblock %}
- {% block config_pre_reg_courses %} - {% include 'ais/config_courseslot_courses.html' %} + {% block curriculum %} + {% include 'ais/curriculum.html' %} {% endblock %}
-
{% block branch_change %} {% include 'academic_procedures/academicadminforbranch.html' %} @@ -225,33 +206,17 @@ {% include 'ais/student_dashboard.html' %} {% endblock %}
- -
- {% block allot_swayam %} - {% include 'academic_procedures/swayam_list.html' %} - {% endblock %} -
- - -
- {% block curriculum %} - {% include 'ais/curriculum.html' %} - {% endblock %} -
-
- - {% block sidepanel%} - {% include 'notifications/academic_procedures_sidepanel.html' %} {% endblock %}
-
+
-->
{% endblock %} diff --git a/FusionIIIT/templates/ais/config_courseslot_courses.html b/FusionIIIT/templates/ais/config_courseslot_courses.html deleted file mode 100644 index ca3bcba67..000000000 --- a/FusionIIIT/templates/ais/config_courseslot_courses.html +++ /dev/null @@ -1,140 +0,0 @@ - - - -{% load static %} -{% block config_courseslot_courses %} - - - -
- -
- -
- -
- -
- -
-
- -
- -
- -
-
-
- - - - -{% endblock %} - - - - - - diff --git a/FusionIIIT/templates/ais/generateSheet.html b/FusionIIIT/templates/ais/generateSheet.html index 59613a28d..fe03efbfd 100755 --- a/FusionIIIT/templates/ais/generateSheet.html +++ b/FusionIIIT/templates/ais/generateSheet.html @@ -21,7 +21,7 @@ success: function(jsondata) { $("#loading").hide(); - // console.log(jsondata); + console.log(jsondata); $('#course_list').html(jsondata.html); }, error: function(data) @@ -33,7 +33,7 @@ -
+
{% csrf_token %}
diff --git a/FusionIIIT/templates/ais/pre_registration_courses.html b/FusionIIIT/templates/ais/pre_registration_courses.html deleted file mode 100644 index e861ec3c8..000000000 --- a/FusionIIIT/templates/ais/pre_registration_courses.html +++ /dev/null @@ -1,254 +0,0 @@ - - - - -{% load static %} -{% block config_pre_registration %} - - - -
-
-
- - -
- -
- - -
-
- -
- - -
- -
- - -
- -
- -
-
- - -
- -
- -
- - - - {% csrf_token %} - - - - - - -
- - -
-
-
- - - -{% endblock %} - - - - diff --git a/FusionIIIT/templates/ais/profile.html b/FusionIIIT/templates/ais/profile.html index d30c5fa0e..479de29f6 100755 --- a/FusionIIIT/templates/ais/profile.html +++ b/FusionIIIT/templates/ais/profile.html @@ -29,7 +29,7 @@

Note : Provide the data in Excel Sheet in following format:

RollNo | First Name | Last Name | Email | Sex | DOB | Father's Name | Mother's Name | Category | Phone No | Address | Department | Specialization | Hall No -

Download the sample Excel, fill the data accordingly and then upload the same

+

Download the sample Excel, fill the data accordingly and then upload the same

diff --git a/FusionIIIT/templates/ais/student_dashboard.html b/FusionIIIT/templates/ais/student_dashboard.html index 9d1a4c45a..06ad5ae92 100644 --- a/FusionIIIT/templates/ais/student_dashboard.html +++ b/FusionIIIT/templates/ais/student_dashboard.html @@ -21,7 +21,7 @@
- +
diff --git a/FusionIIIT/templates/complaintModule/add_workers.html b/FusionIIIT/templates/complaintModule/add_workers.html index 969fad127..842d4397a 100644 --- a/FusionIIIT/templates/complaintModule/add_workers.html +++ b/FusionIIIT/templates/complaintModule/add_workers.html @@ -2,16 +2,16 @@ {% block lodgecomplaint %} {% comment %}The tab menu starts here!{% endcomment %} - +
- + - +
- +
@@ -112,13 +112,13 @@ - +
- - - \ No newline at end of file + {%endblock%} \ No newline at end of file diff --git a/FusionIIIT/templates/complaintModule/assignworker.html b/FusionIIIT/templates/complaintModule/assignworker.html index 97076b99a..458d05ff9 100644 --- a/FusionIIIT/templates/complaintModule/assignworker.html +++ b/FusionIIIT/templates/complaintModule/assignworker.html @@ -1,4 +1,4 @@ - + {% extends 'globals/base.html' %} {% load static %} @@ -34,10 +34,11 @@
{% comment %}The Tab-Menu starts here!{% endcomment %} -