Browse Source

education commit

master
AJITHKUMAR12 1 year ago
commit
25f8499abd
  1. 557
      backend/school/Controller/BuildingAssetController.java
  2. 477
      backend/school/Controller/DropdownsController.java
  3. 128
      backend/school/Controller/MainController.java
  4. 720
      backend/school/Controller/SchoolPropertyController.java
  5. 48
      backend/school/Controller/SchoolReportController.java
  6. 1030
      backend/school/Service/BuildingAssetService.java
  7. 188
      backend/school/Service/DropdownsService.java
  8. 970
      backend/school/Service/SchoolPropertyService.java
  9. 298
      backend/school/Service/SchoolReportService.java
  10. 732
      frontend/school/addelectricalasset.html
  11. 728
      frontend/school/addfurnitureasset.html
  12. 819
      frontend/school/assetmanagement.html
  13. 1582
      frontend/school/building.html
  14. 322
      frontend/school/dashboard.html
  15. 1525
      frontend/school/drinkingwater.html
  16. 405
      frontend/school/electricalassets.html
  17. 411
      frontend/school/furnitureassets.html
  18. 602
      frontend/school/itassets.html
  19. 930
      frontend/school/kitchen.html
  20. 982
      frontend/school/otherdetails.html
  21. 815
      frontend/school/playground.html
  22. 478
      frontend/school/reports.html
  23. 827
      frontend/school/room.html
  24. 1589
      frontend/school/roomassets.html
  25. 775
      frontend/school/staffdetails.html
  26. 687
      frontend/school/studentdetails.html
  27. 567
      frontend/school/toilets.html

557
backend/school/Controller/BuildingAssetController.java

@ -0,0 +1,557 @@
package in.gov.chennaicorporation.gccoffice.school.Controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.gccoffice.school.Service.BuildingAssetService;
import in.gov.chennaicorporation.gccoffice.school.Service.SchoolPropertyService;
@RestController
@RequestMapping("/gcc/api/gccschool/buildingasset")
public class BuildingAssetController {
private BuildingAssetService buildingAssetService;
@Autowired
public BuildingAssetController(BuildingAssetService buildingAssetService) {
this.buildingAssetService = buildingAssetService;
}
// For Buildings
@PostMapping(value = "/saveBuildings")
public String saveBuildings(@RequestBody List<Map<String, Object>> buildingList) {
try {
for (Map<String, Object> building : buildingList) {
String building_name = (String) building.get("building_name");
int total_floor = Integer.parseInt(building.get("total_floor").toString());
int building_material = Integer.parseInt(building.get("building_material").toString());
int roof_material = Integer.parseInt(building.get("roof_material").toString());
// int building_order =
// Integer.parseInt(building.get("building_order").toString());
int school_id = Integer.parseInt(building.get("school_id").toString());
int check_building = buildingAssetService.checkBuilding(building_name, school_id);
if (check_building == 1) {
return "Building Name Alredy Exist";
} else if (check_building == 5) {
return "error";
}
int building_id = buildingAssetService.saveBuildings(building_name, total_floor, building_material,
roof_material, school_id);
System.out.println("Hi");
for (int i = 1; i <= total_floor; i++) {
Map<String, Object> floor = buildingAssetService.getFloor(i);
String floor_name = (String) floor.get("content");
int floor_master_id = Integer.parseInt(floor.get("floor_master_id").toString());
buildingAssetService.saveFloor(floor_name, building_id, floor_master_id, school_id);
System.out.println("Saved Floor Master ID: " + floor_master_id);
}
}
return "Building Saved sucessfully";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
// To Get Saved Buildings
@GetMapping("/getSavedBuildings")
public ResponseEntity<Map<String, Object>> getSavedBuildings(int school_id) {
try {
List<Map<String, Object>> data = buildingAssetService.getSavedBuildings(school_id);
int lastId = buildingAssetService.getLastBuildingOrder(school_id);
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
response.put("lastId", lastId);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
response.put("lastId", lastId);
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get floor Data by buildings
@GetMapping("/getFloorDetails")
public ResponseEntity<Map<String, Object>> getFloorDetails(int building_id) {
try {
List<Map<String, Object>> data = buildingAssetService.getFloorDetails(building_id);
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// For Room mapping --add room
/*
* @PostMapping(value = "/saveRoom") public String saveRoom(@RequestBody
* Map<String, Object> rooms) { try { int building_id = (int)
* rooms.get("building_id"); int floors_id = (int) rooms.get("floors_id"); int
* room_type = Integer.parseInt(rooms.get("room_type").toString());
*
* String room_num = (String) rooms.get("room_num"); int school_id = (int)
* rooms.get("school_id"); buildingAssetService.saveRoomDetails(room_type,
* room_num, building_id, floors_id, school_id); return
* "Rooms Mapped Sucessfully"; } catch (Exception e) { e.printStackTrace();
* return "error"; } }
*/
// vishnu save
@PostMapping(value = "/saveRoom")
public String saveRoom(@RequestBody Map<String, Object> rooms) {
try {
int building_id = Integer.parseInt(rooms.get("building_id").toString());
int floors_id = Integer.parseInt(rooms.get("floors_id").toString());
int room_type = Integer.parseInt(rooms.get("room_type").toString());
String room_num = rooms.get("room_num").toString();
int school_id = Integer.parseInt(rooms.get("school_id").toString());
buildingAssetService.saveRoomDetails(room_type, room_num, building_id, floors_id, school_id);
return "Rooms Mapped Sucessfully";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
// For Edit Room mapping
// @PostMapping(value = "/editRoom")
// public String editRoom(@RequestBody Map<String, Object> rooms) {
// try {
// int room_id = (int) rooms.get("room_id");
// int building_id = (int) rooms.get("building_id");
// int floors_id = (int) rooms.get("floors_id");
// int room_type = (int) rooms.get("room_type");
// String room_num = (String) rooms.get("room_num");
// int school_id = (int) rooms.get("school_id");
// buildingAssetService.editRoom(room_type, room_num, building_id, floors_id, school_id, room_id);
// return "Rooms Edited Sucessfully";
// } catch (Exception e) {
// e.printStackTrace();
// return "error";
// }
// }
// vishnu edit room
@PostMapping(value = "/editRoom")
public String editRoom(@RequestBody Map<String, Object> rooms) {
try {
if (rooms.get("room_id") == null || rooms.get("building_id") == null || rooms.get("floors_id") == null
|| rooms.get("room_type") == null || rooms.get("room_num") == null
|| rooms.get("school_id") == null) {
return "Missing required fields";
}
int room_id = Integer.parseInt(rooms.get("room_id").toString());
int building_id = Integer.parseInt(rooms.get("building_id").toString());
int floors_id = Integer.parseInt(rooms.get("floors_id").toString());
int room_type = Integer.parseInt(rooms.get("room_type").toString());
String room_num = rooms.get("room_num").toString();
int school_id = Integer.parseInt(rooms.get("school_id").toString());
buildingAssetService.editRoom(room_type, room_num, building_id, floors_id, school_id, room_id);
return "Rooms Edited Sucessfully";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
// For Delete Room mapping
/*
* @PostMapping(value = "/deleteRoom") public String deleteRoom(@RequestParam
* int room_id, @RequestParam boolean is_delete) { try { // // from assets //
* List<Map<String, Object>> assets = buildingAssetService.getAssets(room_id);
* // if(!assets.isEmpty()) { // for(Map<String, Object> asset : assets) { // //
* } // } buildingAssetService.deleteRoom(room_id, is_delete); return
* "Rooms Edited Sucessfully"; } catch (Exception e) { e.printStackTrace();
* return "error"; } }
*/
//vishnu
@GetMapping("/getBuildingbyid")
public ResponseEntity<Map<String, Object>> getSimpleBuilding(@RequestParam int building_id) {
try {
Map<String, Object> building = buildingAssetService.getSimpleBuildingById(building_id);
if (building != null) {
return ResponseEntity.ok(Map.of("status", "OK", "data", building));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("status", "Failed", "message", "Building not found"));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Something went wrong"));
}
}
@GetMapping("/getAllMaterials")
public ResponseEntity<Map<String, Object>> getAllMaterials() {
try {
Map<String, List<Map<String, Object>>> materials = buildingAssetService.getAllMaterials();
return ResponseEntity.ok(Map.of("status", "OK", "buildingMaterials", materials.get("buildingMaterials"),
"roofMaterials", materials.get("roofMaterials")));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Failed to load material data"));
}
}
@GetMapping("/getFloorsByBuildingId")
public ResponseEntity<Map<String, Object>> getFloorsByBuildingId(@RequestParam int buildingId) {
try {
List<Map<String, Object>> floors = buildingAssetService.getFloorsByBuildingId(buildingId);
return ResponseEntity.ok(Map.of("status", "OK", "floors", floors));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Could not load floor list"));
}
}
@PostMapping(value = "/deleteBuilding")
public String deleteBuilding(@RequestParam int building_id, @RequestParam boolean is_delete) {
return buildingAssetService.executeDelete(building_id, is_delete);
}
@PostMapping(value = "/deleteRoom")
public String deleteRoom(@RequestParam int room_id, @RequestParam boolean is_delete) {
try {
// from assets
List<Integer> asset_ID = buildingAssetService.getassetRoomID(room_id);
List<Map<String, Object>> electrical_asset = buildingAssetService.getElectricalAssetMasterByRoomId(room_id);
List<Map<String, Object>> furniture_asset = buildingAssetService.getFurnitureAssetMasterByRoomId(room_id);
for (Integer it_details_id : asset_ID) {
buildingAssetService.unmapItAssetMaster(it_details_id);
}
for (Map<String, Object> ele_data : electrical_asset) {
int school_id = (Integer) ele_data.get("school_id");
int sub_asset_id = (Integer) ele_data.get("sub_asset_id");
int asset_qty = (Integer) ele_data.get("asset_qty");
String assetType = "electricalasset";
Map<String, Object> assetMaster = buildingAssetService.getAssetMasterBySchlId(sub_asset_id, school_id,
assetType);
int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0;
int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0;
int map = mapped - asset_qty;
int unMap = unMapped + asset_qty;
buildingAssetService.updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType);
}
for (Map<String, Object> fur_data : furniture_asset) {
int school_id = (Integer) fur_data.get("school_id");
int sub_asset_id = (Integer) fur_data.get("sub_asset_id");
int asset_qty = (Integer) fur_data.get("asset_qty");
String assetType = "furnitureasset";
Map<String, Object> assetMaster = buildingAssetService.getAssetMasterBySchlId(sub_asset_id, school_id,
assetType);
int mapped = assetMaster.get("mapped_qty") != null ? (Integer) assetMaster.get("mapped_qty") : 0;
int unMapped = assetMaster.get("unmapped_qty") != null ? (Integer) assetMaster.get("unmapped_qty") : 0;
int map = mapped - asset_qty;
int unMap = unMapped + asset_qty;
buildingAssetService.updateAssetmaster(map, unMap, school_id, sub_asset_id, assetType);
}
buildingAssetService.unmapAssets(room_id, is_delete);
buildingAssetService.deleteRoom(room_id, is_delete);
return "Rooms Edited Sucessfully";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
@PostMapping(value = "/editBuildings")
public String editBuilding(@RequestParam int building_id, @RequestParam int floor_id) {
return buildingAssetService.editBuildings(building_id, floor_id);
}
@PostMapping(value = "/addFloor")
public String addFloor(@RequestParam int building_id, @RequestParam int exe_order) {
return buildingAssetService.addFloor(building_id, exe_order);
}
@PostMapping(value = "/updateBuilding")
public String updateBuilding(@RequestParam int building_id, @RequestParam String building_name,
@RequestParam int total_floor, @RequestParam String building_material, @RequestParam String roof_material,
@RequestParam int school_id) {
try {
buildingAssetService.updateBuilding(building_id, building_name, total_floor, building_material,
roof_material, school_id);
return "Success";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@GetMapping("/getRoomDetails")
public ResponseEntity<Map<String, Object>> getRoomDetails(@RequestParam int school_id) {
try {
List<Map<String, Object>> data = buildingAssetService.getRoomDetailsBySchoolId(school_id);
Map<String, Object> response = new HashMap<>();
if (data != null && !data.isEmpty()) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error fetching room details: " + e.getMessage()));
}
}
@GetMapping("/getRoomById")
public ResponseEntity<Map<String, Object>> getRoomById(@RequestParam int room_id) {
try {
Map<String, Object> room = buildingAssetService.getRoomDetailsById(room_id);
return ResponseEntity.ok(Map.of("status", "OK", "data", room));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "ERROR", "data", "Room not found"));
}
}
@GetMapping(value = "/getItAssetMapping")
public ResponseEntity<Map<String, Object>> getItAssetMapping(int room_id, String assetType) {
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> data = buildingAssetService.getItAssetMapping(room_id, assetType);
response.put("Status", "OK");
response.put("data", data);
return ResponseEntity.ok(response);
}
@PostMapping(value = "/deleteAssetMapping")
public ResponseEntity<Map<String, Object>> deleteAssetMapping(int it_map_id, boolean is_delete) {
Map<String, Object> response = new HashMap<>();
Map<String, Object> it_Details = buildingAssetService.getIt_Details(it_map_id);
int it_details_id = (Integer) it_Details.get("it_details_id");
String data = buildingAssetService.deleteAssetMapping(it_map_id, is_delete);
buildingAssetService.unmapItAssetMaster(it_details_id);
response.put("status", "Sucess");
response.put("data", data);
return ResponseEntity.ok(response);
}
// For update assets
@PostMapping(value = "/updateassets")
public String updateassets(@RequestBody List<Map<String, Object>> assets) {
return buildingAssetService.updateAssetExecution(assets);
}
@GetMapping(value = "/getSchoolAsset")
public ResponseEntity<Map<String, Object>> getSchoolAsset(@RequestParam int school_id, @RequestParam String type) {
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> data = buildingAssetService.getSchoolAsset(school_id, type);
if (!data.isEmpty()) {
response.put("status", "Success");
response.put("data", data);
} else {
response.put("status", "Error");
}
return ResponseEntity.ok(response);
}
@PostMapping(value = "/mapAssets")
public String mapAssets(@RequestBody List<Map<String, Object>> assets) {
try {
for (Map<String, Object> asset : assets) {
int room_id = Integer.parseInt(asset.get("room_id").toString());
int floor_id = Integer.parseInt(asset.get("floor_id").toString());
int school_id = Integer.parseInt(asset.get("school_id").toString());
int it_details_id = Integer.parseInt(asset.get("it_details_id").toString());
int building_id = Integer.parseInt(asset.get("building_id").toString());
buildingAssetService.mapAssets(room_id, floor_id, school_id, it_details_id, building_id);
}
return "Success";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@PostMapping(value = "/addFurAsset")
public String addFurAsset(@RequestParam int sub_asset_id, @RequestParam int asset_qty, @RequestParam int room_id,
@RequestParam int building_id, @RequestParam int floor_id, @RequestParam int school_id,
@RequestParam String assetType) {
return buildingAssetService.assetUpdation(asset_qty, assetType, sub_asset_id, school_id, room_id, building_id,
floor_id);
}
// Asset Management
@GetMapping(value = "/getAssetManagement")
public ResponseEntity<Map<String, Object>> getSchoolAssetForManagement(@RequestParam int school_id) {
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> data = buildingAssetService.getSchoolAssetForManagement(school_id);
if (!data.isEmpty()) {
response.put("status", "Sucess");
response.put("data", data);
} else {
response.put("status", "Error");
}
return ResponseEntity.ok(response);
}
@PostMapping(value = "/addAsset")
public String addAsset(@RequestParam String code, @RequestParam String name, @RequestParam String source,
@RequestParam String serialNum, @RequestParam String vendorDetail, @RequestParam String invoice_num,
@RequestParam String udise, @RequestParam boolean is_online, @RequestParam int school_id) {
try {
int count = buildingAssetService.getAssetCount(udise, is_online);
String assetCode = "";
if (count >= 0) {
String series = String.format("%04d", count + 1);
String school = String.format("%03d", school_id);
assetCode = code + school + series;
} else {
return "Error";
}
return buildingAssetService.addAsset(assetCode, name, source, serialNum, vendorDetail, invoice_num, udise,
is_online);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@GetMapping(value = "/getAssets")
public ResponseEntity<Map<String, Object>> getAssets(@RequestParam int it_details_id) {
Map<String, Object> response = new HashMap<>();
Map<String, Object> data = buildingAssetService.getAssets(it_details_id);
if (!data.isEmpty()) {
response.put("status", "Success");
response.put("data", data);
} else {
response.put("Status", "Error");
}
return ResponseEntity.ok(response);
}
@PostMapping(value = "/editAsset")
public String editAsset(@RequestParam String assetCode, @RequestParam String name, @RequestParam String source,
@RequestParam String serialNum, @RequestParam String vendorDetail, @RequestParam String invoice_num,
@RequestParam int it_details_id) {
try {
return buildingAssetService.editAsset(assetCode, name, source, serialNum, vendorDetail, invoice_num,
it_details_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@GetMapping("/getStudentStrengthBySchoolId")
public ResponseEntity<Map<String, Object>> getStudentStrengthBySchoolId(@RequestParam int schoolId) {
try {
List<Map<String, Object>> studentStrength = buildingAssetService.getStudentStrengthBySchoolId(schoolId);
if (!studentStrength.isEmpty()) {
return ResponseEntity.ok(Map.of("status", "OK", "studentStrength", studentStrength));
} else {
return ResponseEntity.ok(Map.of("status", "NEW", "studentStrength", studentStrength));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Could not load student strength data"));
}
}
@GetMapping("/getotherdetailsBySchoolId")
public ResponseEntity<Map<String, Object>> getotherdetailsBySchoolId(@RequestParam int schoolId) {
try {
List<Map<String, Object>> getotherdetailsBySchool = buildingAssetService
.getotherdetailsBySchoolId(schoolId);
if (!getotherdetailsBySchool.isEmpty()) {
return ResponseEntity.ok(Map.of("status", "OK", "otherdetailsBySchool", getotherdetailsBySchool));
} else {
return ResponseEntity.ok(Map.of("status", "NEW", "otherdetailsBySchool", getotherdetailsBySchool));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Could not load student strength data"));
}
}
@GetMapping("/getStaffStrengthBySchoolId")
public ResponseEntity<Map<String, Object>> getStaffStrengthBySchoolId(@RequestParam int schoolId) {
try {
List<Map<String, Object>> staffStrength = buildingAssetService.getStaffStrengthBySchoolId(schoolId);
if (!staffStrength.isEmpty()) {
return ResponseEntity.ok(Map.of("status", "OK", "staffStrength", staffStrength));
} else {
return ResponseEntity.ok(Map.of("status", "NEW", "staffStrength", staffStrength));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Could not load student strength data"));
}
}
}

477
backend/school/Controller/DropdownsController.java

@ -0,0 +1,477 @@
package in.gov.chennaicorporation.gccoffice.school.Controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.gccoffice.school.Service.DropdownsService;
@RestController
@RequestMapping("/gcc/api/gccschool/dropdown")
public class DropdownsController {
@Autowired
private DropdownsService dropdownsService;
@Autowired
public DropdownsController(DropdownsService dropdownsService) {
this.dropdownsService = dropdownsService;
}
// To Get Court Dropdown Data
@GetMapping("/getCourtData")
public ResponseEntity<Map<String, Object>> getCourtData() {
try {
List<Map<String, Object>> data = dropdownsService.getCourtData();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Equipmengt Dropdown Data
@GetMapping("/getEquipmentData")
public ResponseEntity<Map<String, Object>> getEquipmentData() {
try {
List<Map<String, Object>> data = dropdownsService.getEquipmentData();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Building Material Dropdown Data
@GetMapping("/getBuildingMaterial")
public ResponseEntity<Map<String, Object>> getBuildingMaterial() {
try {
List<Map<String, Object>> data = dropdownsService.getBuildingMaterial();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Roof Material Dropdown Data
@GetMapping("/getRoofMaterial")
public ResponseEntity<Map<String, Object>> getRoofMaterial() {
try {
List<Map<String, Object>> data = dropdownsService.getRoofMaterial();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Water Source Dropdown Data
@GetMapping("/getWaterSource")
public ResponseEntity<Map<String, Object>> getWaterSource() {
try {
List<Map<String, Object>> data = dropdownsService.getWaterSource();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Water Storage Dropdown Data
@GetMapping("/getWaterStorage")
public ResponseEntity<Map<String, Object>> getWaterStorage() {
try {
List<Map<String, Object>> data = dropdownsService.getWaterStorage();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Rooms Dropdown Data
@GetMapping("/getRooms")
public ResponseEntity<Map<String, Object>> getRooms() {
try {
List<Map<String, Object>> data = dropdownsService.getRooms();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
@GetMapping("/getFloorsByBuilding")
public ResponseEntity<Map<String, Object>> getFloorsByBuilding(@RequestParam("building_id") int buildingId) {
try {
List<Map<String, Object>> data = dropdownsService.getFloorsByBuilding(buildingId);
Map<String, Object> response = new HashMap<>();
if (!data.isEmpty()) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No floors found for the selected building.");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Failed to fetch floors."));
}
}
@GetMapping("/getBuildingsBySchoolId")
public ResponseEntity<Map<String, Object>> getBuildingsBySchoolId(@RequestParam int school_id) {
try {
List<Map<String, Object>> data = dropdownsService.getBuildingsBySchoolId(school_id);
Map<String, Object> response = new HashMap<>();
if (!data.isEmpty()) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No buildings found for the selected school.");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Failed to fetch buildings."));
}
}
@GetMapping("/getDropdownValues")
public List<Map<String, Object>> getDropdownValues(@RequestParam String user_id) {
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> response = new HashMap<>();
String schoolId = dropdownsService.getSchoolId(user_id);
if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) {
response.put("Message", "Failure");
response.put("Data", List.of());
resultList.add(response);
return resultList;
}
List<Map<String, Object>> udiseData = dropdownsService.getUdiseNumbersBySchoolId(schoolId);
if (!udiseData.isEmpty()) {
List<String> udiseList = udiseData.stream().map(m -> (String) m.get("udise")).collect(Collectors.toList());
response.put("Message", "Success");
response.put("Data", udiseList);
} else {
response.put("Message", "No Data Found");
response.put("Data", List.of());
}
resultList.add(response);
return resultList;
}
@GetMapping("/getCategoryValues")
public List<Map<String, Object>> getCategoryValues(@RequestParam String user_id) {
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> response = new HashMap<>();
String schoolId = dropdownsService.getSchoolId(user_id);
if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) {
response.put("Message", "Failure");
response.put("Data", List.of());
resultList.add(response);
return resultList;
}
List<Map<String, Object>> categoryData = dropdownsService.getCategoryBySchoolId(schoolId);
if (!categoryData.isEmpty()) {
List<String> categoryList = categoryData.stream().map(m -> (String) m.get("category"))
.collect(Collectors.toList());
response.put("Message", "Success");
response.put("Data", categoryList);
} else {
response.put("Message", "No Data Found");
response.put("Data", List.of());
}
resultList.add(response);
return resultList;
}
@GetMapping("/getZoneValues")
public List<Map<String, Object>> getZoneValues(@RequestParam String user_id) {
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> response = new HashMap<>();
String schoolId = dropdownsService.getSchoolId(user_id);
if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) {
response.put("Message", "Failure");
response.put("Data", List.of());
resultList.add(response);
return resultList;
}
List<Map<String, Object>> zoneData = dropdownsService.getZoneBySchoolId(schoolId);
if (!zoneData.isEmpty()) {
List<String> zoneList = zoneData.stream().map(m -> (String) m.get("zone")).collect(Collectors.toList());
response.put("Message", "Success");
response.put("Data", zoneList);
} else {
response.put("Message", "No Data Found");
response.put("Data", List.of());
}
resultList.add(response);
return resultList;
}
@GetMapping("/getwardValues")
public List<Map<String, Object>> getWardValues(@RequestParam String user_id) {
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> response = new HashMap<>();
String schoolId = dropdownsService.getSchoolId(user_id);
if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) {
response.put("Message", "Failure");
response.put("Data", List.of());
resultList.add(response);
return resultList;
}
List<Map<String, Object>> wardData = dropdownsService.getWardBySchoolId(schoolId);
if (!wardData.isEmpty()) {
List<String> wardList = wardData.stream().map(m -> (String) m.get("division")).collect(Collectors.toList());
response.put("Message", "Success");
response.put("Data", wardList);
} else {
response.put("Message", "No Data Found");
response.put("Data", List.of());
}
resultList.add(response);
return resultList;
}
@GetMapping("/getAllDropdownValues")
public ResponseEntity<?> getAllDropdownValues(@RequestParam String user_id, @RequestParam String type) {
Map<String, Object> response = new HashMap<>();
List<String> dropdownList = Collections.emptyList();
// First get school_id(s) for this user
String schoolId = dropdownsService.getSchoolId(user_id);
if (schoolId.equals("error")) {
response.put("Message", "Failed to fetch school ID");
response.put("Data", dropdownList);
return ResponseEntity.ok(Collections.singletonList(response));
}
try {
List<Map<String, Object>> rawData;
switch (type.toLowerCase()) {
case "udise":
rawData = dropdownsService.getUdiseNumbersBySchoolId(schoolId);
dropdownList = rawData.stream().map(map -> String.valueOf(map.get("udise")))
.collect(Collectors.toList());
break;
case "category":
rawData = dropdownsService.getCategoryBySchoolId(schoolId);
dropdownList = rawData.stream().map(map -> String.valueOf(map.get("category"))).distinct()
.collect(Collectors.toList());
break;
case "zone":
rawData = dropdownsService.getZoneBySchoolId(schoolId);
dropdownList = rawData.stream().map(map -> String.valueOf(map.get("zone"))).distinct()
.collect(Collectors.toList());
break;
case "ward":
rawData = dropdownsService.getWardBySchoolId(schoolId);
dropdownList = rawData.stream().map(map -> String.valueOf(map.get("division"))).distinct()
.collect(Collectors.toList());
break;
default:
response.put("Message", "Invalid dropdown type");
response.put("Data", dropdownList);
return ResponseEntity.badRequest().body(Collections.singletonList(response));
}
response.put("Message", "Success");
response.put("Data", dropdownList);
return ResponseEntity.ok(Collections.singletonList(response));
} catch (Exception e) {
e.printStackTrace();
response.put("Message", "Error while processing dropdown values");
response.put("Data", dropdownList);
return ResponseEntity.ok(Collections.singletonList(response));
}
}
// To Get Asset Types Data
@GetMapping("/getAssetType")
public ResponseEntity<Map<String, Object>> getAssetType() {
try {
List<Map<String, Object>> data = dropdownsService.getAssetType();
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// To Get Sub Asset Types Data
@GetMapping("/getSubAssetType")
public ResponseEntity<Map<String, Object>> getSubAssetType(int assetid) {
try {
List<Map<String, Object>> data = dropdownsService.getSubAssetType(assetid);
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
@GetMapping("/getSplSubAssetType")
public ResponseEntity<Map<String, Object>> getSplSubAssetType(int school_id, int assetid) {
try {
List<String> assets = dropdownsService.getAssetList(school_id, assetid);
List<Map<String, Object>> data = dropdownsService.getSplSubAssetType(assets, assetid);
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
}

128
backend/school/Controller/MainController.java

@ -0,0 +1,128 @@
package in.gov.chennaicorporation.gccoffice.school.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import in.gov.chennaicorporation.gccoffice.service.LoginUserInfo;
@Controller("schoolcontroller")
@RequestMapping("/gcc/school")
public class MainController {
@GetMapping("/otherdetails")
public String otherdetails(Model model) {
return "modules/school/otherdetails";
}
@GetMapping("/schooldetails")
public String viewschool(Model model) {
return "modules/school/schooldetails";
}
@GetMapping("/schoolmodule")
public String viewmodule(Model model) {
String loginUserId = LoginUserInfo.getLoginUserId();
model.addAttribute("user_id", loginUserId);
System.out.println("loginUserId..........." + loginUserId);
return "modules/school/dashboard";
}
@GetMapping("/staffdetails")
public String staffdetails(Model model) {
return "modules/school/staffdetails";
}
@GetMapping("/roomassets")
public String roomassets(Model model) {
return "modules/school/roomassets";
}
@GetMapping("/assetmanagement")
public String assetmanagement(Model model) {
return "modules/school/assetmanagement";
}
// @GetMapping("/itassets")
// public String itassets(Model model) {
//
// System.out.println("okokokok===");
//
// return "modules/school/itassets";
// }
@GetMapping("/studentdetails")
public String studentdetails(Model model) {
return "modules/school/studentdetails";
}
@GetMapping("/building")
public String buildings(Model model) {
return "modules/school/building";
}
@GetMapping("/room")
public String roomlist(Model model) {
return "modules/school/room";
}
@GetMapping("/playground")
public String playground(Model model) {
return "modules/school/playground";
}
@GetMapping("/drinkingwater")
public String drinkingwater(Model model) {
return "modules/school/drinkingwater";
}
@GetMapping("/toilets")
public String toilet(Model model) {
return "modules/school/toilets";
}
// @GetMapping("/electricalassets")
// public String electricalassets(Model model) {
//
// return "modules/school/electricalassets";
// }
//
// @GetMapping("/furnitureassets")
// public String furnitureassets(Model model) {
//
// return "modules/school/furnitureassets";
// }
@GetMapping("/kitchen")
public String kitchen(Model model) {
return "modules/school/kitchen";
}
@GetMapping("/addelectricalasset")
public String addelectricalasset(Model model) {
return "modules/school/addelectricalasset";
}
@GetMapping("/addfurnitureasset")
public String addfurnitureasset(Model model) {
return "modules/school/addfurnitureasset";
}
@GetMapping("/reports")
public String reportpage(Model model) {
return "modules/school/reports";
}
}

720
backend/school/Controller/SchoolPropertyController.java

@ -0,0 +1,720 @@
package in.gov.chennaicorporation.gccoffice.school.Controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.gccoffice.school.Service.SchoolPropertyService;
@RestController
@CrossOrigin()
@RequestMapping("/gcc/api/gccschool/schoolproperty")
public class SchoolPropertyController {
@Autowired
private SchoolPropertyService schoolPropertyService;
@Autowired
public SchoolPropertyController(SchoolPropertyService schoolPropertyService) {
this.schoolPropertyService = schoolPropertyService;
}
// To Get School Data
@GetMapping("/getSchoolData")
public ResponseEntity<Map<String, Object>> getSchoolData(@RequestParam String udise) {
try {
List<Map<String, Object>> data = schoolPropertyService.getSchoolData(udise);
Map<String, Object> response = new HashMap<>();
if (data.size() != 0) {
response.put("status", "OK");
response.put("data", data);
} else {
response.put("status", "Failed");
response.put("data", "No Data Found");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
// Log the exception details for debugging
e.printStackTrace();
// Provide a user-friendly error message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error getting data: " + e.getMessage()));
}
}
// For Other Details
@PostMapping(value = "/saveSchoolBuildupArea")
public String saveSchoolBuildupArea(@RequestParam("land_area") Double land_area,
@RequestParam("buildup_area") Double buildup_area, @RequestParam("is_compound") Boolean is_compound,
@RequestParam("is_nameboard") Boolean is_nameboard, @RequestParam("is_pasystem") Boolean is_pasystem,
@RequestParam("is_bell") Boolean is_bell, @RequestParam("is_generator") Boolean is_generator,
@RequestParam("school_id") int school_id) {
return schoolPropertyService.saveSchoolBuildupArea(land_area, buildup_area, is_compound, is_nameboard,
is_pasystem, is_bell, is_generator, school_id);
}
// For Student Strength
@PostMapping(value = "/saveStudentStrength")
public String saveStudentStrength(@RequestParam("total_students") int total_students,
@RequestParam("total_girls") int total_girls, @RequestParam("total_boys") int total_boys,
@RequestParam("others") int others, @RequestParam("school_id") int school_id) {
return schoolPropertyService.saveStudentStrength(total_students, total_girls, total_boys, others, school_id);
}
// For Staff Strength
// @PostMapping(value="/saveStaffStrength")
// public String saveStaffStrength(
// @RequestParam("tot_staff") int tot_staff,
// @RequestParam("sg_staff") int sg_staff,
// @RequestParam("bt_staff") int bt_staff,
// @RequestParam("pg_staff") int pg_staff,
// @RequestParam("temp_staff") int temp_staff,
// @RequestParam("ngo_staff") int ngo_staff,
// @RequestParam("kg_staff") int kg_staff,
// @RequestParam("pt_staff") int pt_staff,
// @RequestParam("part_staff") int part_staff,
// @RequestParam("qa_staff") int qa_staff,
// @RequestParam("kg_ayha") int kg_ayha,
// @RequestParam("watchman") int watchman,
// @RequestParam("comp_asst") int comp_asst,
// @RequestParam("scavengers") int scavengers,
// @RequestParam("maint_workers") int maint_workers,
// @RequestParam("school_id") int school_id) {
//
// return schoolPropertyService.saveStaffStrength(tot_staff, sg_staff, bt_staff,pg_staff, temp_staff, ngo_staff, kg_staff, pt_staff,part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id);
// }
// For Toilets
@PostMapping(value = "/saveToilets")
public String saveToilets(@RequestParam("total_toiletBlocks") int total_toiletBlocks,
@RequestParam("total_male_urinals") int total_male_urinals,
@RequestParam("total_wc_male") int total_wc_male, @RequestParam("total_wc_female") int total_wc_female,
@RequestParam("total_diffAbled_toilet") int total_diffAbled_toilet,
@RequestParam("is_napkins") Boolean is_napkins, @RequestParam("school_id") int school_id) {
return schoolPropertyService.saveToilets(total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female,
total_diffAbled_toilet, is_napkins, school_id);
}
// For Kitchen
@PostMapping(value = "/saveKitchen")
public String saveKitchen(@RequestParam(value = "is_cmbfs") Boolean is_cmbfs,
@RequestParam(value = "is_cmbfsIndividual", required = false) Boolean is_cmbfsIndividual,
@RequestParam(value = "is_noonmeal") Boolean is_noonmeal,
@RequestParam(value = "is_noonIndividual", required = false) Boolean is_noonIndividual,
@RequestParam(value = "is_vegGarden", required = false) Boolean is_vegGarden,
@RequestParam(value = "is_anganwadi") Boolean is_anganwadi,
@RequestParam(value = "anganwadi_unique", required = false) String anganwadi_unique,
@RequestParam(value = "is_anganwadiIndividual", required = false) Boolean is_anganwadiIndividual,
@RequestParam(value = "school_id") int school_id) {
if (anganwadi_unique != null && anganwadi_unique.trim().isEmpty()) {
anganwadi_unique = null;
}
return schoolPropertyService.saveKitchen(is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual,
is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id);
}
// For Playground
@PostMapping(value = "/savePlayground")
public ResponseEntity<Map<String, String>> savePlayground(@RequestBody Map<String, Object> payload) {
Map<String, String> response = new HashMap<>();
try {
Boolean is_playground = (Boolean) payload.get("is_playground");
Double playground_area = Double.valueOf(payload.get("playground_area").toString());
Boolean is_court = (Boolean) payload.get("is_court");
int school_id = Integer.parseInt(payload.get("school_id").toString());
// Boolean is_active = (Boolean) payload.get("is_active");
List<String> equipmentidRaw = (List<String>) payload.get("equipmentid");
List<String> courtidRaw = (List<String>) payload.get("courtid");
// Convert string IDs to integers
// List<Integer> equipmentid = equipmentidRaw.stream().map(Integer::parseInt).toList();
// List<Integer> courtid = courtidRaw.stream().map(Integer::parseInt).toList();
int playground_id = schoolPropertyService.savePlayground(is_playground, playground_area, is_court,
school_id);
for (String equipment_id : equipmentidRaw) {
schoolPropertyService.saveEquipmentDetails(equipment_id, school_id, playground_id);
}
for (String court_id : courtidRaw) {
schoolPropertyService.saveCourtDetails(court_id, school_id, playground_id);
}
response.put("status", "OK");
response.put("message", "Playground Details saved successfully");
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
response.put("status", "ERROR");
response.put("message", "Failed to save playground details");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
// For Drinking Water
@PostMapping(value = "/saveDrinkingWater")
public ResponseEntity<Map<String, Object>> saveDrinkingWater(@RequestBody Map<String, Object> requestData) {
try {
// Extract data from the map
List<Map<String, Object>> water = (List<Map<String, Object>>) requestData.get("water");
Boolean is_purifier = "1".equals(requestData.get("is_purifier"));
Double purifier_capacity = requestData.get("purifier_capacity") != null
? Double.valueOf(requestData.get("purifier_capacity").toString())
: null;
Boolean is_borewell = "1".equals(requestData.get("is_borewell"));
Integer borewell_count = requestData.get("borewell_count") != null
? Integer.valueOf(requestData.get("borewell_count").toString())
: null;
Boolean is_storage = "1".equals(requestData.get("is_storage"));
List<Map<String, Object>> storage = (List<Map<String, Object>>) requestData.get("storage");
int school_id = Integer.parseInt(requestData.get("school_id").toString());
Map<String, Object> response = new HashMap<>();
int drinking_water_id = schoolPropertyService.saveDrinkingWater(is_purifier, purifier_capacity, is_borewell,
borewell_count, is_storage, school_id);
for (Map<String, Object> waterSupply : water) {
int source_water_id = (int) waterSupply.get("source_water_id");
String supply_type = (String) waterSupply.get("supply_type");
schoolPropertyService.saveWaterSupply(source_water_id, supply_type, drinking_water_id, school_id);
}
if (!storage.isEmpty()) {
for (Map<String, Object> waterStorage : storage) {
double capacity = Double.valueOf(waterStorage.get("capacity").toString());
int storage_water_id = (int) waterStorage.get("storage_water_id");
schoolPropertyService.saveWaterStorage(capacity, storage_water_id, drinking_water_id, school_id);
}
}
response.put("status", "OK");
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error saving data: " + e.getMessage()));
}
}
@PostMapping("/saveStaffStrength")
public String saveStaffStrength(@RequestParam int sgRegTeacher, @RequestParam int sgTempTeacher,
@RequestParam int sgPtTeacher, @RequestParam int sgNgoTeacher, @RequestParam int btRegTeacher,
@RequestParam int btTempTeacher, @RequestParam int btPtTeacher, @RequestParam int btNgoTeacher,
@RequestParam int pgRegTeacher, @RequestParam int pgTempTeacher, @RequestParam int pgPtTeacher,
@RequestParam int pgNgoTeacher, @RequestParam int kgRegTeacher, @RequestParam int kgTempTeacher,
@RequestParam int petRegTeacher, @RequestParam int petTempTeacher, @RequestParam int petGrade1Teacher,
@RequestParam int petGrade2Teacher, @RequestParam int totOa, @RequestParam int kgAyah,
@RequestParam int compAss, @RequestParam int watchmen, @RequestParam int scavengers,
@RequestParam int maintenanceWork, @RequestParam int schoolId) {
// Call service method
schoolPropertyService.saveStaffStrength(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher,
btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher,
kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa,
kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId);
return "Staff strength details saved successfully!";
}
// For login
@GetMapping(value = "/getLoginDetails")
public List<Map<String, Object>> getLoginDetails(@RequestParam String user_id) {
List<Map<String, Object>> schoolData = new ArrayList<>();
Map<String, Object> response = new HashMap<>();
String schoolId = schoolPropertyService.getSchoolId(user_id);
if (schoolId == null || schoolId.trim().isEmpty() || schoolId.equalsIgnoreCase("error")) {
response.put("Message", "Failure");
response.put("Data", List.of());
schoolData.add(response);
return schoolData;
}
List<Map<String, Object>> sch = schoolPropertyService.getSchoolData1(schoolId);
if (!sch.isEmpty()) {
response.put("Message", "Success");
response.put("Data", sch);
schoolData.add(response);
return schoolData;
} else {
response.put("Message", "No Data Found");
response.put("Data", List.of());
schoolData.add(response);
return schoolData;
}
}
@GetMapping("/getSchoolDetails")
public ResponseEntity<Map<String, Object>> getSchoolDetails(@RequestParam Long schoolId) {
try {
Map<String, Object> data = schoolPropertyService.getSchoolDetails(schoolId);
if (data != null && !data.isEmpty()) {
return ResponseEntity.ok(data);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("status", "Failed", "message", "No school found with given ID"));
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", e.getMessage()));
}
}
@GetMapping("/filterSchools")
public ResponseEntity<?> filterSchools(@RequestParam String user_id, @RequestParam(required = false) String udise,
@RequestParam(required = false) String category, @RequestParam(required = false) String zone,
@RequestParam(required = false) String ward) {
List<Map<String, Object>> filteredSchools = schoolPropertyService.filterSchools(user_id, udise, category, zone,
ward);
Map<String, Object> result = new HashMap<>();
result.put("Message", "Success");
result.put("Data", filteredSchools);
return ResponseEntity.ok(Collections.singletonList(result));
}
@PostMapping("/updateOtherDetails")
public String updateOtherDetails(@RequestParam("land_area") Double land_area,
@RequestParam("buildup_area") Double buildup_area, @RequestParam("is_compound") Boolean is_compound,
@RequestParam("is_nameboard") Boolean is_nameboard, @RequestParam("is_pasystem") Boolean is_pasystem,
@RequestParam("is_bell") Boolean is_bell, @RequestParam("is_generator") Boolean is_generator,
@RequestParam("school_id") int school_id) {
try {
return schoolPropertyService.updateOtherDetails(land_area, buildup_area, is_compound, is_nameboard,
is_pasystem, is_bell, is_generator, school_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@PostMapping(value = "/updateStudentDetails")
public String updateStudentDetails(@RequestParam("total_students") int total_students,
@RequestParam("total_girls") int total_girls, @RequestParam("total_boys") int total_boys,
@RequestParam("others") int others, @RequestParam("school_id") int school_id) {
System.out.println("Update Request => total: " + total_students + ", boys: " + total_boys + ", girls: "
+ total_girls + ", others: " + others + ", school_id: " + school_id);
try {
return schoolPropertyService.updateStudentDetails(total_students, total_girls, total_boys, others,
school_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@GetMapping("/checkPlaygroundDetails")
public ResponseEntity<?> checkPlaygroundDetails(@RequestParam int school_id) {
Map<String, Object> playgroundDetails = schoolPropertyService.checkPlaygroundDetails(school_id);
List<Map<String, Object>> courtDetails = schoolPropertyService.checkCourtDetails(school_id);
List<Map<String, Object>> equipmentDetails = schoolPropertyService.checkEquipmentDetails(school_id);
Map<String, Object> result = new HashMap<>();
result.put("Message", "Success");
result.put("playgroundDetails", playgroundDetails);
result.put("CourtDetails", courtDetails);
result.put("EquipmentDetails", equipmentDetails);
return ResponseEntity.ok(Collections.singletonList(result));
}
/*
* @PostMapping(value = "/updatePlayground") public ResponseEntity<String>
* updatePlayground(@RequestBody Map<String, Object> payload) { try { Boolean
* is_playground = (Boolean) payload.get("is_playground"); Double
* playground_area = Double.valueOf(payload.get("playground_area").toString());
* Boolean is_court = (Boolean) payload.get("is_court"); int school_id =
* Integer.parseInt(payload.get("school_id").toString()); int playground_id =
* Integer.parseInt(payload.get("playground_id").toString());
*
* List<Map<String, Object>> equipments = (List<Map<String, Object>>)
* payload.get("equipments"); List<Map<String, Object>> courts =
* (List<Map<String, Object>>) payload.get("courts");
*
* String result = schoolPropertyService.updatePlaygroundDetails( is_playground,
* playground_area, is_court, equipments, courts, playground_id, school_id );
* return ResponseEntity.ok(result);
*
* } catch (Exception e) { e.printStackTrace(); return
* ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } }
*/
// @PostMapping(value = "/updatePlayground")
// public ResponseEntity<Map<String, String>> updatePlayground(@RequestBody Map<String, Object> payload) {
// Map<String, String> response = new HashMap<>();
// try {
// Boolean is_playground = (Boolean) payload.get("is_playground");
// Double playground_area = Double.valueOf(payload.get("playground_area").toString());
// Boolean is_court = (Boolean) payload.get("is_court");
// int school_id = Integer.parseInt(payload.get("school_id").toString());
// //Boolean is_active = (Boolean) payload.get("is_active");
// int playground_id = Integer.parseInt(payload.get("playground_id").toString());
//
//
// List<String> equipmentidRaw = (List<String>) payload.get("equipments");
// List<String> courtidRaw = (List<String>) payload.get("courts");
//
// // Convert string IDs to integers
// List<Integer> equipmentid = equipmentidRaw.stream().map(Integer::parseInt).toList();
// List<Integer> courtid = courtidRaw.stream().map(Integer::parseInt).toList();
// schoolPropertyService.deactiveCourts(school_id);
// schoolPropertyService.deactiveEquipments(school_id);
// schoolPropertyService.updatePlayground(is_playground, playground_area, is_court, school_id, playground_id);
// //int playground_id = schoolPropertyService.savePlayground(is_playground, playground_area, is_court,
// // school_id);
//
// for (Integer equipment_id : equipmentid) {
// schoolPropertyService.saveEquipmentDetails(equipment_id, school_id, playground_id);
// }
//
// for (Integer court_id : courtid) {
// schoolPropertyService.saveCourtDetails(court_id, school_id, playground_id);
// }
//
// response.put("status", "OK");
// response.put("message", "Playground Details updated successfully");
// return ResponseEntity.ok(response);
//
// } catch (Exception e) {
// e.printStackTrace();
// response.put("status", "ERROR");
// response.put("message", "Failed to updated playground details");
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
// }
// }
@PostMapping(value = "/updatePlayground")
public ResponseEntity<Map<String, String>> updatePlayground(@RequestBody Map<String, Object> payload) {
Map<String, String> response = new HashMap<>();
try {
Boolean is_playground = (Boolean) payload.get("is_playground");
Double playground_area = Double.valueOf(payload.get("playground_area").toString());
Boolean is_court = (Boolean) payload.get("is_court");
int school_id = Integer.parseInt(payload.get("school_id").toString());
int playground_id = Integer.parseInt(payload.get("playground_id").toString());
List<Map<String, Object>> equipmentList = (List<Map<String, Object>>) payload.get("equipments");
List<Map<String, Object>> courtList = (List<Map<String, Object>>) payload.get("courts");
String status = schoolPropertyService.updatePlaygroundDetails(is_playground, playground_area, is_court,
equipmentList, courtList, playground_id, school_id);
response.put("status", status.equals("Success") ? "OK" : "ERROR");
response.put("message",
status.equals("Success") ? "Playground updated successfully" : "Failed to update playground");
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
response.put("status", "ERROR");
response.put("message", "Exception occurred during update");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
@PostMapping(value = "/updateKitchenDetails")
public String updateKitchenDetails(@RequestParam(value = "is_cmbfs") Boolean is_cmbfs,
@RequestParam(value = "is_cmbfsIndividual", required = false) Boolean is_cmbfsIndividual,
@RequestParam(value = "is_noonmeal") Boolean is_noonmeal,
@RequestParam(value = "is_noonIndividual", required = false) Boolean is_noonIndividual,
@RequestParam(value = "is_vegGarden", required = false) Boolean is_vegGarden,
@RequestParam(value = "is_anganwadi") Boolean is_anganwadi,
@RequestParam(value = "anganwadi_unique", required = false) String anganwadi_unique,
@RequestParam(value = "is_anganwadiIndividual", required = false) Boolean is_anganwadiIndividual,
@RequestParam(value = "school_id") int school_id) {
try {
return schoolPropertyService.updateKitchenDetails(is_cmbfs, is_cmbfsIndividual, is_noonmeal,
is_noonIndividual, is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@GetMapping("/checkKitchenDetails")
public ResponseEntity<?> checkKitchenDetails(@RequestParam int school_id) {
Map<String, Object> kitchenDetails = schoolPropertyService.checkKitchenDetails(school_id);
Map<String, Object> result = new HashMap<>();
result.put("Message", "Success");
result.put("Data", kitchenDetails);
return ResponseEntity.ok(Collections.singletonList(result));
}
@PostMapping(value = "/updateStaffDetails")
public String updateStaffDetails(@RequestParam int sgRegTeacher, @RequestParam int sgTempTeacher,
@RequestParam int sgPtTeacher, @RequestParam int sgNgoTeacher, @RequestParam int btRegTeacher,
@RequestParam int btTempTeacher, @RequestParam int btPtTeacher, @RequestParam int btNgoTeacher,
@RequestParam int pgRegTeacher, @RequestParam int pgTempTeacher, @RequestParam int pgPtTeacher,
@RequestParam int pgNgoTeacher, @RequestParam int kgRegTeacher, @RequestParam int kgTempTeacher,
@RequestParam int petRegTeacher, @RequestParam int petTempTeacher, @RequestParam int petGrade1Teacher,
@RequestParam int petGrade2Teacher, @RequestParam int totOa, @RequestParam int kgAyah,
@RequestParam int compAss, @RequestParam int watchmen, @RequestParam int scavengers,
@RequestParam int maintenanceWork, @RequestParam int school_id) {
try {
return schoolPropertyService.updateStaffDetails(sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher,
btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher,
pgNgoTeacher, kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher,
petGrade2Teacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, school_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
/*
* @GetMapping("/checkWaterDetails") public ResponseEntity<?> checkWaterDetails(
*
* @RequestParam int school_id) {
*
* Map<String, Object> drinkingWater =
* schoolPropertyService.checkWaterDetails(school_id); List<Map<String, Object>>
* waterSource = schoolPropertyService.checkWaterSource(school_id);
* List<Map<String, Object>> waterStorage =
* schoolPropertyService.checkWaterStotage(school_id);
*
* Map<String, Object> result = new HashMap<>(); result.put("Message",
* "Success"); result.put("DrinkingWater", drinkingWater);
* result.put("WaterSource", waterSource); result.put("WaterStorage",
* waterStorage);
*
* return ResponseEntity.ok(Collections.singletonList(result)); }
*/
// @PostMapping(value = "/updateDrinkingWater")
// public String updateDrinkingWater(@RequestParam("is_purifier") Boolean is_purifier, @RequestParam("purifier_capacity") Double purifier_capacity,
// @RequestParam("is_borewell") Boolean is_borewell, @RequestParam("borewell_count") int borewell_count, @RequestParam("is_storage") Boolean is_storage,
// @RequestParam("drinking_water_id") int drinking_water_id, @RequestParam("school_id") int school_id, @RequestParam("supply") List<Map<String, Object>> supply,
// @RequestParam("storage") List<Map<String, Object>> storage) {
// try {
//
// return schoolPropertyService.updateDrinkingWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, drinking_water_id, school_id, supply, storage);
//
// } catch (Exception e) {
// e.printStackTrace();
// return "Error";
// }
//
// }
@PostMapping(value = "/updateDrinkingWater")
public ResponseEntity<Map<String, Object>> updateDrinkingWater(@RequestBody Map<String, Object> requestData) {
try {
System.out.println("Received update payload: " + requestData);
// Extract data from the map
// List<Map<String, Object>> water = (List<Map<String, Object>>)
// requestData.get("water");
List<Map<String, Object>> water = (List<Map<String, Object>>) requestData.getOrDefault("supply",
new ArrayList<>());
List<Map<String, Object>> storage = (List<Map<String, Object>>) requestData.getOrDefault("storage",
new ArrayList<>());
Boolean is_purifier = (Boolean) requestData.get("is_purifier");
Double purifier_capacity = requestData.get("purifier_capacity") != null
? Double.valueOf(requestData.get("purifier_capacity").toString())
: 0;
Boolean is_borewell = (Boolean) requestData.get("is_borewell");
Integer borewell_count = requestData.get("borewell_count") != null
? Integer.valueOf(requestData.get("borewell_count").toString())
: 0;
Boolean is_storage = (Boolean) requestData.get("is_storage");
// List<Map<String, Object>> storage = (List<Map<String, Object>>)
// requestData.get("storage");
int school_id = Integer.parseInt(requestData.get("school_id").toString());
int drinking_water_id = Integer.parseInt(requestData.get("drinking_water_id").toString());
Map<String, Object> response = new HashMap<>();
schoolPropertyService.updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count,
is_storage, school_id, drinking_water_id);
schoolPropertyService.deactiveWaterSupply(school_id, drinking_water_id);
schoolPropertyService.deactiveWaterStorage(school_id, drinking_water_id);
for (Map<String, Object> waterSupply : water) {
int source_water_id = (int) waterSupply.get("source_water_id");
String supply_type = (String) waterSupply.get("supply_type");
schoolPropertyService.saveWaterSupply(source_water_id, supply_type, drinking_water_id, school_id);
}
if (!storage.isEmpty()) {
for (Map<String, Object> waterStorage : storage) {
double capacity = Double.valueOf(waterStorage.get("capacity").toString());
int storage_water_id = (int) waterStorage.get("storage_water_id");
schoolPropertyService.saveWaterStorage(capacity, storage_water_id, drinking_water_id, school_id);
}
}
response.put("status", "OK");
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Error saving data: " + e.getMessage()));
}
}
@GetMapping("/checkWaterDetails")
public ResponseEntity<Map<String, Object>> checkWaterDetails(@RequestParam int school_id) {
System.out.println("CHECK 11");
try {
System.out.println("CHECK 1");
Map<String, Object> drinkingWater = schoolPropertyService.checkWaterDetails(school_id);
List<Map<String, Object>> waterSource = schoolPropertyService.checkWaterSource(school_id);
List<Map<String, Object>> waterStorage = schoolPropertyService.checkWaterStotage(school_id);
System.out.println("WATER SOURCE = " + waterSource);
Map<String, Object> response = new HashMap<>();
response.put("DrinkingWater", drinkingWater);
response.put("WaterSource", waterSource);
response.put("WaterStorage", waterStorage);
// ✅ Set status based on content presence
if (drinkingWater != null && !drinkingWater.isEmpty()) {
response.put("status", "OK");
} else {
response.put("status", "NEW");
}
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("status", "Error", "message", "Could not load drinking water data"));
}
}
@GetMapping("/checkToiletDetails")
public ResponseEntity<?> checkToiletDetails(@RequestParam int school_id) {
List<Map<String, Object>> toiletDetails = schoolPropertyService.checkToiletDetails(school_id);
Map<String, Object> result = new HashMap<>();
result.put("Message", "Success");
result.put("Data", toiletDetails);
return ResponseEntity.ok(Collections.singletonList(result));
}
@PostMapping(value = "/updateToiletDetails")
public String updateToiletDetails(@RequestParam("total_toiletBlocks") int total_toiletBlocks,
@RequestParam("total_male_urinals") int total_male_urinals,
@RequestParam("total_wc_male") int total_wc_male, @RequestParam("total_wc_female") int total_wc_female,
@RequestParam("total_diffAbled_toilet") int total_diffAbled_toilet,
@RequestParam("is_napkins") Boolean is_napkins, @RequestParam("school_id") int school_id) {
try {
return schoolPropertyService.updateToiletDetails(total_toiletBlocks, total_male_urinals, total_wc_male,
total_wc_female, total_diffAbled_toilet, is_napkins, school_id);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@PostMapping(value = "/saveAssetMaster")
public ResponseEntity<Map<String, String>> saveAssetMaster(@RequestBody Map<String, Object> payload) {
Map<String, String> response = new HashMap<>();
String status = "";
try {
int school_id = Integer.parseInt(payload.get("school_id").toString());
int asset_id = Integer.parseInt(payload.get("asset_id").toString());
List<Map<String, Object>> equipmentList = (List<Map<String, Object>>) payload.get("data");
for (Map<String, Object> asset : equipmentList) {
int sub_asset_id = Integer.parseInt(asset.get("sub_asset_id").toString());
int master_qty = Integer.parseInt(asset.get("master_qty").toString());
status = schoolPropertyService.saveAssetMaster(sub_asset_id, master_qty, school_id, asset_id);
}
response.put("status", status.equals("Success") ? "OK" : "ERROR");
response.put("message",
status.equals("Success") ? "Asset Master Saved successfully" : "Failed to Save Asset Master");
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
response.put("status", "ERROR");
response.put("message", "Exception occurred during update");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
@GetMapping("/getAssetMaster")
public ResponseEntity<?> getAssetMaster(@RequestParam int school_id, @RequestParam int asset_id) {
List<Map<String, Object>> data = schoolPropertyService.getAssetMaster(school_id, asset_id);
// System.out.println("data=="+data);
Map<String, Object> result = new HashMap<>();
result.put("status", "Success");
result.put("data", data);
return ResponseEntity.ok(result);
}
@GetMapping("/getAssetMasterById")
public ResponseEntity<?> getAssetMasterById(@RequestParam int assetMasterId, @RequestParam int asset_id) {
Map<String, Object> data = schoolPropertyService.getAssetMasterById(assetMasterId, asset_id);
Map<String, Object> result = new HashMap<>();
result.put("status", "Success");
result.put("data", data);
return ResponseEntity.ok(result);
}
@PostMapping(value = "/updateAssetMaster")
public String updateStudentDetails(@RequestParam("master_qty") int master_qty,
@RequestParam("assetMasterId") int assetMasterId, @RequestParam("asset_id") int asset_id) {
try {
Map<String, Object> assetMaster = schoolPropertyService.getAssetMasterById(assetMasterId, asset_id);
int qty = (Integer) assetMaster.get("master_qty");
int unmapped_asset = (Integer) assetMaster.get("unmapped_qty");
int master = qty + master_qty;
int unmapped = master_qty + unmapped_asset;
return schoolPropertyService.updateAssetMaster(assetMasterId, master, asset_id, unmapped);
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
}

48
backend/school/Controller/SchoolReportController.java

@ -0,0 +1,48 @@
package in.gov.chennaicorporation.gccoffice.school.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.gccoffice.school.Service.SchoolReportService;
@RestController
@RequestMapping("/gcc/api/gccschool/report")
public class SchoolReportController {
@Autowired
private SchoolReportService schoolReportService;
@Autowired
public SchoolReportController(SchoolReportService schoolReportService) {
this.schoolReportService = schoolReportService;
}
@GetMapping("/getAEOList")
public ResponseEntity<?> getAEOList(){
return schoolReportService.getAEOList();
}
@GetMapping("/getAEOZone")
public ResponseEntity<?> getAEOZone(@RequestParam String udise){
return schoolReportService.getAEOZone(udise);
}
@GetMapping("/getAEOWard")
public ResponseEntity<?> getAEOWard(@RequestParam String udise, @RequestParam String zone){
return schoolReportService.getAEOWard(udise, zone);
}
@GetMapping("/getAEOSchoolData")
public ResponseEntity<?> getAEOSchoolData(@RequestParam (required = false) List<String> udise,
@RequestParam (required = false) String zone,
@RequestParam (required = false) String ward){
return schoolReportService.getAEOSchoolData(udise, zone, ward);
}
}

1030
backend/school/Service/BuildingAssetService.java
File diff suppressed because it is too large
View File

188
backend/school/Service/DropdownsService.java

@ -0,0 +1,188 @@
package in.gov.chennaicorporation.gccoffice.school.Service;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class DropdownsService {
private JdbcTemplate jdbcTemplate;
// @Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.namedParameterJdbcTemplate= new NamedParameterJdbcTemplate(dataSource);
}
@Transactional
public List<Map<String, Object>> getCourtData() {
String sql = "SELECT * FROM courts_master ";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getEquipmentData() {
String sql = "SELECT * FROM equipment_master ";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getBuildingMaterial() {
String sql = "SELECT * FROM building_material_master ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getRoofMaterial() {
String sql = "SELECT * FROM roof_material_master ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getWaterSource() {
String sql = "SELECT * FROM source_water ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getWaterStorage() {
String sql = "SELECT * FROM water_storage_master ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getRooms() {
String sql = "SELECT * FROM room_master ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getFloorsByBuilding(int buildingId) {
String sql = "SELECT * FROM floor_list WHERE building_id = ? and is_active = true and is_delete = false";
return jdbcTemplate.queryForList(sql, buildingId);
}
@Transactional
public List<Map<String, Object>> getBuildingsBySchoolId(int schoolId) {
String sql = "SELECT buildng_id, building_name FROM buildings WHERE school_id = ? and is_active = true and is_delete = false";
return jdbcTemplate.queryForList(sql, schoolId);
}
// Reuse this for school_id retrieval
@Transactional
public String getSchoolId(String user_id) {
String sql = "SELECT school_id FROM login_details WHERE user_id = ?";
try {
return jdbcTemplate.queryForObject(sql, String.class, user_id);
} catch (DataAccessException e) {
return "error";
}
}
// New method to fetch UDISE numbers for a given school_id
public List<Map<String, Object>> getUdiseNumbersBySchoolId(String schoolId) {
String sql = "SELECT udise FROM school_list WHERE id IN(" + schoolId + ")";
try {
return jdbcTemplate.queryForList(sql);
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
public List<Map<String, Object>> getCategoryBySchoolId(String schoolId) {
String sql = "SELECT category FROM school_list WHERE id IN(" + schoolId + ")";
try {
return jdbcTemplate.queryForList(sql);
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
public List<Map<String, Object>> getZoneBySchoolId(String schoolId) {
String sql = "SELECT zone FROM school_list WHERE id IN(" + schoolId + ")";
try {
return jdbcTemplate.queryForList(sql);
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
public List<Map<String, Object>> getWardBySchoolId(String schoolId) {
String sql = "SELECT division FROM school_list WHERE id IN(" + schoolId + ")";
try {
return jdbcTemplate.queryForList(sql);
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
public List<Map<String, Object>> getAssetType() {
String sql = "SELECT * FROM asset_master ORDER BY execution_order";
return jdbcTemplate.queryForList(sql);
}
@Transactional
public List<Map<String, Object>> getSubAssetType(int assetid) {
String sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = ? ORDER BY execution_order";
return jdbcTemplate.queryForList(sql, assetid);
}
@Transactional
public List<Map<String, Object>> getSplSubAssetType(List<String> assets, int assetid) {
String sql;
Map<String, Object> params = new HashMap<>();
params.put("assetid", assetid);
if (assets == null || assets.isEmpty()) {
sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = :assetid ORDER BY execution_order";
} else {
sql = "SELECT * FROM asset_sub_master WHERE asset_master_id = :assetid AND asset_name NOT IN (:assets) ORDER BY execution_order";
params.put("assets", assets);
}
return namedParameterJdbcTemplate.queryForList(sql, params);
}
@Transactional
public List<String> getAssetList(int school_id, int assetid) {
String sql ="";
if(assetid==2) {
sql = "SELECT asm.asset_name from electrical_master em \r\n"
+ "INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id\r\n"
+ "WHERE em.school_id = ?";
} else if(assetid==3) {
sql = "SELECT asm.asset_name from furniture_master fm \r\n"
+ "INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id\r\n"
+ "WHERE fm.school_id = ?";
}
return jdbcTemplate.queryForList(sql, String.class, school_id);
}
}

970
backend/school/Service/SchoolPropertyService.java

@ -0,0 +1,970 @@
package in.gov.chennaicorporation.gccoffice.school.Service;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SchoolPropertyService {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Transactional
public List<Map<String, Object>> getSchoolData(String udise) {
String sql = "SELECT * FROM school_list WHERE udise = ?";
return jdbcTemplate.queryForList(sql, udise);
}
@Transactional
public String saveSchoolBuildupArea(Double land_area, Double buildup_area, Boolean is_compound,
Boolean is_nameboard, Boolean is_pasystem, Boolean is_bell, Boolean is_generator, int school_id) {
String sql = "INSERT INTO school_buildup_area (land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell, is_generator, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell,
is_generator, school_id);
return "Other Details saved sucessfully";
} catch (DataAccessException e) {
e.printStackTrace();
return "error";
}
}
@Transactional
public String saveStudentStrength(int total_students, int total_girls, int total_boys, int others, int school_id) {
String sql = "INSERT INTO student_strength (total_students, total_girls, total_boys,others,school_id) VALUES (?,?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, total_students, total_girls, total_boys, others, school_id);
return "Student Strength saved sucessfully";
} catch (DataAccessException e) {
e.printStackTrace();
return "error";
}
}
// @Transactional
// public String saveStaffStrength(int tot_staff, int sg_staff, int bt_staff, int pg_staff, int temp_staff,
// int ngo_staff, int kg_staff, int pt_staff, int part_staff, int qa_staff, int kg_ayha, int watchman,
// int comp_asst, int scavengers, int maint_workers, int school_id) {
// String sql = "INSERT INTO staff_strength (tot_staff, sg_staff, bt_staff, pg_staff,temp_staff, ngo_staff, kg_staff, pt_staff,part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
// try {
// jdbcTemplate.update(sql, tot_staff, sg_staff, bt_staff, pg_staff, temp_staff, ngo_staff, kg_staff, pt_staff,
// part_staff, qa_staff, kg_ayha, watchman, comp_asst, scavengers, maint_workers, school_id);
// return "Staff Strength saved sucessfully";
// } catch (DataAccessException e) {
// e.printStackTrace();
// return "error";
// }
// }
@Transactional
public String saveToilets(int total_toiletBlocks, int total_male_urinals, int total_wc_male, int total_wc_female,
int total_diffAbled_toilet, Boolean is_napkins, int school_id) {
String sql = "INSERT INTO toilet (total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female, total_diffAbled_toilet, is_napkins, school_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female,
total_diffAbled_toilet, is_napkins, school_id);
return "Toilet Details saved sucessfully";
} catch (DataAccessException e) {
e.printStackTrace();
return "error";
}
}
@Transactional
public String saveKitchen(Boolean is_cmbfs, Boolean is_cmbfsIndividual, Boolean is_noonmeal,
Boolean is_noonIndividual, Boolean is_vegGarden, Boolean is_anganwadi, String anganwadi_unique,
Boolean is_anganwadiIndividual, int school_id) {
String sql = "INSERT INTO kitchen (is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden, is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden,
is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id);
return "Kitchen Details saved sucessfully";
} catch (DataAccessException e) {
e.printStackTrace();
return "error";
}
}
@Transactional
public int savePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id) {
String sql = "INSERT INTO playground (is_playground, playground_area, is_court, school_id) VALUES (?, ?, ?, ?)";
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setBoolean(1, is_playground);
ps.setDouble(2, playground_area);
ps.setBoolean(3, is_court);
ps.setInt(4, school_id);
return ps;
}, keyHolder);
Number generatedDataId = keyHolder.getKey();
int playgoundID = generatedDataId.intValue();
return playgoundID;
} catch (DataAccessException e) {
e.printStackTrace();
return 0;
}
}
@Transactional
public void saveEquipmentDetails(String equipment_id, int school_id, int playground_id) {
String sql = "INSERT INTO equipment_details (equipment_id, school_id, playground_id) VALUES (?, ?, ?)";
try {
jdbcTemplate.update(sql, equipment_id, school_id, playground_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void updatePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id, int playground_id) {
String sql = "UPDATE playground SET is_playground = ?, playground_area = ?, is_court = ? WHERE playground_id = ? AND school_id = ?";
try {
int rows = jdbcTemplate.update(sql, is_playground, playground_area, is_court, playground_id, school_id);
System.out.println("✅ Rows affected (playground): " + rows);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void saveCourtDetails(String court_id, int school_id, int playground_id) {
String sql = "INSERT INTO courts_details (court_id, school_id, playground_id) VALUES (?, ?, ?)";
try {
jdbcTemplate.update(sql, court_id, school_id, playground_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public int saveDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell,
Integer borewell_count, Boolean is_storage, int school_id) {
String sql = "INSERT INTO drinking_water (is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id) VALUES (?, ?, ?, ?, ?, ?)";
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setBoolean(1, is_purifier);
// Handle possible null values
if (purifier_capacity != null) {
ps.setDouble(2, purifier_capacity);
} else {
ps.setNull(2, Types.DOUBLE);
}
ps.setBoolean(3, is_borewell);
if (borewell_count != null) {
ps.setInt(4, borewell_count);
} else {
ps.setNull(4, Types.INTEGER);
}
ps.setBoolean(5, is_storage);
ps.setInt(6, school_id);
return ps;
}, keyHolder);
Number generatedDataId = keyHolder.getKey();
int drinking_water_id = generatedDataId.intValue();
return drinking_water_id;
} catch (DataAccessException e) {
e.printStackTrace();
return 0;
}
}
@Transactional
public void saveWaterSupply(int source_water_id, String supply_type, int drinking_water_id, int school_id) {
String sql = "INSERT INTO water_supply (source_water_id, supply_type, drinking_water_id, school_id) VALUES (?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, source_water_id, supply_type, drinking_water_id, school_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void saveWaterStorage(double capacity, int storage_water_id, int drinking_water_id, int school_id) {
String sql = "INSERT INTO water_storage (capacity, storage_water_id, drinking_water_id, school_id) VALUES (?, ?, ?, ?)";
try {
jdbcTemplate.update(sql, capacity, storage_water_id, drinking_water_id, school_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void saveStaffStrength(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher,
int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher, int pgRegTeacher, int pgTempTeacher,
int pgPtTeacher, int pgNgoTeacher, int kgRegTeacher, int kgTempTeacher, int petRegTeacher, int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int totOa, int kgAyah, int compAss,
int watchmen, int scavengers, int maintenanceWork, int schoolId) {
String sql = "INSERT INTO staff_strength_1 ("
+ "sg_reg_teacher, sg_temp_teacher, sg_pt_teacher, sg_ngo_teacher, "
+ "bt_reg_teacher, bt_temp_teacher, bt_pt_teacher, bt_ngo_teacher, "
+ "pg_reg_teacher, pg_temp_teacher, pg_pt_teacher, pg_ngo_teacher, "
+ "kg_reg_teacher, kg_temp_teacher, pet_reg_teacher, pet_temp_teacher, pet_grade1_teacher, pet_grade2_teacher, tot_oa, kg_ayah, comp_ass, "
+ "watchmen, scavengers, maintenance_work, school_id) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher, btRegTeacher, btTempTeacher,
btPtTeacher, btNgoTeacher, pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher, kgRegTeacher, kgTempTeacher,
petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa, kgAyah, compAss, watchmen, scavengers, maintenanceWork, schoolId);
}
@Transactional
public String getSchoolId(String user_id) {
String sql = "SELECT school_id FROM login_details WHERE user_id = ?";
try {
return jdbcTemplate.queryForObject(sql, String.class, user_id);
} catch (DataAccessException e) {
return "error";
}
}
public List<Map<String, Object>> getSchoolData1(String schoolId) {
String sql = "SELECT * FROM school_list WHERE id In(" + schoolId + ")";
try {
return jdbcTemplate.queryForList(sql);
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
public Map<String, Object> getSchoolDetails(Long schoolId) {
String sql = "SELECT * FROM school_list WHERE id = ?";
return jdbcTemplate.queryForMap(sql, schoolId);
}
public List<Map<String, Object>> filterSchools(String userId, String udise, String category, String zone, String ward) {
String sql = """
SELECT
s.id,
s.udise,
s.school_name,
s.category,
s.zone,
s.division,
s.address
FROM
school_list s
JOIN
login_details l ON FIND_IN_SET(s.id, l.school_id) > 0
WHERE
l.user_id = ?
AND (? = '' OR s.udise = ?)
AND (? = '' OR s.category = ?)
AND (? = '' OR s.zone = ?)
AND (? = '' OR s.division = ?)
""";
return jdbcTemplate.queryForList(
sql,
userId,
udise, udise,
category, category,
zone, zone,
ward, ward
);
}
@Transactional
public String updateOtherDetails(Double land_area, Double buildup_area, Boolean is_compound, Boolean is_nameboard,
Boolean is_pasystem, Boolean is_bell, Boolean is_generator, int school_id) {
String sql = "UPDATE school_buildup_area SET land_area = ?, buildup_area = ?, is_compound = ?, is_nameboard = ?, is_pasystem = ?, is_bell = ?, is_generator = ? WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, land_area, buildup_area, is_compound, is_nameboard, is_pasystem, is_bell,
is_generator, school_id);
return "Success";
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public String updateStudentDetails(int total_students, int total_girls, int total_boys, int others, int school_id) {
String sql = "UPDATE student_strength SET total_students = ?, total_girls = ?, total_boys = ?, others = ? WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, total_students, total_girls, total_boys, others, school_id);
return "Success";
}catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public Map<String, Object> checkPlaygroundDetails(int school_id) {
String sql = "SELECT * FROM playground WHERE school_id = ?";
try {
return jdbcTemplate.queryForMap(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyMap();
}
}
private void updateCourtDetails(int court_id, int courts_detais_id) {
String sql = "UPDATE courts_details SET court_id = ? WHERE courts_detais_id = ? ";
try {
jdbcTemplate.update(sql, court_id, courts_detais_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
// @Transactional
// public List<Map<String, Object>> checkCourtDetails(int school_id) {
// String sql = "select cm.court_type,cd.Courts_detais_id \r\n"
// + "FROM \r\n"
// + "playground p\r\n"
// + "INNER JOIN \r\n"
// + " courts_details cd ON p.playground_id = cd.playground_id\r\n"
// + "INNER JOIN \r\n"
// + " courts_master cm ON cd.court_id = cm.court_id\r\n"
// + " WHERE \r\n"
// + " p.school_id = ?";
// try {
// return jdbcTemplate.queryForList(sql, school_id);
// } catch (Exception e) {
// e.printStackTrace();
// return List.of();
// }
// }
@Transactional
public List<Map<String, Object>> checkCourtDetails(int school_id) {
String sql = """
SELECT cm.court_type, cd.Courts_detais_id, cd.court_id
FROM playground p
INNER JOIN courts_details cd ON p.playground_id = cd.playground_id
INNER JOIN courts_master cm ON cd.court_id = cm.court_id
WHERE p.school_id = ? and cd.is_active = 1
""";
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
// public List<Map<String, Object>> checkEquipmentDetails(int school_id) {
// String sql = "select em.equipment_type,ed.equipment_detais_id \r\n"
// + "FROM \r\n"
// + "playground p\r\n"
// + "INNER JOIN \r\n"
// + " equipment_details ed ON p.playground_id = ed.playground_id\r\n"
// + "INNER JOIN \r\n"
// + " equipment_master em ON ed.equipment_id = em.equipment_id\r\n"
// + " WHERE \r\n"
// + " p.school_id = ?";
// try {
// return jdbcTemplate.queryForList(sql, school_id);
// } catch (Exception e) {
// e.printStackTrace();
// return List.of();
// }
// }
//ajith
public List<Map<String, Object>> checkEquipmentDetails(int school_id) {
String sql = """
SELECT em.equipment_id, em.equipment_type, ed.equipment_detais_id
FROM playground p
INNER JOIN equipment_details ed ON p.playground_id = ed.playground_id
INNER JOIN equipment_master em ON ed.equipment_id = em.equipment_id
WHERE p.school_id = ? and ed.is_active = 1 """;
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
private void updateEquipmentDetails(Integer equipment_id, int equipment_detais_id) {
String sql = "UPDATE equipment_details SET equipment_id = ? WHERE equipment_detais_id = ? ";
try {
jdbcTemplate.update(sql, equipment_id, equipment_detais_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
/*private void updatePlayground(Boolean is_playground, Double playground_area, Boolean is_court, int school_id, int playground_id) {
String sql = "UPDATE playground SET is_playground = ?, playground_area = ?, is_court = ? WHERE playground_id = ? and school_id = ? ";
try {
jdbcTemplate.update(sql, is_playground, playground_area, is_court, playground_id, school_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}*/
// @Transactional
// public String updatePlaygroundDetails(Boolean is_playground, Double playground_area, Boolean is_court,
// List<Map<String, Object>> equipments, List<Map<String, Object>> courts, int playground_id, int school_id) {
// try {
// // Update playground main record
// updatePlayground(is_playground, playground_area, is_court, school_id, playground_id);
//
// // Update equipment details with null-safe checks
// for (Map<String, Object> equipment : equipments) {
// Object equipDetIdObj = equipment.get("equipment_detais_id");
// Object equipIdObj = equipment.get("equipment_id");
//
// if (equipDetIdObj != null && equipIdObj != null) {
// int equipment_detais_id = Integer.parseInt(equipDetIdObj.toString());
// int equipment_id = Integer.parseInt(equipIdObj.toString());
// updateEquipmentDetails(equipment_id, equipment_detais_id);
// } else {
// System.out.println("⚠️ Skipping equipment update — missing equipment_id or equipment_detais_id: " + equipment);
// }
// }
// if(is_court.booleanValue()) {
// // Update court details with null-safe checks
// for (Map<String, Object> court : courts) {
// Object courtDetIdObj = court.get("Courts_detais_id");
// Object courtIdObj = court.get("court_id");
//
// if (courtDetIdObj != null && courtIdObj != null) {
// int Courts_detais_id = Integer.parseInt(courtDetIdObj.toString());
// int court_id = Integer.parseInt(courtIdObj.toString());
// updateCourtDetails(court_id, Courts_detais_id);
// } else {
// System.out.println("⚠️ Skipping court update — missing court_id or Courts_detais_id: " + court);
// }
// }
// }
// else {
// //inactiveCourtDetails(school_id);
// }
// return "Success";
//
// } catch (Exception e) {
// e.printStackTrace();
// return "Error";
// }
// }
@Transactional
public String updatePlaygroundDetails(Boolean is_playground, Double playground_area, Boolean is_court,
List<Map<String, Object>> equipments, List<Map<String, Object>> courts, int playground_id, int school_id) {
try {
// Step 1: Update main playground table
updatePlayground(is_playground, playground_area, is_court, school_id, playground_id);
// Step 2: Deactivate old entries
deactiveCourts(school_id);
deactiveEquipments(school_id);
// Step 3: Re-insert new equipment selections
for (Map<String, Object> equipment : equipments) {
Object equipmentIdObj = equipment.get("equipment_id");
if (equipmentIdObj != null) {
String equipment_id = equipmentIdObj.toString();
saveEquipmentDetails(equipment_id, school_id, playground_id);
} else {
System.out.println("⚠️ Skipping equipment insert — missing equipment_id: " + equipment);
}
}
// Step 4: Re-insert new court selections (only if court is enabled)
if (Boolean.TRUE.equals(is_court)) {
for (Map<String, Object> court : courts) {
Object courtIdObj = court.get("court_id");
if (courtIdObj != null) {
String court_id = courtIdObj.toString();
saveCourtDetails(court_id, school_id, playground_id);
} else {
System.out.println("⚠️ Skipping court insert — missing court_id: " + court);
}
}
}
return "Success";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public void deactiveCourts(int school_id) {
String sql = "UPDATE courts_details SET is_active = false WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, school_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void deactiveEquipments(int school_id) {
String sql = "UPDATE equipment_details SET is_active = false WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, school_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public String updateKitchenDetails(Boolean is_cmbfs, Boolean is_cmbfsIndividual, Boolean is_noonmeal,
Boolean is_noonIndividual, Boolean is_vegGarden, Boolean is_anganwadi, String anganwadi_unique,
Boolean is_anganwadiIndividual, int school_id) {
String sql = "UPDATE kitchen SET is_cmbfs = ?, is_cmbfsIndividual = ?, is_noonmeal = ?, is_noonIndividual = ?, is_vegGarden = ?, is_anganwadi = ?, anganwadi_unique = ?, is_anganwadiIndividual = ? WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, is_cmbfs, is_cmbfsIndividual, is_noonmeal, is_noonIndividual, is_vegGarden,
is_anganwadi, anganwadi_unique, is_anganwadiIndividual, school_id);
return "Success";
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public Map<String, Object> checkKitchenDetails(int school_id) {
String sql = "SELECT * FROM kitchen WHERE school_id = ?";
try {
return jdbcTemplate.queryForMap(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyMap();
}
}
/*@Transactional
public String updateStaffDetails(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher,
int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher,
int pgRegTeacher, int pgTempTeacher, int pgPtTeacher, int pgNgoTeacher,
int kgTeacher, int petTeacher, int totOa, int kgAyah, int compAss,
int watchmen, int scavengers, int maintenanceWork, int school_id) {
String sql = "UPDATE staff_strength_1 SET sg_reg_teacher = ?, sg_temp_teacher = ?, sg_pt_teacher = ?, sg_ngo_teacher = ?,"
+ " bt_reg_teacher = ?, bt_temp_teacher = ?, bt_pt_teacher = ?, bt_ngo_teacher = ?, "
+ "pg_reg_teacher = ?, pg_temp_teacher = ?, pg_pt_teacher = ?, pg_ngo_teacher = ?,"
+ "kg_teacher = ?, pet_teacher = ?, tot_oa = ?, kg_ayah = ?, comp_ass = ?, watchmen = ?,"
+ " scavengers = ?, maintenance_work = ?WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher,
btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher,
pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher,
kgTeacher, petTeacher, totOa, kgAyah, compAss,
watchmen, scavengers, maintenanceWork, school_id);
return "Success";
}catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}*/
@Transactional
public String updateStaffDetails(int sgRegTeacher, int sgTempTeacher, int sgPtTeacher, int sgNgoTeacher,
int btRegTeacher, int btTempTeacher, int btPtTeacher, int btNgoTeacher,
int pgRegTeacher, int pgTempTeacher, int pgPtTeacher, int pgNgoTeacher,
int kgRegTeacher, int kgTempTeacher, int petRegTeacher, int petTempTeacher, int petGrade1Teacher, int petGrade2Teacher, int totOa, int kgAyah, int compAss,
int watchmen, int scavengers, int maintenanceWork, int school_id) {
String sql = "UPDATE staff_strength_1 SET sg_reg_teacher = ?, sg_temp_teacher = ?, sg_pt_teacher = ?, sg_ngo_teacher = ?," +
" bt_reg_teacher = ?, bt_temp_teacher = ?, bt_pt_teacher = ?, bt_ngo_teacher = ?, " +
" pg_reg_teacher = ?, pg_temp_teacher = ?, pg_pt_teacher = ?, pg_ngo_teacher = ?," +
" kg_reg_teacher = ?, kg_temp_teacher = ?, pet_reg_teacher = ?, pet_temp_teacher = ?, pet_grade1_teacher = ?, pet_grade2_teacher = ?, tot_oa = ?, kg_ayah = ?, comp_ass = ?, watchmen = ?," +
" scavengers = ?, maintenance_work = ? WHERE school_id = ?";
try {
int rowsAffected = jdbcTemplate.update(sql, sgRegTeacher, sgTempTeacher, sgPtTeacher, sgNgoTeacher,
btRegTeacher, btTempTeacher, btPtTeacher, btNgoTeacher,
pgRegTeacher, pgTempTeacher, pgPtTeacher, pgNgoTeacher,
kgRegTeacher, kgTempTeacher, petRegTeacher, petTempTeacher, petGrade1Teacher, petGrade2Teacher, totOa, kgAyah, compAss,
watchmen, scavengers, maintenanceWork, school_id);
if (rowsAffected == 0) {
return "No data found for given school_id";
} else {
return "Success";
}
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public Map<String, Object> checkWaterDetails(int school_id) {
String sql = "select drinking_water_id, is_purifier, borewell_count, is_borewell, is_storage, purifier_capacity from drinking_water where school_id = ?";
try {
return jdbcTemplate.queryForMap(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyMap();
}
}
@Transactional
public List<Map<String, Object>> checkWaterSource(int school_id) {
String sql = "select ws.water_supply_id, ws.source_water_id, ws.supply_type, sw.water_type \r\n"
+ "FROM \r\n"
+ "drinking_water dw\r\n"
+ "INNER JOIN \r\n"
+ " water_supply ws ON dw.drinking_water_id = ws.drinking_water_id\r\n"
+ "INNER JOIN \r\n"
+ " source_water sw ON ws.source_water_id = sw.source_water_id\r\n"
+ " WHERE \r\n"
+ " dw.school_id = ? and ws.is_active = 1";
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
// @Transactional
// public String updateDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell,
// int borewell_count, Boolean is_storage, int drinking_water_id, int school_id,
// List<Map<String, Object>> supply, List<Map<String, Object>> storage) {
// try {
// updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id, drinking_water_id);
// for (Map<String, Object> supplies : supply) {
// int water_supply_id = Integer.parseInt(supplies.get("water_supply_id").toString());
// int source_water_id = Integer.parseInt(supplies.get("source_water_id").toString());
// String supply_type = (String) supplies.get("supply_type");
// updateWaterSupplyDetails(water_supply_id, source_water_id, supply_type);
// }
//
// for (Map<String, Object> store : storage) {
// int water_storage_id = Integer.parseInt(store.get("water_storage_id").toString());
// int storage_water_id = Integer.parseInt(store.get("storage_water_id").toString());
// Double capacity = (Double) store.get("capacity");
// updateWaterStorageDetails(water_storage_id, storage_water_id, capacity);
// }
// return "Sucess";
// } catch (Exception e) {
// e.printStackTrace();
// return "Error";
// }
// }
//Ajithh
@Transactional
public String updateDrinkingWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell,
int borewell_count, Boolean is_storage, int drinking_water_id, int school_id,
List<Map<String, Object>> supply, List<Map<String, Object>> storage) {
try {
// Step 1: Update main table
updateDrinkWater(is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, school_id, drinking_water_id);
// Step 2: UPSERT for water supply
for (Map<String, Object> item : supply) {
int source_water_id = Integer.parseInt(item.get("source_water_id").toString());
String supply_type = item.get("supply_type").toString();
// Check if record exists
String checkSql = "SELECT COUNT(*) FROM water_supply WHERE drinking_water_id = ? AND source_water_id = ?";
Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, drinking_water_id, source_water_id);
if (count != null && count > 0) {
// Update existing
jdbcTemplate.update("UPDATE water_supply SET supply_type = ?, is_active = 1 WHERE drinking_water_id = ? AND source_water_id = ?",
supply_type, drinking_water_id, source_water_id);
} else {
// Insert new
jdbcTemplate.update("INSERT INTO water_supply (drinking_water_id, source_water_id, supply_type, school_id) VALUES (?, ?, ?, ?)",
drinking_water_id, source_water_id, supply_type, school_id);
}
}
// Step 3: UPSERT for water storage
for (Map<String, Object> item : storage) {
int storage_water_id = Integer.parseInt(item.get("storage_water_id").toString());
double capacity = Double.parseDouble(item.get("capacity").toString());
String checkSql = "SELECT COUNT(*) FROM water_storage WHERE drinking_water_id = ? AND storage_water_id = ?";
Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, drinking_water_id, storage_water_id);
if (count != null && count > 0) {
jdbcTemplate.update("UPDATE water_storage SET capacity = ?, is_active = 1 WHERE drinking_water_id = ? AND storage_water_id = ?",
capacity, drinking_water_id, storage_water_id);
} else {
jdbcTemplate.update("INSERT INTO water_storage (drinking_water_id, storage_water_id, capacity, school_id) VALUES (?, ?, ?, ?)",
drinking_water_id, storage_water_id, capacity, school_id);
}
}
return "Sucess";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
// private void updateWaterStorageDetails(int water_storage_id, int storage_water_id, Double capacity) {
// String sql = "UPDATE water_storage SET capacity = ?, storage_water_id = ? WHERE water_storage_id = ? ";
// try {
// jdbcTemplate.update(sql, capacity, storage_water_id, water_storage_id);
//
// }catch (DataAccessException e) {
// e.printStackTrace();
//
// }
//
// }
//
// private void updateWaterSupplyDetails(int water_supply_id, int source_water_id, String supply_type) {
// String sql = "UPDATE water_supply SET source_water_id = ?, supply_type = ? WHERE water_supply_id = ? ";
// try {
// jdbcTemplate.update(sql, source_water_id, supply_type, water_supply_id);
//
// }catch (DataAccessException e) {
// e.printStackTrace();
//
// }
//
// }
//
// private void updateDrinkWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell,
// int borewell_count, Boolean is_storage, int school_id, int drinking_water_id) {
//
// String sql = "UPDATE drinking_water SET is_purifier = ?, purifier_capacity = ?, is_borewell = ?, borewell_count = ?, is_storage = ? WHERE drinking_water_id = ? and school_id = ? ";
// try {
// jdbcTemplate.update(sql, is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, drinking_water_id, school_id);
//
// }catch (DataAccessException e) {
// e.printStackTrace();
//
// }
// }
//ajith
@Transactional
public void updateDrinkWater(Boolean is_purifier, Double purifier_capacity, Boolean is_borewell,
int borewell_count, Boolean is_storage, int school_id, int drinking_water_id) {
System.out.println("===================helooo=================");
String sql = "UPDATE drinking_water SET is_purifier = ?, purifier_capacity = ?, is_borewell = ?, borewell_count = ?, is_storage = ? WHERE drinking_water_id = ? and school_id = ? ";
try {
jdbcTemplate.update(sql, is_purifier, purifier_capacity, is_borewell, borewell_count, is_storage, drinking_water_id, school_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void deactiveWaterSupply(int school_id, int drinking_water_id) {
String sql = "UPDATE water_supply SET is_active = false WHERE school_id = ? and drinking_water_id = ? ";
try {
jdbcTemplate.update(sql, school_id, drinking_water_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public void deactiveWaterStorage(int school_id, int drinking_water_id) {
String sql = "UPDATE water_storage SET is_active = false WHERE school_id = ? and drinking_water_id = ? ";
try {
jdbcTemplate.update(sql, school_id, drinking_water_id);
}catch (DataAccessException e) {
e.printStackTrace();
}
}
private void updateWaterSupplyDetails(int water_supply_id, int source_water_id, String supply_type) {
String sql = "UPDATE water_supply SET source_water_id = ?, supply_type = ? WHERE water_supply_id = ?";
try {
jdbcTemplate.update(sql, source_water_id, supply_type, water_supply_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
private void updateWaterStorageDetails(int water_storage_id, int storage_water_id, Double capacity) {
String sql = "UPDATE water_storage SET capacity = ?, storage_water_id = ? WHERE water_storage_id = ?";
try {
jdbcTemplate.update(sql, capacity, storage_water_id, water_storage_id);
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional
public List<Map<String, Object>> checkWaterStotage(int school_id) {
String sql = " select wst.water_storage_id, wst.capacity, wstm.storage_type\r\n"
+ " FROM \r\n"
+ " drinking_water dw\r\n"
+ " INNER JOIN\r\n"
+ " water_storage wst ON dw.drinking_water_id = wst.drinking_water_id \r\n"
+ "INNER JOIN\r\n"
+ " water_storage_master wstm ON wst.storage_water_id = wstm.storage_water_id \r\n"
+ "WHERE \r\n"
+ " dw.school_id = ? and wst.is_active = 1";
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
public List<Map<String, Object>> checkToiletDetails(int school_id) {
String sql = "SELECT * FROM toilet WHERE school_id = ?";
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
public String updateToiletDetails(int total_toiletBlocks, int total_male_urinals, int total_wc_male,
int total_wc_female, int total_diffAbled_toilet, Boolean is_napkins, int school_id) {
String sql = "UPDATE toilet SET total_toiletBlocks = ?, total_male_urinals = ?, total_wc_male = ?, total_wc_female = ?, total_diffAbled_toilet = ?, is_napkins = ? WHERE school_id = ? ";
try {
jdbcTemplate.update(sql, total_toiletBlocks, total_male_urinals, total_wc_male, total_wc_female,
total_diffAbled_toilet, is_napkins, school_id);
return "Success";
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public String saveAssetMaster(int sub_asset_id, int master_qty, int school_id, int asset_id) {
String sql ="";
if(asset_id==2) {
sql = "INSERT INTO electrical_master (sub_asset_id, master_qty, unmapped_qty, school_id) VALUES (?, ?, ?, ?)";
} else if(asset_id==3) {
sql = "INSERT INTO furniture_master (sub_asset_id, master_qty, unmapped_qty, school_id) VALUES (?, ?, ?, ?)";
}
try {
jdbcTemplate.update(sql, sub_asset_id, master_qty, master_qty, school_id);
return "Success";
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
@Transactional
public List<Map<String, Object>> getAssetMaster(int school_id, int asset_id) {
String sql="";
if(asset_id==2) {
sql = "SELECT asm.asset_name, em.electrical_master_id, em.master_qty, em.mapped_qty, em.unmapped_qty, em.scrap_qty from electrical_master em \r\n"
+ "INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id\r\n"
+ " WHERE em.school_id = ?";
} else if(asset_id==3) {
sql = "SELECT asm.asset_name, fm.furniture_master_id, fm.master_qty, fm.mapped_qty, fm.unmapped_qty, fm.scrap_qty from furniture_master fm \r\n"
+ "INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id\r\n"
+ " WHERE fm.school_id = ?";
}
try {
return jdbcTemplate.queryForList(sql, school_id);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
@Transactional
public Map<String, Object> getAssetMasterById(int assetMasterId, int asset_id) {
String sql="";
if(asset_id==2) {
sql = "SELECT em.*,asm.asset_name from electrical_master em INNER JOIN asset_sub_master asm ON em.sub_asset_id = asm.sub_asset_id where em.electrical_master_id = ?";
} else if(asset_id==3) {
sql = "SELECT fm.*,asm.asset_name from furniture_master fm INNER JOIN asset_sub_master asm ON fm.sub_asset_id = asm.sub_asset_id where fm.furniture_master_id = ?";
}
try {
return jdbcTemplate.queryForMap(sql, assetMasterId);
} catch (Exception e) {
e.printStackTrace();
return Map.of();
}
}
@Transactional
public String updateAssetMaster(int assetMasterId, int master, int asset_id, int unmapped) {
String sql ="";
if (asset_id == 2) {
sql = "UPDATE electrical_master SET master_qty = ?, unmapped_qty = ? WHERE electrical_master_id = ? ";
} else if(asset_id==3) {
sql = "UPDATE furniture_master SET master_qty = ?, unmapped_qty = ? WHERE furniture_master_id = ? ";
}
try {
jdbcTemplate.update(sql, master, unmapped, assetMasterId);
return "Success";
} catch (DataAccessException e) {
e.printStackTrace();
return "Error";
}
}
}

298
backend/school/Service/SchoolReportService.java

@ -0,0 +1,298 @@
package in.gov.chennaicorporation.gccoffice.school.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class SchoolReportService {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSourcemysql(@Qualifier("mysqlSchoolDataSource") DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Transactional
public ResponseEntity<?> getAEOList() {
Map<String, Object> result = new HashMap<>();
String sql = "SELECT aeo_details_id, aeo_num, udise FROM aeo_details";
try {
List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
result.put("Message", "Success");
result.put("data", data);
return ResponseEntity.ok(result);
} catch (Exception e) {
e.printStackTrace();
result.put("Message", "Error");
result.put("Error", "Failed to fetch AEO List: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
@Transactional
public ResponseEntity<?> getAEOZone(String udise) {
Map<String, Object> result = new HashMap<>();
String sql = "SELECT DISTINCT zone FROM school_list WHERE udise In(" + udise + ") ORDER BY zone ASC";
try {
List<String> data = jdbcTemplate.queryForList(sql, String.class);
result.put("message", "Success");
result.put("data", data);
return ResponseEntity.ok(result);
} catch (DataAccessException e) {
e.printStackTrace();
result.put("message", "Error");
result.put("Error", "Failed to Zone List: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
@Transactional
public ResponseEntity<?> getAEOWard(String udise, String zone) {
Map<String, Object> result = new HashMap<>();
String sql = "SELECT DISTINCT division AS Ward FROM school_list WHERE udise In(" + udise + ") and zone = ? ORDER BY Ward ASC";
try {
List<String> data = jdbcTemplate.queryForList(sql, String.class, zone);
result.put("message", "Success");
result.put("data", data);
return ResponseEntity.ok(result);
} catch (DataAccessException e) {
e.printStackTrace();
result.put("message", "Error");
result.put("Error", "Failed to Ward List: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
@Transactional
public ResponseEntity<?> getAEOSchoolData(List<String> udise, String zone, String ward) {
Map<String, Object> response = new HashMap<>();
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
if(udise==null || udise.isEmpty()) {
udise=getUDISE();
}
for(String udises:udise) {
List<String> school = getschoolId(udises, zone, ward);
if(!school.isEmpty() && school!=null) {
for(String sch:school) {
//System.out.println("School_ID = "+sch);
Map<String, Object> result = new HashMap<>();
Map<String, Object> report = getSchoolReport(sch);
result.putAll(report);
String num = (String) report.get("udise");
Map<String, Object> report1 = getSchoolReport1(sch);
result.putAll(report1);
int pending=0;
for (Map.Entry<String, Object> entry : report1.entrySet()) {
if(entry.getValue().toString().equalsIgnoreCase("Pending")) {
++pending;
}
}
result.put("overall_status", pending==0 ? "Completed" : "Pending");
Map<String, Object> report2 = getAEO(num);
result.putAll(report2);
data.add(result);
}
response.put("message", "Success");
response.put("data", data);
}
}
// System.out.println(data.get(0));
// System.out.println(data.get(1));
System.out.println(response.get("message"));
// System.out.println(response.get("data"));
return ResponseEntity.ok(response);
}
private List<String> getUDISE() {
String sql = "SELECT udise FROM aeo_details";
try {
return jdbcTemplate.queryForList(sql, String.class);
} catch (Exception e) {
e.printStackTrace();
return List.of();
}
}
private Map<String, Object> getAEO(String num) {
String sql = "SELECT aeo_num FROM aeo_details WHERE FIND_IN_SET(?, udise) > 0";
try {
return jdbcTemplate.queryForMap(sql, num);
} catch (Exception e) {
e.printStackTrace();
return Map.of();
}
}
private Map<String, Object> getSchoolReport1(String sch) {
String sql = "SELECT "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM school_buildup_area sba "
+ " WHERE sba.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS other_details, "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM staff_strength_1 ss "
+ " WHERE ss.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS staff_details, "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM student_strength sts "
+ " WHERE sts.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS students_details, "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM playground pg "
+ " WHERE pg.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS playground_details, "
+ " CASE "
+ " WHEN EXISTS ("
+ " SELECT 1 "
+ " FROM drinking_water dw "
+ " WHERE dw.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS drinkingwater_details, "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM toilet tot "
+ " WHERE tot.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS toilet_details, "
+ " CASE "
+ " WHEN EXISTS ( "
+ " SELECT 1 "
+ " FROM kitchen kit "
+ " WHERE kit.school_id = ? "
+ " ) THEN 'Completed' "
+ " ELSE 'Pending' "
+ " END AS kitchen_details, "
+ " CASE "
+ " WHEN NOT EXISTS ( "
+ " SELECT 1 FROM buildings WHERE school_id = ? and is_active=1 and is_delete=0 "
+ " ) THEN 'Pending' "
+ " WHEN ( "
+ " SELECT COUNT(*) FROM buildings WHERE school_id = ? and is_active=1 and is_delete=0 "
+ " ) = ( "
+ " SELECT COUNT(DISTINCT rd.building_id) "
+ " FROM room_details rd "
+ " JOIN buildings b ON b.buildng_id = rd.building_id "
+ " WHERE b.school_id = ? and b.is_active=1 and b.is_delete=0 and rd.is_active=1 and rd.is_delete=0 "
+ " ) THEN 'Completed' "
+ " ELSE 'Partially Completed' "
+ "END AS buildings, "
+ "CASE "
+ " WHEN NOT EXISTS ( "
+ " SELECT 1 FROM room_details WHERE school_id = ? and is_active=1 and is_delete=0 "
+ " ) THEN 'Pending' "
+ " WHEN ( "
+ " SELECT COUNT(DISTINCT room_id) "
+ " FROM room_details "
+ " WHERE school_id = ? and is_active=1 and is_delete=0 "
+ " ) = ( "
+ " SELECT COUNT(DISTINCT rd.room_id) "
+ " FROM room_details rd "
+ " JOIN it_mapping im ON im.room_id = rd.room_id "
+ " JOIN electrical_mapping em ON em.room_id = rd.room_id "
+ " JOIN furniture_mapping fm ON fm.room_id = rd.room_id "
+ " WHERE rd.school_id = ? and rd.is_active=1 and rd.is_delete=0 "
+ " and im.is_active=1 and im.is_delete=0 and em.is_active=1 and em.is_delete=0 "
+ " and fm.is_active=1 and fm.is_delete=0 "
+ " AND (im.room_id IS NOT NULL OR em.room_id IS NOT NULL OR fm.room_id IS NOT NULL) "
+ " ) THEN 'Completed' "
+ " WHEN ( "
+ " SELECT COUNT(DISTINCT rd.room_id) "
+ " FROM room_details rd "
+ " JOIN it_mapping im ON im.room_id = rd.room_id "
+ " JOIN electrical_mapping em ON em.room_id = rd.room_id "
+ " JOIN furniture_mapping fm ON fm.room_id = rd.room_id "
+ " WHERE rd.school_id = ? and rd.is_active=1 and rd.is_delete=0 "
+ " and im.is_active=1 and im.is_delete=0 and em.is_active=1 and em.is_delete=0 "
+ " and fm.is_active=1 and fm.is_delete=0 "
+ " AND (im.room_id IS NOT NULL OR em.room_id IS NOT NULL OR fm.room_id IS NOT NULL) "
+ " ) > 0 THEN 'Partially Completed' "
+ " ELSE 'Pending' "
+ "END AS school_assets ";
try {
return jdbcTemplate.queryForMap(sql, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch, sch);
} catch (Exception e) {
e.printStackTrace();
return Map.of();
}
}
private Map<String, Object> getSchoolReport(String sch) {
String sql = "SELECT id as school_id, zone, division, udise FROM school_list WHERE id = ?";
try {
return jdbcTemplate.queryForMap(sql, sch);
} catch (Exception e) {
e.printStackTrace();
return Map.of();
}
}
private List<String> getschoolId(String udise, String zone, String ward) {
String sql = "";
if (zone != null && !zone.isEmpty() && ward != null && !ward.isEmpty()) {
//System.out.println("check1");
sql = "SELECT id FROM school_list WHERE udise In(" + udise + ") and zone = ? and division = ?";
} else if (zone != null && !zone.isEmpty() && (ward == null || ward.isEmpty())) {
sql = "SELECT id FROM school_list WHERE udise In(" + udise + ") and zone = ?";
} else if ((zone == null || zone.isEmpty()) && (ward == null || ward.isEmpty())) {
sql = "SELECT id FROM school_list WHERE udise In(" + udise + ")";
}
try {
if (sql.contains("zone = ?") && sql.contains("division = ?")) {
return jdbcTemplate.queryForList(sql, String.class, zone, ward);
} else if (sql.contains("zone = ?")) {
return jdbcTemplate.queryForList(sql, String.class, zone);
} else {
return jdbcTemplate.queryForList(sql, String.class);
}
} catch (DataAccessException e) {
e.printStackTrace();
return List.of();
}
}
}

732
frontend/school/addelectricalasset.html

@ -0,0 +1,732 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<title>Add Electrical Asset In Master</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
</head>
<style>
/* Remove background image from the container itself */
.select2-container--default .select2-selection--multiple {
padding-right: 30px;
min-height: 38px;
display: flex;
flex-wrap: wrap;
align-items: center;
position: relative; /* important for the ::after */
background-image: none;
}
/* Add the dropdown arrow via a pseudo-element */
.select2-container--default .select2-selection--multiple::after {
content: "";
position: absolute;
top: 50%;
right: 8px;
width: 14px;
height: 14px;
transform: translateY(-50%);
background-image: url("data:image/svg+xml;utf8,<svg fill='gray' height='20' viewBox='0 0 24 24' width='20' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");
background-repeat: no-repeat;
background-size: contain;
pointer-events: none;
}
/* Each selected tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 10px;
margin: 4px 4px 0 0;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 13px;
line-height: 1.4;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* The text inside the tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice__display {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 8px;
}
/* The "X" close icon */
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
position: static;
transform: none;
color: #333;
font-size: 14px;
font-weight: bold;
cursor: pointer;
background: transparent;
border: none;
line-height: 1;
}
.custom-card-wrapper {
padding: 0;
margin-top: -58px;
margin-left: -233px;
}
@media (max-width: 768px) {
.custom-card-wrapper {
margin-left: 0;
margin-top: 0;
padding: 10px;
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card">
<div class="main-content" style="background-color: white;">
<div class="container">
<!-- Card 2: Other Details -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<!-- <div style="padding: 0px;margin-top:-58px;margin-left: -233px;">-->
<div class="card-header d-flex justify-content-between align-items-center">
<b>List of Electrical Assets</b>
<button type="button" class="btn btn-primary add-ebtn"> <i class="ik ik-plus"></i>Add Assets</button>
</div>
<div class="card-body" style="padding: 5px;">
<table id="EAssetManageDatatable"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width: 100%">
<thead class="thead-dark">
<tr>
<th>S.NO</th>
<th>ASSET TYPE</th>
<th>MASTER QTY</th>
<th>MAPPED QTY</th>
<th>UNMAPPED QTY</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div id="pageLoader"
style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="AddEAssetModal" tabindex="-1" role="dialog" aria-labelledby="AddEAssetModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Add Electrical Assets
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group col-6">
<label>Select Asset <span style="color: red;">*</span></label>
<select id="subAssetType" class="form-control" multiple></select>
</div>
</div>
<div id="selectedAssetsContainer" class="mt-3"></div>
<div class="row pb-2 mt-4" id="savingcontainer" style="display: none;">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="savingEAsset">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="EditEAssetModal" tabindex="-1" role="dialog" aria-labelledby="EditEAssetModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<span id="Eeditassetname"></span> - Edit Electrical Asset
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<span id="Eeditid" style="display: none;"></span>
<div class="row">
<div class="form-group col-6">
<label for="Emaster_qty">Master Quantity &nbsp;(&nbsp;Already in master&nbsp;<span id="AEmaster_qty" style="font-style: italic;font-weight: bold;"></span>&nbsp;)<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="Emaster_qty" name="Emaster_qty">
</div>
<div class="form-group col-6">
<label for="Emapped_qty">Mapped Quantity</label>
<input type="text" class="form-control" id="Emapped_qty" name="Emapped_qty" readonly>
</div>
<div class="form-group col-6">
<label for="">Unmapped Quantity</label>
<input type="text" class="form-control" id="Eunmapped_qty" name="Eunmapped_qty" readonly>
</div>
</div>
<div class="row pb-2 mt-4">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="UpdatingEAsset">Update</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
console.log("hi electrical assets...");
$(document).ready(function () {
$('#Emaster_qty').on('input', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
let ElectricalAsseturlParams = new URLSearchParams(window.location.search);
let EAssetschoolId = ElectricalAsseturlParams.get("schoolId");
loadEAsset(EAssetschoolId);
// Only run after DOM and libraries are ready
$('#subAssetType').on('select2:opening', function() {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true); // disable typing
}, 0);
});
if (!window.EassetEventsBound) {
$(document).on('click', '.add-ebtn', function () {
handleAddEAsset(EAssetschoolId);
});
$(document).on('click', '#savingEAsset', function () {
handleSaveEAsset(EAssetschoolId);
});
$(document).on('click', '.edit-btne', handleEAssetEdit);
$(document).on('click', '#UpdatingEAsset', handelEditEAsset);
window.EassetEventsBound = true;
}
$('#subAssetType').on('change', function () {
console.log("hi...");
const selectedOptions = $(this).find('option:selected');
const $container = $('#selectedAssetsContainer');
$container.empty(); // Clear previous entries
if (selectedOptions.length >= 1) {
$('#savingcontainer').show();
} else {
$('#savingcontainer').hide();
}
let labelRow = '';
let inputRow = '';
let counter = 0;
selectedOptions.each(function (index) {
const assetName = $(this).text();
const assetId = $(this).val();
// Start new row every 3 items
if (counter % 3 === 0) {
if (labelRow || inputRow) {
labelRow += '</div>';
inputRow += '</div>';
$container.append(labelRow);
$container.append(inputRow);
}
labelRow = '<div class="row mb-1">';
inputRow = '<div class="row mb-3">';
}
labelRow += `
<div class="col-md-4">
<label><b>${assetName}</b></label>
</div>
`;
inputRow += `
<div class="col-md-4">
<input type="number" class="form-control asset-quantity-input" name="assetQuantity_${assetId}" placeholder="Enter Quantity" min="0">
</div>
`;
counter++;
});
// Append remaining items
if (labelRow || inputRow) {
labelRow += '</div>';
inputRow += '</div>';
$container.append(labelRow);
$container.append(inputRow);
}
});
// Add an event listener to all input fields with the class 'asset-quantity-input'
$(document).on('input', '.asset-quantity-input', function() {
// Replace any character that is NOT a digit with an empty string
this.value = this.value.replace(/[^0-9]/g, '');
});
});
function handleEAssetEdit(){
console.log("Button clicked");
let id = $(this).data('id');
console.log("id=" + id);
$.ajax({
type: "GET",
url: "/gcc/api/gccschool/schoolproperty/getAssetMasterById",
data: { assetMasterId: id,asset_id:2 },
success: function (response) {
if (response.status === "Success" && response.data) {
let data = response.data;
// Populate modal fields
$('#Eeditassetname').text(data.asset_name || '');
//$('#Emaster_qty').val(data.master_qty || '');
$('#Emapped_qty').val(data.mapped_qty || '');
$('#Eunmapped_qty').val(data.unmapped_qty || '');
$('#Eeditid').val(data.electrical_master_id);
$('#AEmaster_qty').text(data.master_qty || '');
// Show the modal
$('#EditEAssetModal').modal('show');
} else {
Swal.fire('Error', 'Unable to fetch Electrical asset details.', 'error');
}
},
error: function (xhr, status, error) {
console.error('Error fetching Electrical asset:', error);
Swal.fire('Error', 'Server error while fetching Electrical asset.', 'error');
}
});
}
function loadEAsset(schoolId) {
//console.log("vvvvvvvvvv");
var buttons = [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
title: 'Electrical Asset List'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
title: 'Electrical Asset List'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title: 'Electrical Asset List'
},
{
extend: 'print',
text: 'Print',
className: 'btn btn-secondary',
id: 'printBtn',
title: 'Electrical Asset List',
exportOptions: {
columns: ':visible:not(.no-print)' // Exclude columns with class 'no-print' from print view
}
}
];
$.get('/gcc/api/gccschool/schoolproperty/getAssetMaster', {school_id: schoolId,asset_id:2}, res => {
if ($.fn.DataTable.isDataTable('#EAssetManageDatatable')) {
$('#EAssetManageDatatable').DataTable().clear().destroy(true);
}
//console.log("hello");
let tableData = [];
if (res.status === "Success" && Array.isArray(res.data)) {
//console.log("res.data="+res.data);
tableData = res.data;
}
$('#EAssetManageDatatable').DataTable({
data: tableData,
columns: [
{data: null, render: (d, t, r, m) => m.row + 1, className: 'text-center'},
{data: 'asset_name',className: 'text-center'},
{data: 'master_qty',className: 'text-center'},
{
data: 'mapped_qty',className: 'text-center',
render: data => data != null ? data : '-'
},
{
data: 'unmapped_qty',className: 'text-center',
render: data => data != null ? data : '-'
},
{
data: 'electrical_master_id',
render: (data, t, row) => `
<div class="text-center">
<button class="btn btn-sm btn-success edit-btne" data-id="${row.electrical_master_id}" ><i class="ik ik-edit-2" style="font-size:medium;margin-left:5px;"></i></button>
</div>`, className: 'text-center'
}
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', '500 rows', 'Show all']
],
dom: 'Bftip',
//fixedColumns: {left: 0, right: 0},
scrollY: '70vh',
scrollX: true,
autoWidth: true,
paging: true,
info: true,
buttons: buttons,
responsive: false,
searching: true,
select: false,
processing: false,
language: {
emptyTable: '<span class="text-danger">No Details found</span>'
}
});
});
}
function loadsubassets(schoolId) {
$.ajax({
url: '/gcc/api/gccschool/dropdown/getSplSubAssetType',
type: 'GET',
data: { school_id:schoolId,assetid: 2 },
success: function (response) {
const $court = $('#subAssetType');
$court.empty();
if (response.status === 'OK' && Array.isArray(response.data)) {
response.data.forEach(item => {
$court.append(`<option value="${item.sub_asset_id}">${item.asset_name}</option>`);
});
} else {
$court.append('<option value="">No Data Found</option>');
}
if ($court.hasClass("select2-hidden-accessible")) {
$court.select2('destroy');
}
$court.select2({
placeholder: "Select Asset",
width: '100%',
minimumResultsForSearch: Infinity,
closeOnSelect: false
});
},
error: function () {
const $court = $('#subAssetType');
$court.empty().append('<option value="">Error loading data</option>');
if ($court.hasClass("select2-hidden-accessible")) {
$court.select2('destroy');
}
$court.select2({
placeholder: "Select Asset",
width: '100%',
minimumResultsForSearch: Infinity,
closeOnSelect: false
});
alert("Something went wrong while fetching asset sub types.");
}
});
}
function handleAddEAsset(schoolId) {
$('#savingcontainer').hide();
$('#subAssetType').empty();
$('#selectedAssetsContainer').empty();
loadsubassets(schoolId);
// Then show the modal
$('#AddEAssetModal').modal('show');
}
function handleSaveEAsset(EAssetschoolId) {
$('#savingEAsset').prop('disabled', true).text('Saving...');
const selectedAssets = $('#subAssetType').val(); // array of selected sub_asset_id
const assetData = [];
if (!selectedAssets || selectedAssets.length === 0) {
$('#savingEAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please select at least one asset.',
});
return;
}
let hasError = false;
let hasZero = false;
let errorAssets = [];
let zeroAssets = [];
selectedAssets.forEach(function (subAssetId) {
const quantityInput = $(`input[name="assetQuantity_${subAssetId}"]`);
const quantity = quantityInput.val();
const assetName = $(`#subAssetType option[value="${subAssetId}"]`).text(); // Get asset name
if (!quantity || isNaN(quantity) || parseInt(quantity) < 0) {
hasError = true;
errorAssets.push(assetName);
} else if (parseInt(quantity) === 0) {
hasZero = true;
zeroAssets.push(assetName);
} else {
assetData.push({
sub_asset_id: subAssetId,
master_qty: parseInt(quantity)
});
}
});
if (hasError) {
$('#savingEAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Validation Error',
html: `Please enter a valid quantity for the following assets:<br><b>${errorAssets.join(', ')}</b>`,
});
return;
}
if (hasZero) {
$('#savingEAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Zero Quantity Error',
html: `You have entered 0 for the following assets:<br><b>${zeroAssets.join(', ')}</b><br>Please remove them from the selection or enter a valid quantity.`,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: true
});
return;
}
const payload = {
school_id: EAssetschoolId,
asset_id: "2", // electrical asset
data: assetData
};
console.log("Final Payload to Save:", payload);
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/saveAssetMaster',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function(response) {
$('#savingEAsset').prop('disabled', false).text('Save');
if (response.status === 'OK') {
//Swal.fire('Success', response.message, 'success');
//$('#AddEAssetModal').modal('hide');
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Success',
text: response.message
}).then(() => {
location.reload();
});
} else {
Swal.fire('Error', response.message, 'error');
}
},
error: function() {
$('#savingEAsset').prop('disabled', false).text('Save');
Swal.fire('Error', 'Something went wrong while saving assets.', 'error');
}
});
}
function handelEditEAsset(){
let emaster_qty = $('#Emaster_qty').val();
let eassetMasterId = $('#Eeditid').val();
console.log("emaster_qty"+emaster_qty);
console.log("eassetMasterId"+eassetMasterId);
if (!emaster_qty || isNaN(emaster_qty)) {
Swal.fire({
icon: 'warning',
title: 'Invalid Quantity',
text: 'Please enter a valid Master Quantity',
});
return;
}
if (!eassetMasterId || isNaN(eassetMasterId)) {
Swal.fire({
icon: 'warning',
title: 'Missing ID',
text: 'Electrical Asset ID is missing or invalid.',
});
return;
}
$.ajax({
type: "POST",
url: "/gcc/api/gccschool/schoolproperty/updateAssetMaster", // your endpoint
data: {
master_qty: parseInt(emaster_qty),
assetMasterId: parseInt(eassetMasterId),
asset_id:2
},
success: function (response) {
if (response === "Success") {
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Asset Updated',
text: 'Asset Updated successfully!'
}).then(() => {
location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Something went wrong while updating asset.'
});
}
},
error: function (xhr, status, error) {
console.error('Error updating assets:', error);
Swal.fire({
icon: 'error',
title: 'Request Failed',
text: 'Unable to send request to the server.'
});
}
});
}
</script>
</body>
</html>

728
frontend/school/addfurnitureasset.html

@ -0,0 +1,728 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<title>Add Furniture Asset In Master</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
</head> <head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
/* Remove background image from the container itself */
.select2-container--default .select2-selection--multiple {
padding-right: 30px;
min-height: 38px;
display: flex;
flex-wrap: wrap;
align-items: center;
position: relative; /* important for the ::after */
background-image: none;
}
/* Add the dropdown arrow via a pseudo-element */
.select2-container--default .select2-selection--multiple::after {
content: "";
position: absolute;
top: 50%;
right: 8px;
width: 14px;
height: 14px;
transform: translateY(-50%);
background-image: url("data:image/svg+xml;utf8,<svg fill='gray' height='20' viewBox='0 0 24 24' width='20' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");
background-repeat: no-repeat;
background-size: contain;
pointer-events: none;
}
/* Each selected tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 10px;
margin: 4px 4px 0 0;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 13px;
line-height: 1.4;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* The text inside the tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice__display {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 8px;
}
/* The "X" close icon */
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
position: static;
transform: none;
color: #333;
font-size: 14px;
font-weight: bold;
cursor: pointer;
background: transparent;
border: none;
line-height: 1;
}
.custom-card-wrapper {
padding: 0;
margin-top: -58px;
margin-left: -233px;
}
@media (max-width: 768px) {
.custom-card-wrapper {
margin-left: 0;
margin-top: 0;
padding: 10px;
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card">
<div class="main-content" style="background-color: white;">
<div class="container">
<!-- Card 2: Other Details -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<!-- <div style="padding: 0px;margin-top:-58px;margin-left: -233px;">-->
<div class="card-header d-flex justify-content-between align-items-center">
<b>List of Furniture Assets</b>
<button type="button" class="btn btn-primary add-fbtn"> <i class="ik ik-plus"></i>Add Assets</button>
</div>
<div class="card-body" style="padding: 5px;">
<table id="FAssetManageDatatable"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width: 100%">
<thead class="thead-dark">
<tr>
<th>S.NO</th>
<th>ASSET TYPE</th>
<th>MASTER QTY</th>
<th>MAPPED QTY</th>
<th>UNMAPPED QTY</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div id="pageLoader"
style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="AddFAssetModal" tabindex="-1" role="dialog" aria-labelledby="AddFAssetModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Add Furniture Assets
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group col-6">
<label>Select Asset <span style="color: red;">*</span></label>
<select id="FsubAssetType" class="form-control" multiple></select>
</div>
</div>
<div id="selectedFAssetsContainer" class="mt-3"></div>
<div class="row pb-2 mt-4" id="savingcontainerf" style="display: none;">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="savingFAsset">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="EditFAssetModal" tabindex="-1" role="dialog" aria-labelledby="EditFAssetModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<span id="Feditassetname"></span> - Edit Furniture Asset
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<span id="Feditid" style="display: none;"></span>
<div class="row">
<div class="form-group col-6">
<label for="Fmaster_qty">Master Quantity&nbsp;(&nbsp;Already in master&nbsp;<span id="AFmaster_qty" style="font-style: italic;font-weight: bold;"></span>&nbsp;)<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="Fmaster_qty" name="Fmaster_qty">
</div>
<div class="form-group col-6">
<label for="Fmapped_qty">Mapped Quantity</label>
<input type="text" class="form-control" id="Fmapped_qty" name="Fmapped_qty" readonly>
</div>
<div class="form-group col-6">
<label for="Funmapped_qty">Unmapped Quantity</label>
<input type="text" class="form-control" id="Funmapped_qty" name="Funmapped_qty" readonly>
</div>
</div>
<div class="row pb-2 mt-4">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="UpdatingFAsset">Update</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
console.log("hi..furniture asset");
$(document).ready(function () {
$('#Fmaster_qty').on('input', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
let FurnitureAsseturlParams = new URLSearchParams(window.location.search);
let FAssetschoolId = FurnitureAsseturlParams.get("schoolId");
loadFAsset(FAssetschoolId);
// Only run after DOM and libraries are ready
$('#FsubAssetType').on('select2:opening', function() {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true); // disable typing
}, 0);
});
if (!window.FassetEventsBound) {
$(document).on('click', '.add-fbtn', function () {
handleAddFAsset(FAssetschoolId);
});
$(document).on('click', '#savingFAsset', function () {
handleSaveFAsset(FAssetschoolId);
});
$(document).on('click', '.edit-btnf', handleFAssetEdit);
$(document).on('click', '#UpdatingFAsset', handelEditFAsset);
window.FassetEventsBound = true;
}
$('#FsubAssetType').on('change', function () {
console.log("hi...");
const selectedOptions = $(this).find('option:selected');
const $container = $('#selectedFAssetsContainer');
$container.empty(); // Clear previous entries
if (selectedOptions.length >= 1) {
$('#savingcontainerf').show();
} else {
$('#savingcontainerf').hide();
}
let labelRow = '';
let inputRow = '';
let counter = 0;
selectedOptions.each(function (index) {
const assetName = $(this).text();
const assetId = $(this).val();
// Start new row every 3 items
if (counter % 3 === 0) {
if (labelRow || inputRow) {
labelRow += '</div>';
inputRow += '</div>';
$container.append(labelRow);
$container.append(inputRow);
}
labelRow = '<div class="row mb-1">';
inputRow = '<div class="row mb-3">';
}
labelRow += `
<div class="col-md-4">
<label><b>${assetName}</b></label>
</div>
`;
inputRow += `
<div class="col-md-4">
<input type="number" class="form-control asset-quantity-input" name="assetQuantity_${assetId}" placeholder="Enter Quantity" min="0">
</div>
`;
counter++;
});
// Append remaining items
if (labelRow || inputRow) {
labelRow += '</div>';
inputRow += '</div>';
$container.append(labelRow);
$container.append(inputRow);
}
});
// Add an event listener to all input fields with the class 'asset-quantity-input'
$(document).on('input', '.asset-quantity-input', function() {
// Replace any character that is NOT a digit with an empty string
this.value = this.value.replace(/[^0-9]/g, '');
});
});
function handleFAssetEdit(){
console.log("Button clicked");
let id = $(this).data('id');
console.log("id=" + id);
$.ajax({
type: "GET",
url: "/gcc/api/gccschool/schoolproperty/getAssetMasterById",
data: { assetMasterId: id,asset_id:3 },
success: function (response) {
if (response.status === "Success" && response.data) {
let data = response.data;
// Populate modal fields
$('#Feditassetname').text(data.asset_name || '');
//$('#Fmaster_qty').val(data.master_qty || '');
$('#Fmapped_qty').val(data.mapped_qty || '');
$('#Funmapped_qty').val(data.unmapped_qty || '');
$('#Feditid').val(data.furniture_master_id);
$('#AFmaster_qty').text(data.master_qty || '');
// Show the modal
$('#EditFAssetModal').modal('show');
} else {
Swal.fire('Error', 'Unable to fetch Furniture asset details.', 'error');
}
},
error: function (xhr, status, error) {
console.error('Error fetching Furniture asset:', error);
Swal.fire('Error', 'Server error while fetching Furniture asset.', 'error');
}
});
}
function loadFAsset(schoolId) {
//console.log("vvvvvvvvvv");
var buttons = [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
title: 'Furniture Asset List'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
title: 'Furniture Asset List'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title: 'Furniture Asset List'
},
{
extend: 'print',
text: 'Print',
className: 'btn btn-secondary',
id: 'printBtn',
title: 'Furniture Asset List',
exportOptions: {
columns: ':visible:not(.no-print)' // Exclude columns with class 'no-print' from print view
}
}
];
$.get('/gcc/api/gccschool/schoolproperty/getAssetMaster', {school_id: schoolId,asset_id:3}, res => {
if ($.fn.DataTable.isDataTable('#FAssetManageDatatable')) {
$('#FAssetManageDatatable').DataTable().clear().destroy(true);
}
//console.log("hello");
let tableData = [];
if (res.status === "Success" && Array.isArray(res.data)) {
//console.log("res.data="+res.data);
tableData = res.data;
}
$('#FAssetManageDatatable').DataTable({
data: tableData,
columns: [
{data: null, render: (d, t, r, m) => m.row + 1, className: 'text-center'},
{data: 'asset_name',className: 'text-center'},
{data: 'master_qty',className: 'text-center'},
{
data: 'mapped_qty',className: 'text-center',
render: data => data != null ? data : '-'
},
{
data: 'unmapped_qty',className: 'text-center',
render: data => data != null ? data : '-'
},
{
data: 'furniture_master_id',
render: (data, t, row) => `
<div class="text-center">
<button class="btn btn-sm btn-success edit-btnf" data-id="${row.furniture_master_id}" ><i class="ik ik-edit-2" style="font-size:medium;margin-left:5px;"></i></button>
</div>`, className: 'text-center'
}
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', '500 rows', 'Show all']
],
dom: 'Bftip',
//fixedColumns: {left: 0, right: 0},
scrollY: '70vh',
scrollX: true,
autoWidth: true,
paging: true,
info: true,
buttons: buttons,
responsive: false,
searching: true,
select: false,
processing: false,
language: {
emptyTable: '<span class="text-danger">No Details found</span>'
}
});
});
}
function loadfsubassets(schoolId) {
$.ajax({
url: '/gcc/api/gccschool/dropdown/getSplSubAssetType',
type: 'GET',
data: { school_id:schoolId,assetid: 3 },
success: function (response) {
const $court = $('#FsubAssetType');
$court.empty();
if (response.status === 'OK' && Array.isArray(response.data)) {
response.data.forEach(item => {
$court.append(`<option value="${item.sub_asset_id}">${item.asset_name}</option>`);
});
} else {
$court.append('<option value="">No Data Found</option>');
}
if ($court.hasClass("select2-hidden-accessible")) {
$court.select2('destroy');
}
$court.select2({
placeholder: "Select Asset",
width: '100%',
minimumResultsForSearch: Infinity,
closeOnSelect: false
});
},
error: function () {
const $court = $('#FsubAssetType');
$court.empty().append('<option value="">Error loading data</option>');
if ($court.hasClass("select2-hidden-accessible")) {
$court.select2('destroy');
}
$court.select2({
placeholder: "Select Asset",
width: '100%',
minimumResultsForSearch: Infinity,
closeOnSelect: false
});
alert("Something went wrong while fetching asset sub types.");
}
});
}
function handleAddFAsset(schoolId) {
$('#savingcontainerf ').hide();
$('#FsubAssetType').empty();
$('#selectedFAssetsContainer').empty();
loadfsubassets(schoolId);
// Then show the modal
$('#AddFAssetModal').modal('show');
}
function handleSaveFAsset(FAssetschoolId) {
$('#savingFAsset').prop('disabled', true).text('Saving...');
const selectedAssets = $('#FsubAssetType').val(); // array of selected sub_asset_id
const assetData = [];
if (!selectedAssets || selectedAssets.length === 0) {
$('#savingFAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please select at least one asset.',
});
return;
}
let hasError = false;
let hasZero = false;
let errorAssets = [];
let zeroAssets = [];
selectedAssets.forEach(function (subAssetId) {
const quantityInput = $(`input[name="assetQuantity_${subAssetId}"]`);
const quantity = quantityInput.val();
const assetName = $(`#subAssetType option[value="${subAssetId}"]`).text(); // Get asset name
if (!quantity || isNaN(quantity) || parseInt(quantity) < 0) {
hasError = true;
errorAssets.push(assetName);
} else if (parseInt(quantity) === 0) {
hasZero = true;
zeroAssets.push(assetName);
} else {
assetData.push({
sub_asset_id: subAssetId,
master_qty: parseInt(quantity)
});
}
});
if (hasError) {
$('#savingFAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Validation Error',
html: `Please enter a valid quantity for the following assets:<br><b>${errorAssets.join(', ')}</b>`,
});
return;
}
if (hasZero) {
$('#savingFAsset').prop('disabled', false).text('Save');
Swal.fire({
icon: 'warning',
title: 'Zero Quantity Error',
html: `You have entered 0 for the following assets:<br><b>${zeroAssets.join(', ')}</b><br>Please remove them from the selection or enter a valid quantity.`,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: true
});
return;
}
const payload = {
school_id: FAssetschoolId,
asset_id: "3", // electrical asset
data: assetData
};
console.log("Final Payload to Save:", payload);
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/saveAssetMaster',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function(response) {
$('#savingFAsset').prop('disabled', false).text('Save');
if (response.status === 'OK') {
//Swal.fire('Success', response.message, 'success');
//$('#AddEAssetModal').modal('hide');
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Success',
text: response.message
}).then(() => {
location.reload();
});
} else {
Swal.fire('Error', response.message, 'error');
}
},
error: function() {
$('#savingFAsset').prop('disabled', false).text('Save');
Swal.fire('Error', 'Something went wrong while saving assets.', 'error');
}
});
}
function handelEditFAsset(){
let fmaster_qty = $('#Fmaster_qty').val();
let fassetMasterId = $('#Feditid').val();
console.log("fmaster_qty"+fmaster_qty);
console.log("fassetMasterId"+fassetMasterId);
if (!fmaster_qty || isNaN(fmaster_qty)) {
Swal.fire({
icon: 'warning',
title: 'Invalid Quantity',
text: 'Please enter a valid Master Quantity',
});
return;
}
if (!fassetMasterId || isNaN(fassetMasterId)) {
Swal.fire({
icon: 'warning',
title: 'Missing ID',
text: 'Furniture Asset ID is missing or invalid.',
});
return;
}
$.ajax({
type: "POST",
url: "/gcc/api/gccschool/schoolproperty/updateAssetMaster", // your endpoint
data: {
master_qty: parseInt(fmaster_qty),
assetMasterId: parseInt(fassetMasterId),
asset_id:3
},
success: function (response) {
if (response === "Success") {
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Asset Updated',
text: 'Asset Updated successfully!'
}).then(() => {
location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Something went wrong while updating asset.'
});
}
},
error: function (xhr, status, error) {
console.error('Error updating assets:', error);
Swal.fire({
icon: 'error',
title: 'Request Failed',
text: 'Unable to send request to the server.'
});
}
});
}
</script>
</body>
</html>

819
frontend/school/assetmanagement.html

@ -0,0 +1,819 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
.custom-card-wrapper {
padding: 0;
margin-top: -58px;
margin-left: -233px;
}
@media (max-width: 768px) {
.custom-card-wrapper {
margin-left: 0;
margin-top: 0;
padding: 10px;
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card">
<div class="main-content" style="background-color: white;">
<div class="container">
<!-- Card 2: Other Details -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<!-- <div style="padding: 0px;margin-top:-58px;margin-left: -233px;"> -->
<div class="card-header d-flex justify-content-between align-items-center">
<b>List of IT Assets</b>
<button type="button" class="btn btn-primary add-btn"> <i class="ik ik-plus"></i>Add Assets</button>
</div>
<div class="card-body" style="padding: 5px;">
<table id="AssetManageDatatable"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width: 100%">
<thead class="thead-dark">
<tr>
<th>S.NO</th>
<th>ASSET CODE</th>
<th>NAME</th>
<th>SOURCE</th>
<th>SERIAL NUMBER</th>
<th>RECEIVED DATE</th>
<th>RECEIVED BY</th>
<th>VENDOR DETAILS</th>
<th>INVOICE NUMBER</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div id="pageLoader"
style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="AddAssetModal2" tabindex="-1" role="dialog" aria-labelledby="AddAssetModal2Label" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Add Assets
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<span id="school_udise" style="display: none;"></span>
<div class="row">
<!-- <div class="form-group col-6">
<label for="assetCode">Asset Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="assetCode" name="assetCode">
</div>-->
<div class="form-group col-6">
<label for="assetName">Name <span class="text-danger">*</span></label>
<select class="form-control" id="assetName" name="assetName" required>
<option value="">-- Select Sub Asset Type --</option>
</select>
</div>
<div class="form-group col-6">
<label for="assetSource">Source<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="assetSource" name="assetSource">
</div>
<div class="form-group col-6">
<label for="serialNumber">Serial Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="serialNumber" name="serialNumber">
</div>
<div class="form-group col-6">
<label for="vendorDetail">Vendor Detail<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="vendorDetail" name="vendorDetail">
</div>
<div class="form-group col-6">
<label for="invoiceNumber">Invoice Number</label>
<input type="text" class="form-control" id="invoiceNumber" name="invoiceNumber">
</div>
</div>
<div class="row pb-2 mt-4">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="savingAsset">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="EditAssetModal2" tabindex="-1" role="dialog" aria-labelledby="EditAssetModal2Label" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Edit Assets
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<span id="editid" style="display: none;"></span>
<div class="row">
<div class="form-group col-6">
<label for="editassetCode">Asset Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="editassetCode" name="editassetCode">
</div>
<div class="form-group col-6">
<label for="editassetName">Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="editassetName" name="editassetName">
</div>
<div class="form-group col-6">
<label for="editassetSource">Source<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="editassetSource" name="editassetSource">
</div>
<div class="form-group col-6">
<label for="editserialNumber">Serial Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="editserialNumber" name="editserialNumber">
</div>
<div class="form-group col-6">
<label for="editvendorDetail">Vendor Detail<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="editvendorDetail" name="vendorDetail">
</div>
<div class="form-group col-6">
<label for="editinvoiceNumber">Invoice Number</label>
<input type="text" class="form-control" id="editinvoiceNumber" name="editinvoiceNumber">
</div>
</div>
<div class="row pb-2 mt-4">
<div class="col-12 d-flex justify-content-center">
<button type="button" class="btn btn-primary" id="UpdatingAsset">Update</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
console.log("hi..asset Management");
$(document).ready(function () {
let AssetManageurlParams = new URLSearchParams(window.location.search);
let AssetManageschoolId = AssetManageurlParams.get("schoolId");
loadSavedBuildingAm(AssetManageschoolId);
if (!window.assetManagementEventsBound) {
$(document).on('click', '.edit-btn1', handleManageEdit);
// $(document).on('click', '.add-btn', handleAddAsset);
$(document).on('click', '.add-btn', function () {
handleAddAsset(AssetManageschoolId);
});
//$(document).on('click', '#savingAsset', handleSavingAsset);
// Pass school ID to the handler
$(document).on('click', '#savingAsset', function () {
handleSavingAsset(AssetManageschoolId);
});
$(document).on('click', '#UpdatingAsset', handelEditAsset);
window.assetManagementEventsBound = true;
}
});
$(document).on('input', '#assetSource, #vendorDetail', function () {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, ''); // Allow only alphanumeric + space
});
$(document).on('input', '#serialNumber, #invoiceNumber', function () {
this.value = this.value.replace(/[^a-zA-Z0-9/]/g, ''); // Allow only alphanumeric + "/"
});
function loadSavedBuildingAm(AssetManageschoolId) {
//console.log("hi");
var buttons = [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn',
title: 'Asset List'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn',
title: 'Asset List'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn',
title: 'Asset List'
},
{
extend: 'print',
text: 'Print',
className: 'btn btn-secondary',
id: 'printBtn',
title: 'Asset List',
exportOptions: {
columns: ':visible:not(.no-print)' // Exclude columns with class 'no-print' from print view
}
}
];
$.get('/gcc/api/gccschool/buildingasset/getAssetManagement', {school_id: AssetManageschoolId}, res => {
if ($.fn.DataTable.isDataTable('#AssetManageDatatable')) {
$('#AssetManageDatatable').DataTable().clear().destroy(true);
}
//console.log("hello");
let tableData = [];
if (res.status === "Sucess" && Array.isArray(res.data)) {
//console.log("res.data="+res.data);
tableData = res.data;
}
$('#AssetManageDatatable').DataTable({
data: tableData,
columns: [
{data: null, render: (d, t, r, m) => m.row + 1, className: 'text-center'},
{data: 'asset_name'},
{data: 'hardware_type'},
{data: 'source_of_asset'},
{data: 'serial_no'},
{data: 'date_received'},
{data: 'asset_category'},
{data: 'vendor_name'},
{data: 'invoice_num'},
{
data: 'it_details_id',
render: (data, t, row) => `
<div class="text-center">
<button class="btn btn-sm btn-success edit-btn1" data-id="${row.it_details_id}" ><i class="ik ik-edit-2" style="font-size:medium;margin-left:5px;"></i></button>
</div>`, className: 'text-center'
}
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', '500 rows', 'Show all']
],
dom: 'Bftip',
//fixedColumns: {left: 0, right: 0},
scrollY: '70vh',
scrollX: true,
autoWidth: true,
paging: true,
info: true,
buttons: buttons,
responsive: false,
searching: true,
select: false,
processing: false,
language: {
emptyTable: '<span class="text-danger">No Details found</span>'
}
});
});
}
// Load sub asset types on modal open or page load
// Load sub asset types on modal open or page load
$.ajax({
url: '/gcc/api/gccschool/dropdown/getSubAssetType',
type: 'GET',
data: { assetid: 1 }, // or dynamic ID later
success: function (res) {
console.log("Sub Asset API Response:", res);
if (res.status === "OK" && Array.isArray(res.data)) {
$('#assetName').empty().append('<option value="">-- Select Sub Asset Type --</option>');
res.data.forEach(function (item) {
$('#assetName').append(
$('<option>', {
value: item.code,
text: item.asset_name
})
);
});
} else {
$('#assetName').empty().append('<option value="">No Sub Asset Types Found</option>');
}
},
error: function (xhr, status, error) {
console.error("Failed to load sub asset types:", error);
$('#assetName').empty().append('<option value="">Error Loading</option>');
}
});
function handleAddAsset(schid) {
$('#AddAssetModal2').modal('show');
$.ajax({
type: 'GET',
url: '/gcc/api/gccschool/schoolproperty/getSchoolDetails',
data: {schoolId: schid},
success: function (data) {
console.log(data);
$('#school_udise').text(data.udise);
},
error: function (xhr) {
console.log("Failed to get udise for school: " + xhr.responseJSON?.message);
}
});
$('#assetCode').val('');
$('#assetName').val('');
$('#assetSource').val('');
$('#serialNumber').val('');
$('#vendorDetail').val('');
$('#invoiceNumber').val('');
}
function handleSavingAsset(assetManageschoolId){
let school_udise = $('#school_udise').text().trim();
// let assetCode = $('#assetCode').val().trim();
//let subAssetId = $('#assetName').val();
//let subAssetId = $('#assetName').val(); // This gives selected value = sub_asset_id
let assetSource = $('#assetSource').val().trim();
let serialNumber = $('#serialNumber').val().trim();
let vendorDetail = $('#vendorDetail').val().trim();
let invoiceNumber = $('#invoiceNumber').val().trim();
//let assetCode = $('#assetName option:selected').text().trim();
let assetCode = $('#assetName').val(); // Get selected value
let assetName = $('#assetName option:selected').text().trim(); // Get selected text
// Console log to verify
console.log("UDISE:", school_udise);
console.log("Asset Code:", assetCode);
console.log("Asset Name:", assetName);
//console.log("Asset Name:", assetName);
console.log("Source:", assetSource);
console.log("Serial Number:", serialNumber);
console.log("Vendor Detail:", vendorDetail);
console.log("Invoice Number:", invoiceNumber);
console.log("assetManageschoolId="+assetManageschoolId);
//console.log("Asset Name:", assetName);
//console.log("Code:", code);
// Validation
/* if (assetCode === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Asset Code',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}*/
if (assetCode === '' || assetName === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please Select Name',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (assetSource === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Source',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (serialNumber === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Serial Number',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (vendorDetail === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Vendor Detail',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
console.log(assetManageschoolId);
/*if (invoiceNumber === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Invoice Number',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}*/
/* if (assetCode === '') {
Swal.fire('Missing Field', 'Please enter Asset Code', 'warning');
return;
}
if (assetName === '') {
Swal.fire('Missing Field', 'Please enter Name', 'warning');
return;
}
if (assetSource === '') {
Swal.fire('Missing Field', 'Please enter Source', 'warning');
return;
}
if (serialNumber === '') {
Swal.fire('Missing Field', 'Please enter Serial Number', 'warning');
return;
}
if (vendorDetail === '') {
Swal.fire('Missing Field', 'Please enter Vendor Detail', 'warning');
return;
}
if (invoiceNumber === '') {
Swal.fire('Missing Field', 'Please enter Invoice Number', 'warning');
return;
}*/
// AJAX POST
$.ajax({
type: "POST",
url: "/gcc/api/gccschool/buildingasset/addAsset", // your endpoint
data: {
// assetCode: code,
// sub_asset_id: subAssetId,
name:assetName,
code:assetCode,
source: assetSource,
serialNum: serialNumber,
vendorDetail: vendorDetail,
invoice_num: invoiceNumber,
udise: school_udise,
is_online: 0,
school_id: assetManageschoolId
},
success: function (response) {
if (response === "Sucess") {
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Asset Added',
text: 'Asset added successfully!'
}).then(() => {
/* loadSavedBuildingAm(assetManageschoolId);
$('#AddAssetModal2').modal('hide'); */
location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Something went wrong while saving asset.'
});
}
},
error: function (xhr, status, error) {
console.error('Error saving assets:', error);
Swal.fire({
icon: 'error',
title: 'Request Failed',
text: 'Unable to send request to the server.'
});
}
});
}
function handleManageEdit(){
console.log("Button clicked");
let id = $(this).data('id');
console.log("id=" + id);
$.ajax({
type: "GET",
url: "/gcc/api/gccschool/buildingasset/getAssets",
data: { it_details_id: id },
success: function (response) {
if (response.status === "Success" && response.data) {
let data = response.data;
// Populate modal fields
$('#editassetCode').val(data.asset_name || '');
$('#editassetName').val(data.hardware_type || '');
$('#editassetSource').val(data.source_of_asset || '');
$('#editserialNumber').val(data.serial_no || '');
$('#editvendorDetail').val(data.vendor_name || '');
$('#editinvoiceNumber').val(data.invoice_num || '');
$('#editid').val(data.it_details_id);
// Show the modal
$('#EditAssetModal2').modal('show');
} else {
Swal.fire('Error', 'Unable to fetch asset details.', 'error');
}
},
error: function (xhr, status, error) {
console.error('Error fetching asset:', error);
Swal.fire('Error', 'Server error while fetching asset.', 'error');
}
});
}
function handelEditAsset(){
let editassetCode = $('#editassetCode').val().trim();
let editassetName = $('#editassetName').val().trim();
let editassetSource = $('#editassetSource').val().trim();
let editserialNumber = $('#editserialNumber').val().trim();
let editvendorDetail = $('#editvendorDetail').val().trim();
let editinvoiceNumber = $('#editinvoiceNumber').val().trim();
let editid= $('#editid').val().trim();
// Validation
/* if (editassetCode === '') {
Swal.fire('Missing Field', 'Please enter Asset Code', 'warning');
return;
}
if (editassetName === '') {
Swal.fire('Missing Field', 'Please enter Name', 'warning');
return;
}
if (editassetSource === '') {
Swal.fire('Missing Field', 'Please enter Source', 'warning');
return;
}
if (editserialNumber === '') {
Swal.fire('Missing Field', 'Please enter Serial Number', 'warning');
return;
}
if (editvendorDetail === '') {
Swal.fire('Missing Field', 'Please enter Vendor Detail', 'warning');
return;
}
if (editinvoiceNumber === '') {
Swal.fire('Missing Field', 'Please enter Invoice Number', 'warning');
return;
}*/
if (editassetCode === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Asset Code',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (editassetName === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Name',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (editassetSource === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Source',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (editserialNumber === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Serial Number',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (editvendorDetail === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Vendor Detail',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
/* if (editinvoiceNumber === '') {
Swal.fire({
icon: 'warning',
title: 'Missing Field',
text: 'Please enter Invoice Number',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}*/
$.ajax({
type: "POST",
url: "/gcc/api/gccschool/buildingasset/editAsset", // your endpoint
data: {
assetCode: editassetCode,
name: editassetName,
source: editassetSource,
serialNum: editserialNumber,
vendorDetail: editvendorDetail,
invoice_num: editinvoiceNumber,
it_details_id: editid
},
success: function (response) {
if (response === "Success") {
Swal.fire({
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
icon: 'success',
title: 'Asset Updated',
text: 'Asset Updated successfully!'
}).then(() => {
location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Something went wrong while updating asset.'
});
}
},
error: function (xhr, status, error) {
console.error('Error updating assets:', error);
Swal.fire({
icon: 'error',
title: 'Request Failed',
text: 'Unable to send request to the server.'
});
}
});
}
</script>
</body>
</html>

1582
frontend/school/building.html
File diff suppressed because it is too large
View File

322
frontend/school/dashboard.html

@ -0,0 +1,322 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
/* 🆕 Added Styles for Better Layout */
.card {
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
background-color: white;
}
.card .row {
margin-top: 10px;
}
.card .col-md-3 {
margin-bottom: 15px;
}
.form-control {
border-radius: 5px;
}
/* 🆕 Centering the Filter Button */
.text-center {
text-align: center;
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content">
<div class="container">
<div class="header">School Module - Dashboard</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
<!-- Card 1: School Information -->
<div class="col-md-12">
<div class="card">
<div class="row">
<div class="col-md-3">
<label>Search with UDISE Number</label>
<select class="form-control" id="udiseDropdown">
<option value="">Select UDISE Number</option>
</select>
</div>
<div class="col-md-3">
<label>Category</label>
<select class="form-control" id="categoryDropdown">
<option value="">Select Category</option>
</select>
</div>
<div class="col-md-3">
<label>Zone</label>
<select class="form-control" id="zoneDropdown">
<option value="">Select Zone</option>
</select>
</div>
<div class="col-md-3">
<label>Ward</label>
<select class="form-control" id="wardDropdown">
<option value="">Select Ward</option>
</select>
</div>
</div> <!-- Row End -->
<!-- Centered Filter Button -->
<div class="row mt-3">
<div class="col-12 text-center">
<button id="filterButton" class="btn btn-primary " style="background-color: #0D587B;">Filter</button>
<button id="resetButton" class="btn btn-secondary">Reset</button>
</div>
</div>
</div> <!-- Card End -->
</div> <!-- Col-md-12 End -->
<!-- 🆕 DataTable -->
<div class="card">
<div class="table-responsive">
<input type="hidden" id="loggedUserId" th:value="${user_id}">
<table id="schoolTable" class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th>S.No</th>
<th>UDISE Number</th>
<th>Name</th>
<th>Category</th>
<th>Zone</th>
<th>Ward</th>
<th>Address</th>
</tr>
</thead>
<tbody id="schoolTableBody">
<!-- Rows will be populated by JS -->
</tbody>
</table>
</div>
</div> <!-- DataTable Card End -->
</div> <!-- Container End -->
</div> <!-- Main Content End -->
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<!-- 🆕 DataTable Initialization Script -->
<script>
$(document).ready(function () {
$('#schoolTable').DataTable({
paging: true,
responsive: false,
searching: true,
select: false,
processing: false,
ordering: true,
info: true,
language: {
zeroRecords: "No schools found for this user.",
emptyTable: "No data available in table"
}
});
});
function loadDropdown(userId, type, dropdownId, placeholderText) {
$.ajax({
url: "/gcc/api/gccschool/dropdown/getAllDropdownValues",
method: "GET",
data: { user_id: userId, type: type },
success: function (response) {
console.log(`Dropdown (${type}) response:`, response);
let dropdown = $(`#${dropdownId}`);
dropdown.empty().append(`<option value="">${placeholderText}</option>`);
if (response[0].Message === "Success" && response[0].Data.length > 0) {
response[0].Data.forEach(item => {
dropdown.append(`<option value="${item}">${item}</option>`);
});
}
},
error: function () {
alert(`Failed to load ${type} dropdown`);
}
});
}
$('#filterButton').click(function () {
const userId = $('#loggedUserId').val();
const udise = $('#udiseDropdown').val();
const category = $('#categoryDropdown').val();
const zone = $('#zoneDropdown').val();
const ward = $('#wardDropdown').val();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/filterSchools',
method: 'GET',
data: {
user_id: userId,
udise: udise,
category: category,
zone: zone,
ward: ward
},
success: function (response) {
const table = $('#schoolTable').DataTable();
table.clear();
if (response.length > 0 && response[0].Message === "Success" && response[0].Data.length > 0) {
let schoolList = response[0].Data;
schoolList.forEach((school, index) => {
table.row.add([
index + 1,
school.udise || '',
school.school_name || '',
school.category || '',
school.zone || '',
school.division || '',
school.address || ''
]);
});
}
table.draw(); // Draw table whether data exists or not
},
error: function () {
alert("Error fetching filtered school data.");
}
});
});
$('#filterButton').click(function () {
filterSchools(); // Call the function on button click
});
function loadSchoolsForUser(userId) {
$.ajax({
url: "/gcc/api/gccschool/schoolproperty/getLoginDetails",
method: "GET",
data: { user_id: userId },
success: function (response) {
if (response.length > 0 && response[0].Message === "Success") {
let schoolList = response[0].Data;
// Destroy and reinitialize the DataTable with createdRow
if ($.fn.DataTable.isDataTable('#schoolTable')) {
$('#schoolTable').DataTable().destroy();
}
const table = $('#schoolTable').DataTable({
createdRow: function (row, data, dataIndex) {
$(row).attr("onclick", `redirectToDetails(${schoolList[dataIndex].id})`);
}
});
table.clear();
schoolList.forEach((school, index) => {
table.row.add([
index + 1,
school.udise || '',
school.school_name || '',
school.category || '',
school.zone || '',
school.division || '',
school.address || ''
]);
});
table.draw();
} else {
alert("No schools found for this user.");
}
},
error: function () {
alert("Failed to load schools.");
}
});
}
// ⏬ Call this on page load with the logged-in user's ID
$(document).ready(function () {
const userId = $('#loggedUserId').val();
loadSchoolsForUser(userId);
loadDropdown(userId, 'udise', 'udiseDropdown', 'Select UDISE Number');
loadDropdown(userId, 'category', 'categoryDropdown', 'Select Category');
loadDropdown(userId, 'zone', 'zoneDropdown', 'Select Zone');
loadDropdown(userId, 'ward', 'wardDropdown', 'Select Ward');
// $('#schoolTable').DataTable();
});
function redirectToDetails(schoolId) {
window.location.href = "/gcc/school/otherdetails?schoolId=" + schoolId;
}
$('#resetButton').click(function () {
location.reload(); // This will reload the entire page
});
</script>
</body>
</html>

1525
frontend/school/drinkingwater.html
File diff suppressed because it is too large
View File

405
frontend/school/electricalassets.html

@ -0,0 +1,405 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content">
<div class="container">
<div class="header">School Module - Master Details - {Id 3232193827918}</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
<!-- Card 1: School Information -->
<div class="col-md-12">
<div class="card">
<div class="card-header" style=" background-color: #404E67;
color: white;">School Information</div>
<table class="table">
<tr>
<th>School Name:</th>
<td>CPS KOLATHUR II</td>
<th>UDISE Code:</th>
<td>33020401404</td>
</tr>
<tr>
<th>Category:</th>
<td>Primary School</td>
<th>Medium:</th>
<td>Tamil, English</td>
</tr>
<tr>
<th>School Type:</th>
<td>Government</td>
<th>Zone:</th>
<td>Zone 11</td>
</tr>
<tr>
<th>Ward:</th>
<td>Ward 122</td>
<th>Address:</th>
<td>1a, school road, Venkat Nagar, Kolathur, Chennai.</td>
</tr>
</table>
</div>
</div>
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center">
<h4>Room Wise Asset Mapping - Furniture Assets</h4>
<button type="button" class="btn btn-primary"
style="background-color: #0D587B; border: none; border-radius: 6px; padding: 6px 16px;"
data-bs-toggle="modal" data-bs-target="#assetModal">
+ Add Assets
</button>
</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<h5 style="font-weight:bold;">List of Electrical Assets</h5>
<h5 style="font-weight:bold;">
<span th:text="${deptId}" id="deptId" style="display:none"></span>
</h5>
<span th:text="${userId}" id="userId" style="display:none"></span>
<div id="completedCPSTable">
<table id="CompletedCPSDatatable" class="table table-striped table-bordered table-hover dataTable" role="grid" style="width:100%">
<thead class="thead-dark">
<tr>
<th style="width: 5%;">S.NO</th>
<th style="width: 10%;">ASSET CODE</th>
<th style="width: 15%;">NAME</th>
<th style="width: 10%;">SOURCE</th>
<th style="width: 15%;">SERIAL NUMBER</th>
<th style="width: 15%;">RECEIVED DATE</th>
<th style="width: 10%;">RECEIVED BY</th>
<th style="width: 10%;">VENDOR DETAILS</th>
<th style="width: 10%;">INVOICE NUMBER</th>
<th style="width: 10%;">LOCATION</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>2</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>3</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Card 2: Other Details -->
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="assetModal" tabindex="-1" role="dialog" aria-labelledby="assetModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Room Wise Asset Mapping - Electrical Assets</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Building Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="buildingDropdown">Select Building *</label>
<select id="buildingDropdown" class="form-control">
<option value="">-- Select Building --</option>
<option value="building1">Building 1</option>
<option value="building2">Building 2</option>
</select>
</div>
</div>
<!-- Floor Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="floorDropdown">Select Floor *</label>
<select id="floorDropdown" class="form-control">
<option value="">-- Select Floor --</option>
<option value="floor1">1st Floor</option>
<option value="floor2">2nd Floor</option>
</select>
</div>
</div>
<!-- Room Type Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomTypeDropdown">Select Room Type *</label>
<select id="roomTypeDropdown" class="form-control">
<option value="">-- Select Room Type --</option>
<option value="classroom">Classroom</option>
<option value="conference">Conference Room</option>
</select>
</div>
</div>
<!-- Room Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomDropdown">Select Room *</label>
<select id="roomDropdown" class="form-control">
<option value="">-- Select Room --</option>
<option value="room1">Number 1</option>
<option value="room2">Number 2</option>
</select>
</div>
</div>
<!-- Assets Dropdown -->
<div class="col-md-12">
<div class="form-group">
<label for="assetDropdown">Select Assets *</label>
<div class="form-control" id="assetDropdown">
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="fan"> Fan
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="Smart TV"> Lights
</div>
</div>
</div>
</div>
<!-- Dynamic Asset Selection Section -->
<div class="col-md-12" id="assetContainer"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
<script>
$(document).ready(function() {
$('#CompletedCPSDatatable').DataTable({
scrollX: true, // Enables horizontal scrolling
autoWidth: false, // Ensures manual column widths are respected
responsive: true, // Ensures better mobile view
dom: 'Bftip',
lengthMenu: [
[10, 50, 100, 200, -1],
['10 rows', '50 rows', '100 rows', 'Show all']
],
buttons: [
{ extend: 'pageLength', className: 'btn btn-warning' },
{ extend: 'copyHtml5', text: 'Copy', className: 'btn btn-secondary' },
{ extend: 'excelHtml5', text: 'Excel', className: 'btn btn-secondary' },
{ extend: 'csvHtml5', text: 'CSV', className: 'btn btn-secondary' },
{ extend: 'pdfHtml5', text: 'PDF', className: 'btn btn-secondary' }
],
fixedHeader: true,
searching: true,
select: false,
processing: false
});
});
document.getElementById('buildingDropdown').addEventListener('change', function () {
const floorDropdown = document.getElementById('floorDropdown').parentElement;
const roomTypeDropdown = document.getElementById('roomTypeDropdown').parentElement;
const roomDropdown = document.getElementById('roomDropdown').parentElement;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (this.value) {
floorDropdown.style.display = 'block';
roomTypeDropdown.style.display = 'block';
roomDropdown.style.display = 'block';
} else {
floorDropdown.style.display = 'none';
roomTypeDropdown.style.display = 'none';
roomDropdown.style.display = 'none';
assetDropdown.style.display = 'none';
}
document.getElementById('floorDropdown').value = "";
document.getElementById('roomTypeDropdown').value = "";
document.getElementById('roomDropdown').value = "";
});
// Show assets only when all dropdowns are selected
function checkAllSelections() {
const building = document.getElementById('buildingDropdown').value;
const floor = document.getElementById('floorDropdown').value;
const roomType = document.getElementById('roomTypeDropdown').value;
const room = document.getElementById('roomDropdown').value;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (building && floor && roomType && room) {
assetDropdown.style.display = 'block';
} else {
assetDropdown.style.display = 'none';
document.getElementById('assetContainer').innerHTML = ''; // Clear asset selection
}
}
document.getElementById('floorDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomTypeDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomDropdown').addEventListener('change', checkAllSelections);
// Initially hide all dependent dropdowns and asset section
window.addEventListener('DOMContentLoaded', function () {
document.getElementById('floorDropdown').parentElement.style.display = 'none';
document.getElementById('roomTypeDropdown').parentElement.style.display = 'none';
document.getElementById('roomDropdown').parentElement.style.display = 'none';
document.getElementById('assetDropdown').parentElement.style.display = 'none';
});
// Dynamic Asset Mapping with Quantity Input
document.querySelectorAll('.asset-checkbox').forEach(checkbox => {
checkbox.addEventListener('change', function () {
const assetContainer = document.getElementById('assetContainer');
const assetValue = this.value;
if (this.checked) {
const assetDiv = document.createElement('div');
assetDiv.classList.add('asset-item');
assetDiv.id = `asset-${assetValue}`;
assetDiv.innerHTML = `
<div class="row">
<div class="col-md-6">
<div class="form-group mt-2">
<label>${assetValue} Quantity *</label>
<input type="number" class="form-control" placeholder="Enter Quantity" required>
</div>
</div>
</div>
`;
assetContainer.appendChild(assetDiv);
} else {
const existingDiv = document.getElementById(`asset-${assetValue}`);
if (existingDiv) {
assetContainer.removeChild(existingDiv);
}
}
});
});
</script>
</html>

411
frontend/school/furnitureassets.html

@ -0,0 +1,411 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content">
<div class="container">
<div class="header">School Module - Master Details - {Id 3232193827918}</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
<!-- Card 1: School Information -->
<div class="col-md-12">
<div class="card">
<div class="card-header" style=" background-color: #404E67;
color: white;">School Information</div>
<table class="table">
<tr>
<th>School Name:</th>
<td>CPS KOLATHUR II</td>
<th>UDISE Code:</th>
<td>33020401404</td>
</tr>
<tr>
<th>Category:</th>
<td>Primary School</td>
<th>Medium:</th>
<td>Tamil, English</td>
</tr>
<tr>
<th>School Type:</th>
<td>Government</td>
<th>Zone:</th>
<td>Zone 11</td>
</tr>
<tr>
<th>Ward:</th>
<td>Ward 122</td>
<th>Address:</th>
<td>1a, school road, Venkat Nagar, Kolathur, Chennai.</td>
</tr>
</table>
</div>
</div>
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center">
<h4>Room Wise Asset Mapping - Furniture Assets</h4>
<button type="button" class="btn btn-primary"
style="background-color: #0D587B; border: none; border-radius: 6px; padding: 6px 16px;"
data-bs-toggle="modal" data-bs-target="#assetModal">
+ Add Assets
</button>
</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<h5 style="font-weight:bold;">List of Furniture Assets</h5>
<h5 style="font-weight:bold;">
<span th:text="${deptId}" id="deptId" style="display:none"></span>
</h5>
<span th:text="${userId}" id="userId" style="display:none"></span>
<div id="completedCPSTable">
<table id="CompletedCPSDatatable" class="table table-striped table-bordered table-hover dataTable" role="grid" style="width:100%">
<thead class="thead-dark">
<tr>
<th style="width: 5%;">S.NO</th>
<th style="width: 10%;">ASSET CODE</th>
<th style="width: 15%;">NAME</th>
<th style="width: 10%;">SOURCE</th>
<th style="width: 15%;">SERIAL NUMBER</th>
<th style="width: 15%;">RECEIVED DATE</th>
<th style="width: 10%;">RECEIVED BY</th>
<th style="width: 10%;">VENDOR DETAILS</th>
<th style="width: 10%;">INVOICE NUMBER</th>
<th style="width: 10%;">LOCATION</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>2</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>3</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Card 2: Other Details -->
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="assetModal" tabindex="-1" role="dialog" aria-labelledby="assetModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Room Wise Asset Mapping - Furniture Assets</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Building Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="buildingDropdown">Select Building *</label>
<select id="buildingDropdown" class="form-control">
<option value="">-- Select Building --</option>
<option value="building1">Building 1</option>
<option value="building2">Building 2</option>
</select>
</div>
</div>
<!-- Floor Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="floorDropdown">Select Floor *</label>
<select id="floorDropdown" class="form-control">
<option value="">-- Select Floor --</option>
<option value="floor1">1st Floor</option>
<option value="floor2">2nd Floor</option>
</select>
</div>
</div>
<!-- Room Type Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomTypeDropdown">Select Room Type *</label>
<select id="roomTypeDropdown" class="form-control">
<option value="">-- Select Room Type --</option>
<option value="classroom">Classroom</option>
<option value="conference">Conference Room</option>
</select>
</div>
</div>
<!-- Room Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomDropdown">Select Room *</label>
<select id="roomDropdown" class="form-control">
<option value="">-- Select Room --</option>
<option value="room1">Number 1</option>
<option value="room2">Number 2</option>
</select>
</div>
</div>
<!-- Assets Dropdown -->
<div class="col-md-12">
<div class="form-group">
<label for="assetDropdown">Select Assets *</label>
<div class="form-control" id="assetDropdown">
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="desk"> Desk
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="bench"> Bench
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="cupboard"> Cup Board
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="blackboard"> Black Board
</div>
</div>
</div>
</div>
<!-- Dynamic Asset Selection Section -->
<div class="col-md-12" id="assetContainer"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
<script>
$(document).ready(function() {
$('#CompletedCPSDatatable').DataTable({
scrollX: true, // Enables horizontal scrolling
autoWidth: false, // Ensures manual column widths are respected
responsive: true, // Ensures better mobile view
dom: 'Bftip',
lengthMenu: [
[10, 50, 100, 200, -1],
['10 rows', '50 rows', '100 rows', 'Show all']
],
buttons: [
{ extend: 'pageLength', className: 'btn btn-warning' },
{ extend: 'copyHtml5', text: 'Copy', className: 'btn btn-secondary' },
{ extend: 'excelHtml5', text: 'Excel', className: 'btn btn-secondary' },
{ extend: 'csvHtml5', text: 'CSV', className: 'btn btn-secondary' },
{ extend: 'pdfHtml5', text: 'PDF', className: 'btn btn-secondary' }
],
fixedHeader: true,
searching: true,
select: false,
processing: false
});
});
document.getElementById('buildingDropdown').addEventListener('change', function () {
const floorDropdown = document.getElementById('floorDropdown').parentElement;
const roomTypeDropdown = document.getElementById('roomTypeDropdown').parentElement;
const roomDropdown = document.getElementById('roomDropdown').parentElement;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (this.value) {
floorDropdown.style.display = 'block';
roomTypeDropdown.style.display = 'block';
roomDropdown.style.display = 'block';
} else {
floorDropdown.style.display = 'none';
roomTypeDropdown.style.display = 'none';
roomDropdown.style.display = 'none';
assetDropdown.style.display = 'none';
}
document.getElementById('floorDropdown').value = "";
document.getElementById('roomTypeDropdown').value = "";
document.getElementById('roomDropdown').value = "";
});
// Show assets only when all dropdowns are selected
function checkAllSelections() {
const building = document.getElementById('buildingDropdown').value;
const floor = document.getElementById('floorDropdown').value;
const roomType = document.getElementById('roomTypeDropdown').value;
const room = document.getElementById('roomDropdown').value;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (building && floor && roomType && room) {
assetDropdown.style.display = 'block';
} else {
assetDropdown.style.display = 'none';
document.getElementById('assetContainer').innerHTML = ''; // Clear asset selection
}
}
document.getElementById('floorDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomTypeDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomDropdown').addEventListener('change', checkAllSelections);
// Initially hide all dependent dropdowns and asset section
window.addEventListener('DOMContentLoaded', function () {
document.getElementById('floorDropdown').parentElement.style.display = 'none';
document.getElementById('roomTypeDropdown').parentElement.style.display = 'none';
document.getElementById('roomDropdown').parentElement.style.display = 'none';
document.getElementById('assetDropdown').parentElement.style.display = 'none';
});
// Dynamic Asset Mapping with Quantity Input
document.querySelectorAll('.asset-checkbox').forEach(checkbox => {
checkbox.addEventListener('change', function () {
const assetContainer = document.getElementById('assetContainer');
const assetValue = this.value;
if (this.checked) {
const assetDiv = document.createElement('div');
assetDiv.classList.add('asset-item');
assetDiv.id = `asset-${assetValue}`;
assetDiv.innerHTML = `
<div class="row">
<div class="col-md-6">
<div class="form-group mt-2">
<label>${assetValue} Quantity *</label>
<input type="number" class="form-control" placeholder="Enter Quantity" required>
</div>
</div>
</div>
`;
assetContainer.appendChild(assetDiv);
} else {
const existingDiv = document.getElementById(`asset-${assetValue}`);
if (existingDiv) {
assetContainer.removeChild(existingDiv);
}
}
});
});
</script>
</html>

602
frontend/school/itassets.html

@ -0,0 +1,602 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content">
<div class="container">
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center">
<h4 style="margin-left: -256px;">Room Wise Asset Mapping - IT Assits</h4>
<button type="button" class="btn btn-primary"
style="background-color: #0D587B; border: none; border-radius: 6px; padding: 6px 16px;"
data-bs-toggle="modal" data-bs-target="#assetModal">
+ Add Assets
</button>
</div>
<hr
style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px; margin-left: -261px;">
</div>
<div class="row mt-4" style=" margin-left: -281px;">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<h5 style="font-weight:bold;">List of IT Assets</h5>
<h5 style="font-weight:bold;">
<span th:text="${deptId}" id="deptId" style="display:none"></span>
</h5>
<span th:text="${userId}" id="userId" style="display:none"></span>
<div id="completedCPSTable">
<table id="CompletedCPSDatatable1"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width:100%">
<thead class="thead-dark">
<tr>
<th style="width: 5%;">S.NO</th>
<th style="width: 10%;">ASSET CODE</th>
<th style="width: 15%;">NAME</th>
<th style="width: 10%;">SOURCE</th>
<th style="width: 15%;">SERIAL NUMBER</th>
<th style="width: 15%;">RECEIVED DATE</th>
<th style="width: 10%;">RECEIVED BY</th>
<th style="width: 10%;">VENDOR DETAILS</th>
<th style="width: 10%;">INVOICE NUMBER</th>
<th style="width: 10%;">LOCATION</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>2</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
<tr>
<td>3</td>
<td>TH40V40I</td>
<td>CAMERA</td>
<td>GCC</td>
<td>22023293837281</td>
<td>JUN 23, 2025 12:40 PM</td>
<td>RECEIVED BY</td>
<td>N/A</td>
<td>2345676543ER</td>
<td>CHENNAI</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4" style="margin-left: -281px;">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<h5 style="font-weight:bold;">Building Wise Asset Mapping status - IT Assets</h5>
<span th:text="${deptId}" id="deptId" style="display:none"></span>
<span th:text="${userId}" id="userId" style="display:none"></span>
<div id="completedCPSTable">
<table id="CompletedCPSDatatable2"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width:100%">
<thead class="thead-dark">
<tr>
<th>S.NO</th>
<th>BUILDING NAME</th>
<th>FLOORS</th>
<th>STATUS</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>RIPON BUILDING</td>
<td>3</td>
<td>COMPLETED</td>
<td><span class="badge badge-success" style="cursor:pointer;"
onclick="openRoomMappingModal(1, 'RIPON BUILDING')">Add Room
Mapping</span></td>
</tr>
<tr>
<td>2</td>
<td>GREEN BUILDING</td>
<td>2</td>
<td>PENDING</td>
<td><span class="badge badge-success" style="cursor:pointer;"
onclick="openRoomMappingModal(2, 'GREEN BUILDING')">Add Room
Mapping</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Card 2: Other Details -->
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="roomMappingModal" tabindex="-1" role="dialog" aria-labelledby="roomMappingModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="roomMappingModalLabel">Room Mapping for <span id="buildingName"></span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<table class="table table-striped">
<thead>
<tr>
<th>S.NO</th>
<th>Floor</th>
<th>Room</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="roomMappingBody">
<!-- Dynamic Data Will Be Inserted Here -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Add Room Mapping Modal -->
<div class="modal fade" id="addRoomMappingModal" tabindex="-1" role="dialog"
aria-labelledby="addRoomMappingModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addRoomMappingModalLabel">Add Room Mapping for <span
id="roomFloor"></span> - <span id="roomName"></span></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<table class="table table-striped">
<thead>
<tr>
<th>S.NO</th>
<th>Room Type</th>
<th>Room Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="addRoomMappingBody">
<!-- Dynamic Data Will Be Inserted Here -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Asset Mapping Modal -->
<div class="modal fade" id="assetMappingModal" tabindex="-1" role="dialog" aria-labelledby="assetMappingModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Asset Mapping for <span id="assetRoomName"></span></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<table class="table table-striped">
<thead>
<tr>
<th>S.NO</th>
<th>Room Type</th>
<th>Assets</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="assetMappingBody"></tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="assetModal" tabindex="-1" role="dialog" aria-labelledby="assetModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Room Wise Asset Mapping - IT Assets</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Building Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="buildingDropdown">Select Building *</label>
<select id="buildingDropdown" class="form-control">
<option value="">-- Select Building --</option>
<option value="building1">Building 1</option>
<option value="building2">Building 2</option>
</select>
</div>
</div>
<!-- Floor Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="floorDropdown">Select Floor *</label>
<select id="floorDropdown" class="form-control">
<option value="">-- Select Floor --</option>
<option value="floor1">1st Floor</option>
<option value="floor2">2nd Floor</option>
</select>
</div>
</div>
<!-- Room Type Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomTypeDropdown">Select Room Type *</label>
<select id="roomTypeDropdown" class="form-control">
<option value="">-- Select Room Type --</option>
<option value="classroom">Classroom</option>
<option value="conference">Conference Room</option>
</select>
</div>
</div>
<!-- Room Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="roomDropdown">Select Room *</label>
<select id="roomDropdown" class="form-control">
<option value="">-- Select Room --</option>
<option value="room1">Number 1</option>
<option value="room2">Number 2</option>
</select>
</div>
</div>
<!-- Assets Dropdown -->
<div class="col-md-12">
<div class="form-group">
<label for="assetDropdown">Select Assets *</label>
<div class="form-control" id="assetDropdown">
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="Computer"> Computer
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="Smart TV"> Smart TV
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="Projector"> Projector
</div>
<div class="form-check">
<input type="checkbox" class="asset-checkbox" value="Printer"> Printer
</div>
</div>
</div>
</div>
<!-- Dynamic Asset Selection Section -->
<div class="col-md-12" id="assetContainer"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
<script>
$(document).ready(function () {
$('#CompletedCPSDatatable1').DataTable({
scrollX: true, // Enables horizontal scrolling
autoWidth: false, // Ensures manual column widths are respected
responsive: true, // Ensures better mobile view
dom: 'Bftip',
lengthMenu: [
[10, 50, 100, 200, -1],
['10 rows', '50 rows', '100 rows', 'Show all']
],
buttons: [
{extend: 'pageLength', className: 'btn btn-warning'},
{extend: 'copyHtml5', text: 'Copy', className: 'btn btn-secondary'},
{extend: 'excelHtml5', text: 'Excel', className: 'btn btn-secondary'},
{extend: 'csvHtml5', text: 'CSV', className: 'btn btn-secondary'},
{extend: 'pdfHtml5', text: 'PDF', className: 'btn btn-secondary'}
],
fixedHeader: true,
searching: true,
select: false,
processing: false
});
$('#CompletedCPSDatatable2').DataTable();
});
document.getElementById('buildingDropdown').addEventListener('change', function () {
const floorDropdown = document.getElementById('floorDropdown').parentElement;
const roomTypeDropdown = document.getElementById('roomTypeDropdown').parentElement;
const roomDropdown = document.getElementById('roomDropdown').parentElement;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (this.value) {
floorDropdown.style.display = 'block';
roomTypeDropdown.style.display = 'block';
roomDropdown.style.display = 'block';
} else {
floorDropdown.style.display = 'none';
roomTypeDropdown.style.display = 'none';
roomDropdown.style.display = 'none';
assetDropdown.style.display = 'none';
}
document.getElementById('floorDropdown').value = "";
document.getElementById('roomTypeDropdown').value = "";
document.getElementById('roomDropdown').value = "";
});
// Show assets only when all dropdowns are selected
function checkAllSelections() {
const building = document.getElementById('buildingDropdown').value;
const floor = document.getElementById('floorDropdown').value;
const roomType = document.getElementById('roomTypeDropdown').value;
const room = document.getElementById('roomDropdown').value;
const assetDropdown = document.getElementById('assetDropdown').parentElement;
if (building && floor && roomType && room) {
assetDropdown.style.display = 'block';
} else {
assetDropdown.style.display = 'none';
document.getElementById('assetContainer').innerHTML = ''; // Clear asset selection
}
}
document.getElementById('floorDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomTypeDropdown').addEventListener('change', checkAllSelections);
document.getElementById('roomDropdown').addEventListener('change', checkAllSelections);
// Initially hide all dependent dropdowns and asset section
window.addEventListener('DOMContentLoaded', function () {
document.getElementById('floorDropdown').parentElement.style.display = 'none';
document.getElementById('roomTypeDropdown').parentElement.style.display = 'none';
document.getElementById('roomDropdown').parentElement.style.display = 'none';
document.getElementById('assetDropdown').parentElement.style.display = 'none';
});
// Dynamic Asset Mapping with Quantity Input
document.querySelectorAll('.asset-checkbox').forEach(checkbox => {
checkbox.addEventListener('change', function () {
const assetContainer = document.getElementById('assetContainer');
const assetValue = this.value;
if (this.checked) {
const assetDiv = document.createElement('div');
assetDiv.classList.add('asset-item');
assetDiv.id = `asset-${assetValue}`;
assetDiv.innerHTML = `
<div class="row">
<div class="col-md-6">
<div class="form-group mt-2">
<label>${assetValue} Quantity *</label>
<input type="number" class="form-control" placeholder="Enter Quantity" required>
</div>
</div>
</div>
`;
assetContainer.appendChild(assetDiv);
} else {
const existingDiv = document.getElementById(`asset-${assetValue}`);
if (existingDiv) {
assetContainer.removeChild(existingDiv);
}
}
});
});
function openRoomMappingModal(buildingId, buildingName) {
$('#buildingName').text(buildingName);
const data = [
{sno: 1, floor: 'G', room: 'CLASSROOMS,LIBRARY', status: 'COMPLETED'},
{sno: 2, floor: 'G+1', room: '-', status: 'PENDING'},
{sno: 3, floor: 'G+2', room: '-', status: 'PENDING'}
];
$('#roomMappingBody').empty();
data.forEach((item) => {
$('#roomMappingBody').append(`
<tr>
<td>${item.sno}</td>
<td>${item.floor}</td>
<td>${item.room}</td>
<td>${item.status}</td>
<td>
<button class="btn btn-success" onclick="openAddRoomMapping('${item.room}', '${item.floor}')">Add Room Mapping</button>
</td>
</tr>
`);
});
$('#roomMappingModal').modal('show');
}
function openAddRoomMapping(roomName, floor) {
$('#roomFloor').text(floor);
$('#roomName').text(roomName);
$('#addRoomMappingModal').modal('show');
// Example Data (You can replace it with AJAX call)
let roomData = [
{sno: 1, roomType: 'Lab', roomName: 'Physics Lab', status: 'Pending'},
{sno: 2, roomType: 'Classroom', roomName: 'Class 10-A', status: 'Completed'}
];
let tbody = $('#addRoomMappingBody');
tbody.empty();
roomData.forEach((item) => {
tbody.append(`
<tr>
<td>${item.sno}</td>
<td>${item.roomType}</td>
<td>${item.roomName}</td>
<td>${item.status}</td>
<td><button class="btn btn-success" onclick="openAssetMappingModal('${item.roomName}', '${item.roomType}')">Add Room Mapping</button></td>
</tr>
`);
});
}
function openAssetMappingModal(roomName, roomType) {
$('#assetRoomName').text(`${roomName} (${roomType})`);
const assetData = [
{ sno: 1, roomType: roomType, assets: 'Projector', status: 'Completed' },
{ sno: 2, roomType: roomType, assets: 'Whiteboard', status: 'Pending' }
];
$('#assetMappingBody').empty();
assetData.forEach((item) => {
$('#assetMappingBody').append(`
<tr>
<td>${item.sno}</td>
<td>${item.roomType}</td>
<td>${item.assets}</td>
<td>${item.status}</td>
<td>
<button class="btn btn-success" onclick="openAssetModal('${roomName}', '${roomType}')">Add Room Mapping</button>
</td>
</tr>
`);
});
$('#assetMappingModal').modal('show');
}
// Function to Open Asset Modal
function openAssetModal(roomName, roomType) {
// Optional: Pre-fill the room name and type in the modal
$('#roomTypeDropdown').val(roomType.toLowerCase());
$('#roomDropdown').val(roomName.toLowerCase());
$('#assetModal').modal('show');
}
</script>
</html>

930
frontend/school/kitchen.html

@ -0,0 +1,930 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
.custom-card-wrapper {
padding: 0;
margin-left: -233px;
}
@media (max-width: 768px) {
.custom-card-wrapper {
margin-left: 0;
padding: 0 15px; /* Optional: adds spacing on small screens */
}
}
.kitchen-data-wrapper {
padding: 18px;
margin-top: -58px;
margin-left: -256px;
}
@media (max-width: 768px) {
.kitchen-data-wrapper {
margin-left: 0;
padding: 15px;
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card">
<div class="main-content" style="background-color: white;">
<div class="container">
<!-- Card 2: Other Details -->
<div class="col-md-12">
<div class="kitchen-data-wrapper">
<div class="card-header"><b>CMBFS-Kitchen</b></div>
<div id="kitchenDataContainer" style="display: none; padding: 15px;">
<table class="table table-bordered">
<tr>
<th>CMBFS Present</th>
<td id="td_k_cmbfs"></td>
<th>CMBFS Building</th>
<td id="td_k_cmbfs_building"></td>
</tr>
<tr>
<th>Noon Meal Present</th>
<td id="td_k_noon"></td>
<th>Noon Meal Building</th>
<td id="td_k_noon_building"></td>
</tr>
<tr>
<th>Vegetable Garden</th>
<td id="td_k_veg"></td>
<th>Anganwadi Present</th>
<td id="td_k_ang"></td>
</tr>
<tr>
<th>Anganwadi Unique No</th>
<td id="td_k_ang_unique"></td>
<th>Anganwadi Building</th>
<td id="td_k_ang_building"></td>
</tr>
</table>
<div class="text-center">
<button type="button" class="btn btn-primary" id="editKitchenBtn">Update</button>
</div>
</div>
</div>
<!-- This block wraps the form -->
<div id="kitchenFormContainer" style="display: none;">
<!-- Card 2: Other Details -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<div class="card-header"><b>CMBFS-Kitchens</b></div>
<div class="row" style=" padding: 15px;">
<div class="col-md-4 form-group">
<label>Is CMBFS-Kitchen Present <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="cmbfskitchenPresentYes"
name="cmbfskitchenPresent" value="1"> Yes
<input type="radio" id="cmbfskitchenPresentNo"
name="cmbfskitchenPresent" value="0"> No
</div>
</div>
<div class="col-md-4 form-group" id="CMBFSfield" style="display: none;">
<label>Individual Building Present <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="cmbfskitchenBuildingYes"
name="cmbfskitchenBuilding" value="1"> Yes
<input type="radio" id="cmbfskitchenBuildingNo"
name="cmbfskitchenBuilding" value="0"> No
</div>
</div>
</div>
</div>
</div>
<!-- card 2 -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<div class="card-header"><b>Noon Meal Center</b></div>
<div class="row" style=" padding: 15px;">
<div class="col-md-4 form-group">
<label>Is Noon Meal Kitchen Present <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="noonMealpresentYes" name="noonMealpresent"
value="1"> Yes
<input type="radio" id="noonMealpresentNo" name="noonMealpresent"
value="0"> No
</div>
</div>
<div id="noonMealfield" style="display: none;" class="col-12">
<div class="row">
<div class="col-md-6 form-group">
<label>Individual Building Present <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="noonMealBuildingYes"
name="noonMealBuilding" value="1"> Yes
<input type="radio" id="noonMealBuildingNo"
name="noonMealBuilding" value="0"> No
</div>
</div>
<div class="col-md-6 form-group">
<label>Presence of Vegetable Garden <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="vegetableGardenYes"
name="vegetableGarden" value="1"> Yes
<input type="radio" id="vegetableGardenNo"
name="vegetableGarden" value="0"> No
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- card -3 -->
<div class="col-md-12">
<div class="custom-card-wrapper">
<div class="card-header"><b>Anganwadi</b></div>
<div class="row" style=" padding: 15px;">
<div class="col-md-4 form-group">
<label>Is Anganwadi Present <span class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="anganwadiPresentYes" name="anganwadiPresent"
value="1"> Yes
<input type="radio" id="anganwadiPresentNo" name="anganwadiPresent"
value="0"> No
</div>
</div>
<div id="anganwadifield" style="display: none" class="col-12">
<div class="row">
<div class="col-md-6 form-group">
<label>Anganwadi unique Number<span
class="text-danger">*</span></label>
<input type="text" class="form-control"
placeholder="Enter Anganwadi unique Number"
id="anganwadiNumber" required />
</div>
<div class="col-md-4 form-group">
<label>Individual Building Present <span
class="text-danger">*</span></label>
<div class="radio-group">
<input type="radio" id="anganwadiBuildingYes"
name="anganwadiBuilding" value="1"> Yes
<input type="radio" id="anganwadiBuildingNo"
name="anganwadiBuilding" value="0"> No
</div>
</div>
</div>
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary" id="requestSubmitBtn"><i
class="ik ik-save"></i>Submit
</button>
<button type="reset" class="btn btn-secondary mr-2" id="resetButton"><i
class="ik ik-refresh-cw"></i>Reset
</button>
</div>
</div>
</div>
</div>
<div id="pageLoader"
style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status"
style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="editKitchenModal" tabindex="-1" aria-labelledby="editKitchenModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form id="kitchenForm">
<div class="modal-header">
<h5 class="modal-title">Edit Kitchen Details</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden>&times;</span></button>
</div>
<div class="modal-body">
<!-- Kitchen Form -->
<div class="row mb-3">
<div class="col-md-6">
<label>Is CMBFS-Kitchen Present? *</label>
<div class="radio-group">
<input type="radio" name="modalcmbfskitchenPresent" value="1"> Yes
<input type="radio" name="modalcmbfskitchenPresent" value="0"> No
</div>
</div>
<div class="col-md-6" id="modalCMBFSfield" style="display: none;">
<label>Individual Building Present *</label>
<div class="radio-group">
<input type="radio" name="modalcmbfskitchenBuilding" value="1"> Yes
<input type="radio" name="modalcmbfskitchenBuilding" value="0"> No
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label>Is Noon Meal Kitchen Present? *</label>
<div class="radio-group">
<input type="radio" name="modalnoonMealpresent" value="1"> Yes
<input type="radio" name="modalnoonMealpresent" value="0"> No
</div>
</div>
</div>
<div class="row mb-3" id="modalnoonMealfield" style="display: none;">
<div class="col-md-6">
<label>Individual Building Present *</label>
<div class="radio-group">
<input type="radio" name="modalnoonMealBuilding" value="1"> Yes
<input type="radio" name="modalnoonMealBuilding" value="0"> No
</div>
</div>
<div class="col-md-6">
<label>Presence of Vegetable Garden *</label>
<div class="radio-group">
<input type="radio" name="modalvegetableGarden" value="1"> Yes
<input type="radio" name="modalvegetableGarden" value="0"> No
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label>Is Anganwadi Present? *</label>
<div class="radio-group">
<input type="radio" name="modalanganwadiPresent" value="1"> Yes
<input type="radio" name="modalanganwadiPresent" value="0"> No
</div>
</div>
</div>
<div class="row mb-3" id="modalanganwadifield" style="display: none;">
<div class="col-md-6">
<label>Anganwadi Unique Number *</label>
<input type="text" id="modalanganwadiNumber" class="form-control" />
</div>
<div class="col-md-6">
<label>Individual Building Present *</label>
<div class="radio-group">
<input type="radio" name="modalanganwadiBuilding" value="1"> Yes
<input type="radio" name="modalanganwadiBuilding" value="0"> No
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="updateSubmitBtn">Submit</button>
<button type="reset" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
document.querySelectorAll('input[name="cmbfskitchenPresent"]').forEach(radio => {
radio.addEventListener('change', function () {
const CMBFSfieldDiv = document.getElementById('CMBFSfield');
if (this.value === '1') {
CMBFSfieldDiv.style.display = 'block'; // Show the input field
} else {
CMBFSfieldDiv.style.display = 'none'; // Hide the input field
document.querySelectorAll('input[name="cmbfskitchenBuilding"]').forEach(radio => {
radio.checked = false;
});
}
});
});
document.querySelectorAll('input[name="noonMealpresent"]').forEach(radio => {
radio.addEventListener('change', function () {
const noonMealfieldDiv = document.getElementById('noonMealfield');
if (this.value === '1') {
noonMealfieldDiv.style.display = 'block'; // Show the input field
} else {
noonMealfieldDiv.style.display = 'none'; // Hide the input field
document.querySelectorAll('input[name="noonMealBuilding"]').forEach(radio => {
radio.checked = false;
});
document.querySelectorAll('input[name="vegetableGarden"]').forEach(radio => {
radio.checked = false;
});
}
});
});
document.querySelectorAll('input[name="anganwadiPresent"]').forEach(radio => {
radio.addEventListener('change', function () {
const anganwadifieldDiv = document.getElementById('anganwadifield');
if (this.value === '1') {
anganwadifieldDiv.style.display = 'block'; // Show the input field
} else {
anganwadifieldDiv.style.display = 'none'; // Hide the input field
document.querySelectorAll('input[name="anganwadiBuilding"]').forEach(radio => {
radio.checked = false;
});
document.getElementById('anganwadiNumber').value = '';
}
});
});
$("input[name='modalcmbfskitchenPresent']").change(function () {
if ($(this).val() === "1") {
$("#modalCMBFSfield").show();
} else {
$("#modalCMBFSfield").hide();
}
});
// 2. Toggle Noon Meal building and garden fields
$("input[name='modalnoonMealpresent']").change(function () {
if ($(this).val() === "1") {
$("#modalnoonMealfield").show();
} else {
$("#modalnoonMealfield").hide();
}
});
// 3. Toggle Anganwadi fields
$("input[name='modalanganwadiPresent']").change(function () {
if ($(this).val() === "1") {
$("#modalanganwadifield").show();
} else {
$("#modalanganwadifield").hide();
}
});
});
$(document).ready(function () {
const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId");
$('input[name="school_id"]').val(schoolId);
function toggleField(radioGroup, targetDiv, resetSelectors = []) {
document.querySelectorAll(`input[name="${radioGroup}"]`).forEach(radio => {
radio.addEventListener('change', function () {
if (this.value === '1') {
document.getElementById(targetDiv).style.display = 'block';
} else {
document.getElementById(targetDiv).style.display = 'none';
resetSelectors.forEach(sel => {
$(sel).prop('checked', false);
if ($(sel).is('input[type="text"]')) $(sel).val('');
});
}
});
});
}
toggleField('cmbfskitchenPresent', 'CMBFSfield', ['input[name="cmbfskitchenBuilding"]']);
toggleField('noonMealpresent', 'noonMealfield', ['input[name="noonMealBuilding"]', 'input[name="vegetableGarden"]']);
toggleField('anganwadiPresent', 'anganwadifield', ['input[name="anganwadiBuilding"]', '#anganwadiNumber']);
// ---------------- Data Fetch -------------------
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/checkKitchenDetails',
type: 'GET',
data: {school_id: schoolId},
success: function (response) {
const hasValidData = response && response[0] && response[0].Data && Object.values(response[0].Data).some(val => val !== null && val !== false && val !== "");
if (hasValidData) {
const data = response[0].Data;
//const yesNo = val => val === true ? 'Yes' : 'No';
const yesNo = val => val === true ? 'Yes' : val === false ? 'No' : '-';
$('#td_k_cmbfs').text(yesNo(data.is_cmbfs));
$('#td_k_cmbfs_building').text(yesNo(data.is_cmbfsIndividual));
$('#td_k_noon').text(yesNo(data.is_noonmeal));
$('#td_k_noon_building').text(yesNo(data.is_noonIndividual));
$('#td_k_veg').text(yesNo(data.is_vegGarden));
$('#td_k_ang').text(yesNo(data.is_anganwadi));
$('#td_k_ang_unique').text(data.anganwadi_unique || '-');
$('#td_k_ang_building').text(yesNo(data.is_anganwadiIndividual));
$('#kitchenDataContainer').show(); // ✅ Show table
$('#kitchenFormContainer').hide(); // ❌ Hide form
$('#editKitchenBtn').data('kitchenData', data);
} else {
$('#kitchenDataContainer').hide(); // ❌ Hide table
$('#kitchenFormContainer').show(); // ✅ Show form
}
},
error: function () {
$('#kitchenDataContainer').hide(); // ❌ hide table
$('#kitchenFormContainer').show(); // ✅ show form
}
});
$('input[name="modalanganwadiPresent"]').on('change', function () {
if (this.value === '1') {
$('#editKitchenModalAnganwadiField').show();
} else {
$('#editKitchenModalAnganwadiField').hide();
// Clear the Anganwadi Building radio buttons
$('input[name="modalanganwadiBuilding"]').prop('checked', false);
// Clear the Anganwadi Number field
$('#modalanganwadiNumber').val('');
}
});
$('input[name="modalnoonMealpresent"]').on('change', function () {
if (this.value === '1') {
$('#editKitchenModalNoonField').show();
} else {
$('#editKitchenModalNoonField').hide();
$('input[name="modalnoonMealBuilding"]').prop('checked', false);
$('input[name="modalvegetableGarden"]').prop('checked', false);
}
});
$('input[name="modalcmbfskitchenPresent"]').on('change', function () {
if (this.value === '1') {
$('#editKitchenModalCMBFSfield').show();
} else {
$('#editKitchenModalCMBFSfield').hide();
$('input[name="modalcmbfskitchenBuilding"]').prop('checked', false);
}
});
// ---------------- On Update Button -------------------
$('#editKitchenBtn').click(function () {
const data = $(this).data('kitchenData');
$(`input[name="modalcmbfskitchenPresent"][value="${data.is_cmbfs ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalcmbfskitchenBuilding"][value="${data.is_cmbfsIndividual ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalnoonMealpresent"][value="${data.is_noonmeal ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalnoonMealBuilding"][value="${data.is_noonIndividual ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalvegetableGarden"][value="${data.is_vegGarden ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalanganwadiPresent"][value="${data.is_anganwadi ? 1 : 0}"]`).prop('checked', true);
$(`input[name="modalanganwadiBuilding"][value="${data.is_anganwadiIndividual ? 1 : 0}"]`).prop('checked', true);
$('#modalanganwadiNumber').val(data.anganwadi_unique || '');
// 👇 Force the toggle to display the dependent fields
$(`#editKitchenModal input[name="modalcmbfskitchenPresent"]:checked`).trigger('change');
$(`#editKitchenModal input[name="modalnoonMealpresent"]:checked`).trigger('change');
$(`#editKitchenModal input[name="modalanganwadiPresent"]:checked`).trigger('change');
// Show modal
const kitchenModal = new bootstrap.Modal(document.getElementById('editKitchenModal'));
kitchenModal.show();
});
// --- Toggle logic for modal form fields inside editKitchenModal ---
function toggleModalField(radioGroupName, fieldId, resetSelectors = []) {
$(`#editKitchenModal input[name="${radioGroupName}"]`).on('change', function () {
if (this.value === '1') {
$(`#editKitchenModal #${fieldId}`).show();
} else {
$(`#editKitchenModal #${fieldId}`).hide();
resetSelectors.forEach(sel => {
$(`#editKitchenModal ${sel}`).prop('checked', false);
if ($(sel).is('input[type="text"]')) $(sel).val('');
});
}
});
}
// Apply for each group
toggleModalField('cmbfskitchenPresent', 'CMBFSfield', ['input[name="cmbfskitchenBuilding"]']);
toggleModalField('noonMealpresent', 'noonMealfield', ['input[name="noonMealBuilding"]', 'input[name="vegetableGarden"]']);
toggleModalField('anganwadiPresent', 'anganwadifield', ['input[name="anganwadiBuilding"]', '#anganwadiNumber']);
document.getElementById('anganwadiNumber').addEventListener('input', function () {
// Keep only alphanumeric characters
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
document.getElementById('modalanganwadiNumber').addEventListener('input', function () {
// Keep only alphanumeric characters
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
$(document).on('click', '#requestSubmitBtn', function () {
let cmbfskitchenPresent = $('input[name="cmbfskitchenPresent"]:checked').val();
let cmbfskitchenBuilding = null;
if (cmbfskitchenPresent === '1') {
cmbfskitchenBuilding = $('input[name="cmbfskitchenBuilding"]:checked').val();
if (!cmbfskitchenBuilding) {
Swal.fire({
icon: 'warning',
title: 'Validation Error!',
text: 'Individual Building Present is required for CMBFS kitchen .',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
}
let noonMealpresent = $('input[name="noonMealpresent"]:checked').val();
let noonMealBuilding = null;
let vegetableGarden = null;
if (noonMealpresent === '1') {
noonMealBuilding = $('input[name="noonMealBuilding"]:checked').val();
if (!noonMealBuilding) {
Swal.fire({
icon: 'warning',
title: 'Validation Error!',
text: 'Individual Building Present is required for Noon Meal Center .',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
vegetableGarden = $('input[name="vegetableGarden"]:checked').val();
if (!vegetableGarden) {
Swal.fire({
icon: 'warning',
title: 'Validation Error!',
text: 'Presence of Vegetable Garden is required .',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
}
let anganwadiPresent = $('input[name="anganwadiPresent"]:checked').val();
let anganwadiBuilding = null;
let anganwadiNumber = null;
if (anganwadiPresent === '1') {
anganwadiNumber = $('#anganwadiNumber').val();
anganwadiBuilding = $('input[name="anganwadiBuilding"]:checked').val();
if (!anganwadiNumber) {
Swal.fire({
icon: 'warning',
title: 'Validation Error!',
text: 'AnganwadiNumber is required',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
if (!anganwadiBuilding) {
Swal.fire({
icon: 'warning',
title: 'Validation Error!',
text: 'Individual Building Present is required for Anganwadi.',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
}
// let school_id = 1;
console.log("cmbfskitchenPresent=", cmbfskitchenPresent);
console.log("anganwadiBuilding=", anganwadiBuilding);
console.log("noonMealpresent=", noonMealpresent);
console.log("noonMealBuilding=", noonMealBuilding);
console.log("vegetableGarden=", vegetableGarden);
console.log("anganwadiPresent=", anganwadiPresent);
console.log("anganwadiNumber=", anganwadiNumber);
console.log("anganwadiBuilding=", anganwadiBuilding);
console.log("school_id=", schoolId);
// Validate inputs
let fields = {
"Is CMBFS-Kitchen Present": cmbfskitchenPresent,
"Is noonMealpresent Present": noonMealpresent,
"Is Anganwadi Present": anganwadiPresent,
};
for (let key in fields) {
if (!fields[key] || isNaN(fields[key])) {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: `Please enter ${key}.`,
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return; // Stop execution if validation fails
}
}
// Prepare Data for AJAX
let requestData = {
is_cmbfs: cmbfskitchenPresent,
is_cmbfsIndividual: cmbfskitchenBuilding,
is_noonmeal: noonMealpresent,
is_noonIndividual: noonMealBuilding,
is_vegGarden: vegetableGarden,
is_anganwadi: anganwadiPresent,
anganwadi_unique: anganwadiNumber || null,
is_anganwadiIndividual: anganwadiBuilding,
school_id: schoolId
};
$('#requestSubmitBtn').prop('disabled', true).text('Processing...');
$('#pageLoader').show();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/saveKitchen',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $.param(requestData),
success: function (response) {
$('#pageLoader').hide();
$('#requestSubmitBtn').prop('disabled', false).text('Submit');
Swal.fire({
icon: 'success',
title: 'Success',
text: response,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
$('#requestSubmitBtn').prop('disabled', false).text('Submit');
location.reload();
}
});
},
error: function (xhr, status, error) {
$('#pageLoader').hide();
$('#requestSubmitBtn').prop('disabled', false).text('Submit');
let errorMessage = xhr.responseText;
Swal.fire({
icon: 'error',
title: 'Error',
text: errorMessage,
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
console.error('Error:', xhr.responseText);
}
});
});
function resetFacilityFields() {
console.log("Reset button clicked - Facilities");
// Uncheck all radio buttons
$('input[type="radio"]').prop('checked', false);
// Clear input fields
$('#anganwadiNumber').val('');
// Hide dependent sections
$('#CMBFSfield, #noonMealfield, #anganwadifield').hide();
}
// Event Listener for Reset Button
$(document).on('click', '#resetButton', function (event) {
event.preventDefault();
resetFacilityFields();
});
$(document).on('click', '#updateSubmitBtn', function (e) {
e.preventDefault();
submitModalKitchenUpdate();
});
function submitModalKitchenUpdate() {
let cmbfskitchenPresent = $('#editKitchenModal input[name="modalcmbfskitchenPresent"]:checked').val();
let cmbfskitchenBuilding = cmbfskitchenPresent === '1' ? $('#editKitchenModal input[name="modalcmbfskitchenBuilding"]:checked').val() : null;
/*if (cmbfskitchenPresent === '1' && !cmbfskitchenBuilding) {
return Swal.fire('Validation Error!', 'Individual Building Present is required for CMBFS kitchen.', 'warning');
}*/
if (cmbfskitchenPresent === '1' && !cmbfskitchenBuilding) {
return Swal.fire({
title: 'Validation Error!',
text: 'Individual Building Present is required for CMBFS kitchen.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
let noonMealpresent = $('#editKitchenModal input[name="modalnoonMealpresent"]:checked').val();
let noonMealBuilding = noonMealpresent === '1' ? $('#editKitchenModal input[name="modalnoonMealBuilding"]:checked').val() : null;
let vegetableGarden = noonMealpresent === '1' ? $('#editKitchenModal input[name="modalvegetableGarden"]:checked').val() : null;
/*if (noonMealpresent === '1' && (!noonMealBuilding || !vegetableGarden)) {
return Swal.fire('Validation Error!', 'Fields under Noon Meal Center are required.', 'warning');
}*/
if (noonMealpresent === '1' && (!noonMealBuilding || !vegetableGarden)) {
return Swal.fire({
title: 'Validation Error!',
text: 'Fields under Noon Meal Center are required.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
let anganwadiPresent = $('#editKitchenModal input[name="modalanganwadiPresent"]:checked').val();
let anganwadiBuilding = anganwadiPresent === '1' ? $('#editKitchenModal input[name="modalanganwadiBuilding"]:checked').val() : null;
let anganwadiNumber = anganwadiPresent === '1' ? $('#editKitchenModal #modalanganwadiNumber').val() : null;
/*if (anganwadiPresent === '1' && (!anganwadiBuilding || !anganwadiNumber)) {
return Swal.fire('Validation Error!', 'All Anganwadi fields are required.', 'warning');
}*/
if (anganwadiPresent === '1' && (!anganwadiBuilding || !anganwadiNumber)) {
return Swal.fire({
title: 'Validation Error!',
text: 'All Anganwadi fields are required.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
const requestData = {
is_cmbfs: cmbfskitchenPresent,
is_cmbfsIndividual: cmbfskitchenBuilding,
is_noonmeal: noonMealpresent,
is_noonIndividual: noonMealBuilding,
is_vegGarden: vegetableGarden,
is_anganwadi: anganwadiPresent,
anganwadi_unique: anganwadiNumber || null,
is_anganwadiIndividual: anganwadiBuilding,
school_id: schoolId
};
$('#updateSubmitBtn').prop('disabled', true).text('Updating...');
$('#pageLoader').show();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/updateKitchenDetails',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $.param(requestData),
success: function (response) {
$('#pageLoader').hide();
$('#updateSubmitBtn').prop('disabled', false).text('Submit');
//Swal.fire('Success', response, 'success').
Swal.fire({
title: 'Success',
text: 'Kitchen details updated successfully!!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
})
.then(() => {
$('#editKitchenModal').modal('hide');
location.reload();
});
},
error: function (xhr) {
$('#pageLoader').hide();
$('#updateSubmitBtn').prop('disabled', false).text('Submit');
//Swal.fire('Error', xhr.responseText || 'Failed to update.', 'error');
Swal.fire({
title: 'Error',
text: xhr.responseText || 'Failed to update.',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
}
});
</script>
</body>
</html>

982
frontend/school/otherdetails.html

@ -0,0 +1,982 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content">
<div class="container">
<div class="header">School Module - Master Details</div>
<hr style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;">
<!-- Card 1: School Information -->
<div class="col-md-12">
<div class="card">
<div class="card-header" style="background-color: #404E67; color: white;">
School Information
</div>
<table class="table" id="schoolInfoTable" >
<!-- Table rows will be dynamically injected -->
</table>
</div>
</div>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item"><a class="nav-link active" id="otherDetailsTab" href="#">Other Details</a>
</li>
<li class="nav-item"><a class="nav-link" id="staffDetailsTab" data-toggle="tab"
href="/gcc/school/staffdetails" role="tab" aria-controls="staffdetails"
aria-selected="false">Staff
Details</a></li>
<li class="nav-item"><a class="nav-link" id="staffDetailsTab" data-toggle="tab"
href="/gcc/school/studentdetails" role="tab" aria-controls="staffdetails"
aria-selected="false">Student
Details</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="buildingDetailstab"
href="#">Buildings</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="playgroundDetailstab"
data-toggle="tab" href="/gcc/school/playground" role="tab" aria-controls="playground"
aria-selected="false">Playground</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="drinkingwaterDetailstab"
data-toggle="tab" href="/gcc/school/drinkingwater" role="tab"
aria-controls="drinkingwater" aria-selected="false">Drinking
Water</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="tioletsDetailstab"
data-toggle="tab" href="/gcc/school/toilets" role="tab" aria-controls="tiolets"
aria-selected="false">Toilets</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="itassestsDetailstab"
href="#">School Assets</a></li>
</li>
<li class="nav-item" role="presentation"><a class="nav-link" id="kitchenDetailstab"
data-toggle="tab" href="/gcc/school/kitchen" role="tab" aria-controls="kitchen"
aria-selected="false">Kitchen</a></li>
</ul>
<div id="itassestsDetailsSection" style="display: none;">
<ul class="nav nav-tabs" id="itAssetsSubTabs">
<li class="nav-item"><a class="nav-link active" id="RoomAssetTab"
data-url="/gcc/school/roomassets" href="#">Rooms Assets Mapping</a></li>
<li class="nav-item"><a class="nav-link" id="AssetManageTab"
data-url="/gcc/school/assetmanagement" href="#">IT Asset Management</a></li>
<li class="nav-item"><a class="nav-link" id="AddElectricalAssetTab"
data-url="/gcc/school/addelectricalasset" href="#">Electrical Asset Management</a></li>
<li class="nav-item"><a class="nav-link" id="AddFurnitureAssetTab"
data-url="/gcc/school/addfurnitureasset" href="#">Furniture Asset Management</a></li>
</ul>
<div id="itAssetsContent"></div>
</div>
<!-- This section should be initially hidden -->
<div id="buildingDetailsSection" style="display: none;">
<!-- Place for sub-tabs -->
<ul id="buildingSubTabs" class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" id="buildingListTab" data-url="/gcc/school/building"
href="#">Building List</a>
</li>
<li class="nav-item">
<a class="nav-link" id="roomListTab" data-url="/gcc/school/room" href="#">Room List</a>
</li>
</ul>
<!-- Content loaded by tab click -->
<div id="buildingContent"></div>
</div>
<div id="staffDetailsSection" style="display: none;">Loading
staff details...</div>
<div id="playgroundDetailsSection" style="display: none;">
Loading playground details...</div>
<div id="drinkingwaterDetailsSection" style="display: none;">
Loading drinking water details...</div>
<div id="toiletsDetailsSection" style="display: none;">
Loading toilets details...</div>
<div id="itassestsDetailsSection" style="display: none;">
Loading IT assets details...</div>
<div id="kitchenDetailsSection" style="display: none;">
Loading kitchen details...</div>
<!-- Single Card Wrapper -->
<div class="col-md-12" id="otherDetailsSection" style="display: none;">
<div class="card" style="padding: 18px; margin-top: 27px;">
<div class="card-header">
<b>Site & Built Up Area</b>
</div>
<!-- Read-Only View -->
<div id="otherDetailsReadOnlyView" style="display: none; text-align: center;">
<br>
<div style="display: inline-block; width: 100%; max-width: 900px; text-align: left;">
<table class="table table-bordered">
<tbody>
<tr>
<td><b> Site Area (Acre)</b></td>
<td id="ro_land_area"></td>
<td><b> Built-up Area (Sq. ft)</b></td>
<td id="ro_buildup_area"></td>
</tr>
<tr>
<td><b>Compound Wall</b></td>
<td id="ro_compoundWall"></td>
<td><b>Name Board</b></td>
<td id="ro_nameBoard"></td>
</tr>
<tr>
<td><b>PA System</b></td>
<td id="ro_paSystem"></td>
<td><b>Electric Bell</b></td>
<td id="ro_electricBell"></td>
</tr>
<tr>
<td><b>Generator Set</b></td>
<td id="ro_generatorSet"></td>
<td colspan="2"></td>
</tr>
</tbody>
</table>
<div class="text-center">
<button type="button" class="btn btn-primary"
id="updateOtherDetailsBtn">Update</button>
</div>
</div>
</div>
<!-- Form View -->
<div id="otherDetailsSectionform" style="display: none;">
<form id="schoolDetailsForm">
<div class="row" style="padding: 15px;">
<div class="col-md-6 form-group">
<label>Approx Site Area of the School (In Acre) *</label>
<input type="text" id="land_area" class="form-control"
placeholder="Enter in Acre" required />
</div>
<div class="col-md-6 form-group">
<label> Approx Built Up Area of the School (In Sq. ft) *</label>
<input type="text" id="buildup_area" class="form-control"
placeholder="Enter in Sq. ft" required />
</div>
</div>
<div class="card-header"><b>Compound & Name Board</b></div>
<div class="row" style="padding: 15px;">
<div class="col-md-6 form-group">
<label>Presence of Compound Wall *</label>
<div class="radio-group">
<input type="radio" name="compoundWall" value="Yes"> Yes
<input type="radio" name="compoundWall" value="No"> No
</div>
</div>
<div class="col-md-6 form-group">
<label>Presence of School Name Board (New Board) *</label>
<div class="radio-group">
<input type="radio" name="nameBoard" value="Yes"> Yes
<input type="radio" name="nameBoard" value="No"> No
</div>
</div>
</div>
<div class="card-header"><b>Electrical</b></div>
<div class="row" style="padding: 15px;">
<div class="col-md-4 form-group">
<label>Is PA System Available? *</label>
<div class="radio-group">
<input type="radio" name="paSystem" value="Yes"> Yes
<input type="radio" name="paSystem" value="No"> No
</div>
</div>
<div class="col-md-4 form-group">
<label>Is Electric Bell Available? *</label>
<div class="radio-group">
<input type="radio" name="electricBell" value="Yes"> Yes
<input type="radio" name="electricBell" value="No"> No
</div>
</div>
<div class="col-md-4 form-group">
<label>Is Generator Set Available? *</label>
<div class="radio-group">
<input type="radio" name="generatorSet" value="Yes"> Yes
<input type="radio" name="generatorSet" value="No"> No
</div>
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary" id="requestSubmitBtn"><i
class="ik ik-save"></i> Submit</button>
<button type="reset" class="btn btn-secondary mr-2" id="resetButton"><i
class="ik ik-refresh-cw"></i> Reset</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
<!-- Form -->
<!-- Modal -->
<div class="modal fade" id="otherDetailsModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="otherDetailsModalLabel"
aria-hidden="true" >
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="otherDetailsModalLabel">Update Other
Details</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div id="otherDetailsFormWrapper">
<form id="updateOtherDetailsForm">
<div class="row mb-3">
<div class="col-md-6">
<label> Approx Site Area of the School (In Acre) *</label>
<input type="text" id="modal_land_area" class="form-control"
placeholder="Enter in Acres" required />
</div>
<div class="col-md-6">
<label> Approx Built Up Area of the School (In Sq. ft)
*</label>
<input type="text" id="modal_buildup_area" class="form-control"
placeholder="Enter in Sq. ft" required />
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label>Presence of Compound Wall *</label>
<div>
<input type="radio" name="modalcompoundWall" value="1"> Yes
<input type="radio" name="modalcompoundWall" value="0"> No
</div>
</div>
<div class="col-md-6">
<label>Presence of School Name Board (New Board)* </label>
<div>
<input type="radio" name="modalnameBoard" value="1"> Yes
<input type="radio" name="modalnameBoard" value="0">
No
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-4">
<label>Is PA System Available? *</label>
<div>
<input type="radio" name="modalpaSystem" value="1">
Yes
<input type="radio" name="modalpaSystem" value="0">
No
</div>
</div>
<div class="col-md-4">
<label>Is Electric Bell Available? *</label>
<div>
<input type="radio" name="modalelectricBell" value="1"> Yes
<input type="radio" name="modalelectricBell" value="0"> No
</div>
</div>
<div class="col-md-4">
<label>Is Generator Set Available? *</label>
<div>
<input type="radio" name="modalgeneratorSet" value="1"> Yes
<input type="radio" name="modalgeneratorSet" value="0"> No
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" id="requestSubmitBtn">Submit</button>
<!--<button type="reset" class="btn btn-secondary btn-gap"
id="resetButton">Reset</button>-->
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
// jQuery or vanilla JS to open the modal
$(document).on('click', '#updateOtherDetailsBtn', function () {
$('#otherDetailsModal').modal('show');
});
const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId");
$(document).ready(function () {
/* const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId"); */
$.ajax({
type: 'GET',
url: '/gcc/api/gccschool/schoolproperty/getSchoolDetails',
data: {schoolId: schoolId},
success: function (data) {
console.log(data);
const html = `
<tr><th>School Name:</th><td>${data.school_name}</td><th>UDISE Code:</th><td>${data.udise}</td></tr>
<tr><th>Category:</th><td>${data.category}</td><th>Ward:</th><td>${data.division}</td></tr>
<tr></td><th>Zone:</th><td>${data.zone}</td>
<th>Address:</th><td>${data.address}</td></tr>
`;
$('#schoolInfoTable').html(html);
}
});
$('.nav-link').click(function (e) {
e.preventDefault();
let url = $(this).attr(
'href');
let targetId = $(this)
.attr('id');
// Hide all sections
$(
'#otherDetailsSection, #staffDetailsSection, #buildingDetailsSection, #playgroundDetailsSection, #drinkingwaterDetailsSection, #toiletsDetailsSection, #itassestsDetailsSection, #kitchenDetailsSection')
.hide();
// Remove active class from all nav links
$('.nav-link').removeClass(
'active');
$(this).addClass('active');
// Handle Section Display and Load Data
switch (targetId) {
case 'otherDetailsTab':
$('#otherDetailsSection').show();
$('#schoolDetailsForm')[0].reset();
break;
case 'staffDetailsTab':
$(
'#staffDetailsSection')
.show();
loadData(url,
'#staffDetailsSection');
break;
case 'buildingDetailstab':
$('#buildingDetailsSection').show();
// Set Building List as default
$('#buildingListTab').addClass('active');
$('#roomListTab').removeClass('active');
// Load Building List content
$('#buildingContent').html('<p>Loading Building List...</p>');
loadData('/gcc/school/building', '#buildingContent');
break;
case 'roomListTab':
$('#buildingDetailsSection').show();
// Reset sub-tab states
$('#buildingListTab').removeClass('active');
$('#roomListTab').addClass('active');
// Load Building List by default
$('#buildingContent').html('<p>Loading Room List...</p>');
loadData('/gcc/school/room', '#buildingContent');
break;
case 'playgroundDetailstab':
$(
'#playgroundDetailsSection')
.show();
loadData(url,
'#playgroundDetailsSection');
break;
case 'drinkingwaterDetailstab':
$(
'#drinkingwaterDetailsSection')
.show();
loadData(url,
'#drinkingwaterDetailsSection');
break;
case 'tioletsDetailstab':
$(
'#toiletsDetailsSection')
.show();
loadData(url,
'#toiletsDetailsSection');
break;
case 'kitchenDetailstab':
$(
'#kitchenDetailsSection')
.show();
loadData(url,
'#kitchenDetailsSection');
break;
case 'itassestsDetailstab':
$('#itassestsDetailsSection').show();
// Set Building List as default
$('#RoomAssetTab').addClass('active');
$('#AssetManageTab').removeClass('active');
$('#AddElectricalAssetTab').removeClass('active');
$('#AddFurnitureAssetTab').removeClass('active');
// Load Building List content
$('#itAssetsContent').html('<p>Loading Asset Room List...</p>');
loadData('/gcc/school/roomassets', '#itAssetsContent');
break;
case 'AssetManageTab':
$('#itassestsDetailsSection').show();
// Reset sub-tab states
$('#AssetManageTab').addClass('active');
$('#RoomAssetTab').removeClass('active');
$('#AddElectricalAssetTab').removeClass('active');
$('#AddFurnitureAssetTab').removeClass('active');
// Load Building List by default
$('#itAssetsContent').html('<p>Loading Asset List...</p>');
loadData('/gcc/school/assetmanagement', '#itAssetsContent');
break;
case 'AddElectricalAssetTab':
$('#itassestsDetailsSection').show();
// Reset sub-tab states
$('#AssetManageTab').removeClass('active');
$('#RoomAssetTab').removeClass('active');
$('#AddElectricalAssetTab').addClass('active');
$('#AddFurnitureAssetTab').removeClass('active');
// Load Building List by default
$('#itAssetsContent').html('<p>Loading Add Electrical Asset content...</p>');
loadData('/gcc/school/addelectricalasset', '#itAssetsContent');
break;
case 'AddFurnitureAssetTab':
$('#itassestsDetailsSection').show();
// Reset sub-tab states
$('#AssetManageTab').removeClass('active');
$('#RoomAssetTab').removeClass('active');
$('#AddElectricalAssetTab').removeClass('active');
$('#AddFurnitureAssetTab').addClass('active');
// Load Building List by default
$('#itAssetsContent').html('<p>Loading Add Furniture Asset content...</p>');
loadData('/gcc/school/addfurnitureasset', '#itAssetsContent');
break;
}
});
// Handle IT Assets Sub-tabs Click
/*$('#itAssetsSubTabs').on('click', '.nav-link', function (e) {
e.preventDefault();
let url = $(this).attr('href');
$('#itAssetsSubTabs .nav-link').removeClass('active');
$(this).addClass('active');
// Ensure #itAssetsContent is cleared before loading
$('#itAssetsContent').html('<p>Loading...</p>');
$.get(url, function (data) {
$('#itAssetsContent').html(data);
}).fail(function () {
$('#itAssetsContent').html('<p>Error loading data. Please try again later.</p>');
});
});*/
// Click event for Room List Tab
/* $(document).on('click', '#roomListTab', function (e) {
e.preventDefault();
// Show the main building section
$('#buildingDetailsSection').show();
// Set active tab
$('#roomListTab').addClass('active');
$('#buildingListTab').removeClass('active');
// Load Room List content
$('#buildingContent').html('<p>Loading Room List...</p>');
loadData('/gcc/school/room', '#buildingContent');
}); */
// Click event for Building List Tab
$(document).on('click', '#buildingListTab', function (e) {
e.preventDefault();
// Show the main building section
$('#buildingDetailsSection').show();
// Set active tab
$('#buildingListTab').addClass('active');
$('#roomListTab').removeClass('active');
// Load Building List content
$('#buildingContent').html('<p>Loading Building List...</p>');
loadData('/gcc/school/building', '#buildingContent');
});
$(document).on('click', '#RoomAssetTab', function (e) {
e.preventDefault();
// Show the main building section
$('#itassestsDetailsSection').show();
// Set active tab
$('#RoomAssetTab').addClass('active');
$('#AssetManageTab').removeClass('active');
// Load Building List content
$('#itAssetsContent').html('<p>Loading Asset Room List...</p>');
loadData('/gcc/school/roomassets', '#itAssetsContent');
});
// 🔁 Delegate Click Event for Building Sub-tabs
/* $(document).on('click', '#buildingSubTabs .nav-link', function (e) {
e.preventDefault();
// Remove active class from all sub-tabs
$('#buildingSubTabs .nav-link').removeClass('active');
$(this).addClass('active');
// Get the correct API URL from `data-url`
let contentUrl = $(this).data('url');
// Load content dynamically
if (contentUrl) {
$('#buildingContent').html('<p>Loading...</p>');
$.get(contentUrl, function (data) {
$('#buildingContent').html(data);
}).fail(function () {
$('#buildingContent').html('<p>Error loading data. Please try again later.</p>');
});
}
});*/
});
// Function to load data via AJAX
function loadData(url, sectionId) {
$.get(url, function (data) {
$(sectionId).html(data);
}).fail(function () {
$(sectionId).html('<p>Error loading data. Please try again later.</p>');
});
}
document.getElementById('buildup_area').addEventListener('input', function () {
// Allow only whole numbers (no decimals)
this.value = this.value.replace(/[^0-9]/g, '');
// Prevent negative values
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('modal_buildup_area').addEventListener('input', function () {
// Allow only whole numbers (no decimals)
this.value = this.value.replace(/[^0-9]/g, '');
// Prevent negative values
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('land_area').addEventListener('input', function () {
// Remove any non-numeric characters except decimal point
this.value = this.value.replace(/[^0-9.]/g, '');
// Ensure the value is nfot negative
if (this.value < 0) {
this.value = '';
}
});
document.getElementById('modal_land_area').addEventListener('input', function () {
// Remove any non-numeric characters except decimal point
this.value = this.value.replace(/[^0-9.]/g, '');
// Ensure the value is nfot negative
if (this.value < 0) {
this.value = '';
}
});
$('#requestSubmitBtn').on('click', function (e) {
e.preventDefault();
let landArea = $('#land_area').val().trim();
let buildupArea = $('#buildup_area').val().trim();
let isCompound = $('input[name="compoundWall"]:checked').val();
let isNameboard = $('input[name="nameBoard"]:checked').val();
let isPasystem = $('input[name="paSystem"]:checked').val();
let isBell = $('input[name="electricBell"]:checked').val();
let isGenerator = $('input[name="generatorSet"]:checked').val();
//let schoolId = 1; // hardcoded
// Field validation
if (isNaN(parseFloat(landArea)) || landArea <= 0 ) {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: 'Site Area numbers greater than 0.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
});
return;
}
if ( isNaN(parseFloat(buildupArea)) || buildupArea < 50) {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: ' Built-up Area must be numbers greater than 50.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
});
return;
}
let fields = {
"Site Area of the School": landArea,
"Built Up Area of the School": buildupArea,
"Compound Wall": isCompound,
"School Name Board": isNameboard,
"PA System": isPasystem,
"Electric Bell": isBell,
"Generator Set": isGenerator
};
for (let key in fields) {
if (!fields[key] || fields[key] === "") {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: `Please enter/select: ${key}`,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
});
return;
}
}
// Check numeric fields
// Show loader
$('#pageLoader').show();
// Prepare form data
let formData = {
land_area: parseFloat(landArea),
buildup_area: parseFloat(buildupArea),
is_compound: isCompound ,
is_nameboard: isNameboard,
is_pasystem: isPasystem,
is_bell: isBell,
is_generator: isGenerator,
school_id: schoolId
};
// AJAX call
$.ajax({
type: 'POST',
url: '/gcc/api/gccschool/schoolproperty/saveSchoolBuildupArea',
data: $.param(formData), // Serialize object to x-www-form-urlencoded
success: function (data) {
$('#pageLoader').hide();
Swal.fire({
title: 'Success!',
text: 'School Build-up Area data saved successfully!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(() => {
window.location.reload();
});
},
error: function (xhr, status, error) {
console.error('AJAX Error:', error);
$('#pageLoader').hide();
Swal.fire({
title: 'Error!',
text: 'Something went wrong while saving the data.',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
});
}
});
});
/* document.getElementById("resetButton").addEventListener("click", function (event) {
event.preventDefault(); // Prevent default reset behavior (which might refresh or reset other logic)
// Clear all input fields (text)
document.querySelectorAll('input[type="text"]').forEach(input => input.value = "");
// Uncheck all radio buttons
document.querySelectorAll('input[type="radio"]').forEach(radio => radio.checked = false);
});*/
$(document).ready(function () {
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getotherdetailsBySchoolId',
type: 'GET',
data: {schoolId},
success: function (response) {
if (response.status === 'OK' && response.otherdetailsBySchool.length > 0) {
const data = response.otherdetailsBySchool[0];
const hasValidData =
!!data.land_area ||
!!data.buildup_area ||
data.is_compound !== null ||
data.is_nameboard !== null ||
data.is_pasystem !== null ||
data.is_bell !== null ||
data.is_generator !== null;
if (hasValidData) {
// Fill read-only
$('#ro_land_area').text(data.land_area || '');
$('#ro_buildup_area').text(data.buildup_area || '');
$('#ro_compoundWall').text(data.is_compound ? 'Yes' : 'No');
$('#ro_nameBoard').text(data.is_nameboard ? 'Yes' : 'No');
$('#ro_paSystem').text(data.is_pasystem ? 'Yes' : 'No');
$('#ro_electricBell').text(data.is_bell ? 'Yes' : 'No');
$('#ro_generatorSet').text(data.is_generator ? 'Yes' : 'No');
$('#otherDetailsSection').show();
$('#otherDetailsReadOnlyView').show();
$('#otherDetailsSectionform').hide();
} else {
$('#otherDetailsSection').show();
$('#otherDetailsReadOnlyView').hide();
$('#otherDetailsSectionform').show();
}
} else {
// ✅ No data at all
$('#otherDetailsSection').show();
$('#otherDetailsReadOnlyView').hide();
$('#otherDetailsSectionform').show();
}
},
error: function () {
console.error('Error fetching other details');
$('#otherDetailsSection').show();
$('#otherDetailsReadOnlyView').hide();
$('#otherDetailsSectionform').show();
}
});
$('#updateOtherDetailsBtn').on('click', function () {
console.log("schoolId", schoolId);
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getotherdetailsBySchoolId',
type: 'GET',
data: {schoolId},
success: function (response) {
console.log("response");
console.log(response);
if (response.status === 'OK' && response.otherdetailsBySchool.length > 0) {
const data = response.otherdetailsBySchool[0];
console.log("land_area:", data.land_area);
console.log("buildup_area:", data.buildup_area);
$('#modal_land_area').val(data.land_area);
$('#modal_buildup_area').val(data.buildup_area );
//$('#buildup_area').val(data.buildup_area);
$('input[name="modalcompoundWall"][value="' + (data.is_compound ? '1' : '0') + '"]').prop('checked', true);
$('input[name="modalnameBoard"][value="' + (data.is_nameboard ? '1' : '0') + '"]').prop('checked', true);
$('input[name="modalpaSystem"][value="' + (data.is_pasystem ? '1' : '0') + '"]').prop('checked', true);
$('input[name="modalelectricBell"][value="' + (data.is_bell ? '1' : '0') + '"]').prop('checked', true);
$('input[name="modalgeneratorSet"][value="' + (data.is_generator ? '1' : '0') + '"]').prop('checked', true);
$('#otherDetailsFormWrapper').show();
$('#otherDetailsReadOnlyView').show();
$('#otherDetailsModal').modal('show');
}
}
});
});
$('#updateOtherDetailsForm').on('submit', function (e) {
e.preventDefault();
// Collect values from modal
const land_area = parseFloat($('#modal_land_area').val().trim());
const buildup_area = parseFloat($('#modal_buildup_area').val().trim());
const is_compound = $('input[name="modalcompoundWall"]:checked').val();
const is_nameboard = $('input[name="modalnameBoard"]:checked').val();
const is_pasystem = $('input[name="modalpaSystem"]:checked').val();
const is_bell = $('input[name="modalelectricBell"]:checked').val();
const is_generator = $('input[name="modalgeneratorSet"]:checked').val();
console.log("text");
console.log(land_area);
console.log(is_bell);
if (isNaN(land_area) || isNaN(buildup_area)) {
Swal.fire("Validation Error", "Please enter valid area values.", "warning");
return;
}
if (isNaN(parseFloat(land_area)) || land_area <= 0 || isNaN(parseFloat(buildup_area)) || buildup_area <= 50) {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: 'Site Area and Built-up Area must be valid numbers.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
});
return;
}
// Prepare payload
const formData = {
land_area,
buildup_area,
is_compound,
is_nameboard,
is_pasystem,
is_bell,
is_generator,
school_id: schoolId // already declared in your script
};
// AJAX call to your controller
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/updateOtherDetails',
type: 'POST',
data: formData,
success: function (response) {
/* if (response === 'Success') {
Swal.fire("Success!", "Other details updated successfully.", "success")
.then(() => window.location.reload());
} else {
Swal.fire("Error", "Something went wrong. Try again.", "error");
}
},
error: function (xhr, status, error) {
console.error("AJAX Error:", error);
Swal.fire("Error", "Server error occurred.", "error");
}*/
if (response === 'Success') {
Swal.fire({
title: "Success!",
text: "Other details updated successfully.",
icon: "success",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
}).then(() => window.location.reload());
} else {
Swal.fire({
title: "Error",
text: "Something went wrong. Try again.",
icon: "error",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
});
}
},
error: function (xhr, status, error) {
console.error("AJAX Error:", error);
Swal.fire({
title: "Error",
text: "Server error occurred.",
icon: "error",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false
});
}
});
});
});
</script>
</body>
</html>

815
frontend/school/playground.html

@ -0,0 +1,815 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Playground Details</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
body {
background-color: #f8f9fa;
}
/* Remove background image from the container itself */
.select2-container--default .select2-selection--multiple {
padding-right: 30px;
min-height: 38px;
display: flex;
flex-wrap: wrap;
align-items: center;
position: relative; /* important for the ::after */
background-image: none;
}
/* Add the dropdown arrow via a pseudo-element */
.select2-container--default .select2-selection--multiple::after {
content: "";
position: absolute;
top: 50%;
right: 8px;
width: 14px;
height: 14px;
transform: translateY(-50%);
background-image: url("data:image/svg+xml;utf8,<svg fill='gray' height='20' viewBox='0 0 24 24' width='20' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");
background-repeat: no-repeat;
background-size: contain;
pointer-events: none;
}
/* Each selected tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 10px;
margin: 4px 4px 0 0;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 13px;
line-height: 1.4;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* The text inside the tag */
.select2-container--default .select2-selection--multiple .select2-selection__choice__display {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 8px;
}
/* The "X" close icon */
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
position: static;
transform: none;
color: #333;
font-size: 14px;
font-weight: bold;
cursor: pointer;
background: transparent;
border: none;
line-height: 1;
}
</style>
</head>
<body>
<div class="container mt-4">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<form id="playgroundForm">
<div class="card p-3">
<div class="card-header">
<b>Playground</b>
</div>
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Presence of Playground <span style="color: red;">*</span></label>
<div class="radio-group">
<input type="radio" name="hasPlayground" value="Yes"> Yes
<input type="radio" name="hasPlayground" value="No"> No
</div>
</div>
<div class="col-md-6 form-group" id="playgroundAreaGroup" style="display: none;">
<label>Area of Playground (Sq. ft) <span style="color: red;">*</span></label>
<input type="number" class="form-control" id="playground_area" min="0">
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Presence of Court <span style="color: red;">*</span></label>
<div class="radio-group">
<input type="radio" name="hasCourt" value="Yes"> Yes
<input type="radio" name="hasCourt" value="No"> No
</div>
</div>
<!-- <div class="col-md-6 form-group" id="courtTypeGroup" style="display: none;">
<label>Type of Court <span class="text-danger">*</span></label>
<div class="custom-select-wrapper">
<select id="court_type" class="form-control custom-select-style" multiple="multiple">
Options will be added dynamically here
</select>
<i class="bi bi-caret-down-fill dropdown-icon"></i>
</div>
</div> -->
<div class="col-md-6 form-group" id="courtTypeGroup" style="display: none;">
<label>Type of Court <span style="color: red;">*</span></label>
<select id="court_type" class="form-control " multiple > </select>
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Inventory Items <span style="color: red;">*</span></label>
<select id="inventory" class="form-control" multiple></select>
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">
<i class="ik ik-save"></i> Submit
</button>
<button type="button" class="btn btn-secondary" id="resetBtn">
<i class="ik ik-refresh-cw"></i> Reset
</button>
</div>
</div>
</form>
</div>
<div class="modal fade" id="editPlaygroundModal" tabindex="-1" aria-labelledby="editPlaygroundModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form id="playgroundEditForm">
<div class="modal-header">
<h5 class="modal-title" id="editPlaygroundModalLabel">Playground Details</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Presence of Playground <span style="color: red;">*</span></label>
<div class="radio-group">
<input type="radio" name="modalhasPlayground" value="Yes"> Yes
<input type="radio" name="modalhasPlayground" value="No"> No
</div>
</div>
<div class="col-md-6 form-group" id="modalplaygroundAreaGroup" style="display: none;">
<label>Area of Playground (Sq. ft) <span style="color: red;">*</span></label>
<input type="number" class="form-control" id="modalplayground_area" min="0">
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Presence of Court <span style="color: red;">*</span></label>
<div class="radio-group">
<input type="radio" name="modalhasCourt" value="Yes"> Yes
<input type="radio" name="modalhasCourt" value="No"> No
</div>
</div>
<div class="col-md-6 form-group" id="modalcourtTypeGroup" style="display: none;">
<label>Type of Court <span style="color: red;">*</span></label>
<select id="modalcourt_type" class="form-control" multiple="multiple"></select>
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 form-group">
<label>Inventory Items <span style="color: red;">*</span></label>
<select id="modalinventory" class="form-control" multiple="multiple"></select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">
<i class="ik ik-save"></i> Submit
</button>
</div>
</form>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script>
$(document).ready(function () {
const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId");
document.getElementById('playground_area').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
console.log("Playground form JS ready.");
/*$('#court_type, #inventory').select2({width: '100%'});
// Load dropdown data
$.get('/gcc/api/gccschool/dropdown/getCourtData', function (response) {
const $court = $('#court_type').empty();
$court.append('<option value="">Select Type of court </option>');
response.data.forEach(item => {
$court.append(`<option value="${item.court_id}">${item.court_type}</option>`);
});
});*/
$.get('/gcc/api/gccschool/dropdown/getCourtData', function (response) {
const $court = $('#court_type');
$court.empty(); // Clear existing options
response.data.forEach(item => {
$court.append(`<option value="${item.court_id}">${item.court_type}</option>`);
});
// Destroy any previous select2 instance if reinitializing
if ($court.hasClass("select2-hidden-accessible")) {
$court.select2('destroy');
}
$court.select2({
placeholder: "Select Type of Court",
width: '100%',
minimumResultsForSearch: Infinity, // disables typing/search box
closeOnSelect: false // allow multiple selection
});
});
$('#court_type').on('select2:opening', function() {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true); // disable typing
}, 0);
});
$.get('/gcc/api/gccschool/dropdown/getEquipmentData', function (response) {
const $equip = $('#inventory').empty();
$equip.append('<option value="">Select Inventory Items </option>');
response.data.forEach(item => {
$equip.append(`<option value="${item.equipment_id}">${item.equipment_type}</option>`);
});
$equip.select2({
placeholder: "Select Inventory Items",
width: '100%',
multiple: true,
minimumResultsForSearch: Infinity, // disables search typing
closeOnSelect: false
});
// Optional: disable typing in the input
$equip.on('select2:opening', function() {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true);
}, 0);
});
});
// Populate modal court types
/*$.get('/gcc/api/gccschool/dropdown/getCourtData', function (response) {
const $modalCourt = $('#modalcourt_type').empty();
response.data.forEach(item => {
$modalCourt.append(`<option value="${item.court_id}">${item.court_type}</option>`);
});
$modalCourt.select2({
placeholder: "Select Type of Court",
width: '100%',
closeOnSelect: false,
minimumResultsForSearch: Infinity
});
$modalCourt.on('select2:opening', function () {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true);
}, 0);
});
});
// Populate modal inventory items
$.get('/gcc/api/gccschool/dropdown/getEquipmentData', function (response) {
const $modalInventory = $('#modalinventory').empty();
response.data.forEach(item => {
$modalInventory.append(`<option value="${item.equipment_id}">${item.equipment_type}</option>`);
});
$modalInventory.select2({
placeholder: "Select Inventory Items",
width: '100%',
closeOnSelect: false,
minimumResultsForSearch: Infinity
});
$modalInventory.on('select2:opening', function () {
setTimeout(() => {
$('.select2-search__field').prop('readonly', true);
}, 0);
});
});*/
// Toggle Playground Area based on radio button selection
$('input[name="modalhasPlayground"]').on('change', function () {
if ($(this).val() === 'Yes') {
$('#modalplaygroundAreaGroup').show();
} else {
$('#modalplaygroundAreaGroup').hide();
//$('#modalplayground_area').val(''); // optional: clear input
}
});
// Toggle Court Type section based on radio button selection
$('input[name="modalhasCourt"]').on('change', function () {
if ($(this).val() === 'Yes') {
$('#modalcourtTypeGroup').show();
} else {
$('#modalcourtTypeGroup').hide();
//$('#modalcourt_type').val(null).trigger('change'); // ✅ Correct // optional: clear selected items
}
});
/*$.get('/gcc/api/gccschool/dropdown/getEquipmentData', function (response) {
const $equip = $('#inventory').empty();
$equip.append('<option value="">Select Inventory Items </option>');
response.data.forEach(item => {
$equip.append(`<option value="${item.equipment_id}">${item.equipment_type}</option>`);
});
});*/
$.get('/gcc/api/gccschool/schoolproperty/checkPlaygroundDetails', { school_id: schoolId }, function (response) {
const data = response && response[0];
const pg = data?.playgroundDetails;
// Show form if no data or if critical values are missing
if (!pg || Object.keys(pg).length === 0 || pg.is_playground === undefined || pg.is_court === undefined) {
$('#playgroundForm').show();
return;
}
// Construct comma-separated court and equipment lists
let courtList = data.CourtDetails?.map(cd => cd.court_type).join(", ") || "—";
let equipmentList = data.EquipmentDetails?.map(ed => ed.equipment_type).join(", ") || "—";
const table = `
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-body" id="playgroundTableWrapper">
<h5 class="mb-0"> Playground Details</h5>
<div class="table-responsive">
<table class="table table-bordered">
<tr><th>Playground Present</th><td>${pg.is_playground ? 'Yes' : 'No'}</td></tr>
<tr><th>Playground Area</th><td>${pg.playground_area ?? '—'}</td></tr>
<tr><th>Court Present</th><td>${pg.is_court ? 'Yes' : 'No'}</td></tr>
<tr><th>Type of Court</th><td>${courtList}</td></tr>
<tr><th>Inventory Items</th><td>${equipmentList}</td></tr>
</table>
</div>
<div class="text-center mt-3">
<button id="editPlaygroundBtn" class="btn btn-primary px-4">Update</button>
</div>
</div>
</div>
</div>
`;
$('.container.mt-4').prepend(table);
$('#playgroundForm').hide();
// Enable Edit mode: fill form and show
/*$(document).on('click', '#editPlaygroundBtn', function () {
// Populate fields
$(`input[name="modalhasPlayground"][value="${pg.is_playground ? 'Yes' : 'No'}"]`).prop('checked', true).trigger('change');
$('#modalplayground_area').val(pg.playground_area);
$(`input[name="modalhasCourt"][value="${pg.is_court ? 'Yes' : 'No'}"]`).prop('checked', true).trigger('change');
const courtIds = data.CourtDetails?.map(cd => cd.court_id?.toString()) || [];
const equipIds = data.EquipmentDetails?.map(ed => ed.equipment_detais_id?.toString()) || [];
setTimeout(() => {
$('#modalcourt_type').val(courtIds).trigger('change');
$('#modalinventory').val(equipIds).trigger('change');
}, 200);
const courtIds = data.CourtDetails?.map(cd => cd.Courts_detais_id?.toString()) || [];
const equipIds = data.EquipmentDetails?.map(ed => ed.equipment_detais_id?.toString()) || [];
setTimeout(() => {
$('#modalcourt_type').val(courtIds).trigger('change');
$('#modalinventory').val(equipIds).trigger('change');
}, 200);
$('button[type="submit"]').html('Save changes');
console.log(courtIds);
// Show modal
const editModal = new bootstrap.Modal(document.getElementById('editPlaygroundModal'));
editModal.show();
});*/
$(document).on('click', '#editPlaygroundBtn', function () {
window.modalDrinkingRawResponse = data;
// Store playground ID for use during update
$('#editPlaygroundModal').data('playground_id', pg.playground_id);
// Pre-select radio values and playground area
$(`input[name="modalhasPlayground"][value="${pg.is_playground ? 'Yes' : 'No'}"]`).prop('checked', true).trigger('change');
$('#modalplayground_area').val(pg.playground_area);
$(`input[name="modalhasCourt"][value="${pg.is_court ? 'Yes' : 'No'}"]`).prop('checked', true).trigger('change');
const $modalCourt = $('#modalcourt_type');
const $modalInventory = $('#modalinventory');
// Preload detail row IDs and selection IDs
const courtData = data.CourtDetails?.map(cd => ({
Courts_detais_id: cd.Courts_detais_id, // ✅ correct DB ID
court_id: cd.court_id.toString() // ✅ select2 expects string
})) || [];
const equipmentData = data.EquipmentDetails?.map(ed => ({
equipment_detais_id: ed.equipment_detais_id, // ✅ correct DB ID
equipment_id: ed.equipment_id.toString()
})) || [];
// Extract just the selected IDs to set values in select2
const courtIds = courtData.map(cd => cd.court_id);
const equipIds = equipmentData.map(ed => ed.equipment_id);
console.log("Preselected Court IDs:", courtIds);
console.log("Preselected Equipment IDs:", equipIds);
// Fetch dropdown options and then trigger modal
Promise.all([
$.get('/gcc/api/gccschool/dropdown/getCourtData'),
$.get('/gcc/api/gccschool/dropdown/getEquipmentData')
]).then(([courtResponse, equipResponse]) => {
// COURT
$modalCourt.empty();
courtResponse.data.forEach(item => {
$modalCourt.append(`<option value="${item.court_id}">${item.court_type}</option>`);
});
$modalCourt.select2({
placeholder: "Select Type of Court",
width: '100%',
closeOnSelect: false,
minimumResultsForSearch: Infinity
});
// INVENTORY
$modalInventory.empty();
equipResponse.data.forEach(item => {
$modalInventory.append(`<option value="${item.equipment_id}">${item.equipment_type}</option>`);
});
$modalInventory.select2({
placeholder: "Select Inventory Items",
width: '100%',
closeOnSelect: false,
minimumResultsForSearch: Infinity
});
// Set preselected values after a slight delay
setTimeout(() => {
$modalCourt.val(courtIds).trigger('change');
$modalInventory.val(equipIds).trigger('change');
}, 150);
// Store full detail info for use in form submission (you can also use hidden inputs if needed)
$('#editPlaygroundModal').data('courtDetailData', courtData);
$('#editPlaygroundModal').data('equipDetailData', equipmentData);
// Show the modal
setTimeout(() => {
const editModal = new bootstrap.Modal(document.getElementById('editPlaygroundModal'));
editModal.show();
}, 300);
});
});
});
$('input[name="hasPlayground"]').change(function () {
if ($(this).val() === 'Yes') {
$('#playgroundAreaGroup').show();
} else {
$('#playgroundAreaGroup').hide();
$('#playground_area').val(''); // Clear the input when "No" is selected
}
});
$('input[name="hasCourt"]').change(function () {
if ($(this).val() === 'Yes') {
$('#courtTypeGroup').show();
} else {
$('#courtTypeGroup').hide();
$('#court_type').val(null).trigger('change'); // Clears dropdown
}
});
$('#playgroundForm').on('submit', function (e) {
e.preventDefault();
console.log("Submit triggered");
const hasPlayground = $('input[name="hasPlayground"]:checked').val();
const hasCourt = $('input[name="hasCourt"]:checked').val();
const playgroundArea = $('#playground_area').val();
const courtTypes = $('#court_type').val();
const equipmentList = $('#inventory').val();
//const schoolId = 1;
/*if (!hasPlayground) return Swal.fire('Validation Error', 'Select presence of playground.', 'warning');
if (hasPlayground === 'Yes' && (!playgroundArea || parseFloat(playgroundArea) < 0))
return Swal.fire('Validation Error', 'Enter valid playground area.', 'warning');
if (!hasCourt) return Swal.fire('Validation Error', 'Select presence of court.', 'warning');
if (hasCourt === 'Yes' && (!courtTypes || courtTypes.length === 0))
return Swal.fire('Validation Error', 'Select at least one court type.', 'warning');
if (!equipmentList || equipmentList.length === 0)
return Swal.fire('Validation Error', 'Select at least one inventory item.', 'warning');*/
if (!hasPlayground) {
return Swal.fire({
title: 'Validation Error',
text: 'Select presence of playground.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if (hasPlayground === 'Yes' && (!playgroundArea || parseFloat(playgroundArea) < 100)) {
return Swal.fire({
title: 'Validation Error',
text: 'playground area must be numbers greater than 100.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if (!hasCourt) {
return Swal.fire({
title: 'Validation Error',
text: 'Select presence of court.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if (hasCourt === 'Yes' && (!courtTypes || courtTypes.length === 0)) {
return Swal.fire({
title: 'Validation Error',
text: 'Select at least one court type.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if (!equipmentList || equipmentList.length === 0) {
return Swal.fire({
title: 'Validation Error',
text: 'Select at least one inventory item.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
const payload = {
is_playground: hasPlayground === 'Yes',
playground_area: hasPlayground === 'Yes' ? parseFloat(playgroundArea) : 0,
is_court: hasCourt === 'Yes',
courtid: courtTypes,
equipmentid: equipmentList,
school_id: schoolId,
};
console.log("Payload:", payload);
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/savePlayground',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function (response) {
Swal.fire({
title: 'Success',
text: 'Playground saved successfully!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => location.reload());
},
error: function (xhr) {
console.error("Error:", xhr);
Swal.fire({
title: 'Error',
text: 'Failed to save playground details.',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
});
$('#playgroundEditForm').on('submit', function (e) {
e.preventDefault();
const hasPlayground = $('input[name="modalhasPlayground"]:checked').val();
const hasCourt = $('input[name="modalhasCourt"]:checked').val();
const playgroundArea = $('#modalplayground_area').val();
const courtTypes = $('#modalcourt_type').val(); // court_id[]
const equipmentList = $('#modalinventory').val(); // equipment_id[]
const playgroundId = $('#editPlaygroundModal').data('playground_id');
if (!hasPlayground) return Swal.fire('Validation Error', 'Select presence of playground.', 'warning');
if (hasPlayground === 'Yes' && (!playgroundArea || parseFloat(playgroundArea) < 100))
return Swal.fire('Validation Error', 'playground area must be numbers greater than 100.', 'warning');
if (!hasCourt) return Swal.fire('Validation Error', 'Select presence of court.', 'warning');
if (hasCourt === 'Yes' && (!courtTypes || courtTypes.length === 0))
return Swal.fire('Validation Error', 'Select at least one court type.', 'warning');
if (!equipmentList || equipmentList.length === 0)
return Swal.fire('Validation Error', 'Select at least one inventory item.', 'warning');
// ✅ Extract preloaded backend data (used to get *_detais_id)
const courtData = courtTypes.map(id => {
const match = window.modalDrinkingRawResponse?.CourtDetails?.find(c => c.court_id == id);
return {
court_id: parseInt(id),
Courts_detais_id: match?.Courts_detais_id || 0
};
});
const equipmentData = equipmentList.map(id => {
const match = window.modalDrinkingRawResponse?.EquipmentDetails?.find(e => e.equipment_id == id);
return {
equipment_id: parseInt(id),
equipment_detais_id: match?.equipment_detais_id || 0
};
});
const payload = {
is_playground: hasPlayground === 'Yes',
playground_area: hasPlayground === 'Yes' ? parseFloat(playgroundArea) : 0,
is_court: hasCourt === 'Yes',
school_id: parseInt(new URLSearchParams(window.location.search).get("schoolId")),
playground_id: parseInt(playgroundId),
equipments: equipmentData,
courts: courtData
};
console.log("✅ Final Playground Update Payload:", payload);
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/updatePlayground',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function (res) {
if (res.status === "OK") {
// Swal.fire('Success', res.message || 'Playground updated!', 'success').then(() => location.reload());
Swal.fire({
title: 'Success',
text: res.message || 'Playground updated!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => location.reload());
} else {
// Swal.fire('Error', res.message || 'Update failed.', 'error');
Swal.fire({
title: 'Error',
text: res.message || 'Update failed.',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
},
error: function (xhr) {
console.error("XHR Error:", xhr);
let msg = xhr.responseText || "Unknown error occurred";
Swal.fire('Error', msg, 'error');
}
});
});
function resetFacilityFields() {
console.log("Reset button clicked - Facilities");
// Uncheck all radio buttons
$('input[type="radio"]').prop('checked', false);
// Clear input fields
$('#playground_area').val('');
// Clear multi-select dropdowns
$('#court_type').val(null).trigger('change');
$('#inventory').val(null).trigger('change');
// Hide conditional sections
$('#playgroundAreaGroup').hide();
$('#courtTypeGroup').hide();
}
// Event Listener for Reset Button
$(document).on('click', '#resetBtn', function (event) {
event.preventDefault();
resetFacilityFields();
});
});
</script>
</body>
</html>

478
frontend/school/reports.html

@ -0,0 +1,478 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
</head>
<style>
</style>
<body>
<div class="wrapper">
<!-- header top menu Start -->
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<!-- header top menu end -->
<div class="page-wrap">
<!--=============== Left Menu side Start ================-->
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<!--=============== Left side End ================-->
<div class="main-content">
<div class="container-fluid">
<div class="page-header mb-2">
<div class="row align-items-end">
<div class="col-lg-8">
<div class="page-header-title">
<i class="fa fa-list-alt bg-blue"></i>
<div class="d-inline">
<h5>Schools Reports</h5>
</div>
</div>
</div>
<div class="col-lg-4">
<nav class="breadcrumb-container" aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/gcc/index"><i
class="ik ik-home"></i></a></li>
<li class="breadcrumb-item" aria-current="page">school</li>
<li class="breadcrumb-item active" aria-current="page">Reports</li>
</ol>
</nav>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-12">
<div class="card">
<div class="card-header">
<span style="font-size: medium;font-weight: bold;">Reports Filters</span>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-2 mb-2">
<label for="aeodropdown" style="font-size: medium;">AEO:</label>
<select id="aeodropdown" class="form-control">
<option value="">Select</option>
</select>
</div>
<div class="col-sm-2 mb-2">
<label for="zonedropdown" style="font-size: medium;">Zone:</label>
<select id="zonedropdown" class="form-control">
<option value="">Select</option>
</select>
</div>
<div class="col-sm-2 mb-2">
<label for="warddropdown" style="font-size: medium;">Ward:</label>
<select id="warddropdown" class="form-control">
<option value="">Select</option>
</select>
</div>
</div>
<div class="row mt-4">
<div class="col-12 d-flex justify-content-center">
<button type="submit" id="searchBtn"
class="btn btn-primary mx-2">Search</button>
<button class="btn btn-danger mx-2" id="resetBtn"
name="reset" type="reset">Reset</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<span style="font-size: medium;font-weight: bold;">Reports List</span>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="ReportDatatable"
class="table table-striped table-bordered table-hover dataTable"
role="grid">
<thead class="thead-dark">
<tr role="row">
<th class="text-center no-sort">S.No</th>
<th class="text-center" style="width: 100px;">AEO</th>
<th class="text-center">Zone</th>
<th class="text-center">Ward</th>
<th class="text-center">UDISE code</th>
<th class="text-center">Other Details</th>
<th class="text-center">Staff Details</th>
<th class="text-center">Student Details</th>
<th class="text-center">Buildings</th>
<th class="text-center">Playground</th>
<th class="text-center">Drinking Water</th>
<th class="text-center">Toilets</th>
<th class="text-center">School Assets</th>
<th class="text-center">Kitchen</th>
<th class="text-center">Overall status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
<footer th:replace="~{fragments/modules/base/footer :: footer}"></footer>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<!-- sweet alert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
fetchAEOSchoolData([], '', '');
let aeoDropdown = document.getElementById('aeodropdown');
let zoneDropdown = document.getElementById('zonedropdown');
let wardDropdown = document.getElementById('warddropdown');
fetch('/gcc/api/gccschool/report/getAEOList')
.then(response => response.json())
.then(data => {
// Clear existing options
aeoDropdown.innerHTML = `<option value="">Select</option>`;
// Add options from the API response
data.data.forEach(aeo => {
aeoDropdown.innerHTML += `<option value="${aeo.udise}">${aeo.aeo_num}</option>`;
});
})
.catch(error => {
console.error('Error fetching in AEO List:', error);
});
aeoDropdown.addEventListener('change', function () {
const selectedGroup = aeoDropdown.value;
if (selectedGroup) {
fetch(`/gcc/api/gccschool/report/getAEOZone?udise=${encodeURIComponent(selectedGroup)}`)
.then(response => response.json())
.then(data => {
// Clear existing options
zoneDropdown.innerHTML = `<option value="">Select</option>`;
// Add options from the API response
data.data.forEach(zone => {
zoneDropdown.innerHTML += `<option value="${zone}">${zone}</option>`;
});
wardDropdown.innerHTML = `<option value="">Select</option>`;
})
.catch(error => {
console.error('Error fetching zone for aeo:', error);
});
} else {
zoneDropdown.innerHTML = `<option value="">Select</option>`;
wardDropdown.innerHTML = `<option value="">Select</option>`;
}
});
zoneDropdown.addEventListener('change', function () {
const selectedAeo = aeoDropdown.value;
const selectedZone= zoneDropdown.value;
if (selectedAeo && selectedZone) {
fetch(`/gcc/api/gccschool/report/getAEOWard?udise=${encodeURIComponent(selectedAeo)}&zone=${encodeURIComponent(selectedZone)}`)
.then(response => response.json())
.then(data => {
// Clear existing options
wardDropdown.innerHTML = `<option value="">Select</option>`;
// Add options from the API response
data.data.forEach(Ward => {
wardDropdown.innerHTML += `<option value="${Ward}">${Ward}</option>`;
});
})
.catch(error => {
console.error('Error fetching ward for aeo:', error);
});
} else {
wardDropdown.innerHTML = `<option value="">Select</option>`;
}
});
});
$(document).ready(function() {
/* var table = $('#ReportDatatable').DataTable({
dom: 'Bftip',
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: '80vh',
scrollX: true,
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn'
}
],
fixedHeader: true,
autoWidth: true,
responsive: false,
searching: true,
select: false,
processing: false
}); */
document.getElementById('resetBtn').addEventListener('click', function () {
event.preventDefault();
location.reload();
});
document.getElementById('searchBtn').addEventListener('click', function (e) {
let aeoDropdown = document.getElementById('aeodropdown');
let zoneDropdown = document.getElementById('zonedropdown');
let wardDropdown = document.getElementById('warddropdown');
// ✅ Extract selected values from a multi-select dropdown as an array
let aeovalue = Array.from(aeoDropdown.selectedOptions).map(opt => opt.value);
//let aeovalue =aeoDropdown.value;
let zonevalue = zoneDropdown.value;
let wardvalue = wardDropdown.value;
console.log("aeovalue: ",aeovalue);
console.log("zonevalue: ",zonevalue);
console.log("wardvalue: ",wardvalue);
if (!aeovalue || aeovalue.length === 0) {
Swal.fire({
icon: 'info',
title: 'Info',
text: 'Please Select AEO',
showConfirmButton: true,
timer: 3000
});
e.preventDefault();
return;
}
fetchAEOSchoolData(aeovalue, zonevalue, wardvalue);
});
});
function fetchAEOSchoolData(aeovalue, zonevalue, wardvalue)
{
const params = new URLSearchParams();
aeovalue.forEach(val =>{ console.log("Appending udise:", val);
params.append("udise", val)}); // Use 'udiseList' as repeated query parameter
params.append("zone", zonevalue);
params.append("ward", wardvalue);
$('#pageLoader').show();
$.ajax({
type: "GET",
url: `/gcc/api/gccschool/report/getAEOSchoolData?${params.toString()}`, // Append query string to URL
contentType: "application/json",
success: function (response) {
console.log("API Response:", response);
$('#pageLoader').hide();
if (response.message === "Success") {
console.log("Details Array:", response.data);
// Ensure details is an array and has at least one entry
if (Array.isArray(response.data) && response.data.length > 0) {
let scrollHeight = response.data.length <= 50 ? 'auto' : '80vh';
let table = $('#ReportDatatable').DataTable({
destroy: true,
searching: true,
autoWidth: true,
paging: true,
info: true,
data: response.data,
columns: [
{
data: null,
render: (data, type, row, meta) => meta.row + 1,
className: 'text-center'
},
{ data: 'aeo_num', defaultContent: '-', className: 'text-center' },
{ data: 'zone', defaultContent: '-', className: 'text-center' },
{ data: 'division', defaultContent: '-', className: 'text-center' },
{ data: 'udise', defaultContent: '-', className: 'text-center' },
{ data: 'other_details', defaultContent: '-', className: 'text-center' },
{ data: 'staff_details', defaultContent: '-', className: 'text-center' },
{ data: 'students_details', defaultContent: '-', className: 'text-center' },
{ data: 'buildings', defaultContent: '-', className: 'text-center' },
{ data: 'playground_details', defaultContent: '-', className: 'text-center' },
{ data: 'drinkingwater_details', defaultContent: '-', className: 'text-center' },
{ data: 'toilet_details', defaultContent: '-', className: 'text-center' },
{ data: 'school_assets', defaultContent: '-', className: 'text-center' },
{ data: 'kitchen_details', defaultContent: '-', className: 'text-center' },
{ data: 'overall_status', defaultContent: '-', className: 'text-center' }
],
dom: 'Bfrtip',
buttons: [
{
extend: 'pageLength',
className: 'btn btn-warning'
},
{
title: 'Data export',
extend: 'copyHtml5',
text: 'Copy',
className: 'btn btn-secondary',
id: 'copyBtn'
},
{
extend: 'excelHtml5',
text: 'Excel',
className: 'btn btn-secondary',
id: 'excelBtn'
},
{
extend: 'csvHtml5',
text: 'CSV',
className: 'btn btn-secondary',
id: 'csvBtn'
},
{
extend: 'pdfHtml5',
text: 'PDF',
className: 'btn btn-secondary',
id: 'pdfBtn'
}
],
columnDefs: [
{ targets: 'no-sort', orderable: false }
],
lengthMenu: [
[50, 100, 200, 500, -1],
['50 rows', '100 rows', '200 rows', 'Show all']
],
scrollY: scrollHeight,
scrollX: true,
responsive: false,
searching: true
});
}
}
else if (response.message === "NoData") {
$('#pageLoader').hide();
Swal.fire({
icon: 'warning',
title: response.data,
text: 'No data available for the selected criteria.'
});
}
else {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
},
error: function (error) {
$('#pageLoader').hide();
Swal.fire({
icon: 'error',
title: 'Error',
text: response.message || 'Something went wrong!'
});
}
});
}
</script>
</body>
</html>

827
frontend/school/room.html

@ -0,0 +1,827 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
#assetModal .modal-body {
max-height: 80vh;
overflow-y: auto;
}
#floordetailsModal .modal-body {
max-height: 80vh;
overflow-y: auto;
}
#roomMappingModal .modal-body {
max-height: 80vh;
overflow-y: auto;
min-height: 40vh;
}
/* Default desktop view */
/*.responsive-section {
margin-left: -256px;
}*/
/* Wider negative margin if needed */
/*.responsive-section-wide {
margin-left: -281px;
}*/
/* Mobile responsiveness */
@media (max-width: 768px) {
.responsive-section,
.responsive-section-wide {
margin-left: 0 !important;
padding: 0 10px;
}
.btn.mb-2 {
width: 100%;
margin-top: 10px;
}
.d-flex.justify-content-between {
flex-direction: column;
align-items: flex-start;
}
.table {
display: block;
width: 100%;
overflow-x: auto;
white-space: nowrap;
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="main-content" style="margin-top: 6px; padding-left: 0px;">
<div class="container">
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center responsive-section">
<!-- <h4 style="margin-left: -256px;">Rooms</h4>-->
<h4 >Rooms</h4>
<button type="button" class="btn btn-primary mb-2 add-room-btn" id="addRoomBtn"
style="background-color: #0D587B; border: none; border-radius: 6px; padding: 6px 16px;"
data-bs-toggle="modal" data-bs-target="#addRoomModal">
<i class="bi bi-plus-lg"></i>Add Room
</button>
</div>
<hr class="responsive-section"
style="border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px;" >
</div>
<div class="row mt-4 responsive-section-wide">
<div class="col-md-12">
<div class="card">
<div class="card-block">
<table id="CompletedCPSDatatable"
class="table table-striped table-bordered table-hover dataTable" role="grid"
style="width: 100%">
<thead class="thead-dark">
<tr>
<th style="width: 5%;">S.NO</th>
<th style="width: 10%;">Room Name</th>
<th style="width: 15%;">Building Name</th>
<th style="width: 10%;">Floor</th>
<th style="width: 15%;">Room Type</th>
<th style="width: 10%;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Card 2: Other Details -->
</div>
</div>
</div>
</div>
<!-- Modal -->
<!-- Floor Details Modal -->
<div class="modal fade" id="floordetailsModal" tabindex="-1" role="dialog" aria-labelledby="floordetailsModalLabel"
aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="detailsModalLabel">Floor Details</h5>
<button type="button" class="close" data-dismiss="modal"
onclick="$('#floordetailsModal').modal('hide');" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<table class="table table-striped table-bordered" id="floorDetailsTable">
<thead class="thead-dark">
<tr>
<th class="text-center">S.No</th>
<th class="text-center">Room Name</th>
<th class="text-center">Building Name</th>
<th class="text-center">Floor</th>
<th class="text-center">Room Type</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<!-- Data will be inserted here -->
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"
onclick="$('#floordetailsModal').modal('hide');">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="viewRoomModal" tabindex="-1" aria-labelledby="viewRoomModalLabel" data-bs-backdrop="static" data-bs-keyboard="false" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header bg-primary text-white">
<h5 class="modal-title">View Room Details</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Room Name</label> <input type="text" id="viewRoomName"
class="form-control" readonly>
</div>
<div class="col-md-6">
<label class="form-label">Building Name</label> <input type="text" id="viewBuildingName"
class="form-control" readonly>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Floor</label> <input type="text" id="viewFloor"
class="form-control" readonly>
</div>
<div class="col-md-6">
<label class="form-label">Room Type</label> <input type="text" id="viewRoomType"
class="form-control" readonly>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Edit Room Modal -->
<div class="modal fade" id="editRoomModal" tabindex="-1" aria-labelledby="editRoomModalLabel" data-bs-backdrop="static" data-bs-keyboard="false" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">Edit Room Details</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Room Name</label> <input type="text" id="editRoomName"
class="form-control"> <input type="hidden" id="editRoomId">
</div>
<div class="col-md-6">
<label class="form-label">Building</label> <select id="editBuildingId" class="form-control" disabled>
<option value="">Select Building</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Floor</label> <select id="editFloorId" class="form-control">
<option value="">Select Floor</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Room Type</label> <select id="editRoomTypeId"
class="form-control">
<option value="">Select Room Type</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="saveEditRoom">Save
Changes</button>
<button type="button" class="btn btn-danger" id="roomDelete">Delete</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="addRoomModal" tabindex="-1"
data-bs-backdrop="static" data-bs-keyboard="false"
aria-labelledby="addRoomModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary text-white">
<h5 class="modal-title">Add New Room</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Building<span style="color: red;">*</span></label> <select id="addBuildingId" class="form-control">
<option value="">Select Building</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Floor<span style="color: red;">*</span></label> <select id="addFloorId" class="form-control">
<option value="">Select Floor</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Room Type<span style="color: red;">*</span></label> <select id="addRoomTypeId" class="form-control">
<option value="">Select Room Type</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Room Name<span style="color: red;">*</span></label> <input type="text" id="addRoomName"
class="form-control">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="saveAddRoom">Save Room</button>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
<script>
window.schoolId = window.schoolId || new URLSearchParams(window.location.search).get('schoolId');
if (!window.schoolId) {
Swal.fire("Missing School ID", "No schoolId found in the URL", "warning");
throw new Error("Missing schoolId");
}
function loadSavedRoomDetails(school_id) {
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getRoomDetails',
type: 'GET',
contentType: 'application/json',
data: { school_id },
success: function (response) {
if (response.status === "OK") {
$('#CompletedCPSDatatable').DataTable({
destroy: true,
searching: true,
select: false,
autoWidth: true,
scrollY: '60vh',
scrollCollapse: true,
processsing: false,
responsive: true,
paging: true,
info: true,
data: response.data,
columns: [
{ data: null, render: (data, type, row, meta) => meta.row + 1, className: 'text-center' },
{ data: 'room_name', defaultContent: '-', className: 'text-center' },
{ data: 'building_name', defaultContent: '-', className: 'text-center' },
{ data: 'floor', defaultContent: '-', className: 'text-center' },
{ data: 'room_type', defaultContent: '-', className: 'text-center' },
{
data: 'room_id',
render: function (data, type, row) {
return `
<div class="text-center">
<button class="btn btn-sm btn-primary me-1 view-btn2" data-room-id="${data}" title="View">
<i class="bi bi-eye"></i>
</button>
<button class="btn btn-sm btn-success edit-btn2" data-room-id="${data}" data-building-id="${row.building_id}" title="Edit">
<i class="bi bi-pencil"></i>
</button>
</div>`;
},
className: 'text-center'
}
]
});
} else {
$('#CompletedCPSDatatable tbody').html(`<tr><td colspan="6" class="text-center text-danger">${response.data}</td></tr>`);
}
},
error: function () {
Swal.fire("Error", "Something went wrong while fetching room details.", "error");
}
});
}
function loadBuildingsDropdown(schoolId, selectedBuildingId = null) {
$.ajax({
url: '/gcc/api/gccschool/dropdown/getBuildingsBySchoolId',
type: 'GET',
data: { school_id: schoolId },
success: function (response) {
const dropdown = $('#editBuildingId');
dropdown.empty().append('<option value="">Select Building</option>');
if (response.status === "OK") {
response.data.forEach(building => {
const selected = building.buildng_id == selectedBuildingId ? 'selected' : '';
dropdown.append(`<option value="${building.buildng_id}" ${selected}>${building.building_name}</option>`);
});
}
},
error: function () {
Swal.fire("Error", "Unable to load buildings", "error");
}
});
}
function loadRoomTypesDropdown() {
$.ajax({
url: '/gcc/api/gccschool/dropdown/getRooms',
type: 'GET',
success: function (response) {
const dropdown = $('#editRoomTypeId');
dropdown.empty().append('<option value="">Select Room Type</option>');
if (response.status === 'OK') {
response.data.forEach(room => {
dropdown.append(`<option value="${room.room_master_id}">${room.room_type}</option>`);
});
}
}
});
}
function loadBuildingsDropdownForAdd(schoolId) {
$.get('/gcc/api/gccschool/dropdown/getBuildingsBySchoolId', { school_id: schoolId }, function (response) {
const dropdown = $('#addBuildingId');
dropdown.empty().append('<option value="">Select Building</option>');
if (response.status === 'OK') {
response.data.forEach(building => {
dropdown.append(`<option value="${building.buildng_id}">${building.building_name}</option>`);
});
}
});
}
function loadRoomTypesDropdownForAdd() {
$.get('/gcc/api/gccschool/dropdown/getRooms', function (response) {
const dropdown = $('#addRoomTypeId');
dropdown.empty().append('<option value="">Select Room Type</option>');
if (response.status === 'OK') {
response.data.forEach(room => {
dropdown.append(`<option value="${room.room_master_id}">${room.room_type}</option>`);
});
}
});
}
$('#addRoomModal').on('show.bs.modal', function () {
$('#addBuildingId').val('');
$('#addFloorId').val('');
$('#addRoomTypeId').val('');
$('#addRoomName').val('');
});
$(document).ready(function () {
loadRoomTypesDropdown();
loadRoomTypesDropdownForAdd();
loadBuildingsDropdownForAdd(schoolId);
loadSavedRoomDetails(schoolId);
});
$(document).on('click', '.view-btn2', function () {
const roomId = $(this).data('room-id');
$.ajax({
url: `/gcc/api/gccschool/buildingasset/getRoomById`,
method: 'GET',
data: { room_id: roomId },
success: function (response) {
if (response.status === 'OK' && response.data) {
const room = response.data;
$('#viewRoomName').val(room.room_name || '');
$('#viewBuildingName').val(room.building_name || '');
$('#viewFloor').val(room.floor || '');
$('#viewRoomType').val(room.room_type || '');
$('#viewRoomModal').modal('show');
} else {
Swal.fire("Error", response.data || "Room data not found", "error");
}
},
error: function () {
Swal.fire("Error", "Failed to load room details", "error");
}
});
});
$(document).on('click', '.edit-btn2', function () {
const roomId = $(this).data('room-id');
const buildingIdFromAttr = $(this).data('building-id');
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getRoomById',
method: 'GET',
data: { room_id: roomId },
success: function (response) {
if (response.status === 'OK') {
const room = response.data;
$('#editRoomId').val(room.room_id);
$('#editRoomName').val(room.room_name);
loadBuildingsDropdown(room.school_id, buildingIdFromAttr);
loadFloorDropdown(buildingIdFromAttr, room.floors_id);
$('#editRoomTypeId').val(room.room_master_id);
$('#editRoomModal').modal('show');
} else {
Swal.fire("Error", response.data || "Room not found", "error");
}
},
error: function () {
Swal.fire("Error", "Failed to load room details", "error");
}
});
});
$('#saveEditRoom').on('click', function () {
const updatedRoom = {
room_id: $('#editRoomId').val(),
room_num: $('#editRoomName').val(),
building_id: $('#editBuildingId').val(),
floors_id: $('#editFloorId').val() || null,
room_type: $('#editRoomTypeId').val(),
school_id: schoolId
};
$.ajax({
url: '/gcc/api/gccschool/buildingasset/editRoom',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(updatedRoom),
success: function (response) {
if (response === 'Rooms Edited Sucessfully') {
$('#editRoomModal').modal('hide');
Swal.fire({
icon: 'success',
title: 'Success',
text: 'Room updated successfully',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => {
loadSavedRoomDetails(schoolId);
});
} else {
Swal.fire({
icon: 'error',
title: 'Error',
text: response || "Update failed",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
},
error: function () {
Swal.fire({
icon: 'error',
title: 'Error',
text: "Something went wrong while saving changes",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
});
$('#saveAddRoom').on('click', function () {
const buildingId = $('#addBuildingId').val();
const floorId = $('#addFloorId').val();
const roomType = $('#addRoomTypeId').val();
const roomName = $('#addRoomName').val().trim();
if (!buildingId) {
Swal.fire({
icon: 'warning',
title: 'Building Required',
text: 'Please select a building .',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!floorId) {
Swal.fire({
icon: 'warning',
title: 'Floor Required',
text: 'Please select a floor .',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!roomType) {
Swal.fire({
icon: 'warning',
title: 'Room Type Required',
text: 'Please select a room type.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!roomName) {
Swal.fire({
icon: 'warning',
title: 'Room Name Required',
text: 'Please enter a room name .',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
const payload = {
room_num: $('#addRoomName').val(),
building_id: $('#addBuildingId').val(),
floors_id: $('#addFloorId').val(),
room_type: $('#addRoomTypeId').val(),
school_id: schoolId
};
$.ajax({
url: '/gcc/api/gccschool/buildingasset/saveRoom',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function (response) {
if (response === 'Rooms Mapped Sucessfully') {
$('#addRoomModal').modal('hide');
Swal.fire({
title: "Success",
text: "Room added successfully",
icon: "success",
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
}).then(() => {
location.reload(); // 🔁 This reloads the page after user confirms the success alert
});}
else {
Swal.fire({
icon: 'error',
title: 'Error',
text: response || 'Save failed',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
},
error: function () {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Something went wrong while saving',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
});
function loadFloorDropdown(buildingId, selectedFloorId = null) {
$.ajax({
url: '/gcc/api/gccschool/dropdown/getFloorsByBuilding',
type: 'GET',
data: { building_id: buildingId },
success: function (response) {
const dropdown = $('#editFloorId');
dropdown.empty().append('<option value="">Select Floor</option>');
if (response.status === 'OK') {
response.data.forEach(floor => {
const selected = floor.floors_id == selectedFloorId ? 'selected' : '';
dropdown.append(`<option value="${floor.floors_id}" ${selected}>${floor.floor_name}</option>`);
});
}
},
error: function () {
Swal.fire("Error", "Failed to load floors", "error");
}
});
}
$('#addBuildingId').on('change', function () {
const buildingId = $(this).val();
$.get('/gcc/api/gccschool/dropdown/getFloorsByBuilding', { building_id: buildingId }, function (response) {
const dropdown = $('#addFloorId');
dropdown.empty().append('<option value="">Select Floor</option>');
if (response.status === 'OK') {
response.data.forEach(floor => {
dropdown.append(`<option value="${floor.floors_id}">${floor.floor_name}</option>`);
});
}
});
});
$('#roomDelete').on('click', function () {
const roomId = $('#editRoomId').val();
const isDelete = true;
Swal.fire({
title: 'Are you sure?',
text: "Do you really want to delete this room?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then((result) => {
if (result.isConfirmed) {
// Call AJAX only if user confirms
$.ajax({
url: '/gcc/api/gccschool/buildingasset/deleteRoom',
method: 'POST',
data: {
room_id: roomId,
is_delete: isDelete
},
success: function (response) {
Swal.fire({
icon: 'success',
title: 'Success',
text: response,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(() => {
location.reload();
});
},
error: function () {
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Failed to delete the room.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
// Show info alert when cancelled
Swal.fire({
icon: 'info',
title: 'Cancelled',
text: 'No changes were made.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
});
});
</script>
</html>

1589
frontend/school/roomassets.html
File diff suppressed because it is too large
View File

775
frontend/school/staffdetails.html

@ -0,0 +1,775 @@
<!DOCTYPE html>
<html lang="en" dir="ltr" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<meta charset="UTF-8" />
<title>Staff Strength Management</title>
<style>
body {
background-color: #f8f9fa;
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
/* Optional: styling update button gap */
.btn-gap {
margin-left: 1rem;
}
</style>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap CSS (you may already have it from your fragments) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" />
<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-4">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card p-3">
<div id="staffReadOnlyView" class="container mt-4" style="display: none; "></div>
<!-- Update Button for Staff (if record exists) -->
<div class="text-center mt-3" id="updateStaffContainer" style="display: none;">
<button type="button" class="btn btn-primary" id="updateStaffBtn">Update</button>
</div>
<!-- Container for Editable Staff Form -->
<div id="staffFormContainer">
<form id="staffStrengthForm" novalidate>
<!-- SG Teachers -->
<div class="col-md-12">
<div class="card" style="background-color: lightgrey; padding: 20px;">
<div class="card-header">
<b>1. SG Teachers *</b>
</div>
<div class="row mt-3">
<div class="col-md-3">
<label>No of Regu Teachers</label>
<input type="number" class="form-control" name="sgRegTeacher" id="sgRegTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Smc Teachers</label>
<input type="number" class="form-control" name="sgTempTeacher" id="sgTempTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Part-time Teachers</label>
<input type="number" class="form-control" name="sgPtTeacher" id="sgPtTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of NGO Teachers</label>
<input type="number" class="form-control" name="sgNgoTeacher" id="sgNgoTeacher" placeholder="Enter Value" required />
</div>
</div>
</div>
</div>
<!-- BT Teachers -->
<div class="col-md-12">
<div class="card" style="background-color: aliceblue; padding: 20px; ">
<div class="card-header">
<b>2. BT Teachers *</b>
</div>
<div class="row mt-3">
<div class="col-md-3">
<label>No of Regu Teachers</label>
<input type="number" class="form-control" name="btRegTeacher" id="btRegTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Smc Teachers</label>
<input type="number" class="form-control" name="btTempTeacher" id="btTempTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Part-time Teachers</label>
<input type="number" class="form-control" name="btPtTeacher" id="btPtTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of NGO Teachers</label>
<input type="number" class="form-control" name="btNgoTeacher" id="btNgoTeacher" placeholder="Enter Value" required />
</div>
</div>
</div>
</div>
<!-- PG Teachers -->
<div class="col-md-12">
<div class="card" style="background-color: cornsilk; padding: 20px;">
<div class="card-header">
<b>3. PG Teachers *</b>
</div>
<div class="row mt-3">
<div class="col-md-3">
<label>No of Regu Teachers</label>
<input type="number" class="form-control" name="pgRegTeacher" id="pgRegTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Smc Teachers</label>
<input type="number" class="form-control" name="pgTempTeacher" id="pgTempTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Part-time Teachers</label>
<input type="number" class="form-control" name="pgPtTeacher" id="pgPtTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of NGO Teachers</label>
<input type="number" class="form-control" name="pgNgoTeacher" id="pgNgoTeacher" placeholder="Enter Value" required />
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="card mt-3" style="background-color: lavender; padding: 20px;">
<div class="card-header">
<b>4. PET Teachers*</b>
</div>
<div class="row mt-3">
<div class="col-md-3">
<label>No of Regu Teachers</label>
<input type="number" class="form-control" name="petRegTeacher" id="petRegTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Smc Teachers</label>
<input type="number" class="form-control" name="petTempTeacher" id="petTempTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Grade 1 Teachers</label>
<input type="number" class="form-control" name="petGrade1Teacher" id="petGrade1Teacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Grade 2 Teachers</label>
<input type="number" class="form-control" name="petGrade2Teacher" id="petGrade2Teacher" placeholder="Enter Value" required />
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="card mt-3" style="background-color: honeydew; padding: 20px; ">
<div class="card-header">
<b>5. kG Teachers*</b>
</div>
<div class="row mt-3">
<div class="col-md-3">
<label>No of Regu Teachers</label>
<input type="number" class="form-control" name="kgRegTeacher" id="kgRegTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of Smc Teachers</label>
<input type="number" class="form-control" name="kgTempTeacher" id="kgTempTeacher" placeholder="Enter Value" required />
</div>
</div>
</div>
</div>
<!-- Other Details -->
<div class="col-md-12">
<div class="card" style="padding: 20px; background-color: #f8f9fa; margin-top: 10px;">
<div class="card-header">
<b>Other Details *</b>
</div>
<div class="row mt-3">
<!-- <div class="col-md-3">
<label>No of KG Teachers</label>
<input type="number" class="form-control" name="kgTeacher" id="kgTeacher" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>No of PT Teachers</label>
<input type="number" class="form-control" name="petTeacher" id="petTeacher" placeholder="Enter Value" required />
</div>-->
<div class="col-md-3">
<label>Total No of OA</label>
<input type="number" class="form-control" name="totOa" id="totOa" placeholder="Enter Value" required />
</div>
<div class="col-md-3">
<label>KG Ayah</label>
<input type="number" class="form-control" name="kgAyah" id="kgAyah" placeholder="Enter Value" required />
</div>
<div class="col-md-3 mt-3">
<label>Computer Assistance</label>
<input type="number" class="form-control" name="compAss" id="compAss" placeholder="Enter Value" required />
</div>
<div class="col-md-3 mt-3">
<label>Watchman</label>
<input type="number" class="form-control" name="watchmen" id="watchmen" placeholder="Enter Value" required />
</div>
<div class="col-md-3 mt-3">
<label>Scavengers</label>
<input type="number" class="form-control" name="scavengers" id="scavengers" placeholder="Enter Value" required />
</div>
<div class="col-md-3 mt-3">
<label>Sweeper</label>
<input type="number" class="form-control" name="maintenanceWork" id="maintenanceWork" placeholder="Enter Value" required />
</div>
</div>
<div class="card-footer text-center mt-3">
<button type="submit" class="btn btn-primary" id="requestSubmitBtn">
<i class="ik ik-save"></i> Submit
</button>
<button type="reset" class="btn btn-secondary ml-2" id="resetButton">
<i class="ik ik-refresh-cw"></i> Reset
</button>
</div>
</div>
</div>
</form>
</div>
<!-- End of Staff Form -->
<!-- Page Loader -->
<div id="pageLoader" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Staff Update Modal -->
<div class="modal fade" id="staffUpdateModal" tabindex="-1">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Staff Strength</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<div class="row g-3">
<!-- SG Section -->
<div class="col-md-3"><label>SG - Regu Teachers *</label><input type="number" id="modal_sgRegTeacher" class="form-control" /></div>
<div class="col-md-3"><label>SG - Smc Teachers *</label><input type="number" id="modal_sgTempTeacher" class="form-control" /></div>
<div class="col-md-3"><label>SG - Part-time Teachers *</label><input type="number" id="modal_sgPtTeacher" class="form-control" /></div>
<div class="col-md-3"><label>SG - NGO Teachers *</label><input type="number" id="modal_sgNgoTeacher" class="form-control" /></div>
<!-- BT Section -->
<div class="col-md-3"><label>BT - Regu Teachers *</label><input type="number" id="modal_btRegTeacher" class="form-control" /></div>
<div class="col-md-3"><label>BT - Smc Teachers *</label><input type="number" id="modal_btTempTeacher" class="form-control" /></div>
<div class="col-md-3"><label>BT - Part-time Teachers *</label><input type="number" id="modal_btPtTeacher" class="form-control" /></div>
<div class="col-md-3"><label>BT - NGO Teachers *</label><input type="number" id="modal_btNgoTeacher" class="form-control" /></div>
<!-- PG Section -->
<div class="col-md-3"><label>PG - Regu Teachers *</label><input type="number" id="modal_pgRegTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PG - Smc Teachers *</label><input type="number" id="modal_pgTempTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PG - Part-time Teachers *</label><input type="number" id="modal_pgPtTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PG - NGO Teachers *</label><input type="number" id="modal_pgNgoTeacher" class="form-control" /></div>
<!-- PET Section -->
<div class="col-md-3"><label>PET - Regu Teachers *</label><input type="number" id="modal_petRegTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PET - Smc Teachers *</label><input type="number" id="modal_petTempTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PET - Grade 1 Teachers *</label><input type="number" id="modal_petg1Teacher" class="form-control" /></div>
<div class="col-md-3"><label>PET - Grade 2 Teachers *</label><input type="number" id="modal_petg2Teacher" class="form-control" /></div>
<!-- kg Section -->
<div class="col-md-3"><label>KG - Regu Teachers *</label><input type="number" id="modal_kgRegTeacher" class="form-control" /></div>
<div class="col-md-3"><label>KG - Smc Teachers *</label><input type="number" id="modal_kgTempTeacher" class="form-control" /></div>
<!-- Other Section -->
<!-- <div class="col-md-3"><label>KG Teachers *</label><input id="modal_kgTeacher" class="form-control" /></div>
<div class="col-md-3"><label>PT Teachers *</label><input id="modal_petTeacher" class="form-control" /></div>-->
<div class="col-md-3"><label>Total OA *</label><input type="number" id="modal_totOa" class="form-control" /></div>
<div class="col-md-3"><label>KG Ayah *</label><input type="number" id="modal_kgAyah" class="form-control" /></div>
<div class="col-md-3"><label>Computer Assistance *</label><input type="number" id="modal_compAss" class="form-control" /></div>
<div class="col-md-3"><label>Watchmen *</label><input type="number" id="modal_watchmen" class="form-control" /></div>
<div class="col-md-3"><label>Scavengers *</label><input type="number" id="modal_scavengers" class="form-control" /></div>
<div class="col-md-3"><label>Sweeper *</label><input type="number" id="modal_maintenanceWork" class="form-control" /></div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="saveStaffModalUpdate">Save Changes</button>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<!-- Scripts -->
<script>
$(document).ready(function () {
const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId");
// Allow only whole positive numbers in number fields
document.querySelectorAll('input[type="number"]').forEach(function (input) {
input.addEventListener("input", function () {
this.value = this.value.replace(/[^0-9]/g, "");
if (parseInt(this.value) < 0) {
this.value = "";
}
});
});
// Fetch staff data against schoolId
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getStaffStrengthBySchoolId',
type: 'GET',
data: { schoolId },
success: function (response) {
console.log(response);
if (response.status === 'OK' && response.staffStrength.length > 0) {
const data = response.staffStrength[0];
// Build a read-only table with fetched staff data
const tableHtml = `
<h6 class="text-left mb-3"><b>Staff Strength Details</b></h6>
<hr>
<!-- SG Teachers -->
<h6><b>1. SG Teachers *</b></h6>
<table class="table">
<tbody>
<tr><td>No of Regu Teachers</td><td>${data.sg_reg_teacher || 0}</td></tr>
<tr><td>No of Smc Teachers</td><td>${data.sg_temp_teacher || 0}</td></tr>
<tr><td>No of Part-time Teachers</td><td>${data.sg_pt_teacher || 0}</td></tr>
<tr><td>No of NGO Teachers</td><td>${data.sg_ngo_teacher || 0}</td></tr>
</tbody>
</table>
<!-- BT Teachers -->
<h6><b>2. BT Teachers *</b></h6>
<table class="table">
<tbody>
<tr><td>No of Regu Teachers</td><td>${data.bt_reg_teacher || 0}</td></tr>
<tr><td>No of Smc Teachers</td><td>${data.bt_temp_teacher || 0}</td></tr>
<tr><td>No of Part-time Teachers</td><td>${data.bt_pt_teacher || 0}</td></tr>
<tr><td>No of NGO Teachers</td><td>${data.bt_ngo_teacher || 0}</td></tr>
</tbody>
</table>
<!-- PG Teachers -->
<h6><b>3. PG Teachers *</b></h6>
<table class="table">
<tbody>
<tr><td>No of Regu Teachers</td><td>${data.pg_reg_teacher || 0}</td></tr>
<tr><td>No of Smc Teachers</td><td>${data.pg_temp_teacher || 0}</td></tr>
<tr><td>No of Part-time Teachers</td><td>${data.pg_pt_teacher || 0}</td></tr>
<tr><td>No of NGO Teachers</td><td>${data.pg_ngo_teacher || 0}</td></tr>
</tbody>
</table>
<!-- PG Teachers -->
<h6><b>4. PET Teachers *</b></h6>
<table class="table">
<tbody>
<tr><td>No of Regu Teachers</td><td>${data.pet_reg_teacher || 0}</td></tr>
<tr><td>No of Smc Teachers</td><td>${data.pet_temp_teacher || 0}</td></tr>
<tr><td>No of Grade 1 Teachers</td><td>${data.pet_grade1_teacher || 0}</td></tr>
<tr><td>No of Grade 2 Teachers</td><td>${data.pet_grade2_teacher || 0}</td></tr>
</tbody>
</table>
<!-- PG Teachers -->
<h6><b>5. kG Teachers *</b></h6>
<table class="table">
<tbody>
<tr><td>No of Regu Teachers</td><td>${data.kg_reg_teacher || 0}</td></tr>
<tr><td>No of Smc Teachers</td><td>${data.kg_temp_teacher || 0}</td></tr>
</tbody>
</table>
<!-- Other Details -->
<h6><b>6. Other Details *</b></h6>
<table class="table">
<tbody>
<tr><td>Total OA</td><td>${data.tot_oa || 0}</td></tr>
<tr><td>KG Ayah</td><td>${data.kg_ayah || 0}</td></tr>
<tr><td>Computer Assistance</td><td>${data.comp_ass || 0}</td></tr>
<tr><td>Watchmen</td><td>${data.watchmen || 0}</td></tr>
<tr><td>Scavengers</td><td>${data.scavengers || 0}</td></tr>
<tr><td>Sweeper</td><td>${data.maintenance_work || 0}</td></tr>
</tbody>
</table>
`;
// Populate read-only view and hide staff form
$('#staffReadOnlyView').html(tableHtml).show();
$('#staffFormContainer').hide();
$('#updateStaffContainer').show();
// Bind Update button click event to open the modal with prefilled values
$('#updateStaffBtn').click(() => {
$('#modal_sgRegTeacher').val(data.sg_reg_teacher);
$('#modal_sgTempTeacher').val(data.sg_temp_teacher);
$('#modal_sgPtTeacher').val(data.sg_pt_teacher);
$('#modal_sgNgoTeacher').val(data.sg_ngo_teacher);
$('#modal_btRegTeacher').val(data.bt_reg_teacher);
$('#modal_btTempTeacher').val(data.bt_temp_teacher);
$('#modal_btPtTeacher').val(data.bt_pt_teacher);
$('#modal_btNgoTeacher').val(data.bt_ngo_teacher);
$('#modal_pgRegTeacher').val(data.pg_reg_teacher);
$('#modal_pgTempTeacher').val(data.pg_temp_teacher);
$('#modal_pgPtTeacher').val(data.pg_pt_teacher);
$('#modal_pgNgoTeacher').val(data.pg_ngo_teacher);
$('#modal_petRegTeacher').val(data.pet_reg_teacher);
$('#modal_petTempTeacher').val(data.pet_temp_teacher);
$('#modal_petg1Teacher').val(data.pet_grade1_teacher);
$('#modal_petg2Teacher').val(data.pet_grade2_teacher);
$('#modal_kgRegTeacher').val(data.kg_reg_teacher);
$('#modal_kgTempTeacher').val(data.kg_temp_teacher);
$('#modal_totOa').val(data.tot_oa);
$('#modal_kgAyah').val(data.kg_ayah);
$('#modal_compAss').val(data.comp_ass);
$('#modal_watchmen').val(data.watchmen);
$('#modal_scavengers').val(data.scavengers);
$('#modal_maintenanceWork').val(data.maintenance_work);
$('#staffUpdateModal').modal('show');
});
} else {
// No staff data found – show form for entry
$('#staffReadOnlyView').hide();
$('#staffFormContainer').show();
$('#updateStaffContainer').hide();
}
}
});
// Staff Form submission event
$("#staffStrengthForm").submit(function (event) {
event.preventDefault();
console.log("Submit button clicked for Staff");
console.log("SchoolId:", schoolId);
// Validation: Check required fields
/* const requiredFields = {
'sgRegTeacher': 'SG - Regular Teachers',
'sgTempTeacher': 'SG - Temp Teachers',
'sgPtTeacher': 'SG - Part-time Teachers',
'sgNgoTeacher': 'SG - NGO Teachers',
'btRegTeacher': 'BT - Regular Teachers',
'btTempTeacher': 'BT - Temp Teachers',
'btPtTeacher': 'BT - Part-time Teachers',
'btNgoTeacher': 'BT - NGO Teachers',
'pgRegTeacher': 'PG - Regular Teachers',
'pgTempTeacher': 'PG - Temp Teachers',
'pgPtTeacher': 'PG - Part-time Teachers',
'pgNgoTeacher': 'PG - NGO Teachers',
'kgTeacher': 'KG Teachers',
'petTeacher': 'PT Teachers',
'totOa': 'Total OA',
'kgAyah': 'KG Ayah',
'compAss': 'Computer Assistance',
'watchmen': 'Watchman',
'scavengers': 'Scavengers',
'maintenanceWork': 'Maintenance Works'
};*/
const requiredFields = {
sgRegTeacher: 'SG - Regular Teachers',
sgTempTeacher: 'SG - Smc Teachers',
sgPtTeacher: 'SG - Part-time Teachers',
sgNgoTeacher: 'SG - NGO Teachers',
btRegTeacher: 'BT - Regular Teachers',
btTempTeacher: 'BT - Smc Teachers',
btPtTeacher: 'BT - Part-time Teachers',
btNgoTeacher: 'BT - NGO Teachers',
pgRegTeacher: 'PG - Regular Teachers',
pgTempTeacher: 'PG - Smc Teachers',
pgPtTeacher: 'PG - Part-time Teachers',
pgNgoTeacher: 'PG - NGO Teachers',
petRegTeacher: 'PET - Regular Teachers',
petTempTeacher: 'PET - Smc Teachers',
petGrade1Teacher: 'PET - Grade 1 Teachers',
petGrade2Teacher: 'PET - Grade 2 Teachers',
kgRegTeacher: 'KG - Regular Teachers',
kgTempTeacher: 'KG - Smc Teachers',
totOa: 'Total OA',
kgAyah: 'KG Ayah',
compAss: 'Computer Assistance',
watchmen: 'Watchman',
scavengers: 'Scavengers',
maintenanceWork: 'Sweeper'
};
for (let fieldId in requiredFields) {
const value = $(`#${fieldId}`).val();
if (value === null || value.trim() === "" || isNaN(Number(value)) || parseInt(value) < 0) {
Swal.fire({
icon: 'warning',
title: 'Missing or Invalid Input',
text: `Please enter a valid number for "${requiredFields[fieldId]}"`,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
}
// Show loader before submitting
$('#pageLoader').show();
// Prepare form data
var formData = new FormData(document.getElementById("staffStrengthForm"));
formData.append("schoolId", schoolId);
// Debug log (optional)
const debugObj = {};
formData.forEach((value, key) => {
debugObj[key] = value;
});
console.log("Form Data Collected:", debugObj);
// Submit via AJAX
$.ajax({
type: "POST",
url: "/gcc/api/gccschool/schoolproperty/saveStaffStrength",
data: formData,
processData: false,
contentType: false,
success: function (response) {
$("#pageLoader").hide();
console.log("Data Submitted Successfully:", response);
Swal.fire({
icon: "success",
title: "Data Saved!",
text: "Staff strength details saved successfully!",
confirmButtonColor: "#3085d6",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => {
$("#staffStrengthForm")[0].reset();
// Optionally, reload page to refresh view
location.reload();
});
},
error: function (xhr, status, error) {
$("#pageLoader").hide();
console.error("Submission Error:", xhr.responseText);
Swal.fire({
icon: "error",
title: "Error!",
text: "Something went wrong. Please try again.",
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonColor: "#d33"
});
}
});
});
function resetStaffFields() {
console.log("Reset button clicked");
$('#staffStrengthForm input[type="number"]').val('');
}
$(document).on('click', '#resetButton', function (event) {
event.preventDefault();
resetStaffFields();
});
// Reset Button click event
/* $("#resetButton").click(function () {
Swal.fire({
title: "Are you sure?",
text: "This will reset all form fields!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, reset!"
}).then((result) => {
if (result.isConfirmed) {
$("input[type='number']").val("");
Swal.fire("Reset!", "Form has been cleared.", "success");
}
});
});*/
// Handle Save from Staff Update Modal
$("#saveStaffModalUpdate").on('click', function () {
const modalRequiredFields = {
modal_sgRegTeacher: 'SG - Regular Teachers',
modal_sgTempTeacher: 'SG - Smc Teachers',
modal_sgPtTeacher: 'SG - Part-time Teachers',
modal_sgNgoTeacher: 'SG - NGO Teachers',
modal_btRegTeacher: 'BT - Regular Teachers',
modal_btTempTeacher: 'BT - Smc Teachers',
modal_btPtTeacher: 'BT - Part-time Teachers',
modal_btNgoTeacher: 'BT - NGO Teachers',
modal_pgRegTeacher: 'PG - Regular Teachers',
modal_pgTempTeacher: 'PG - Smc Teachers',
modal_pgPtTeacher: 'PG - Part-time Teachers',
modal_pgNgoTeacher: 'PG - NGO Teachers',
modal_petRegTeacher: 'PET - Regular Teachers',
modal_petTempTeacher: 'PET - Smc Teachers',
modal_petg1Teacher: 'PET - Grade 1 Teachers',
modal_petg2Teacher: 'PET - Grade 2 Teachers',
modal_kgRegTeacher: 'KG - Regular Teachers',
modal_kgTempTeacher: 'KG - Smc Teachers',
modal_totOa: 'Total OA',
modal_kgAyah: 'KG Ayah',
modal_compAss: 'Computer Assistance',
modal_watchmen: 'Watchmen',
modal_scavengers: 'Scavengers',
modal_maintenanceWork: 'Sweeper'
};
for (let fieldId in modalRequiredFields) {
const value = $(`#${fieldId}`).val();
if (value === null || value.trim() === "" || isNaN(Number(value)) || parseInt(value) < 0) {
Swal.fire({
icon: 'warning',
title: 'Missing or Invalid Input',
text: `Please enter a valid number for "${modalRequiredFields[fieldId]}"`,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return false; // Prevent further execution if validation fails
}
}
const updatedData = {
sgRegTeacher: $('#modal_sgRegTeacher').val(),
sgTempTeacher: $('#modal_sgTempTeacher').val(),
sgPtTeacher: $('#modal_sgPtTeacher').val(),
sgNgoTeacher: $('#modal_sgNgoTeacher').val(),
btRegTeacher: $('#modal_btRegTeacher').val(),
btTempTeacher: $('#modal_btTempTeacher').val(),
btPtTeacher: $('#modal_btPtTeacher').val(),
btNgoTeacher: $('#modal_btNgoTeacher').val(),
pgRegTeacher: $('#modal_pgRegTeacher').val(),
pgTempTeacher: $('#modal_pgTempTeacher').val(),
pgPtTeacher: $('#modal_pgPtTeacher').val(),
pgNgoTeacher: $('#modal_pgNgoTeacher').val(),
petRegTeacher: $('#modal_petRegTeacher').val(),
petTempTeacher: $('#modal_petTempTeacher').val(),
petGrade1Teacher: $('#modal_petg1Teacher').val(),
petGrade2Teacher: $('#modal_petg2Teacher').val(),
kgRegTeacher: $('#modal_kgRegTeacher').val(),
kgTempTeacher: $('#modal_kgTempTeacher').val(),
totOa: $('#modal_totOa').val(),
kgAyah: $('#modal_kgAyah').val(),
compAss: $('#modal_compAss').val(),
watchmen: $('#modal_watchmen').val(),
scavengers: $('#modal_scavengers').val(),
maintenanceWork: $('#modal_maintenanceWork').val(),
school_id: schoolId // IMPORTANT: use same name as @RequestParam
};
$('#pageLoader').show();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/updateStaffDetails',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $.param(updatedData),
success: function (res) {
$('#pageLoader').hide();
$('#staffUpdateModal').modal('hide');
// Swal.fire('Updated!', res, 'success').then(() => location.reload());
Swal.fire({
title: 'Updated!',
text: 'Staff strength details updated successfully!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => location.reload());
},
error: function (err) {
$('#pageLoader').hide();
Swal.fire({
title: 'Error',
text: err.responseText,
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
//Swal.fire('Error', err.responseText, 'error');
}
});
});
});
</script>
</body>
</html>

687
frontend/school/studentdetails.html

@ -0,0 +1,687 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}"></head>
<style>
body {
background-color: #f8f9fa;
/* font-family: Arial, sans-serif;*/
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
.info-table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
.info-table td,
.info-table th {
border: 1px solid #ddd;
padding: 10px;
vertical-align: middle;
}
.info-table td:first-child {
font-weight: bold;
width: 50%;
}
.info-table td:last-child {
color: #555;
}
.btn-gap {
margin-left: 1rem;
/* or any value you like */
}
.student-data-wrapper {
padding: 0px;
margin-top: -58px;
margin-left: -186px;
width: 120%;
}
@media (max-width: 768px) {
.student-data-wrapper {
margin-left: 0;
width: 100%;
padding: 0 15px; /* Optional horizontal spacing */
}
}
</style>
<body>
<div class="wrapper">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div class="page-wrap">
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card">
<div class="main-content" style="background-color: white;">
<!-- <div class="container">
<div>
<div style="padding: 0px;margin-top:-58px;margin-left: -233px;width:120%;">
<div class="row" style=" padding: 15px;">
<div class="col-md-6 form-group">
<label>Total No of Students <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Enter the value"
id="total_students" required />
</div>
</div>
<div class="row" style=" padding: 15px;">
<div class="col-md-4 form-group">
<label>No of Boys <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Enter the value"
id="total_boys" required />
</div>
<div class="col-md-4 form-group">
<label>No of Girls <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Enter the value"
id="total_girls" required />
</div>
<div class="col-md-4 form-group">
<label>Others <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Enter the value"
id="others" required />
</div>
</div>
<div class="card-footer text-center" >
<button type="submit" class="btn btn-primary" id="StudentSubmitBtn"><i
class="ik ik-save"></i>Submit
</button>
<button type="reset" class="btn btn-secondary mr-2" id="StudentresetButton"><i
class="ik ik-refresh-cw"></i>Reset
</button>
</div>
</div>-->
<div class="student-data-wrapper">
<div class="card-header d-flex justify-content-between align-items-center">
<b>Student Details</b>
</div>
<!-- Read-only View -->
<div id="studentReadOnlyView" style="display: none;">
<table class="info-table">
<tr>
<td>Total No of Students</td>
<td id="readonly_total_students">-</td>
</tr>
<tr>
<td>No of Boys</td>
<td id="readonly_total_boys">-</td>
</tr>
<tr>
<td>No of Girls</td>
<td id="readonly_total_girls">-</td>
</tr>
<tr>
<td>Transgender</td>
<td id="readonly_others">-</td>
</tr>
</table>
<br>
<div class=" text-center">
<button type="button" class="btn btn-primary" id="processupdate"
style="display:none;">Update</button>
</div>
</div>
<!-- Editable Form -->
<div id="studentEntryForm" style="display: none;">
<div class="row p-3">
<div class="col-md-6 form-group">
<label>Total No of Student <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="total_students" required />
</div>
</div>
<div class="row p-3">
<div class="col-md-4 form-group">
<label>No of Boys <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="total_boys" required />
</div>
<div class="col-md-4 form-group">
<label>No of Girls <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="total_girls" required />
</div>
<div class="col-md-4 form-group">
<label>Transgender <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="others" required />
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary" id="StudentSubmitBtn"><i
class="ik ik-save"></i> Submit</button>
<button type="reset" class="btn btn-secondary" id="StudentresetButton"><i
class="ik ik-refresh-cw"></i> Reset</button>
</div>
</div>
<!-- Modal for Update -->
<div class="modal fade" id="studentUpdateModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Student Details</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="form-group"><label>Total Students *</label><input
id="modal_total_students" class="form-control"></div>
<div class="form-group"><label>No of Boys *</label><input id="modal_total_boys"
class="form-control"></div>
<div class="form-group"><label>No of Girls *</label><input
id="modal_total_girls" class="form-control"></div>
<div class="form-group"><label>Transgender *</label><input id="modal_others"
class="form-control"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveModalUpdate">Save
Changes</button>
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div id="pageLoader"
style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; text-align: center;">
<div style="position: relative; top: 50%; transform: translateY(-50%);">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>
<!-- Add the 'Please wait' text below the spinner -->
<p style="margin-top: 1rem; font-size: 1.2rem; color: #007bff;">Please wait...</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
const urlParams = new URLSearchParams(window.location.search);
const schoolId = urlParams.get("schoolId");
document.getElementById('total_students').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('total_boys').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('total_girls').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('others').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('modal_total_students').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('modal_total_boys').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('modal_total_girls').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
document.getElementById('modal_others').addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) {
this.value = '';
}
});
/* $.ajax({
url: '/gcc/api/gccschool/buildingasset/getStudentStrengthBySchoolId',
type: 'GET',
data: {schoolId},
success: function (response) {
console.log(response);
if (response.status === 'OK') {
if(response.studentStrength.length > 0){
const data = response.studentStrength[0]; // Get the first object from the array
// Show the update button (assuming it's an ID, use #)
$('#processupdate').show();
//$('.card-footer').hide();
$('#StudentSubmitBtn').hide();
$('#StudentresetButton').hide();
$('#refreshButton').show();
// Populate values into the respective HTML elements
$('#total_students').val(data.total_students || 0);
$('#total_boys').val(data.total_boys || 0);
$('#total_girls').val(data.total_girls || 0);
$('#others').val(data.others || 0);
}else
{
// Optional: handle the case where studentStrength is empty
$('#total_students').text('');
$('#total_boys').text('');
$('#total_girls').text('');
$('#others').text('');
$('#processupdate').hide(); // hide update button if no data
}
}
else if(response.status==='NEW'){
$('#processupdate').hide();
$('#refreshButton').hide();
$('.card-footer').show();
}
}
});*/
$.ajax({
url: '/gcc/api/gccschool/buildingasset/getStudentStrengthBySchoolId',
type: 'GET',
data: {schoolId},
success: function (response) {
if (response.status === 'OK' && response.studentStrength.length > 0) {
const data = response.studentStrength[0];
$('#readonly_total_students').text(data.total_students || 0);
$('#readonly_total_boys').text(data.total_boys || 0);
$('#readonly_total_girls').text(data.total_girls || 0);
$('#readonly_others').text(data.others || 0);
$('#studentReadOnlyView').show();
$('#studentEntryForm').hide();
$('#processupdate').show();
$('#refreshButton').show();
} else {
$('#studentReadOnlyView').hide();
$('#studentEntryForm').show();
$('.card-footer').show();
$('#processupdate').hide();
$('#refreshButton').hide();
}
}
});
$('#processupdate').on('click', function () {
$('#modal_total_students').val($('#readonly_total_students').text());
$('#modal_total_boys').val($('#readonly_total_boys').text());
$('#modal_total_girls').val($('#readonly_total_girls').text());
$('#modal_others').val($('#readonly_others').text());
$('#studentUpdateModal').modal('show');
});
$('#saveModalUpdate').on('click', function () {
let requestData = {
total_students: parseInt($('#modal_total_students').val()) || 0,
total_boys: parseInt($('#modal_total_boys').val()) || 0,
total_girls: parseInt($('#modal_total_girls').val()) || 0,
others: parseInt($('#modal_others').val()) || 0,
school_id: schoolId
};
if (!$('#modal_total_students').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter Total No of Students.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#modal_total_boys').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Boys.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#modal_total_girls').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Girls.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#modal_others').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Transgender.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (requestData.total_students !== (requestData.total_boys + requestData.total_girls + requestData.others)) {
Swal.fire('Validation Error', 'Total should equal Boys + Girls + Transgender.', 'warning');
return;
}
$('#pageLoader').show();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/updateStudentDetails',
type: 'POST',
contentType: 'application/x-www-form-urlencoded', // important
data: $.param(requestData), // flatten the object correctly
success: function (res) {
console.log("res:" + res);
$('#pageLoader').hide();
$('#studentUpdateModal').modal('hide');
// Swal.fire('Updated!', res, 'success').then(() => location.reload());
Swal.fire({
title: 'Updated!',
text: 'Student strength details updated successfully!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => location.reload());
},
error: function (err) {
$('#pageLoader').hide();
Swal.fire({
title: 'Error',
text: err.responseText,
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
// Swal.fire('Error', err.responseText, 'error');
}
});
});
$(document).on('click', '#StudentSubmitBtn', function () {
//parseInt($('#tot_staff').val()) || 0;
let total_students = parseInt($('#total_students').val()) || 0;
let total_boys = parseInt($('#total_boys').val()) || 0;
let total_girls = parseInt($('#total_girls').val()) || 0;
let others = parseInt($('#others').val()) || 0;
//let school_id = 1;
console.log("total_students=", total_students);
console.log("total_boys=", total_boys);
console.log("total_girls=", total_girls);
console.log("others=", others);
console.log("school_id=", schoolId);
if (!$('#total_students').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter Total No of Students.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#total_boys').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Boys.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#total_girls').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Girls.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
if (!$('#others').val().trim()) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please enter No of Transgender.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}
// Validate inputs
let fields = {
"Total No of Students": total_students,
"No of Boys": total_boys,
"No of Girls": total_girls,
"Others": others,
};
/*for (let key in fields) {
if (!fields[key] || isNaN(fields[key])) {
Swal.fire({
icon: 'info',
title: 'Validation Error',
text: `Please enter ${key}` + " , IF No means Enter 0",
confirmButtonText: 'OK'
});
return; // Stop execution if validation fails
}
}*/
if (total_students !== (total_boys + total_girls + others)) {
Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Total Students must be equal to the sum of No of Boys, No of Girls, and Transgender.',
allowOutsideClick: false, // Disable clicking outside the modal to close it
allowEscapeKey: false, // Disable escape key to close the modal
allowEnterKey: false, // Disable enter key to close the modal
showConfirmButton: true
});
return;
}
// Prepare Data for AJAX
let requestData = {
total_students: total_students,
total_boys: total_boys,
total_girls: total_girls,
school_id: schoolId,
others: others
};
$('#StudentSubmitBtn').prop('disabled', true).text('Processing...');
$('#pageLoader').show();
$.ajax({
url: '/gcc/api/gccschool/schoolproperty/saveStudentStrength',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $.param(requestData),
success: function (response) {
$('#pageLoader').hide();
$('#StudentSubmitBtn').prop('disabled', false).text('Submit');
Swal.fire({
icon: 'success',
title: 'Success',
text: response,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
$('#StudentSubmitBtn').prop('disabled', false).text('Submit');
location.reload();
}
});
},
error: function (xhr, status, error) {
$('#pageLoader').hide();
$('#StudentSubmitBtn').prop('disabled', false).text('Submit');
let errorMessage = xhr.responseText;
Swal.fire({
icon: 'error',
title: 'Error',
text: errorMessage,
confirmButtonText: 'OK'
});
console.error('Error:', xhr.responseText);
}
});
});
function resetStudentFields() {
console.log("Reset button clicked");
$('#total_students, #total_boys, #total_girls, #others').val('');
}
// Event Listener for Reset Button
$(document).on('click', '#StudentresetButton', function (event) {
event.preventDefault();
resetStudentFields();
});
$('#refreshButton').on('click', function (e) {
e.preventDefault(); // prevent default reset behavior, optional
location.reload();
});
});
</script>
</body>
</html>

567
frontend/school/toilets.html

@ -0,0 +1,567 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/modules/base/head :: head}">
<style>
body {
background-color: #f8f9fa;
}
.header {
font-size: 22px;
font-weight: bold;
margin-bottom: 20px;
}
.table {
border: 1px solid #dee2e6;
}
.table th,
.table td {
border: 1px solid #dee2e6;
padding: 10px;
}
.section-title {
font-size: 18px;
font-weight: bold;
margin-top: 20px;
border-bottom: 2px solid #007bff;
padding-bottom: 5px;
}
.form-group {
margin-top: 15px;
}
.radio-group {
display: flex;
gap: 20px;
margin-top: 10px;
}
.card1 {
padding: 0px;
margin-top: -58px;
margin-left: -230px;
}
/* ✅ Responsive Fix for Mobile Screens */
@media (max-width: 768px) {
.card1 {
margin-top: 0 !important;
padding: 15px;
}
.container {
padding-left: 10px;
padding-right: 10px;
}
}
@media (max-width: 768px) {
#toiletDataContainer table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
} </style>
</head>
<body>
<div class="container mt-4">
<header th:replace="~{fragments/modules/base/header :: header}"></header>
<div th:replace="~{fragments/modules/base/menu :: menu}"></div>
<div class="card p-3">
<div class="card-header">
<b>Toilets</b>
</div>
<br>
<!-- View Table -->
<div id="toiletDataContainer" style="display: none;">
<table class="table table-bordered">
<tr>
<th>No of Toilet Blocks</th>
<td id="td_blocks"></td>
<th>Male Toilets (Urinals)</th>
<td id="td_urinals"></td>
</tr>
<tr>
<th>Male Toilets (W.C)</th>
<td id="td_wc_male"></td>
<th>Female Toilets (W.C)</th>
<td id="td_wc_female"></td>
</tr>
<tr>
<th>Differently Abled Toilets</th>
<td id="td_disabled"></td>
<th>Incinerator for Napkin Disposal</th>
<td id="td_napkins"></td>
</tr>
</table>
<div class="text-center">
<button class="btn btn-primary" id="editToiletBtn">Update</button>
</div>
</div>
<form id="toiletForm" novalidate>
<input type="hidden" name="school_id">
<input type="hidden" id="toilet_id" name="toilet_id" />
<div class="row p-3">
<div class="col-md-6 form-group">
<label>No of Toilet Blocks *</label>
<input type="text" class="form-control" name="total_toiletBlocks"
id="total_toiletBlocks" required>
</div>
<div class="col-md-6 form-group">
<label>Total Male Toilets (Urinals) *</label>
<input type="text" class="form-control" name="total_male_urinals"
id="total_male_urinals" required>
</div>
</div>
<div class="row p-3">
<div class="col-md-6 form-group">
<label>Total Male Toilets (W.C) *</label>
<input type="text" class="form-control" name="total_wc_male"
id="total_wc_male" required>
</div>
<div class="col-md-6 form-group">
<label>Total Female Toilets (W.C) *</label>
<input type="text" class="form-control" name="total_wc_female"
id="total_wc_female" required>
</div>
<div class="col-md-6 form-group">
<label>Incinerator for Napkins Disposal *</label>
<div class="radio-group">
<input type="radio" name="is_napkins" value="true"> Yes
<input type="radio" name="is_napkins" value="false"> No
</div>
</div>
<div class="col-md-6 form-group">
<label>Differently Abled Toilets *</label>
<input type="text" class="form-control" name="total_diffAbled_toilet"
id="total_diffAbled_toilet" required>
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary"><i class="ik ik-save"></i>
Submit</button>
<button type="reset" class="btn btn-secondary"><i class="ik ik-refresh-cw"></i>
Reset</button>
</div>
</form>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="toiletModal" tabindex="-1" aria-labelledby="toiletModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="toiletUpdateForm">
<div class="modal-header">
<h5 class="modal-title">Update Toilet Details</h5>
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<input type="hidden" id="modal_toilet_id" />
<input type="hidden" id="modal_school_id" />
<div class="mb-2"><label>No of Toilet Blocks *</label><input type="number" id="modal_blocks"
class="form-control" required /></div>
<div class="mb-2"><label>Male Toilets (Urinals) *</label><input type="number"
id="modal_urinals" class="form-control" required /></div>
<div class="mb-2"><label>Male Toilets (W.C) *</label><input type="number" id="modal_wc_male"
class="form-control" required /></div>
<div class="mb-2"><label>Female Toilets (W.C) *</label><input type="number"
id="modal_wc_female" class="form-control" required /></div>
<div class="mb-2"><label>Differently Abled Toilets *</label><input type="number"
id="modal_disabled" class="form-control" required /></div>
<div class="mb-2">
<label>Incinerator for Napkin Disposal *</label><br>
<input type="radio" name="modal_napkins" value="true" /> Yes
<input type="radio" name="modal_napkins" value="false" /> No
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script th:replace="~{fragments/modules/base/script :: script}"></script>
<script>
$(document).ready(function () {
const schoolId = new URLSearchParams(window.location.search).get("schoolId");
$('input[name="school_id"]').val(schoolId);
$('#modal_school_id').val(schoolId);
/*$('#total_toiletBlocks').on('input', function () {
const value = parseInt($(this).val()) || 0;
if (value === 0) {
$('#total_male_urinals').val(0);
$('#total_wc_male').val(0);
$('#total_wc_female').val(0);
$('#total_diffAbled_toilet').val(0);
}
else{
$('#total_male_urinals').val('');
$('#total_wc_male').val('');
$('#total_wc_female').val('');
$('#total_diffAbled_toilet').val('');
}
});*/
/* $('#modal_blocks').on('input', function () {
const value = parseInt($(this).val()) || 0;
if (value === 0) {
$('#modal_urinals').val(0);
$('#modal_wc_male').val(0);
$('#modal_wc_female').val(0);
$('#modal_disabled').val(0);
}
else{
$('#modal_urinals').val('');
$('#modal_wc_male').val('');
$('#modal_wc_female').val('');
$('#modal_disabled').val('');
}
});*/
// ✅ Enforce only numeric input
['total_toiletBlocks', 'total_male_urinals', 'total_wc_male', 'total_wc_female', 'total_diffAbled_toilet']
.forEach(id => {
document.getElementById(id).addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) this.value = '';
});
});
['modal_blocks', 'modal_urinals', 'modal_wc_male', 'modal_wc_female', 'modal_disabled']
.forEach(id => {
document.getElementById(id).addEventListener('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value) < 0) this.value = '';
});
});
// ✅ Function to reload table data after update
function reloadToiletTable() {
$.get('/gcc/api/gccschool/schoolproperty/checkToiletDetails', { school_id: schoolId }, function (res) {
if (res && res[0]?.Data?.length > 0) {
const d = res[0].Data[0];
// Update table with fresh values
$('#td_blocks').text(d.total_toiletBlocks);
$('#td_urinals').text(d.total_male_urinals);
$('#td_wc_male').text(d.total_wc_male);
$('#td_wc_female').text(d.total_wc_female);
$('#td_disabled').text(d.total_diffAbled_toilet);
$('#td_napkins').text(d.is_napkins === true || d.is_napkins === "true" ? 'Yes' : 'No');
$('#toiletDataContainer').show();
$('#editToiletBtn').data('toiletData', d);
}
});
}
// ✅ Initial load
$.get('/gcc/api/gccschool/schoolproperty/checkToiletDetails', { school_id: schoolId }, function (res) {
if (res && res[0]?.Data?.length > 0) {
const d = res[0].Data[0];
$('#toilet_id').val(d.toilet_id);
$('#toiletForm').hide();
$('#toiletDataContainer').show();
$('#td_blocks').text(d.total_toiletBlocks);
$('#td_urinals').text(d.total_male_urinals);
$('#td_wc_male').text(d.total_wc_male);
$('#td_wc_female').text(d.total_wc_female);
$('#td_disabled').text(d.total_diffAbled_toilet);
$('#td_napkins').text(d.is_napkins === true ? 'Yes' : 'No');
$('#editToiletBtn').data('toiletData', d);
} else {
$('#toiletForm').show();
$('#toiletDataContainer').hide();
}
});
// ✅ Save new toilet form (first time entry)
$('#toiletForm').submit(function (e) {
e.preventDefault();
const blocks = parseInt($('#total_toiletBlocks').val()) || 0;
const urinals = parseInt($('#total_male_urinals').val()) || 0;
const wc_male = parseInt($('#total_wc_male').val()) || 0;
const wc_female = parseInt($('#total_wc_female').val()) || 0;
const diff_abled = parseInt($('#total_diffAbled_toilet').val()) || 0;
const isNapkins = $('input[name="is_napkins"]:checked').val();
/* if (blocks === 0) {
$('#total_male_urinals').val(0);
$('#total_wc_male').val(0);
$('#total_wc_female').val(0);
$('#total_diffAbled_toilet').val(0);
}*/
if ($('#total_toiletBlocks').val().trim() === '') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter Total Toilet Blocks ',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if ($('#total_male_urinals').val().trim() === '') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter number of Male Urinals (0 or more).',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if ($('#total_wc_male').val().trim() === '') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter number of Male WC (0 or more).',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if ($('#total_wc_female').val().trim() === '') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter number of Female WC (0 or more).',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if (typeof isNapkins === 'undefined') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Please select whether there is an Incinerator for Napkins Disposal.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
if ($('#total_diffAbled_toilet').val().trim() === '') {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter number of Differently Abled Toilets (0 or more).',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}
// Total toilets entered
/* const totalToilets = urinals + wc_male + wc_female + diff_abled;
if (blocks !== totalToilets) {
Swal.fire({
icon: 'warning',
title: 'Mismatch Detected',
text: `The number of toilet blocks (${blocks}) must match the total toilets (${totalToilets}) entered.`,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}*/
const formData = new FormData(this);
$.ajax({
type: 'POST',
url: '/gcc/api/gccschool/schoolproperty/saveToilets',
data: formData,
processData: false,
contentType: false,
success: res => {
// Swal.fire('Saved', res, 'success').then(() => {
Swal.fire({
title: 'Saved',
text: res,
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => {
location.reload();
// $('#toiletForm').hide();
// reloadToiletTable(); // refresh table
});
},
error: xhr =>Swal.fire({
title: 'Error',
text: xhr.responseText || 'Unknown error',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
})
//Swal.fire('Error', xhr.responseText || 'Unknown error', 'error')
});
});
let originalModalData = {};
$('#editToiletBtn').click(function () {
const d = $(this).data("toiletData");
$('#modal_toilet_id').val(d.toilet_id);
$('#modal_blocks').val(d.total_toiletBlocks);
$('#modal_urinals').val(d.total_male_urinals);
$('#modal_wc_male').val(d.total_wc_male);
$('#modal_wc_female').val(d.total_wc_female);
$('#modal_disabled').val(d.total_diffAbled_toilet);
$(`input[name="modal_napkins"][value="${d.is_napkins}"]`).prop('checked', true);
// ✅ Store original values
originalModalData = {
total_toiletBlocks: d.total_toiletBlocks.toString(),
total_male_urinals: d.total_male_urinals.toString(),
total_wc_male: d.total_wc_male.toString(),
total_wc_female: d.total_wc_female.toString(),
total_diffAbled_toilet: d.total_diffAbled_toilet.toString(),
is_napkins: d.is_napkins.toString()
};
const modal = new bootstrap.Modal(document.getElementById('toiletModal'));
modal.show();
});
$('#toiletUpdateForm').submit(function (e) {
e.preventDefault();
const updateBlocks = parseInt($('#modal_blocks').val()) || 0;
const updateUrinals = parseInt($('#modal_urinals').val()) || 0;
const updateWCMale = parseInt($('#modal_wc_male').val()) || 0;
const updateWCFemale = parseInt($('#modal_wc_female').val()) || 0;
const updateDisabled = parseInt($('#modal_disabled').val()) || 0;
/* if (!updateBlocks ) {
return Swal.fire({
icon: 'warning',
title: 'Validation Error',
text: 'Enter Total Toilet Blocks greater than 0.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
}*/
/* const updateTotal = updateUrinals + updateWCMale + updateWCFemale + updateDisabled;
if (updateBlocks !== updateTotal) {
Swal.fire({
icon: 'warning',
title: 'Mismatch Detected',
text: `The number of toilet blocks (${updateBlocks}) must match the total toilets (${updateTotal}) entered.`,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
return;
}*/
const currentData = {
total_toiletBlocks: $('#modal_blocks').val(),
total_male_urinals: $('#modal_urinals').val(),
total_wc_male: $('#modal_wc_male').val(),
total_wc_female: $('#modal_wc_female').val(),
total_diffAbled_toilet: $('#modal_disabled').val(),
is_napkins: $('input[name="modal_napkins"]:checked').val()
};
// ✅ Check if any value has changed
const hasChanged = Object.keys(currentData).some(key => currentData[key] !== originalModalData[key]);
/* if (!hasChanged) {
Swal.fire('No Changes', 'Please make a change before submitting.', 'info');
return;
}*/
currentData.school_id = $('#modal_school_id').val();
$.post('/gcc/api/gccschool/schoolproperty/updateToiletDetails', currentData, function () {
// Swal.fire('Updated', 'Toilet data updated successfully!', 'success').then(() => {
Swal.fire({
title: 'Updated',
text: 'Toilet data updated successfully!',
icon: 'success',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
}).then(() => {
const modalInstance = bootstrap.Modal.getInstance(document.getElementById('toiletModal'));
modalInstance.hide();
location.reload();
});
}).fail(() => {
// Swal.fire('Error', 'Update failed', 'error');
Swal.fire({
title: 'Error',
text: 'Update failed',
icon: 'error',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
showConfirmButton: true
});
});
});
});
</script>
</body>
</html>
Loading…
Cancel
Save