From 5e8975d9d5dff131f6068280a5b6f172ed1cb84b Mon Sep 17 00:00:00 2001 From: Balaji <104271023+tbalaji0001@users.noreply.github.com> Date: Sat, 24 May 2025 12:22:23 +0530 Subject: [PATCH] New Module Added New modules updated --- .DS_Store | Bin 6148 -> 6148 bytes mobileservice/.DS_Store | Bin 8196 -> 8196 bytes mobileservice/src/.DS_Store | Bin 6148 -> 6148 bytes mobileservice/src/main/.DS_Store | Bin 6148 -> 6148 bytes .../mobileservice/ImageUrlValidator.java | 78 + .../controller/BusShelterController.java | 92 ++ .../busshelters/controller/package-info.java | 1 + .../busshelters/package-info.java | 1 + .../service/BusShelterActivity.java | 507 ++++++ .../busshelters/service/package-info.java | 1 + .../controller/APIC_D_WasteController.java | 285 ++++ .../API_C_D_WasteUserController.java | 59 + .../c_d_waste/controller/package-info.java | 1 + .../mobileservice/c_d_waste/package-info.java | 1 + .../c_d_waste/service/c_d_WasteService.java | 1397 ++++++++++++++++ .../service/c_d_WasteUserService.java | 1073 +++++++++++++ .../c_d_waste/service/package-info.java | 1 + .../component/ApiLoggingFilter.java | 64 + .../mobileservice/component/package-info.java | 1 + .../configuration/AppConfig.java | 1 + .../configuration/DataSourceConfig.java | 101 +- .../configuration/WebConfig.java | 26 + .../gccactivity/service/Activity.java | 42 + .../controller/EducationController.java | 149 ++ .../gcceducation/controller/package-info.java | 1 + .../gcceducation/package-info.java | 1 + .../service/EducationActivity.java | 1067 +++++++++++++ .../gcceducation/service/package-info.java | 1 + .../gccparks/controller/ParksController.java | 238 ++- .../gccparks/service/ParksService.java | 277 +++- .../controller/SchoolUserController.java | 12 +- .../service/SchoolUserActivity.java | 66 +- .../controller/StreetVendorController.java | 267 ++++ .../controller/package-info.java | 1 + .../service/StreetVendorService.java | 337 ++++ .../gccstreetvendor/service/package-info.java | 1 + .../hoardings/services/HoardingsService.java | 25 +- .../controller/API_FoggingController.java | 213 +++ .../controller/API_MosquitoController.java | 136 ++ .../controller/package-info.java | 1 + .../mosquitosurvey/package-info.java | 1 + .../service/FoggingService.java | 1404 +++++++++++++++++ .../service/MosquitoService.java | 570 +++++++ .../mosquitosurvey/service/package-info.java | 1 + .../penalty/service/CattleCatchService.java | 143 +- .../toilets/controller/APIController.java | 33 +- .../toilets/service/activity.java | 198 ++- .../works/controller/WorksController.java | 98 ++ .../works/controller/package-info.java | 1 + .../mobileservice/works/package-info.java | 1 + .../works/service/WorksService.java | 699 ++++++++ .../works/service/package-info.java | 1 + .../resources/application-local.properties | 4 +- .../application-production.properties | 4 +- .../src/main/resources/application.properties | 11 +- 55 files changed, 9482 insertions(+), 212 deletions(-) create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/ImageUrlValidator.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/ApiLoggingFilter.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/WebConfig.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/EducationController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/StreetVendorController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/StreetVendorService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_FoggingController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_MosquitoController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/FoggingService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/MosquitoService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/WorksController.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/package-info.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/WorksService.java create mode 100644 mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/package-info.java diff --git a/.DS_Store b/.DS_Store index 7b6c89dd4e51811f119a5b60ef9f68d419240acf..edfd92dea5dfe8033ff47507c67ccd0829c57d2b 100644 GIT binary patch delta 548 zcmZoMXfc=|#>B!ku~2NHo+2a5#(>?7ixZfc7+EIsFqJa0Pi|t0X5^TBk14%AGr6oF zDJMUPfr0T*QbA5;afyM!eE|VRCT12^Hg*n9E^Z!PK7Ii~Az?ugK~YgrF>z5LNh#@g z0pX;?=lq=fBBz|v)OZ2@;*9)q&*c2PfTGm0%+&ITlGKWl;LIwZln|PR zpwyJOq26E^PGE@B1(uz|{B9PdTAnTHg@^f+m@{2P|GV}8y zW5Cvzq~?0&rR4*y1UbRK03=l$mReK{q|x-$=jTPl<|HPi=J@A1<(HJ?=SC(L6(#1S zr#e+eWCHyGay!`0;DW^D%)E4E`wt9Yz^Uw@0bvO+C_@+w3>+db7L;b>49UySOI3CV zfCwl%ctd447_=E283KbDVi*b;8W^TCEM{2GaFF2~!()c8jLeL@jAD#RjM|JkjHZm{ zj1G*Bj6saSj1i295baEiP-A4EG?Ze@0>-f1WLM^Eo7p+|Ie=+kb0G6~=E?jbjvPQO NOdw^OBSh9P0{|?Kj>`Z5 delta 79 zcmZoMXfc=|#>B)qu~2NHo+2aj#(>?7jLegHSV|c=CO5G}GjdM8$C5tTkp0?b1&%k& io7p+|Ie^MH3vzsCp3E=e$iV;vj0_Acn6<&~H3OQ<_*vTavICt*ZX(C^5d*1NxC2PAua!8*#R277<^{$}pTBj3|$oYpiQ@fVn zzHjr8MwGMW#>hS*y%pBsiDlYCEl5k@9U{U6r!+&(oV&j35x>SNJc@X)=?dYpE~)G~ zG@Jq)*rwv9QM69x*IC+c2!^UdAL?gk@N5 zzy@r=9=w7BcnhE43w(#4IE!;Qj~8(f%XkHs(86V`V*?#@GxZE+2P delta 115 zcmZp1XmOa}&nUPtU^hRb;N-Q!7Lz9k6f$y5W)+KOYf0C{!C78ktN^5EYr+DW)=chG-5<|K>!oWsDme{FyehOMGKt LVqn}@$jS@=)JY)> diff --git a/mobileservice/src/.DS_Store b/mobileservice/src/.DS_Store index 43bd6ff5bc85ed79da12a2848f77704b1822309e..547ae1dedaaf84bc4249b44ce8cfcd8ed442fd1e 100644 GIT binary patch delta 112 zcmZoMXffE}%_O`fsURn_xWvHV8Y2@k3o9Et2m9nWrf7E#&UgWl>S_ZW1%p~0g=%vX uAj`tsw6>O$LsVJcIw(FnCpRy@jR6c886h+SFO-H+?VFi_hAw8|5C8zWU=-2- delta 89 zcmZoMXffE}%_O`%sURn_xWvHV8Y2@k3o9Et2gl?%rf4lr&UgXw>S`l%V;u#9S{;RI sLqj7I9R&+>)7n~24pC)&>!A4ToZP(p&dCp$S_ZW1%p~0g=%vX oAj`tsw6>O$LsVJcIw(FnCpRy@ZE`)EJY)N2W>yyF#Vi~G0Np getBusShelterList(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "loginId", required = false) String loginId){ + return busShelterActivity.getBusShelterList(formData, latitude, longitude,loginId); + } + + @GetMapping(value="/getQuestionsList") // Old App + public List getQuestionsList(@RequestParam(value="loginId", required = false) String cby){ + return busShelterActivity.getQuestionsList(); + } + + @GetMapping(value="/getParentQuestionsList") + public List getParentQuestionsList( + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value="qtype", required = true) String qtype){ + return busShelterActivity.getParentQuestionsList(qtype); + } + + @GetMapping(value="/getChildQuestionsList") + public List getChildQuestionsList( + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value="pid", required = true) String pid + ){ + return busShelterActivity.getChildQuestionsList(pid); + } + + @PostMapping(value="/saveFeedback") + public List saveFeedback( + @RequestParam(value="shelter_id", required = true) String shelter_id, + @RequestParam(value="loginId", required = true) String cby, + @RequestParam(value="latitude", required = true) String latitude, + @RequestParam(value="longitude", required = true) String longitude, + @RequestParam(value="action", required = true) String type, + @RequestParam(value="zone", required = true) String zone, + @RequestParam(value="ward", required = true) String ward, + @RequestParam(value="q_1", required = false) String q_1, + @RequestParam(value="q_2", required = false) String q_2, + @RequestParam(value="q_3", required = false) String q_3, + @RequestParam(value="q_4", required = false) String q_4, + @RequestParam(value="q_5", required = false) String q_5, + @RequestParam(value="q_6", required = false) String q_6, + @RequestParam(value="q_7", required = false) String q_7, + @RequestParam(value="q_8", required = false) String q_8, + @RequestParam(value="q_9", required = false) String q_9, + @RequestParam(value="q_10", required = false) String q_10, + @RequestParam(value="q_11", required = false) String q_11, + @RequestParam(value="remarks", required = false) String remarks, + @RequestParam(value = "file", required = false) MultipartFile filedata, + + @RequestParam(value="file_1", required = false) MultipartFile file_1, + @RequestParam(value="file_2", required = false) MultipartFile file_2, + @RequestParam(value="file_3", required = false) MultipartFile file_3, + @RequestParam(value="file_4", required = false) MultipartFile file_4, + @RequestParam(value="file_5", required = false) MultipartFile file_5, + @RequestParam(value="file_6", required = false) MultipartFile file_6, + @RequestParam(value="file_7", required = false) MultipartFile file_7, + @RequestParam(value="file_8", required = false) MultipartFile file_8, + @RequestParam(value="file_9", required = false) MultipartFile file_9, + @RequestParam(value="file_10", required = false) MultipartFile file_10, + @RequestParam(value="file_11", required = false) MultipartFile file_11 + ){ + return busShelterActivity.saveFeedback(shelter_id, cby, latitude, longitude, zone, ward, + q_1, q_2, q_3, q_4, q_5, q_6, q_7, q_8, q_9, q_10, q_11, remarks, filedata, + file_1, file_2, file_3, file_4, file_5, file_6, file_7, file_8, file_9, file_10, file_11,type); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java new file mode 100644 index 0000000..d1e67af --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.busshelters.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java new file mode 100644 index 0000000..34d1cfd --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.busshelters; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java new file mode 100644 index 0000000..a3f790d --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java @@ -0,0 +1,507 @@ +package in.gov.chennaicorporation.mobileservice.busshelters.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class BusShelterActivity { + private JdbcTemplate jdbcBusShelterTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlBusShelterDataSource") DataSource BusShelterDataSource) { + this.jdbcBusShelterTemplate = new JdbcTemplate(BusShelterDataSource); + } + + @Autowired + public BusShelterActivity(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("busshelter_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + ////////////////////////////// + public String getConfigValue() { + String sqlQuery = "SELECT `id`, `lat_long_radius` FROM `config` LIMIT 1"; + String value = "50"; // default fallback value + List> results = jdbcBusShelterTemplate.queryForList(sqlQuery); + + if (!results.isEmpty()) { + Map row = results.get(0); + value = String.valueOf(row.get("lat_long_radius")); // corrected key name + } + + return value; + } + + + ////////////////////////////// + + public List> getBusShelterList( + MultiValueMap formData, + String latitude, + String longitude, + String loginid + ) { + + String sqlWhere = ""; + String radius = getConfigValue(); + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude)), 9))) < "+radius+")" + + " ORDER BY" + + " bsl.`id` DESC"; + } + + String sql = "SELECT " + + " bsl.*, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', bsl.image) AS photo, " + + " bf.type AS qtype, " + + " DATE_FORMAT(bf.latest_feedback_date, '%d-%m-%Y') AS latestfeedbackdate " + + "FROM " + + " bus_shelter_list bsl " + + "LEFT JOIN ( " + + " SELECT " + + " bsf.shelter_id, " + + " bsf.type, " + + " bsf.cdate AS latest_feedback_date " + + " FROM " + + " bus_shelter_feedback bsf " + + " INNER JOIN ( " + + " SELECT " + + " shelter_id, " + + " MAX(id) AS max_id " + + " FROM " + + " bus_shelter_feedback " + + " GROUP BY shelter_id " + + " ) latest ON bsf.shelter_id = latest.shelter_id AND bsf.id = latest.max_id " + + ") bf ON bsl.id = bf.shelter_id " + + "WHERE " + + " bsl.isactive = 1 " + + " AND bsl.gcc_app_updated = 0 "+sqlWhere; + System.out.println(sql); + List> result = jdbcBusShelterTemplate.queryForList(sql); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getQuestionsList() { + String sql = "SELECT * FROM question_list WHERE isactive=1"; + List> result = jdbcBusShelterTemplate.queryForList(sql); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getParentQuestionsList(String qtype) { + //String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0 AND `qtype` LIKE ?"; + String sql = "SELECT ql.id AS question_id, ql.q_english, ql.q_tamil, " + + "ql.isactive, ql.img_required, ql.pid, ql.qtype, ql.feedbacktype, " + + "CASE WHEN ql.feedbacktype = 'select' THEN JSON_ARRAYAGG" + + "( JSON_OBJECT( 'option_id', qov.id, 'english_name', qov.english_name, 'tamil_name', " + + "qov.tamil_name, 'value', qov.value, 'isactive', qov.isactive, 'isdelete', qov.isdelete ) ) " + + "ELSE NULL END AS options FROM question_list ql " + + "LEFT JOIN q_option_value qov ON qov.qid = ql.id " + + "AND ql.feedbacktype = 'select' WHERE ql.isactive = 1 AND `pid`=0 AND `qtype` LIKE ? GROUP BY ql.id"; + + List> result = jdbcBusShelterTemplate.queryForList(sql,"%" + qtype + "%"); + + ObjectMapper mapper = new ObjectMapper(); + for (Map row : result) { + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Parent Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getChildQuestionsList(String pid) { + String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?"; + List> result = jdbcBusShelterTemplate.queryForList(sql,pid); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Bus Shelter Child Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public String inactiveFeedBack(String type, String toilet_id) { + + String sql = "UPDATE `bus_shelter_feedback` SET `isactive`=0 WHERE DATE(`bus_shelter_feedback`.`cdate`) = CURDATE() AND `type`= ? AND `shelter_id`=?"; + jdbcBusShelterTemplate.update(sql,type,toilet_id); + + return "sussess"; + } + + @Transactional + public List> saveFeedback( + String shelter_id, + String cby, + String latitude, + String longitude, + String zone, + String ward, + String q_1, + String q_2, + String q_3, + String q_4, + String q_5, + String q_6, + String q_7, + String q_8, + String q_9, + String q_10, + String q_11, + String remarks, + MultipartFile file, + + MultipartFile file_1, + MultipartFile file_2, + MultipartFile file_3, + MultipartFile file_4, + MultipartFile file_5, + MultipartFile file_6, + MultipartFile file_7, + MultipartFile file_8, + MultipartFile file_9, + MultipartFile file_10, + MultipartFile file_11, + String type) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + String image_q1 = ""; + String image_q2 = ""; + String image_q3 = ""; + String image_q4 = ""; + String image_q5 = ""; + String image_q6 = ""; + String image_q7 = ""; + String image_q8 = ""; + String image_q9 = ""; + String image_q10 = ""; + String image_q11 = ""; + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + image = fileUpload("feedback", "0", file); + } + + // Question Images + if (file_1 != null && !file_1.isEmpty()) { + image_q1 = fileUpload("1", "q1", file_1); + } + + if (file_2 != null && !file_2.isEmpty()) { + image_q2 = fileUpload("2", "q2", file_2); + } + + if (file_3 != null && !file_3.isEmpty()) { + image_q3 = fileUpload("3", "q3", file_3); + } + + if (file_4 != null && !file_4.isEmpty()) { + image_q4 = fileUpload("4", "q4", file_4); + } + + if (file_5 != null && !file_5.isEmpty()) { + image_q5 = fileUpload("5", "q5", file_5); + } + + if (file_6 != null && !file_6.isEmpty()) { + image_q6 = fileUpload("6", "q6", file_6); + } + + if (file_7 != null && !file_7.isEmpty()) { + image_q7 = fileUpload("7", "q7", file_7); + } + + if (file_8 != null && !file_8.isEmpty()) { + image_q8 = fileUpload("8", "q8", file_8); + } + + if (file_9 != null && !file_9.isEmpty()) { + image_q9 = fileUpload("9", "q9", file_9); + } + + if (file_10 != null && !file_10.isEmpty()) { + image_q10 = fileUpload("10", "q10", file_10); + } + + if (file_11 != null && !file_11.isEmpty()) { + image_q11 = fileUpload("11", "q11", file_11); + } + + String feedbackimg = image; + + String q1_image = image_q1; + String q2_image = image_q2; + String q3_image = image_q3; + String q4_image = image_q4; + String q5_image = image_q5; + String q6_image = image_q6; + String q7_image = image_q7; + String q8_image = image_q8; + String q9_image = image_q9; + String q10_image = image_q10; + String q11_image = image_q11; + + //String type = // Get before & after + + // Get today's date + LocalDate today = LocalDate.now(); + + // Format it in the desired format (yyyy-MM-dd) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayDate = today.format(formatter); + + inactiveFeedBack(type, shelter_id); // Upadte already insert data. + + String sqlQuery = "INSERT INTO `bus_shelter_feedback`(" + + "`shelter_id`, `cby`, " + + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " + + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`," + + "`q1_image`, `q2_image`, `q3_image`, `q4_image`, `q5_image`, `q6_image`, " + + "`q7_image`, `q8_image`, `q9_image`, `q10_image`, `q11_image`" + + ") " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcBusShelterTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, shelter_id); + ps.setString(2, cby); + ps.setString(3, q_1); + ps.setString(4, q_2); + ps.setString(5, q_3); + ps.setString(6, q_4); + ps.setString(7, q_5); + ps.setString(8, q_6); + ps.setString(9, q_7); + ps.setString(10, q_8); + ps.setString(11, q_9); + ps.setString(12, q_10); + ps.setString(13, q_11); + ps.setString(14, remarks); + ps.setString(15, latitude); + ps.setString(16, longitude); + ps.setString(17, zone); + ps.setString(18, ward); + ps.setString(19, type); + ps.setString(20, feedbackimg); + + ps.setString(21, q1_image); + ps.setString(22, q2_image); + ps.setString(23, q3_image); + ps.setString(24, q4_image); + ps.setString(25, q5_image); + ps.setString(26, q6_image); + ps.setString(27, q7_image); + ps.setString(28, q8_image); + ps.setString(29, q9_image); + ps.setString(30, q10_image); + ps.setString(31, q11_image); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new feedback was inserted successfully!"); + System.out.println("A new feedback was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new feedback. Asset ID:" + shelter_id); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java new file mode 100644 index 0000000..fb2e6bb --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.busshelters.service; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java new file mode 100644 index 0000000..0954246 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java @@ -0,0 +1,285 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.c_d_waste.service.c_d_WasteService; + +@RequestMapping("/gccofficialapp/c_dwaste/api") +@RestController("apiCandDWasteRest") +public class APIC_D_WasteController { + + @Autowired + private c_d_WasteService c_d_WasteService; + + @GetMapping("/getWasteTypeList") + public List getWasteTypeList( + ) { + return c_d_WasteService.getWasteTypeList(); + } + + @GetMapping("/checkComplaintExits") + public List checkComplaintExits( + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return c_d_WasteService.checkComplaintExits(latitude,longitude); + } + + @PostMapping(value="/saveWaste") + public List saveWaste(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "address", required = true) String address, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "tonage", required = true) String tonage, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "wastetype", required = true) String type + ) { + return c_d_WasteService.saveWaste(cby,latitude,longitude,zone,ward,address,tonage,file, type); + } + + @PostMapping(value="/saveVendorWaste") + public List saveVendorWaste(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "address", required = true) String address, + @RequestParam(value = "ref_id", required = true) String ref_id, + @RequestParam(value = "tonage", required = true) int tonage, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "wastetype", required = true) String type + ) { + return c_d_WasteService.saveVendorWaste(latitude,longitude,zone,ward,address,tonage,file,type,ref_id); + } + + @GetMapping("/getComplaintList") + public List getComplaintList( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE + ) { + return c_d_WasteService.getComplaintList(fromDATE,toDATE); + } + + @PostMapping(value="/updateComplaint") + public List updateComplaint(@RequestParam MultiValueMap formData, + @RequestParam(value = "comp_id", required = true) String wlid, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "after_image", required = true) String file, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "completed_date", required = true) String datetxt, + @RequestParam(value = "tonage", required = true) String tonage + ) { + return c_d_WasteService.saveReply(wlid,latitude,longitude,file,remarks,datetxt,tonage); + } + + + @GetMapping("/getMyticketllist") + public List getMyticketllist( + @RequestParam(value = "loginId", required = true) String loginId + ) { + return c_d_WasteService.getMyticketllist(loginId); + } + + @GetMapping("/getApprovalPendingList") + public List getApprovalPendingList( + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "ward", required = true) String ward + ) { + return c_d_WasteService.getApprovalPendingList(loginId,ward); + } + + @GetMapping("/checkApprovalLocation") + public List checkApprovalLocation( + @RequestParam(value = "comp_id", required = true) String id, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return c_d_WasteService.checkApprovalLocation(id,latitude,longitude); + } + + @PostMapping(value="/saveApproval") + public List saveApproval(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "comp_id", required = true) String comp_id, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "in_out", required = true) String in_out, + @RequestParam(value = "status", required = true) String status, + @RequestParam(value = "reject_txt", required = false) String reject_txt + ) { + return c_d_WasteService.saveApproval(loginId, comp_id, latitude, longitude, in_out, status, reject_txt); + } + + @GetMapping("/get2ApprovalPendingList") + public List get2ApprovalPendingList( + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "ward", required = true) String ward + ) { + return c_d_WasteService.get2ApprovalPendingList(loginId,ward); + } + + @PostMapping(value="/save2Approval") + public List save2Approval(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "comp_id", required = true) String comp_id, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "status", required = true) String status + ) { + return c_d_WasteService.save2Approval(loginId, comp_id, latitude, longitude, status); + } + + @GetMapping("/getZoneWiseCount") + public List getZoneWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Vendor','Officer'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getZoneWiseCount(fromDATE,toDATE,requestBy); + } + + @GetMapping("/getWardWiseCount") + public List getWardWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Vendor','Officer'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getWardWiseCount(fromDATE,toDATE, zone,requestBy); + } + + @GetMapping("/getOfficerZoneWiseCount") + public List getOfficerZoneWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Officer'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getOfficerZoneWiseCount(fromDATE,toDATE,requestBy); + } + + @GetMapping("/getOfficerWardWiseCount") + public List getOfficerWardWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Officer'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getOfficerWardWiseCount(fromDATE,toDATE, zone,requestBy); + } + + @GetMapping("/getVendorZoneWiseCount") + public List getVendorZoneWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Vendor'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getVendorZoneWiseCount(fromDATE,toDATE,requestBy); + } + + @GetMapping("/getVendorWardWiseCount") + public List getVendorWardWiseCount( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Vendor'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getVendorWardWiseCount(fromDATE,toDATE, zone,requestBy); + } + + @GetMapping("/getListByStatus") + public List getComplaintList( + @RequestParam(value = "fromDate", required = true) String fromDATE, + @RequestParam(value = "toDate", required = true) String toDATE, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "status", required = true) String status, + @RequestParam(value = "requestBy", required = false) String requestBy + ) { + + if (requestBy == null || requestBy.isBlank()) { + requestBy = "'Vendor','Officer'"; + } + else { + requestBy = "'"+requestBy+"'"; + } + + return c_d_WasteService.getListByStatus(fromDATE,toDATE, zone, ward, status,requestBy); + } + + @GetMapping("/getWardSumReport") + public List getWardSumReport( + @RequestParam(value = "fromDate", required = false) String fromDATE, + @RequestParam(value = "toDate", required = false) String toDATE, + @RequestParam(value = "ward", required = true) String ward + ) { + return c_d_WasteService.getWardSumReport(ward); + } + + @GetMapping("/getTicketDetailsByWLID") + public List getTicketDetailsByWLID( + @RequestParam(value = "wlid", required = true) String wlid + ) { + return c_d_WasteService.getTicketDetailsByWLID(wlid); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java new file mode 100644 index 0000000..baed4ee --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java @@ -0,0 +1,59 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.c_d_waste.service.c_d_WasteUserService; + +@RequestMapping("/gccofficialapp/c_dwaste/api") +@RestController("apiCandDUserWasteRest") +public class API_C_D_WasteUserController { + + @Autowired + private c_d_WasteUserService c_d_WasteUserService; + + @PostMapping(value="/saveUserWaste") + public List saveuserWaste(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = false) String latitude, + @RequestParam(value = "longitude", required = false) String longitude, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "address", required = true) String address, + @RequestParam(value = "ref_id", required = true) String ref_id, + @RequestParam(value = "tonage", required = true) String tonage, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "wastetype", required = true) String type + ) { + return c_d_WasteUserService.saveUserWaste(latitude,longitude,zone,ward,address,tonage,file,type,ref_id); + } + + @GetMapping("/getUserApprovalPendingList") + public List getApprovalPendingList( + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "ward", required = true) String ward + ) { + return c_d_WasteUserService.getApprovalPendingList(loginId,ward); + } + + @PostMapping(value="/saveUserApproval") + public List saveApproval(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "comp_id", required = true) String comp_id, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "in_out", required = true) String in_out, + @RequestParam(value = "status", required = true) String status, + @RequestParam(value = "tonage_kg", required = true) String tonage_kg, + @RequestParam(value = "reject_txt", required = false) String reject_txt + ) { + return c_d_WasteUserService.saveApproval(loginId, comp_id, latitude, longitude, in_out, status, reject_txt, tonage_kg); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/package-info.java new file mode 100644 index 0000000..c6334e4 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java new file mode 100644 index 0000000..953aee6 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java new file mode 100644 index 0000000..3bd29a2 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java @@ -0,0 +1,1397 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +import javax.net.ssl.*; +import java.security.cert.X509Certificate; +import java.security.NoSuchAlgorithmException; +import java.security.KeyManagementException; + +@Service +public class c_d_WasteService { + private JdbcTemplate jdbcWasteTemplate; + private JdbcTemplate jdbcPGRTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource( + @Qualifier("mysqlC_D_WasteDataSource") DataSource wasteDataSource, + @Qualifier("mysqlPGRMasterDataSource") DataSource pgrDataSource + ) { + this.jdbcWasteTemplate = new JdbcTemplate(wasteDataSource); + this.jdbcPGRTemplate = new JdbcTemplate(pgrDataSource); + } + + @Autowired + public c_d_WasteService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + //CONCAT('"+fileBaseUrl+"/gccofficialapp/files/', al.image) AS imageUrl, + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("c_d_waste_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + var date =DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public String fileUrlUpload(String name, String id, String fileUrl) { + + // Set the directory for saving the file + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("c_d_waste_foldername"); + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + month +"/reply"; + + try { + // Bypass SSL certificate validation (this will ignore SSL handshake errors) + TrustManager[] trustAllCertificates = new TrustManager[]{ + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCertificates, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Generate datetime string for the file name + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + + // Generate a random string for the file name + String fileName = name + "_" + id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + ".jpg"; // Assuming it's a .jpg file + fileName = fileName.replaceAll("\\s+", ""); // Remove spaces in filename + + String filePath = uploadDirectory + "/" + fileName; // Full local file path + String relativeFilePath = "/" + serviceFolderName + year + "/" + month + "/reply/" + fileName; // Relative path to save in DB + + // Create a URL object from the file URL + URL url = new URL(fileUrl); + + // Open a connection to the URL and download the file + try (InputStream inputStream = url.openStream()) { + // Write the input stream to the local file + Files.copy(inputStream, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING); + System.out.println("File downloaded and saved at: " + filePath); + } + + // Return the relative path to be stored in the database + return relativeFilePath; + + } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { + e.printStackTrace(); + System.out.println("Failed to download and save file from URL " + fileUrl); + return "error"; + } + } + + public List> getWasteTypeList() { + String sql = "SELECT * FROM `waste_type` WHERE isactive=1 ORDER BY `name`"; + return jdbcWasteTemplate.queryForList(sql); + } + + public List> checkComplaintExits(String latitude, String longitude) { + + String sql = "SELECT " + + " wlm.`wlid` AS comp_id, " + + " wlm.`zone` AS comp_zone, " + + " wlm.`ward` AS comp_ward, " + + " eg_user.`EXTRAFIELD2` AS comp_contact, " + + " eg_user.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(wlm.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wlm.`latitude` AS comp_latitude, " + + " wlm.`longitude` AS comp_longitude, " + + " wlm.`address` AS comp_area, " + + " wlm.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', wlm.`file`) AS image, " + + " wlm.`status` AS comp_status " + + "FROM " + + " `waste_location_mapping` wlm " + + "JOIN " + + " `erp_pgr`.`EG_USER` eg_user " + + " ON wlm.`cby` = eg_user.`id` " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wlm.`type` = wt.`typeid` " + + "WHERE " + + " wlm.`isactive` = 12 " + + " AND ((6371008.8 * acos(ROUND(cos(radians(?)) * cos(radians(wlm.latitude)) * cos(radians(wlm.longitude) - radians(?)) + sin(radians(?)) * sin(radians(wlm.latitude)), 9))) < 10) " + + " AND wlm.`status` = 'open' " + + "ORDER BY wlm.`cdate` DESC"; + + // we set wlm.`isactive` = 12 /***************** Important *********************/ + + // Use latitude, longitude, and schoolType as positional parameters + return jdbcWasteTemplate.queryForList(sql, new Object[]{latitude, longitude, latitude}); + } + + public List> getComplaintList(String fromDATE, String toDATE) { + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + + " `EG_USER`.`FIRST_NAME` AS comp_name," + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `ref_id` AS ref_id, " + + " CASE WHEN `final_vendor_approval` = 'yes' THEN 'approved' " + + " WHEN `final_vendor_approval` = 'no' THEN 'rejected' " + + " ELSE 'pending'" + + " END AS approval_status, " + + " DATE_FORMAT(`approved_date`, '%d-%m-%Y %r') AS comp_approved_date " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + //+ " AND `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.approved_date) BETWEEN ? AND ?"; + + return jdbcWasteTemplate.queryForList(sql, fromDATE, toDATE); + } + + private boolean checkisCouncillor(String cby) { + String sql = "SELECT `id`,`EXTRAFIELD1` FROM `erp_pgr`.`EG_USER` WHERE `id`=? AND `EXTRAFIELD1`='councillor'"; + System.out.println("SELECT `id`,`EXTRAFIELD1` FROM `erp_pgr`.`EG_USER` WHERE `id`="+cby+" AND `EXTRAFIELD1`='councillor'"); + List> taskresult = jdbcPGRTemplate.queryForList(sql, cby); + return !taskresult.isEmpty(); + } + + private String checkIsOtherOfficer(String cby) { + String sql = "SELECT `id`, `EXTRAFIELD1` FROM `erp_pgr`.`EG_USER` WHERE `id` = ? AND `EXTRAFIELD1` = 'otherOfficer'"; + + // Debugging Log (Safe Version) + System.out.println("Executing SQL Query: " + sql + " with parameter: " + cby); + + List> taskresult = jdbcPGRTemplate.queryForList(sql, cby); + + // Check if results exist before accessing + if (!taskresult.isEmpty()) { + return (String) taskresult.get(0).get("EXTRAFIELD1"); // Get EXTRAFIELD1 safely + } else { + return "no"; + } + } + + @Transactional + public List> saveWaste( + String cby, + String latitude, + String longitude, + String zone, + String ward, + String address, + String tonage, + //String remarks, + MultipartFile file, + String type) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload("Created", cby, file); + } + + String storeIMG = image; + + String sqlQuery = "INSERT INTO `waste_location_mapping`" + + "(`zone`, `ward`, `cby`, `latitude`, `longitude`, `address`, `tonage`, `file`, " + + "`status`,`type`,`request_by_type`, `approved`, `approvedby`,`final_vendor_approval`,`approved_date`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String request_by_type = "Officer"; + String approved = "yes"; + String approvedby = cby; + String final_vendor_approval = "yes"; + Boolean councillor = checkisCouncillor(cby); + String OtherOfficer = checkIsOtherOfficer(cby); + System.out.println("councillor :"+councillor); + + if(councillor) { + request_by_type = "councillor"; + approved = "pending"; + approvedby ="0"; + final_vendor_approval = "pending"; + } + + System.out.println("IS otherOfficer :"+OtherOfficer); + + if(OtherOfficer.contains("otherOfficer")){ + request_by_type = "IE"; + approved = "yes"; //"pending"; + approvedby = cby; //"0"; + final_vendor_approval = "yes"; //"pending"; + } + + final String request_by_type_final = request_by_type; + final String approved_final = approved; + final String approvedby_final = approvedby; + final String final_vendor_approval_final = final_vendor_approval; + + try { + int affectedRows = jdbcWasteTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "wlid" }); + ps.setString(1, zone); + ps.setString(2, ward); + ps.setString(3, cby); + ps.setString(4, latitude); + ps.setString(5, longitude); + ps.setString(6, address); + ps.setString(7, tonage); + ps.setString(8, storeIMG); + ps.setString(9, "open"); + ps.setString(10, type); + ps.setString(11, request_by_type_final); + ps.setString(12, approved_final); + ps.setString(13, approvedby_final); + ps.setString(14, final_vendor_approval_final); + ps.setString(15, formattedDate); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new C&D Waste was inserted successfully!"); + System.out.println("A new C&D Waste was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new C&D Waste."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> saveVendorWaste( + String latitude, + String longitude, + String zone, + String ward, + String address, + int tonage, + MultipartFile file, + String type, + String ref_id) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload("Created", "0", file); + } + + String storeIMG = image; + + String sqlQuery = "INSERT INTO `waste_location_mapping`" + + "(`zone`, `ward`, `cby`, `latitude`, `longitude`, `address`, `tonage`, `file`, `status`,`type`,`request_by_type`,`ref_id`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + String tonagetxt = String.valueOf(tonage); + + int affectedRows = jdbcWasteTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "wlid" }); + ps.setString(1, zone); + ps.setString(2, ward); + ps.setString(3, "13451"); + ps.setString(4, latitude); + ps.setString(5, longitude); + ps.setString(6, address); + ps.setString(7, tonagetxt); + ps.setString(8, storeIMG); + ps.setString(9, "open"); + ps.setString(10, type); + ps.setString(11, "Vendor"); + ps.setString(12, ref_id); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("ref_id", ref_id); + response.put("status", "success"); + response.put("message", "A new C&D Waste was inserted successfully!"); + System.out.println("A new C&D Waste was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new C&D Waste."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + private void inactiveTheReply(String wlid) { + String sql = "UPDATE `waste_reply` SET `isactive`=0 WHERE `wlid`=?"; + jdbcWasteTemplate.update(sql,wlid); + } + + private void updateStatus(String wlid, int reply_id, String status) { + String sql = "UPDATE `waste_location_mapping` SET `status`=?, reply_id=? WHERE `wlid`=?"; + jdbcWasteTemplate.update(sql, status, reply_id, wlid); + } + + @Transactional + public List> saveReply( + String wlid, + String latitude, + String longitude, + String file, + String remarks, + String datetxt, + String tonage) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + /* + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload("Created", cby, file); + } + + String storeIMG = image; + */ + + // Call fileUpload to download and save the file locally + String filePath = fileUrlUpload("Reply", wlid, file); // Save file locally and get its path + + if(filePath.equals("error")) { + filePath = file; + } + else { + filePath = "https://gccservices.in/gccofficialapp/files"+filePath; + } + String fileURL = filePath; + + inactiveTheReply(wlid); // Set Old reply inactive + + String sqlQuery = "INSERT INTO `waste_reply`(`wlid`, `latitude`, `longitude`, `file`, `remarks`,`completed_date`,`tonage`) " + + "VALUES (?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcWasteTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "wlid" }); + ps.setString(1, wlid); + ps.setString(2, latitude); + ps.setString(3, longitude); + ps.setString(4, fileURL); + ps.setString(5, remarks); + ps.setString(6, datetxt); + ps.setString(7, tonage); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + updateStatus(wlid, lastInsertId, "close"); // Update the complaint status + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A complaint reply added successfully!"); + System.out.println("A new complaint reply added successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to add the complaint reply!."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public List> getMyticketllist(String loginId) { + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `cby`=? " + + "ORDER BY `cdate` DESC"; + + return jdbcWasteTemplate.queryForList(sql, loginId); + } + + public String getWardByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `ward` FROM `gcc_penalty_hoardings`.`hoading_user_list` WHERE `userid` = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcWasteTemplate.queryForList(sqlQuery, loginid); + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + // Extract the ward value from the first result + return (String) results.get(0).get("ward"); + } + + // Handle the case where no result is found + return "000"; // or return null based on your needs + } + + public List> getApprovalPendingList(String loginId, String ward) { + + String approve_check_ward = getWardByLoginId(loginId,""); + + System.out.println("Login ID: "+ loginId + + "/n Type: ae " + + "/n approve_check_ward: "+approve_check_ward); + + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `EG_USER`.id = `waste_location_mapping`.`cby`" + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `ward`= ? " + //+ " AND `request_by_type`='Vendor' " + + " AND `status`='open' " + + " AND `approved`='pending' " + + "ORDER BY `cdate` DESC"; + + return jdbcWasteTemplate.queryForList(sql, approve_check_ward); + } + + public List> checkApprovalLocation(String comp_id, String latitude, String longitude) { + + String sql = "SELECT " + + " wlm.`wlid` AS comp_id, " + /* + + " wlm.`zone` AS comp_zone, " + + " wlm.`ward` AS comp_ward, " + + " eg_user.`EXTRAFIELD2` AS comp_contact, " + + " eg_user.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(wlm.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wlm.`latitude` AS comp_latitude, " + + " wlm.`longitude` AS comp_longitude, " + + " wlm.`address` AS comp_area, " + + " wlm.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', wlm.`file`) AS image, " + */ + + " wlm.`status` AS comp_status " + + "FROM " + + " `waste_location_mapping` wlm " + + "JOIN " + + " `erp_pgr`.`EG_USER` eg_user " + + " ON wlm.`cby` = eg_user.`id` " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wlm.`type` = wt.`typeid` " + + "WHERE " + + " wlm.`isactive` = 1 " + + " AND wlm.`wlid` = ? " + + " AND ((6371008.8 * acos(ROUND(cos(radians(?)) * cos(radians(wlm.latitude)) * cos(radians(wlm.longitude) - radians(?)) + sin(radians(?)) * sin(radians(wlm.latitude)), 9))) < 50) " + + " AND wlm.`status` = 'open' " + + "ORDER BY wlm.`cdate` DESC"; + + // Execute the query and check the result + List> result = jdbcWasteTemplate.queryForList(sql, new Object[]{comp_id, latitude, longitude, latitude}); + + // Create response map with 'status' field based on result existence + Map response = new HashMap<>(); + response.put("status", !result.isEmpty()); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + public List> saveApproval( + String loginId, String comp_id, + String latitude, String longitude, + String in_out, String status, String reject_txt + ) { + + //approve : yes or no + String final_vendor_approval = "pending"; + + if(in_out.equals("in") && status.equals("yes")) { + final_vendor_approval = "yes"; + } + + if(in_out.equals("in") && status.equals("no")) { + final_vendor_approval = "no"; + } + + if(in_out.equals("out") && status.equals("yes")) { + final_vendor_approval = "yes"; + //final_vendor_approval = "pending"; + } + + if(in_out.equals("out") && status.equals("no")) { + final_vendor_approval = "no"; + } + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sql = "UPDATE `waste_location_mapping` SET `approved`=? , `approvedby`=?, `reject_comments`=?, " + + "`approve_latitude`=?, `approve_longitude`=?, `approve_in_out`=?, `final_vendor_approval`=?, `approved_date`=? " + + " WHERE `wlid`=?"; + + // Execute the update query + int rowsAffected = jdbcWasteTemplate.update(sql, new Object[]{ + status, loginId, reject_txt, latitude, longitude, in_out, final_vendor_approval, formattedDate, comp_id + }); + + // Create a response map + Map response = new HashMap<>(); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + + public List> get2ApprovalPendingList(String loginId, String ward) { + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `EG_USER`.id =? " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `ward`=? " + //+ " AND `request_by_type`='Vendor' " + + " AND `status`='open' " + + " AND `approved`='yes' " + + " AND `approve_in_out`='out' " + + " AND `approved_2`='-' " + + "ORDER BY `cdate` DESC"; + + return jdbcWasteTemplate.queryForList(sql,loginId, ward); + } + + public List> save2Approval( + String loginId, String comp_id, + String latitude, String longitude, + String status + ) { + + //approve : yes or no + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sql = "UPDATE `waste_location_mapping` SET `approved_2`=? , `approvedby_2`=?, `approve_latitude_2`=?, " + + "`approve_longitude_2`=?, `final_vendor_approval`=?,`approved_date_2`=? " + + " WHERE `wlid`=? AND `approve_in_out`='out'"; + + // Execute the update query + int rowsAffected = jdbcWasteTemplate.update(sql, new Object[]{ + status, loginId, latitude, longitude, status, formattedDate, comp_id + }); + + // Create a response map + Map response = new HashMap<>(); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + public List> getZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`),2) AS `Open_Tonage`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END),2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + public List> getWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`),2) AS `Open_Tonage`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END),2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + + // New Report + + public List> getOfficerZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN `waste_location_mapping`.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + public List> getOfficerWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN `waste_location_mapping`.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + + public List> getVendorZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Approved_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN 1 END) AS `Rejected_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Rejected_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN 1 END) AS `Approved_Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN" + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE" + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + //+ " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY" + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + + public List> getVendorWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Approved_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN 1 END) AS `Rejected_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Rejected_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN 1 END) AS `Approved_Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN" + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE" + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + //+ " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY" + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + /////////// + + public List> getListByStatus(String fromDATE, String toDATE, String zone, String ward, String status, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + String sqlwhere=""; + if(status.equals("pending")) { + status = "open"; + sqlwhere = " AND wlm.`final_vendor_approval`='pending'"; + System.out.println(sqlwhere); + } + + String sql = "SELECT " + + " wlm.`wlid` AS comp_id, " + + " wlm.`zone` AS comp_zone, " + + " wlm.`ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(wlm.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wlm.`latitude` AS comp_latitude, " + + " wlm.`longitude` AS comp_longitude, " + + " wlm.`address` AS comp_area, " + + " wlm.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CASE WHEN wlm.`status` = 'Close' THEN wr.`tonage` ELSE 0 END AS `reply_tonage`, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', wlm.`file`) AS image, " + + " wlm.`status` AS comp_status " + + "FROM " + + " `waste_location_mapping` wlm " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON wlm.`cby` = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr " + + " ON wlm.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wlm.`type` = wt.`typeid` " + + "WHERE " + + " wlm.`isactive` = 1 " + + " AND wlm.`zone` = ? " + + " AND wlm.`ward` = ? " + + sqlwhere + + " AND wlm.`status` = ? " + + " AND wlm.`request_by_type` IN ("+requestBy+") " + + " AND DATE(wlm.`cdate`) BETWEEN ? AND ?"; + + System.out.println(sql); + return jdbcWasteTemplate.queryForList(sql, zone, ward, status, formattedFromDate, formattedToDate); + } + + public List> getWardSumReport(String ward) { + + // Get current date + LocalDate toDate = LocalDate.now(); + // Calculate 7 days before current date + LocalDate fromDate = toDate.minusDays(7); + + // Define the input and output date formats + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + // SQL query for fetching data + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " `waste_location_mapping`.`request_by_type` AS `request_by_type`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " SUM(`waste_location_mapping`.`tonage`) AS `Total_Tonage`, " + + " SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END) AS `Close_Tonage`, " + + " SUM(`waste_location_mapping`.`tonage`) - " + + " SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END) AS `Ton_Difference`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'yes' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Approved`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'no' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Rejected`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'pending' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Pending` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive` = 1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`ward` = ? " + + " AND `waste_location_mapping`.`request_by_type` IS NOT NULL " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + "GROUP BY " + + " `waste_location_mapping`.`ward`, `waste_location_mapping`.`request_by_type` " + + "ORDER BY `waste_location_mapping`.`ward`"; + + // Fetch the data from the database + List> result = jdbcWasteTemplate.queryForList(sql, ward, formattedFromDate, formattedToDate); + + // Prepare the response + Map response = new HashMap<>(); + response.put("filterDate", formattedFromDate + " to " + formattedToDate); + + boolean hasVendorData = false; + boolean hasOfficerData = false; + + // Separate Officer and Vendor data + List> officerData = new ArrayList<>(); + List> vendorData = new ArrayList<>(); + + for (Map row : result) { + String requestByType = (String) row.get("request_by_type"); + + if ("Officer".equals(requestByType)) { + officerData.add(row); + hasOfficerData = true; + } else if ("Vendor".equals(requestByType)) { + vendorData.add(row); + hasVendorData = true; + } + } + + // If no Officer data, add a default entry with zero values + if (!hasOfficerData) { + Map officerRow = new HashMap<>(); + officerRow.put("ward", "0"); + officerRow.put("request_by_type", "Officer"); + officerRow.put("Open", 0); + officerRow.put("Close", 0); + officerRow.put("Total", 0); + officerRow.put("Total_Tonage", 0); + officerRow.put("Close_Tonage", 0); + officerRow.put("Ton_Difference", 0); + officerRow.put("Total_Ton_Approved", 0); + officerRow.put("Total_Ton_Rejected", 0); + officerRow.put("Total_Ton_Pending", 0); + + officerData.add(officerRow); + } + + // If no vendor data, add a default entry with zero values + if (!hasVendorData) { + Map vendorRow = new HashMap<>(); + vendorRow.put("ward", "0"); + vendorRow.put("request_by_type", "Vendor"); + vendorRow.put("Open", 0); + vendorRow.put("Close", 0); + vendorRow.put("Total", 0); + vendorRow.put("Total_Tonage", 0); + vendorRow.put("Close_Tonage", 0); + vendorRow.put("Ton_Difference", 0); + vendorRow.put("Total_Ton_Approved", 0); + vendorRow.put("Total_Ton_Rejected", 0); + vendorRow.put("Total_Ton_Pending", 0); + + vendorData.add(vendorRow); + } + + response.put("Officer", officerData); + response.put("Vendor", vendorData); + response.put("message", "Data List."); + + return Collections.singletonList(response); + } + + public List> getTicketDetailsByWLID(String wlid) { + + String sql = "SELECT " + + " wl.`wlid` AS comp_id, " + + " wl.`zone` AS comp_zone, " + + " wl.`ward` AS comp_ward, " + + " eg.`EXTRAFIELD2` AS comp_contact, " + + " CONCAT(COALESCE(eg.FIRST_NAME, ''), ' ', COALESCE(eg.MIDDLE_NAME, '')) AS comp_name, " + // + " eg.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(wl.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wl.`latitude` AS comp_latitude, " + + " wl.`longitude` AS comp_longitude, " + + " wl.`address` AS comp_area, " + + " wl.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', wl.`file`) AS image, " + + " wl.`status` AS comp_status, " + + " wr.`remarks` AS reply_remarks, " + + " wr.`latitude` AS reply_latitude, " + + " wr.`longitude` AS reply_longitude, " + + " wr.`completed_date` AS reply_completed_date, " + + " DATE_FORMAT(wr.`cdate`, '%d-%m-%Y %r') AS reply_in_date, " + + " wr.`file` AS reply_file, " + + " wr.`tonage` AS reply_tonage, " + + " wr.`inby` AS reply_inby " + + "FROM " + + " `waste_location_mapping` wl " + + "JOIN " + + " `erp_pgr`.`EG_USER` eg " + + " ON wl.cby = eg.id " + + "LEFT JOIN " + + " `waste_reply` wr " + + " ON wl.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wl.type = wt.typeid " + + "WHERE " + + " wl.`isactive` = 1 " + + "AND wl.`wlid` = ?"; + + return jdbcWasteTemplate.queryForList(sql, wlid); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java new file mode 100644 index 0000000..11b5a29 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java @@ -0,0 +1,1073 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +import javax.net.ssl.*; +import java.security.cert.X509Certificate; +import java.security.NoSuchAlgorithmException; +import java.security.KeyManagementException; + +@Service +public class c_d_WasteUserService { + private JdbcTemplate jdbcUserWasteTemplate; + private JdbcTemplate jdbcPGRTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource( + @Qualifier("mysqlC_D_WasteUserDataSource") DataSource wasteUserDataSource, + @Qualifier("mysqlPGRMasterDataSource") DataSource pgrDataSource + ) { + this.jdbcUserWasteTemplate = new JdbcTemplate(wasteUserDataSource); + this.jdbcPGRTemplate = new JdbcTemplate(pgrDataSource); + } + + @Autowired + public c_d_WasteUserService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + //CONCAT('"+fileBaseUrl+"/gccofficialapp/files/', al.image) AS imageUrl, + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("c_d_waste_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + var date =DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName+"web_user/" + year +"/"+month+"/"+date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + "web_user/" + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + //BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + //byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public String fileUrlUpload(String name, String id, String fileUrl) { + + // Set the directory for saving the file + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("c_d_waste_foldername"); + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + "web_user/" + year + "/" + month +"/reply"; + + try { + // Bypass SSL certificate validation (this will ignore SSL handshake errors) + TrustManager[] trustAllCertificates = new TrustManager[]{ + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCertificates, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Generate datetime string for the file name + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + + // Generate a random string for the file name + String fileName = name + "_" + id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + ".jpg"; // Assuming it's a .jpg file + fileName = fileName.replaceAll("\\s+", ""); // Remove spaces in filename + + String filePath = uploadDirectory + "/" + fileName; // Full local file path + String relativeFilePath = "/" + serviceFolderName + "web_user/" + year + "/" + month + "/reply/" + fileName; // Relative path to save in DB + + // Create a URL object from the file URL + URL url = new URL(fileUrl); + + // Open a connection to the URL and download the file + try (InputStream inputStream = url.openStream()) { + // Write the input stream to the local file + Files.copy(inputStream, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING); + System.out.println("File downloaded and saved at: " + filePath); + } + + // Return the relative path to be stored in the database + return relativeFilePath; + + } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { + e.printStackTrace(); + System.out.println("Failed to download and save file from URL " + fileUrl); + return "error"; + } + } + + @Transactional + public List> saveUserWaste( + String latitude, + String longitude, + String zone, + String ward, + String address, + String tonage, + MultipartFile file, + String type, + String ref_id) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload("Created", "0", file); + } + + String storeIMG = image; + + String sqlQuery = "INSERT INTO `waste_location_mapping`" + + "(`zone`, `ward`, `cby`, `latitude`, `longitude`, `address`, `tonage`, `file`, `status`,`type`,`request_by_type`,`ref_id`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + //String tonagetxt = String.valueOf(tonage); + String tonagetxt = tonage; + + int affectedRows = jdbcUserWasteTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "wlid" }); + ps.setString(1, zone); + ps.setString(2, ward); + ps.setString(3, "13451"); + ps.setString(4, latitude); + ps.setString(5, longitude); + ps.setString(6, address); + ps.setString(7, tonagetxt); + ps.setString(8, storeIMG); + ps.setString(9, "open"); + ps.setString(10, type); + ps.setString(11, "Web_User"); + ps.setString(12, ref_id); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("ref_id", ref_id); + response.put("status", "success"); + response.put("message", "A new C&D Waste was inserted successfully!"); + System.out.println("A new C&D Waste was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new C&D Waste."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + + + + public List> getMyticketllist(String loginId) { + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `cby`=? " + + "ORDER BY `cdate` DESC"; + + return jdbcUserWasteTemplate.queryForList(sql, loginId); + } + + public String getWardByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `ward` FROM `gcc_penalty_hoardings`.`hoading_user_list` WHERE `userid` = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcUserWasteTemplate.queryForList(sqlQuery, loginid); + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + // Extract the ward value from the first result + return (String) results.get(0).get("ward"); + } + + // Handle the case where no result is found + return "000"; // or return null based on your needs + } + + public List> getApprovalPendingList(String loginId, String ward) { + + String approve_check_ward = getWardByLoginId(loginId,""); + + System.out.println("Login ID: "+ loginId + + "/n Type: ae " + + "/n approve_check_ward: "+approve_check_ward); + + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `waste_location_mapping`.`user_mobile` AS comp_contact, " + + " `waste_location_mapping`.`user_name` AS comp_name, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `EG_USER`.id = `waste_location_mapping`.`cby`" + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `ward`= ? " + //+ " AND `request_by_type`='Vendor' " + + " AND `status`='open' " + + " AND `approved`='pending' " + + "ORDER BY `cdate` DESC"; + + return jdbcUserWasteTemplate.queryForList(sql, approve_check_ward); + } + + public List> checkApprovalLocation(String comp_id, String latitude, String longitude) { + + String sql = "SELECT " + + " wlm.`wlid` AS comp_id, " + /* + + " wlm.`zone` AS comp_zone, " + + " wlm.`ward` AS comp_ward, " + + " eg_user.`EXTRAFIELD2` AS comp_contact, " + + " eg_user.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(wlm.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wlm.`latitude` AS comp_latitude, " + + " wlm.`longitude` AS comp_longitude, " + + " wlm.`address` AS comp_area, " + + " wlm.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', wlm.`file`) AS image, " + */ + + " wlm.`status` AS comp_status " + + "FROM " + + " `waste_location_mapping` wlm " + + "JOIN " + + " `erp_pgr`.`EG_USER` eg_user " + + " ON wlm.`cby` = eg_user.`id` " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wlm.`type` = wt.`typeid` " + + "WHERE " + + " wlm.`isactive` = 1 " + + " AND wlm.`wlid` = ? " + + " AND ((6371008.8 * acos(ROUND(cos(radians(?)) * cos(radians(wlm.latitude)) * cos(radians(wlm.longitude) - radians(?)) + sin(radians(?)) * sin(radians(wlm.latitude)), 9))) < 50) " + + " AND wlm.`status` = 'open' " + + "ORDER BY wlm.`cdate` DESC"; + + // Execute the query and check the result + List> result = jdbcUserWasteTemplate.queryForList(sql, new Object[]{comp_id, latitude, longitude, latitude}); + + // Create response map with 'status' field based on result existence + Map response = new HashMap<>(); + response.put("status", !result.isEmpty()); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + public List> saveApproval( + String loginId, String comp_id, + String latitude, String longitude, + String in_out, String status, String reject_txt, + String tonage_kg + ) { + + //approve : yes or no + String final_vendor_approval = "pending"; + + if(in_out.equals("in") && status.equals("yes")) { + final_vendor_approval = "yes"; + } + + if(in_out.equals("in") && status.equals("no")) { + final_vendor_approval = "no"; + } + + if(in_out.equals("out") && status.equals("yes")) { + final_vendor_approval = "yes"; + //final_vendor_approval = "pending"; + } + + if(in_out.equals("out") && status.equals("no")) { + final_vendor_approval = "no"; + } + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sql = "UPDATE `waste_location_mapping` SET `approved`=? , `approvedby`=?, `reject_comments`=?, " + + "`approve_latitude`=?, `approve_longitude`=?, `approve_in_out`=?, `final_vendor_approval`=?, `approved_date`=?, " + + "`tonage`=?" + + " WHERE `wlid`=?"; + + // Execute the update query + int rowsAffected = jdbcUserWasteTemplate.update(sql, new Object[]{ + status, loginId, reject_txt, latitude, longitude, in_out, final_vendor_approval, formattedDate, tonage_kg, comp_id + }); + + // Create a response map + Map response = new HashMap<>(); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + + public List> get2ApprovalPendingList(String loginId, String ward) { + String sql = "SELECT " + + " `wlid` AS comp_id, " + + " `zone` AS comp_zone, " + + " `ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " `latitude` AS comp_latitude, " + + " `longitude` AS comp_longitude, " + + " `address` AS comp_area, " + + " `tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS image, " + + " `status` AS comp_status " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON `EG_USER`.id =? " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON waste_location_mapping.type = wt.typeid " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `ward`=? " + //+ " AND `request_by_type`='Vendor' " + + " AND `status`='open' " + + " AND `approved`='yes' " + + " AND `approve_in_out`='out' " + + " AND `approved_2`='-' " + + "ORDER BY `cdate` DESC"; + + return jdbcUserWasteTemplate.queryForList(sql,loginId, ward); + } + + public List> save2Approval( + String loginId, String comp_id, + String latitude, String longitude, + String status + ) { + + //approve : yes or no + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sql = "UPDATE `waste_location_mapping` SET `approved_2`=? , `approvedby_2`=?, `approve_latitude_2`=?, " + + "`approve_longitude_2`=?, `final_vendor_approval`=?,`approved_date_2`=? " + + " WHERE `wlid`=? AND `approve_in_out`='out'"; + + // Execute the update query + int rowsAffected = jdbcUserWasteTemplate.update(sql, new Object[]{ + status, loginId, latitude, longitude, status, formattedDate, comp_id + }); + + // Create a response map + Map response = new HashMap<>(); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + public List> getZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`),2) AS `Open_Tonage`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END),2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + public List> getWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`),2) AS `Open_Tonage`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END),2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + + // New Report + + public List> getOfficerZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN `waste_location_mapping`.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + public List> getOfficerWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN `waste_location_mapping`.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY " + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + + public List> getVendorZoneWiseCount(String fromDATE, String toDATE, String requestBy) { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`zone` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`zone` " + + " END AS `zone`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Approved_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN 1 END) AS `Rejected_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Rejected_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN 1 END) AS `Approved_Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN" + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE" + + " `waste_location_mapping`.isactive = 1 " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + //+ " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY" + + " `waste_location_mapping`.`zone` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, formattedFromDate, formattedToDate); + } + + + public List> getVendorWardWiseCount(String fromDATE, String toDATE, String zone, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total_Identified_Count`, " + + " FORMAT(SUM(`waste_location_mapping`.`tonage`)/1000, 2) AS `Total_Identified_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Approved_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN 1 END) AS `Rejected_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'no' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Rejected_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN 1 END) AS `Approved_Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`final_vendor_approval` = 'pending' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Approved_Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Pending_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Open' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN waste_location_mapping.`tonage` ELSE 0 END)/1000, 2) AS `Pending_Tonage`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN 1 END) AS `Closed_Count`, " + + " FORMAT(SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' AND `waste_location_mapping`.`final_vendor_approval` = 'yes' THEN wr.`tonage` ELSE 0 END)/1000, 2) AS `Close_Tonage` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN" + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "WHERE" + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`zone`= ? " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + //+ " AND `waste_location_mapping`.request_by_type IN ("+requestBy+") " + + "GROUP BY" + + " `waste_location_mapping`.`ward` " + + "WITH ROLLUP"; + + return jdbcUserWasteTemplate.queryForList(sql, zone, formattedFromDate, formattedToDate); + } + /////////// + + public List> getListByStatus(String fromDATE, String toDATE, String zone, String ward, String status, String requestBy) { + + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input dates to LocalDate + LocalDate fromDate = LocalDate.parse(fromDATE, inputFormatter); + LocalDate toDate = LocalDate.parse(toDATE, inputFormatter); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + String sqlwhere=""; + if(status.equals("pending")) { + status = "open"; + sqlwhere = " AND wlm.`final_vendor_approval`='pending'"; + System.out.println(sqlwhere); + } + + String sql = "SELECT " + + " wlm.`wlid` AS comp_id, " + + " wlm.`zone` AS comp_zone, " + + " wlm.`ward` AS comp_ward, " + + " `EG_USER`.`EXTRAFIELD2` AS comp_contact, " + //+ " `EG_USER`.`FIRST_NAME` AS comp_name, " + + " CONCAT(COALESCE(EG_USER.FIRST_NAME, ''), ' ', COALESCE(EG_USER.MIDDLE_NAME, '')) AS comp_name, " + + " DATE_FORMAT(wlm.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wlm.`latitude` AS comp_latitude, " + + " wlm.`longitude` AS comp_longitude, " + + " wlm.`address` AS comp_area, " + + " wlm.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CASE WHEN wlm.`status` = 'Close' THEN wr.`tonage` ELSE 0 END AS `reply_tonage`, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', wlm.`file`) AS image, " + + " wlm.`status` AS comp_status " + + "FROM " + + " `waste_location_mapping` wlm " + + "JOIN " + + " `erp_pgr`.`EG_USER` " + + " ON wlm.`cby` = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr " + + " ON wlm.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wlm.`type` = wt.`typeid` " + + "WHERE " + + " wlm.`isactive` = 1 " + + " AND wlm.`zone` = ? " + + " AND wlm.`ward` = ? " + + sqlwhere + + " AND wlm.`status` = ? " + + " AND wlm.`request_by_type` IN ("+requestBy+") " + + " AND DATE(wlm.`cdate`) BETWEEN ? AND ?"; + + System.out.println(sql); + return jdbcUserWasteTemplate.queryForList(sql, zone, ward, status, formattedFromDate, formattedToDate); + } + + public List> getWardSumReport(String ward) { + + // Get current date + LocalDate toDate = LocalDate.now(); + // Calculate 7 days before current date + LocalDate fromDate = toDate.minusDays(7); + + // Define the input and output date formats + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Format the LocalDate to the required format + String formattedFromDate = fromDate.format(outputFormatter); + String formattedToDate = toDate.format(outputFormatter); + + // SQL query for fetching data + String sql = "SELECT " + + " CASE " + + " WHEN `waste_location_mapping`.`ward` IS NULL THEN 'Total' " + + " ELSE `waste_location_mapping`.`ward` " + + " END AS `ward`, " + + " `waste_location_mapping`.`request_by_type` AS `request_by_type`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Open' THEN 1 END) AS `Open`, " + + " COUNT(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN 1 END) AS `Close`, " + + " COUNT(`waste_location_mapping`.`wlid`) AS `Total`, " + + " SUM(`waste_location_mapping`.`tonage`) AS `Total_Tonage`, " + + " SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END) AS `Close_Tonage`, " + + " SUM(`waste_location_mapping`.`tonage`) - " + + " SUM(CASE WHEN `waste_location_mapping`.`status` = 'Close' THEN wr.`tonage` ELSE 0 END) AS `Ton_Difference`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'yes' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Approved`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'no' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Rejected`, " + + " SUM(CASE " + + " WHEN waste_location_mapping.`approved` = 'pending' THEN waste_location_mapping.`tonage` " + + " ELSE 0 " + + " END) AS `Total_Ton_Pending` " + + "FROM " + + " `waste_location_mapping` " + + "JOIN " + + " `erp_pgr`.`EG_USER` ON `waste_location_mapping`.cby = `EG_USER`.id " + + "LEFT JOIN " + + " `waste_reply` wr ON `waste_location_mapping`.`wlid` = wr.`wlid` AND wr.`isactive` = 1 " + + "WHERE " + + " `waste_location_mapping`.isactive = 1 " + + " AND `waste_location_mapping`.`ward` = ? " + + " AND `waste_location_mapping`.`request_by_type` IS NOT NULL " + + " AND DATE(`waste_location_mapping`.cdate) BETWEEN ? AND ? " + + "GROUP BY " + + " `waste_location_mapping`.`ward`, `waste_location_mapping`.`request_by_type` " + + "ORDER BY `waste_location_mapping`.`ward`"; + + // Fetch the data from the database + List> result = jdbcUserWasteTemplate.queryForList(sql, ward, formattedFromDate, formattedToDate); + + // Prepare the response + Map response = new HashMap<>(); + response.put("filterDate", formattedFromDate + " to " + formattedToDate); + + boolean hasVendorData = false; + boolean hasOfficerData = false; + + // Separate Officer and Vendor data + List> officerData = new ArrayList<>(); + List> vendorData = new ArrayList<>(); + + for (Map row : result) { + String requestByType = (String) row.get("request_by_type"); + + if ("Officer".equals(requestByType)) { + officerData.add(row); + hasOfficerData = true; + } else if ("Vendor".equals(requestByType)) { + vendorData.add(row); + hasVendorData = true; + } + } + + // If no Officer data, add a default entry with zero values + if (!hasOfficerData) { + Map officerRow = new HashMap<>(); + officerRow.put("ward", "0"); + officerRow.put("request_by_type", "Officer"); + officerRow.put("Open", 0); + officerRow.put("Close", 0); + officerRow.put("Total", 0); + officerRow.put("Total_Tonage", 0); + officerRow.put("Close_Tonage", 0); + officerRow.put("Ton_Difference", 0); + officerRow.put("Total_Ton_Approved", 0); + officerRow.put("Total_Ton_Rejected", 0); + officerRow.put("Total_Ton_Pending", 0); + + officerData.add(officerRow); + } + + // If no vendor data, add a default entry with zero values + if (!hasVendorData) { + Map vendorRow = new HashMap<>(); + vendorRow.put("ward", "0"); + vendorRow.put("request_by_type", "Vendor"); + vendorRow.put("Open", 0); + vendorRow.put("Close", 0); + vendorRow.put("Total", 0); + vendorRow.put("Total_Tonage", 0); + vendorRow.put("Close_Tonage", 0); + vendorRow.put("Ton_Difference", 0); + vendorRow.put("Total_Ton_Approved", 0); + vendorRow.put("Total_Ton_Rejected", 0); + vendorRow.put("Total_Ton_Pending", 0); + + vendorData.add(vendorRow); + } + + response.put("Officer", officerData); + response.put("Vendor", vendorData); + response.put("message", "Data List."); + + return Collections.singletonList(response); + } + + public List> getTicketDetailsByWLID(String wlid) { + + String sql = "SELECT " + + " wl.`wlid` AS comp_id, " + + " wl.`zone` AS comp_zone, " + + " wl.`ward` AS comp_ward, " + + " eg.`EXTRAFIELD2` AS comp_contact, " + + " CONCAT(COALESCE(eg.FIRST_NAME, ''), ' ', COALESCE(eg.MIDDLE_NAME, '')) AS comp_name, " + // + " eg.`FIRST_NAME` AS comp_name, " + + " DATE_FORMAT(wl.`cdate`, '%d-%m-%Y %r') AS comp_date, " + + " wl.`latitude` AS comp_latitude, " + + " wl.`longitude` AS comp_longitude, " + + " wl.`address` AS comp_area, " + + " wl.`tonage` AS appx_tonage, " + + " wt.`name` AS comp_type, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', wl.`file`) AS image, " + + " wl.`status` AS comp_status, " + + " wr.`remarks` AS reply_remarks, " + + " wr.`latitude` AS reply_latitude, " + + " wr.`longitude` AS reply_longitude, " + + " wr.`completed_date` AS reply_completed_date, " + + " DATE_FORMAT(wr.`cdate`, '%d-%m-%Y %r') AS reply_in_date, " + + " wr.`file` AS reply_file, " + + " wr.`tonage` AS reply_tonage, " + + " wr.`inby` AS reply_inby " + + "FROM " + + " `waste_location_mapping` wl " + + "JOIN " + + " `erp_pgr`.`EG_USER` eg " + + " ON wl.cby = eg.id " + + "LEFT JOIN " + + " `waste_reply` wr " + + " ON wl.`wlid` = wr.`wlid` AND wr.`isactive`=1 " + + "LEFT JOIN " + + " `waste_type` wt " + + " ON wl.type = wt.typeid " + + "WHERE " + + " wl.`isactive` = 1 " + + "AND wl.`wlid` = ?"; + + return jdbcUserWasteTemplate.queryForList(sql, wlid); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/package-info.java new file mode 100644 index 0000000..f5df7f3 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.c_d_waste.service; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/ApiLoggingFilter.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/ApiLoggingFilter.java new file mode 100644 index 0000000..760cf40 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/ApiLoggingFilter.java @@ -0,0 +1,64 @@ +package in.gov.chennaicorporation.mobileservice.component; + +import java.io.IOException; +import java.time.LocalDateTime; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +@Component +public class ApiLoggingFilter implements Filter { + + @Autowired + private JdbcTemplate jdbcAPITemplate; + + @Autowired + public void setDataSource(@Qualifier("mysqlAPIDataSource") DataSource apiDataSource) { + this.jdbcAPITemplate = new JdbcTemplate(apiDataSource); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + + System.out.println("API Logging Filter triggered"); + + HttpServletRequest httpRequest = (HttpServletRequest) request; + String ipAddress = request.getRemoteAddr(); + LocalDateTime accessTime = LocalDateTime.now(); + String endpoint = httpRequest.getRequestURI(); + String userAgent = httpRequest.getHeader("User-Agent"); + + // Log to check if filter is being triggered + System.out.println("Request Details: IP Address = " + ipAddress + ", Endpoint = " + endpoint); + + + // Insert log into the database + String sql = "INSERT INTO api_access_log (ip_address, access_time, endpoint, user_agent) VALUES (?, ?, ?, ?)"; + jdbcAPITemplate.update(sql, ipAddress, accessTime, endpoint, userAgent); + + // Continue with the request-response cycle + chain.doFilter(request, response); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // Initialization logic if needed + } + + @Override + public void destroy() { + // Cleanup logic if needed + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java new file mode 100644 index 0000000..5d23cd5 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.component; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java index 2dc6828..50a5a00 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java @@ -11,6 +11,7 @@ public class AppConfig { public String mtm = "http://117.232.67.158:8060"; public String petRegistration = "http://117.232.67.158:8061"; public String garbageCollection = "http://117.232.67.158:8067"; //117.232.67.158 + public String otpurl = "https://tmegov.onex-aura.com/api/sms?"; public String gccappsMysqlPassword = ""; diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java index f5430c8..f26a612 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java @@ -107,12 +107,12 @@ public class DataSourceConfig { //////////////////////////////(For Cattle Catch Master) //////////////////////// @Bean(name = "mysqlHoardingsDataSource") public DataSource mysqlHoardingsDataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://"+host+"/gcc_penalty_hoardings"); - dataSource.setUsername("root"); - dataSource.setPassword(dbpassword); - return dataSource; + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_penalty_hoardings"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; } //////////////////////////////(For PGR Master) //////////////////////// @@ -203,6 +203,95 @@ public class DataSourceConfig { return dataSource; } + + //////////////////////////////(For C&D Waste) //////////////////////// + @Bean(name = "mysqlC_D_WasteDataSource") + public DataSource mysqlC_D_WasteDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_c_d_waste"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Schools) //////////////////////// + @Bean(name = "mysqlC_D_WasteUserDataSource") + public DataSource mysqlC_D_WasteUserDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_c_d_waste_user"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Schools) //////////////////////// + @Bean(name = "mysqlMosquitoDataSource") + public DataSource mysqlMosquitoDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_mosquito_survey"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Works) //////////////////////// + @Bean(name = "mysqlWorksDataSource") + public DataSource mysqlWorksDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_works_status"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Street Vendor`s) //////////////////////// + @Bean(name = "mysqlGccStreetVendorDataSource") + public DataSource mysqlGccStreetVendorDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_street_vendor"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Street Vendor`s) //////////////////////// + @Bean(name = "mysqlGccEducationDataSource") + public DataSource mysqlGccEducationDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_schools_web"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For Street Vendor`s) //////////////////////// + @Bean(name = "mysqlBusShelterDataSource") + public DataSource mysqlBusShelterDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_bus_shelters"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + + //////////////////////////////(For API Application Log) //////////////////////// + @Bean(name = "mysqlAPIDataSource") + public DataSource mysqlAPIDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_api_access_logs"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + ////////////////////////////// ORACLE //////////////////////// @Bean(name = "oracleERPDataSource") public DataSource oracleERPDataSource() { diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/WebConfig.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/WebConfig.java new file mode 100644 index 0000000..51a8141 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/WebConfig.java @@ -0,0 +1,26 @@ +package in.gov.chennaicorporation.mobileservice.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.boot.web.servlet.FilterRegistrationBean; + +import in.gov.chennaicorporation.mobileservice.component.ApiLoggingFilter; + +@Configuration +public class WebConfig { + + @Autowired + private ApiLoggingFilter apiLoggingFilter; + + // Register the ApiLoggingFilter using FilterRegistrationBean + @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(apiLoggingFilter); // Set the filter + registrationBean.addUrlPatterns("/**/api/*"); // Apply to all API endpoints + registrationBean.setOrder(1); // Optional: Set order if needed + System.out.println("API Logging Filter Registered for URL patterns: /api/*"); + return registrationBean; + } +} \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java index 46ff50d..e732126 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java @@ -221,12 +221,54 @@ public String assetFileUpload(String catId, MultipartFile file) { String serviceFolderName = environment.getProperty("activity_new_asset_foldername"); String filePath=serviceFolderName + assetTypeId+"/"; //String sqlQuery = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/"+filePath+"', image) AS imageUrl FROM `asset_list` WHERE `category_id`=? AND `streetid`=?"; + + /* String sqlQuery="SELECT al.*, CONCAT('"+fileBaseUrl+"/gccofficialapp/files/', al.image) AS imageUrl, " + "af.feedback_date AS lastfeedbackdate FROM asset_list al " + "LEFT JOIN ( SELECT af1.*, af2.latest_feedback_date FROM activity_feedback af1 " + "INNER JOIN ( SELECT asset_id, MAX(feedback_date) AS latest_feedback_date FROM activity_feedback GROUP BY asset_id ) af2 " + "ON af1.asset_id = af2.asset_id AND af1.feedback_date = af2.latest_feedback_date ) af " + "ON al.id = af.asset_id WHERE al.category_id = ? AND al.streetid = ?"; + */ + + String sqlQuery ="SELECT " + + " al.*, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files/', al.image) AS imageUrl, " + + " DATE_FORMAT(af.latest_feedback_date, '%d-%m-%Y') AS lastfeedbackdate, " + + " CASE " + + " WHEN ab.has_before = 1 THEN TRUE " + + " ELSE FALSE " + + " END AS is_before, " + + " CASE " + + " WHEN aa.has_after = 1 THEN TRUE " + + " ELSE FALSE " + + " END AS is_after " + + "FROM " + + " asset_list al " + + "LEFT JOIN ( " + + " SELECT " + + " asset_id, " + + " MAX(feedback_date) AS latest_feedback_date " + + " FROM activity_feedback " + + " GROUP BY asset_id " + + ") af ON al.id = af.asset_id " + + "LEFT JOIN ( " + + " SELECT " + + " asset_id, " + + " 1 AS has_before " + + " FROM activity_feedback " + + " WHERE feedback_id = 0 " + + " GROUP BY asset_id " + + ") ab ON al.id = ab.asset_id " + + "LEFT JOIN ( " + + " SELECT " + + " asset_id, " + + " 1 AS has_after " + + " FROM activity_feedback " + + " WHERE feedback_id > 0 " + + " GROUP BY asset_id " + + ") aa ON al.id = aa.asset_id " + + " WHERE al.category_id = ? AND al.streetid = ?"; List> result = jdbcActivityTemplate.queryForList(sqlQuery,assetTypeId,streetId); return result; } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/EducationController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/EducationController.java new file mode 100644 index 0000000..ba7e0ff --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/EducationController.java @@ -0,0 +1,149 @@ +package in.gov.chennaicorporation.mobileservice.gcceducation.controller; + +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.jdbc.core.JdbcTemplate; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gcceducation.service.EducationActivity; + +@RequestMapping("/gccofficialapp/api/gcceducation/") +@RestController("gccofficialappEducationRest") +public class EducationController { + @Autowired + private JdbcTemplate jdbcEducationTemplate; + + @Autowired + private EducationActivity educationActivity; + + @GetMapping(value="/getUnmapSchoolList") + public List getSchoolList(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getUnmapSchoolList(formData,loginId); + } + + @GetMapping(value="/getSchoolList") + public List getSchoolList(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getSchoolList(formData, latitude, longitude, loginId); + } + + @GetMapping(value="/getMenu") + public List getMenu(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getMenu(formData, loginId); + } + + @GetMapping(value="/getBuildings") + public List getBuildings(@RequestParam MultiValueMap formData, + @RequestParam(required = true) String school_details_id, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getBuildings(formData, school_details_id, loginId); + } + + @GetMapping(value="/getBuilding_list") + public List getBuilding_list(@RequestParam MultiValueMap formData, + @RequestParam(required = true) String school_details_id, + @RequestParam(required = true) String menu_id, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getBuilding_list(formData, school_details_id, menu_id, loginId); + } + + @GetMapping(value="/getFloor_list") + public List getFloor_list(@RequestParam MultiValueMap formData, + @RequestParam(required = true) String school_details_id, + @RequestParam(required = true) String menu_id, + @RequestParam(required = true) String building_id, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getFloor_list(formData, school_details_id, menu_id, building_id, loginId); + } + + @GetMapping(value="/getRoom_list") + public List getRoom_list(@RequestParam MultiValueMap formData, + @RequestParam(required = true) String school_details_id, + @RequestParam(required = true) String menu_id, + @RequestParam(required = true) String building_id, + @RequestParam(required = true) String floors_id, + @RequestParam(value = "loginId", required = false) String loginId){ + return educationActivity.getRoom_list(formData, school_details_id, menu_id, building_id, floors_id, loginId); + } + + @GetMapping(value="/getParentQuestionsList") + public List getParentQuestionsList( + @RequestParam(required = true) String school_details_id, + @RequestParam(value="menu_id", required = true) String menu_id, + @RequestParam(required = true) String building_id, + @RequestParam(required = true) String floors_id, + @RequestParam(required = true) String room_id, + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value="qtype", required = true) String qtype){ + return educationActivity.getParentQuestionsList(school_details_id, menu_id, building_id, floors_id, room_id, qtype); + } + + @GetMapping(value="/getChildQuestionsList") + public List getChildQuestionsList( + @RequestParam(required = true) String school_details_id, + @RequestParam(required = true) String menu_id, + @RequestParam(required = true) String building_id, + @RequestParam(required = true) String floors_id, + @RequestParam(required = true) String room_id, + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value="pid", required = true) String pid + ){ + return educationActivity.getChildQuestionsList(school_details_id, menu_id, building_id, floors_id, room_id, pid); + } + + @PostMapping("/saveFeedback") + public List saveFeedback( + @RequestParam MultiValueMap formData, + @RequestParam Map fileMap, + @RequestParam(required = true) String school_details_id, + @RequestParam(required = true) String building_id, + @RequestParam(required = true) String floor_id, + @RequestParam(required = true) String room_id, + @RequestParam(required = true) String categoryId, + @RequestParam(required = true) String zone, + @RequestParam(required = true) String division, + @RequestParam(required = true) String latitude, + @RequestParam(required = true) String longitude, + @RequestParam(required = true) String inby + ) { + return educationActivity.saveFeedback( + formData, fileMap, school_details_id, building_id, floor_id, room_id, + categoryId, zone, division, latitude, longitude, inby); + } + + @PostMapping("/saveCompoundAndBoard") + public ResponseEntity saveCompoundAndBoard( + + @RequestParam(required = false) MultipartFile feedPhoto, // file is optional + @RequestParam(required = true) int school_details_id, // school_details_id is optional + @RequestParam String zone, + @RequestParam String division, + @RequestParam double latitude, + @RequestParam double longitude, + @RequestParam String user_id ) { + + try { + // Save feedback for both questions + //educationActivity.saveCompoundAndBoard(categoryId, newboardconstructQa, newboardconstructAns, + // SchoolunderConstructQa, SchoolunderConstructAns, feedPhoto, school_details_id, zone, division,latitude,longitude,user_id); + + return new ResponseEntity<>("Feedback saved successfully.", HttpStatus.OK); + } catch (Exception e) { + return new ResponseEntity<>("Failed to save feedback: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java new file mode 100644 index 0000000..b916b9f --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.gcceducation.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java new file mode 100644 index 0000000..548b8c6 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.gcceducation; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java new file mode 100644 index 0000000..cb7b50a --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java @@ -0,0 +1,1067 @@ +package in.gov.chennaicorporation.mobileservice.gcceducation.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class EducationActivity { + private JdbcTemplate jdbcEducationTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlGccEducationDataSource") DataSource educationDataSource) { + this.jdbcEducationTemplate = new JdbcTemplate(educationDataSource); + } + + @Autowired + public EducationActivity(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("gcceducation_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + // Helper method to convert G, G+1, etc. to readable names + private String getReadableFloorName(String shortName) { + Map floorMap = Map.of( + "G", "Ground Floor", + "G+1", "First Floor", + "G+2", "Second Floor", + "G+3", "Third Floor", + "G+4", "Fourth Floor", + "G+5", "Fifth Floor", + "G+6", "Sixth Floor", + "G+7", "Seventh Floor", + "G+8", "Eighth Floor" + ); + return floorMap.getOrDefault(shortName, shortName); // fallback to original if not found + } + + ////////////////////////////// + + public String getConfigValue() { + String sqlQuery = "SELECT `id`, `lat_long_radius` FROM `config` LIMIT 1"; + String value = "50"; // default fallback value + List> results = jdbcEducationTemplate.queryForList(sqlQuery); + + if (!results.isEmpty()) { + Map row = results.get(0); + value = String.valueOf(row.get("lat_long_radius")); // corrected key name + } + + return value; + } + + ////////////////////////////// + + public List> getUnmapSchoolList( + MultiValueMap fromData, + String loginid){ + String sql = "SELECT * FROM `school_list` WHERE `gcc_app_updated`=0 AND `isactive`=1"; + List> result = jdbcEducationTemplate.queryForList(sql); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "UnMapped School List."); + response.put("data", result); + + return Collections.singletonList(response); + } + public List> getSchoolList( + MultiValueMap formData, + String latitude, + String longitude, + String loginid + ) { + + String sqlWhere = ""; + String radius = getConfigValue(); + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(sd.latitude)) * cos(radians(sd.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(sd.latitude)), 9))) < "+radius+")" + + " ORDER BY" + + " sd.`id` DESC"; + } + + String sql = "SELECT sl.*, sd.latitude, sd.longitude FROM `school_details` sd " + + "LEFT JOIN `school_list` sl ON sl.gcc_app_updated=sd.id " + + "WHERE `isactive`=1 "+sqlWhere; + //System.out.println(sql); + List> result = jdbcEducationTemplate.queryForList(sql); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Near By School List."); + response.put("data", result); + + return Collections.singletonList(response); + } + /////////////////////////////// + + public List> getMenu( + MultiValueMap formData, + String loginid + ){ + + String sql ="SELECT *,CONCAT('https://gccservices.in/gccofficialapp/files/app_icon/menu/', icon) " + + "AS iconUrl FROM `mobile_category` WHERE `isactive`=1 AND `isdelete`=0 " + + "ORDER BY orderby"; + List> result = jdbcEducationTemplate.queryForList(sql); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Menu List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getBuildings( + MultiValueMap formData, + String school_details_id, + String loginid + ){ + + String sql ="SELECT `buildng_id` as building_id, `building_name`, `total_floor`, `bmm`.`content` AS `building_material`, " + + "`rmm`.`content` AS `roof_material`, `building_order`, `school_id` FROM `buildings` as `b` " + + "LEFT JOIN `building_material_master` as `bmm` ON `bmm`.`bm_id`=`b`.`building_material` " + + "LEFT JOIN `roof_material_master` as `rmm` ON `rmm`.`rm_id`=`b`.`roof_material` " + + " WHERE (`b`.`is_active`=1 AND `b`.`is_delete`=0) AND `b`.`school_id`=?"; + List> result = jdbcEducationTemplate.queryForList(sql, school_details_id); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Building List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + private List getRoomTypeByMenuId(String menu_id) { + String sql = "SELECT room_master_id FROM room_master WHERE mobile_category = ?"; + List roomTypes = jdbcEducationTemplate.queryForList(sql, new Object[]{menu_id}, String.class); + // If no data is found, return a list with "0" + if (roomTypes.isEmpty()) { + roomTypes.add("0"); + } + + return roomTypes; + } + + public List> getBuilding_list( + MultiValueMap formData, + String school_details_id, + String menu_id, + String loginid + ){ + + // Get room types + List roomTypes = getRoomTypeByMenuId(menu_id); + // Construct the SQL + String sql = "SELECT b.buildng_id AS building_id, b.building_name, b.total_floor, " + + "bmm.content AS building_material, rmm.content AS roof_material, " + + "b.building_order, b.school_id " + + "FROM buildings b " + + "LEFT JOIN building_material_master bmm ON bmm.bm_id = b.building_material " + + "LEFT JOIN roof_material_master rmm ON rmm.rm_id = b.roof_material " + + "WHERE b.is_active = 1 AND b.is_delete = 0 AND b.buildng_id IN ( " + + " SELECT building_id FROM room_details WHERE room_type IN (:roomTypes) AND school_id = :schoolId " + + ")"; + // System.out.println(roomTypes); + // Use NamedParameterJdbcTemplate to inject list + Map params = new HashMap<>(); + params.put("roomTypes", roomTypes); + params.put("schoolId", school_details_id); + + NamedParameterJdbcTemplate namedJdbc = new NamedParameterJdbcTemplate(jdbcEducationTemplate); + List> result = namedJdbc.queryForList(sql, params); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Building List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getFloor_list( + MultiValueMap formData, + String school_details_id, + String menu_id, + String building_id, + String loginid + ){ + + // Get room types + List roomTypes = getRoomTypeByMenuId(menu_id); + // Construct the SQL + String sql = "SELECT floors_id, floor_name FROM `floor_list` where floors_id IN (" + + " SELECT floors_id FROM room_details WHERE room_type IN (:roomTypes) AND school_id = :schoolId AND `building_id` = :buildingId" + + ")"; + //List> result = jdbcEducationTemplate.queryForList(sql, school_details_id, building_id); + + // Use NamedParameterJdbcTemplate to inject list + Map params = new HashMap<>(); + params.put("roomTypes", roomTypes); + params.put("schoolId", school_details_id); + params.put("buildingId", building_id); + + NamedParameterJdbcTemplate namedJdbc = new NamedParameterJdbcTemplate(jdbcEducationTemplate); + List> result = namedJdbc.queryForList(sql, params); + + // Map short floor name to readable format + for (Map floor : result) { + String shortName = (String) floor.get("floor_name"); + floor.put("floor_name", getReadableFloorName(shortName)); + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Building List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getRoom_list( + MultiValueMap formData, + String school_details_id, + String menu_id, + String building_id, + String floors_id, + String loginid + ){ + + // Get room types + List roomTypes = getRoomTypeByMenuId(menu_id); + // Construct the SQL + String sql = "SELECT rd.`room_id`, rd.`room_type`, rm.`room_type` AS `room_type_name`, rd.`room_num` as `room_name`, rd.`building_id`, rd.`floors_id`, rd.`school_id` FROM `room_details` rd " + + "LEFT JOIN room_master rm ON rm.room_master_id=rd.room_type WHERE rd.room_type IN (:roomTypes) AND rd.`school_id` = :schoolId AND rd.`building_id` = :buildingId AND rd.`floors_id` = :foorsId"; + + //List> result = jdbcEducationTemplate.queryForList(sql, school_details_id, building_id, floors_id); + + // Use NamedParameterJdbcTemplate to inject list + Map params = new HashMap<>(); + params.put("roomTypes", roomTypes); + params.put("schoolId", school_details_id); + params.put("buildingId", building_id); + params.put("foorsId", floors_id); + + NamedParameterJdbcTemplate namedJdbc = new NamedParameterJdbcTemplate(jdbcEducationTemplate); + List> result = namedJdbc.queryForList(sql, params); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Floors List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getLibrary( + MultiValueMap formData, + String school_details_id, + String loginid + ){ + + String sql ="SELECT `room_id`, `LIBRARY`, `room_num`, `building_id`, `floors_id`, `school_id`, " + + "`is_active`, `is_delete` FROM `room_details` WHERE `building_id`=? AND `school_id`=?"; + List> result = jdbcEducationTemplate.queryForList(sql, school_details_id); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Rooms List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getParentQuestionsList(String school_details_id, String menu_id, + String building_id, String floors_id, String room_id, String qtype) { + //String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0 AND `qtype` LIKE ?"; + String sql = "SELECT " + + " ql.id AS question_id, " + + " ql.q_english, " + + " ql.q_tamil, " + + " ql.isactive, " + + " ql.ismandatory, " + + " ql.img_required, " + + " ql.pid, " + + " ql.qtype, " + + " ql.feedbacktype, " + + + " ql.view_table_name, " + + " ql.view_field_name, " + + " ql.school_details_id, " + + " ql.building_id, " + + " ql.floors_id, " + + " ql.room_id, " + + " ql.othercond, " + + + " ql.feedback_column as return_name, " + + " CASE " + + " WHEN (ql.feedbacktype = 'select' OR ql.feedbacktype = 'radio') THEN JSON_ARRAYAGG( " + + " JSON_OBJECT( " + + " 'option_id', qov.id, " + + " 'english_name', qov.english_name, " + + " 'tamil_name', qov.tamil_name, " + + " 'value', qov.value, " + //+ " 'isactive', qov.isactive, " + //+ " 'isdelete', qov.isdelete " + + " 'orderby', qov.orderby " + + " ) " + + " ) " + + " ELSE NULL " + + " END AS options " + + "FROM " + + " mobile_question_list ql " + + "LEFT JOIN " + + " mobile_q_option_value qov " + + " ON qov.qid = ql.id " + + "AND (ql.feedbacktype = 'select' OR ql.feedbacktype = 'radio') " + + "AND (qov.isactive=1 AND qov.isdelete=0) " + + "WHERE " + + " ql.isactive = 1 " + + " AND ql.pid = 0 " + + " AND ql.mobile_category = ? " + + " AND ql.qtype LIKE ? " + + "GROUP BY " + + " ql.id " + + "ORDER BY ql.orderby"; + + List> result = jdbcEducationTemplate.queryForList(sql,menu_id, "%" + qtype + "%"); + + ObjectMapper mapper = new ObjectMapper(); + for (Map row : result) { + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + + // Sort options by 'orderby' + optionsParsed.sort(Comparator.comparing(opt -> { + Object order = opt.get("orderby"); + return (order instanceof Number) ? ((Number) order).intValue() : 0; + })); + + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + + // Get Question value from HM Entry + String tableName = (String) row.get("view_table_name"); + String fieldName = (String) row.get("view_field_name"); + String whereCond = (String) row.get("othercond"); + + if (tableName != null && fieldName != null) { + StringBuilder whereClause = new StringBuilder(" WHERE 1=1 "); + List params = new ArrayList<>(); + + // Always check school_details_id (assuming it's always used) + Boolean schoolIdFlag = row.get("school_details_id") instanceof Boolean && (Boolean) row.get("school_details_id"); + if (schoolIdFlag) { + String schoolIdVal = school_details_id; + if(schoolIdVal != null) { + whereClause.append(" AND school_id = ?"); + params.add(schoolIdVal); + } + } + + // Conditionally check and add based on boolean flags + Boolean buildingIdFlag = row.get("building_id") instanceof Boolean && (Boolean) row.get("building_id"); + if (buildingIdFlag) { + String buildingIdVal = building_id; + if (buildingIdVal != null) { + whereClause.append(" AND building_id = ?"); + params.add(buildingIdVal); + } + } + + Boolean floorIdFlag = row.get("floors_id") instanceof Boolean && (Boolean) row.get("floors_id"); + if (floorIdFlag) { + String floorIdVal = floors_id; + if (floorIdVal != null) { + whereClause.append(" AND floor_id = ?"); + params.add(floorIdVal); + } + } + + Boolean roomIdFlag = row.get("room_id") instanceof Boolean && (Boolean) row.get("room_id"); + if (roomIdFlag) { + String roomIdVal = room_id; + if (roomIdVal != null) { + whereClause.append(" AND room_id = ?"); + params.add(roomIdVal); + } + } + + String whereCondQuery =""; + System.out.println("whereCond: "+whereCond); + if (whereCond != null && !whereCond.trim().isEmpty()) { + whereCondQuery = " AND ("+whereCond+")"; + } + + if (!params.isEmpty()) { + try { + /* + String query = String.format("SELECT %s AS val FROM %s %s LIMIT 1", + fieldName, tableName, whereClause.toString()); + + String value = jdbcEducationTemplate.query(query, params.toArray(), + rs -> rs.next() ? rs.getString("val") : null); + + row.put("q_display_value", value != null ? value : ""); + */ + + String query = String.format("SELECT %s AS val FROM %s %s %s", fieldName, tableName, whereClause.toString(), whereCondQuery); + + List values = jdbcEducationTemplate.query(query, params.toArray(), (rs, rowNum) -> rs.getString("val")); + + String joinedValues = String.join(",", values); + + row.put("q_display_value", joinedValues.isEmpty() ? "" : joinedValues); + + // FOR ERROR CHECK + String reconstructedQuery = query; + for (Object param : params) { + String paramStr = (param instanceof String) ? "'" + param + "'" : String.valueOf(param); + reconstructedQuery = reconstructedQuery.replaceFirst("\\?", paramStr); + } + System.out.println("Full SQL with values: " + reconstructedQuery); + + } catch (Exception e) { + row.put("q_display_value", ""); + System.out.println("Edu Error : "+e.getMessage().toString()); + } + } else { + row.put("q_display_value", ""); + } + } else { + row.put("q_display_value", ""); + } + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Parent Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getChildQuestionsList(String school_details_id, String menu_id, + String building_id, String floors_id, String room_id, String pid) { + String sql = "SELECT " + + " ql.id AS question_id, " + + " ql.q_english, " + + " ql.q_tamil, " + + " ql.isactive, " + + " ql.ismandatory, " + + " ql.img_required, " + + " ql.pid, " + + " ql.qtype, " + + " ql.feedbacktype, " + + " ql.feedback_column as return_name, " + + " CASE " + + " WHEN (ql.feedbacktype = 'select' OR ql.feedbacktype = 'radio') THEN JSON_ARRAYAGG( " + + " JSON_OBJECT( " + + " 'option_id', qov.id, " + + " 'english_name', qov.english_name, " + + " 'tamil_name', qov.tamil_name, " + + " 'value', qov.value, " + //+ " 'isactive', qov.isactive, " + //+ " 'isdelete', qov.isdelete " + + " 'orderby', qov.orderby " + + " ) " + + " ) " + + " ELSE NULL " + + " END AS options " + + "FROM " + + " mobile_question_list ql " + + "LEFT JOIN " + + " mobile_q_option_value qov " + + " ON qov.qid = ql.id " + + "AND (ql.feedbacktype = 'select' OR ql.feedbacktype = 'radio') " + + "AND (qov.isactive=1 AND qov.isdelete=0) " + + "WHERE " + + " ql.isactive = 1 " + + " AND ql.pid = ? " + + "GROUP BY " + + " ql.id " + + "ORDER BY ql.orderby"; + List> result = jdbcEducationTemplate.queryForList(sql,pid); + + ObjectMapper mapper = new ObjectMapper(); + for (Map row : result) { + Object optionsRaw = row.get("options"); + if (optionsRaw != null && optionsRaw instanceof String) { + try { + List> optionsParsed = mapper.readValue((String) optionsRaw, List.class); + + // Sort options by 'orderby' + optionsParsed.sort(Comparator.comparing(opt -> { + Object order = opt.get("orderby"); + return (order instanceof Number) ? ((Number) order).intValue() : 0; + })); + + row.put("options", optionsParsed); + } catch (Exception e) { + row.put("options", null); // fallback if malformed + } + } + } + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Child Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + private String setValue(String school_details_id, String categoryId, MultipartFile value, String key) { + String fileURL=""; + if (value != null && !value.isEmpty()) { + fileURL = fileUpload(school_details_id+"_"+categoryId, key, value); + } + + return fileURL; + } + /* + @Transactional + public List> saveFeedback( + MultiValueMap formData, + Map fileMap, + String school_details_id, + String building_id, + String floor_id, + String room_id, + String categoryId, + String zone, + String division, + String latitude, + String longitude, + String inby) { + + Map response = new HashMap<>(); + KeyHolder keyHolder = new GeneratedKeyHolder(); + int lastInsertId = 0; + + String tableName = categoryId + "_feedback"; // e.g., 1_feedback + + List columns = new ArrayList<>(); + List placeholders = new ArrayList<>(); + List values = new ArrayList<>(); + + for (String key : formData.keySet()) { + + columns.add("`" + key + "`"); + placeholders.add("?"); + values.add(formData.getFirst(key)); + + // Check for file matching this key + String fileKey = key + "_file"; + + System.out.println("Field: "+ fileKey); + + if (fileMap.containsKey(fileKey)) { + columns.add("`" + fileKey + "`"); + placeholders.add("?"); + MultipartFile file = fileMap.get(fileKey); + String fileUrl = setValue(school_details_id, categoryId, file, fileKey); + System.out.println(fileUrl); + values.add(fileUrl); + } + } + + String sql = String.format( + "INSERT INTO `%s` (%s) VALUES (%s)", + tableName, + String.join(", ", columns), + String.join(", ", placeholders) + ); + System.out.println(sql); + try { + int affectedRows = jdbcEducationTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + for (int i = 0; i < values.size(); i++) { + ps.setObject(i + 1, values.get(i)); + System.out.println(i + "," + values.get(i)); + } + return ps; + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new feedback was inserted successfully!"); + System.out.println("A new feedback was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new feedback. School Details ID: " + school_details_id); + } + + } catch (DataAccessException e) { + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } +*/ + @Transactional + public List> saveFeedback( + MultiValueMap formData, + Map fileMap, + String school_details_id, + String building_id, + String floor_id, + String room_id, + String categoryId, + String zone, + String division, + String latitude, + String longitude, + String inby) { + + Map response = new HashMap<>(); + KeyHolder keyHolder = new GeneratedKeyHolder(); + int lastInsertId = 0; + + String tableName = categoryId + "_feedback"; // e.g., 1_feedback + + List columns = new ArrayList<>(); + List placeholders = new ArrayList<>(); + List values = new ArrayList<>(); + + // 1. Handle formData (keys as-is) + for (String key : formData.keySet()) { + columns.add("`" + key + "`"); + placeholders.add("?"); + values.add(formData.getFirst(key)); + } + + // 2. Handle fileMap (keys as key_file) + for (Map.Entry entry : fileMap.entrySet()) { + String originalKey = entry.getKey(); + String columnName = originalKey; // already like fieldname_file + MultipartFile file = entry.getValue(); + + String fileUrl = setValue(school_details_id, categoryId, file, columnName); + + columns.add("`" + columnName + "`"); + placeholders.add("?"); + values.add(fileUrl); + } + + String sql = String.format( + "INSERT INTO `%s` (%s) VALUES (%s)", + tableName, + String.join(", ", columns), + String.join(", ", placeholders) + ); + System.out.println(sql); + try { + int affectedRows = jdbcEducationTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + for (int i = 0; i < values.size(); i++) { + ps.setObject(i + 1, values.get(i)); + } + return ps; + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new feedback was inserted successfully!"); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new feedback. School Details ID: " + school_details_id); + } + + } catch (DataAccessException e) { + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + /* + @Transactional + public List> saveFeedback( + String school_id, + String cby, + String latitude, + String longitude, + String zone, + String ward, + String q_1, + String q_2, + String q_3, + String q_4, + String q_5, + String q_6, + String q_7, + String q_8, + String q_9, + String q_10, + String q_11, + String remarks, + MultipartFile file, + + MultipartFile file_1, + MultipartFile file_2, + MultipartFile file_3, + MultipartFile file_4, + MultipartFile file_5, + MultipartFile file_6, + MultipartFile file_7, + MultipartFile file_8, + MultipartFile file_9, + MultipartFile file_10, + MultipartFile file_11, + String type) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + String image_q1 = ""; + String image_q2 = ""; + String image_q3 = ""; + String image_q4 = ""; + String image_q5 = ""; + String image_q6 = ""; + String image_q7 = ""; + String image_q8 = ""; + String image_q9 = ""; + String image_q10 = ""; + String image_q11 = ""; + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + image = fileUpload("feedback", "0", file); + } + + // Question Images + if (file_1 != null && !file_1.isEmpty()) { + image_q1 = fileUpload("1", "q1", file_1); + } + + if (file_2 != null && !file_2.isEmpty()) { + image_q2 = fileUpload("2", "q2", file_2); + } + + if (file_3 != null && !file_3.isEmpty()) { + image_q3 = fileUpload("3", "q3", file_3); + } + + if (file_4 != null && !file_4.isEmpty()) { + image_q4 = fileUpload("4", "q4", file_4); + } + + if (file_5 != null && !file_5.isEmpty()) { + image_q5 = fileUpload("5", "q5", file_5); + } + + if (file_6 != null && !file_6.isEmpty()) { + image_q6 = fileUpload("6", "q6", file_6); + } + + if (file_7 != null && !file_7.isEmpty()) { + image_q7 = fileUpload("7", "q7", file_7); + } + + if (file_8 != null && !file_8.isEmpty()) { + image_q8 = fileUpload("8", "q8", file_8); + } + + if (file_9 != null && !file_9.isEmpty()) { + image_q9 = fileUpload("9", "q9", file_9); + } + + if (file_10 != null && !file_10.isEmpty()) { + image_q10 = fileUpload("10", "q10", file_10); + } + + if (file_11 != null && !file_11.isEmpty()) { + image_q11 = fileUpload("11", "q11", file_11); + } + + String feedbackimg = image; + + String q1_image = image_q1; + String q2_image = image_q2; + String q3_image = image_q3; + String q4_image = image_q4; + String q5_image = image_q5; + String q6_image = image_q6; + String q7_image = image_q7; + String q8_image = image_q8; + String q9_image = image_q9; + String q10_image = image_q10; + String q11_image = image_q11; + + //String type = // Get before & after + + // Get today's date + LocalDate today = LocalDate.now(); + + // Format it in the desired format (yyyy-MM-dd) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayDate = today.format(formatter); + + //inactiveFeedBack(type, shelter_id); // Upadte already insert data. + + String sqlQuery = "INSERT INTO `bus_shelter_feedback`(" + + "`shelter_id`, `cby`, " + + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " + + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`," + + "`q1_image`, `q2_image`, `q3_image`, `q4_image`, `q5_image`, `q6_image`, " + + "`q7_image`, `q8_image`, `q9_image`, `q10_image`, `q11_image`" + + ") " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcEducationTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, shelter_id); + ps.setString(2, cby); + ps.setString(3, q_1); + ps.setString(4, q_2); + ps.setString(5, q_3); + ps.setString(6, q_4); + ps.setString(7, q_5); + ps.setString(8, q_6); + ps.setString(9, q_7); + ps.setString(10, q_8); + ps.setString(11, q_9); + ps.setString(12, q_10); + ps.setString(13, q_11); + ps.setString(14, remarks); + ps.setString(15, latitude); + ps.setString(16, longitude); + ps.setString(17, zone); + ps.setString(18, ward); + ps.setString(19, type); + ps.setString(20, feedbackimg); + + ps.setString(21, q1_image); + ps.setString(22, q2_image); + ps.setString(23, q3_image); + ps.setString(24, q4_image); + ps.setString(25, q5_image); + ps.setString(26, q6_image); + ps.setString(27, q7_image); + ps.setString(28, q8_image); + ps.setString(29, q9_image); + ps.setString(30, q10_image); + ps.setString(31, q11_image); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new feedback was inserted successfully!"); + System.out.println("A new feedback was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new feedback. Asset ID:" + shelter_id); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + */ +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java new file mode 100644 index 0000000..f15a674 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.gcceducation.service; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java index 5009eaa..8d0d58f 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java @@ -2,6 +2,7 @@ package in.gov.chennaicorporation.mobileservice.gccparks.controller; import java.io.IOException; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -813,99 +814,168 @@ public class ParksController { // flowering and Non Flowering API - @GetMapping("/getparkNameByEnumType") - public ResponseEntity>> getparkNameByEnumType(@RequestParam("enum_Type") int enum_Type, - @RequestParam("latitude") String latitude, @RequestParam("longitude") String longitude){ - - List> parkNameByEnum = parksService.getparkNameByEnumType(enum_Type,latitude,longitude); - - if(parkNameByEnum == null || parkNameByEnum.isEmpty()) - { - throw new NoDataException("No Data found"); - }else { - return ResponseEntity.ok(parkNameByEnum); - } - - } - - - @PostMapping("/saveFloweringandNonFlowering") - public ResponseEntity saveFloweringandNonFlowering( - @RequestParam("enumType") String enumType,@RequestParam("parkname") String parkname, @RequestParam("userId") String userId, - @RequestParam("enumerationId") int enumerationId, @RequestParam(value="floweringPlantCount", required = false) int floweringPlantCount, - @RequestParam(value="nonFloweringPlantCount", required = false) int nonFloweringPlantCount, - @RequestParam(value="floweringImage", required = false) MultipartFile floweringImg, - @RequestParam(value="nonFloweringImage", required = false) MultipartFile nonFloweringImg) throws Exception { - - int flowringData = parksService.saveFlowringandNonFlowringDetails(enumerationId, enumType,parkname, floweringPlantCount, floweringImg, - nonFloweringPlantCount, nonFloweringImg, userId); - - if (flowringData == 0 || flowringData == -1) { - return ResponseEntity.ok("Failed to save the details"); - } - - return ResponseEntity.ok("Details were saved successfully"); + @GetMapping("/getparkNameByEnumType") + public ResponseEntity>> getparkNameByEnumType(@RequestParam("enum_Type") int enum_Type, + @RequestParam("latitude") String latitude, @RequestParam("longitude") String longitude){ + + List> parkNameByEnum = parksService.getparkNameByEnumType(enum_Type,latitude,longitude); + + if(parkNameByEnum == null || parkNameByEnum.isEmpty()) + { + throw new NoDataException("No Data found"); + }else { + return ResponseEntity.ok(parkNameByEnum); + } + + } + + @PostMapping("/saveFloweringandNonFlowering") + public ResponseEntity saveFloweringandNonFlowering( + @RequestParam("enumType") String enumType,@RequestParam("parkname") String parkname, @RequestParam("userId") String userId, + @RequestParam("enumerationId") int enumerationId, @RequestParam(value="floweringPlantCount", required = false) int floweringPlantCount, + @RequestParam(value="nonFloweringPlantCount", required = false) int nonFloweringPlantCount, + @RequestParam(value="floweringImage", required = false) MultipartFile floweringImg, + @RequestParam(value="nonFloweringImage", required = false) MultipartFile nonFloweringImg) throws Exception { + + int flowringData = parksService.saveFlowringandNonFlowringDetails(enumerationId, enumType,parkname, floweringPlantCount, floweringImg, + nonFloweringPlantCount, nonFloweringImg, userId); + + if (flowringData == 0 || flowringData == -1) { + return ResponseEntity.ok("Failed to save the details"); } + return ResponseEntity.ok("Details were saved successfully"); + + } + + + @GetMapping("/getFlowringZoneCount") + public ResponseEntity>> getFlowringZoneData(@RequestParam("enumeration_type") String enumeration_type, + @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, + @RequestParam(value="userId", required = false) String userId){ - @GetMapping("/getFlowringZoneCount") - public ResponseEntity>> getFlowringZoneData(@RequestParam("enumeration_type") String enumeration_type, - @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, - @RequestParam(value="userId", required = false) String userId){ - - List> floweringZoneCount = parksService.getFloweringZoneCount(enumeration_type,fromdate,todate,userId); - - if(floweringZoneCount == null || floweringZoneCount.isEmpty()) { - throw new NoDataException("No data found"); - } - - return ResponseEntity.ok(floweringZoneCount); + List> floweringZoneCount = parksService.getFloweringZoneCount(enumeration_type,fromdate,todate,userId); + + if(floweringZoneCount == null || floweringZoneCount.isEmpty()) { + throw new NoDataException("No data found"); } + + return ResponseEntity.ok(floweringZoneCount); + } + + @GetMapping("/getFlowringWardCount") + public ResponseEntity>> getFlowringWardData(@RequestParam("enumeration_type") String enumeration_type, + @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, + @RequestParam(value="userId", required = false) String userId, @RequestParam("zone") String zone){ - @GetMapping("/getFlowringWardCount") - public ResponseEntity>> getFlowringWardData(@RequestParam("enumeration_type") String enumeration_type, - @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, - @RequestParam(value="userId", required = false) String userId, @RequestParam("zone") String zone){ - - List> floweringWardCount = parksService.getFloweringWardCount(zone, fromdate, todate, enumeration_type, userId); - - if (floweringWardCount == null || floweringWardCount.isEmpty()) { - throw new NoDataException("No data found"); - } - return ResponseEntity.ok(floweringWardCount); + List> floweringWardCount = parksService.getFloweringWardCount(zone, fromdate, todate, enumeration_type, userId); + + if (floweringWardCount == null || floweringWardCount.isEmpty()) { + throw new NoDataException("No data found"); } + return ResponseEntity.ok(floweringWardCount); + } + + @GetMapping("/getFloweringDetails") + public ResponseEntity>> getFloweringDetails(@RequestParam("enumeration_type") String enumeration_type, + @RequestParam("zone") String zone, @RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, + @RequestParam("todate") String todate, @RequestParam(value="userId" , required = false) String userId, + @RequestParam("parkname") String parkname){ - @GetMapping("/getFloweringDetails") - public ResponseEntity>> getFloweringDetails(@RequestParam("enumeration_type") String enumeration_type, - @RequestParam("zone") String zone, @RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, - @RequestParam("todate") String todate, @RequestParam(value="userId" , required = false) String userId, - @RequestParam("parkname") String parkname){ - - List> floweringDetails = parksService.getFloweringDetails(enumeration_type, zone, ward, fromdate, todate, userId, parkname); - if(floweringDetails == null || floweringDetails.isEmpty()) - { - throw new NoDataException( "No data found"); - } - return ResponseEntity.ok(floweringDetails); - - } - - @GetMapping("/getParkwiseFloweringCount") - public ResponseEntity>> getParkwiseFloweringCount(@RequestParam("enumeration_type") String enumeration_type, - @RequestParam("zone") String zone, @RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, - @RequestParam("todate") String todate, @RequestParam(value="userId", required = false) String userId){ - - - List> parkwiseCount = parksService.getParkwiseFloweringCount(enumeration_type, zone, ward, fromdate, todate, userId); - - if(parkwiseCount == null || parkwiseCount.isEmpty()) - { - throw new NoDataException( "No data found"); - } - return ResponseEntity.ok(parkwiseCount); - + List> floweringDetails = parksService.getFloweringDetails(enumeration_type, zone, ward, fromdate, todate, userId, parkname); + if(floweringDetails == null || floweringDetails.isEmpty()) + { + throw new NoDataException( "No data found"); + } + return ResponseEntity.ok(floweringDetails); + + } + + @GetMapping("/getParkwiseFloweringCount") + public ResponseEntity>> getParkwiseFloweringCount(@RequestParam("enumeration_type") String enumeration_type, + @RequestParam("zone") String zone, @RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, + @RequestParam("todate") String todate, @RequestParam(value="userId", required = false) String userId){ + + + List> parkwiseCount = parksService.getParkwiseFloweringCount(enumeration_type, zone, ward, fromdate, todate, userId); + + if(parkwiseCount == null || parkwiseCount.isEmpty()) + { + throw new NoDataException( "No data found"); } + return ResponseEntity.ok(parkwiseCount); + + } + + @GetMapping("/getComplaintList") + public ResponseEntity>> getComplaintList(@RequestParam("userid") String userid) { + + List> complaintListforFeedback = parksService.getComplaintListforFeedback(userid); + + if (complaintListforFeedback == null || complaintListforFeedback.isEmpty()) { + throw new NoDataException("No data found"); + + } + return ResponseEntity.ok(complaintListforFeedback); + } + + @GetMapping("/confirmLocation") + public ResponseEntity> confirmLocation(@RequestParam("compId") String compId, + @RequestParam("latitude") String latitude, + @RequestParam("longitude") String longitude) { + Map response = new HashMap<>(); + try { + boolean locationStatus = parksService.confirmLocationforComplaint(compId, latitude, longitude); + + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", locationStatus ? "true" : "false"); + return ResponseEntity.ok(response); + + } catch (Exception e) { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "false"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + @PostMapping("/updateComplaint") + public ResponseEntity> updateComplaint(@RequestParam("compId") String compId, @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam("compImg") MultipartFile compImg, @RequestParam("userid") String userid, + @RequestParam("latitude") String latitude, @RequestParam("longitude") String longitude) throws Exception { + + Map response = new HashMap<>(); + + if (remarks == null || remarks.isEmpty()) { + remarks = "N/A"; + } + try { + + List> updateComplaint = parksService.updateComplaintDetails(compId, remarks, compImg, latitude, longitude, userid); + + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", updateComplaint.size() > 0 ? "Details were saved successfully" : "Error in saving details"); + return ResponseEntity.ok(response); + + } catch (Exception e) { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "Error in saving details"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + @GetMapping("/getZoneComplaintList") + public ResponseEntity>> getZoneComplaintList(@RequestParam("loginId") String loginId) { + + List> complaintListforFeedback = parksService.getZoneComplaintListforFeedback(loginId); + + if (complaintListforFeedback == null || complaintListforFeedback.isEmpty()) { + throw new NoDataException("No data found"); + + } + return ResponseEntity.ok(complaintListforFeedback); + } + } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java index 98616b7..7893aec 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java @@ -29,6 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; @@ -646,6 +647,11 @@ public class ParksService { SaveFeedBack(trimmingProperlyQa, trimmingProperlyAns, activity_Id); SaveFeedBack(weedingQa, weedingAns, activity_Id); int saveFeedBackId = SaveFeedBack(handRailingQa, handRailingAns, activity_Id); + + saveComplaintFeedback(irrigationProperlyQa, irrigationProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(trimmingProperlyQa, trimmingProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(weedingQa, weedingAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(handRailingQa, handRailingAns, activity_Id, zone, ward, latitude, longitude, userId); return saveFeedBackId; @@ -790,9 +796,19 @@ public class ParksService { SaveFeedBack(improvementQa, improvementAns, activity_Id); SaveFeedBack(fountainAvailableQa, fountainAvailableAns, activity_Id); SaveFeedBack(fountainWorkingQa, fountainWorkingAns, activity_Id); - int saveFeedBackId = SaveFeedBack(handRailingQa, handRailingAns, activity_Id); + + saveComplaintFeedback(irrigationProperlyQa, irrigationProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(trimmingProperlyQa, trimmingProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(weedingQa, weedingans, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(improvementQa, improvementAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(fountainAvailableQa, fountainAvailableAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(fountainWorkingQa, fountainWorkingAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(gapFillingQa, gapFilingAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(handRailingQa, handRailingAns, activity_Id, zone, ward, latitude, longitude, userId); + + return saveFeedBackId; } @@ -836,7 +852,16 @@ public class ParksService { SaveFeedBack(trimmingProperlyQa, trimmingProperlyAns, activity_Id); SaveFeedBack(weedingQa, weedingans, activity_Id); SaveFeedBack(improvementQa, improvementAns, activity_Id); + int saveFeedBackId = SaveFeedBack(gapFillingQa, gapFillingAns, activity_Id); + + saveComplaintFeedback(irrigationProperlyQa, irrigationProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(trimmingProperlyQa, trimmingProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(weedingQa, weedingans, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(improvementQa, improvementAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(gapFillingQa, gapFillingAns, activity_Id, zone, ward, latitude, longitude, userId); + + return saveFeedBackId; } @@ -896,6 +921,21 @@ public class ParksService { SaveFeedBack(debrisRemovalQa, debrisRemovalAns, activity_Id); int saveFeedBackId = SaveFeedBack(toiletAQA, toiletAns, activity_Id); + + saveComplaintFeedback(civilWorkQa, civilWorkAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(noWatchmenQa, noWatchmenAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(noSweeperQa, noSweeperAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(openedQa, openedAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(irrigationProperlyQa, irrigationProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(trimmingProperlyQa, trimmingProperlyAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(weedingQa, weedingans, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(gapFillingQa, gapFillingAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(playandGymQa, playandGymAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(overAllQa, overAllAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(properLightQa, properLightAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(debrisRemovalQa, debrisRemovalAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(toiletAQA, toiletAns, activity_Id, zone, ward, latitude, longitude, userId); + return saveFeedBackId; } @@ -938,7 +978,14 @@ public class ParksService { SaveFeedBack(openedOrNotQa, openedOrNotAns, activity_Id); SaveFeedBack(bookAvailableQa, bookAvailableAns, activity_Id); SaveFeedBack(improvementQa, improvementAns, activity_Id); + int saveFeedBackId = SaveFeedBack(newsapaperAvailableQa, newsapaperAvailableAns, activity_Id); + + saveComplaintFeedback(openedOrNotQa, openedOrNotAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(bookAvailableQa, bookAvailableAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(improvementQa, improvementAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(newsapaperAvailableQa, newsapaperAvailableAns, activity_Id, zone, ward, latitude, longitude, userId); + return saveFeedBackId; @@ -989,6 +1036,15 @@ public class ParksService { SaveFeedBack(plantingDoneQa, plantingDoneAns, activity_Id); int saveFeedBackId = SaveFeedBack(cctvQa, cctvAns, activity_Id); + + saveComplaintFeedback(saplingAvailQa, saplingAvailAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(fencingAvailbilityQa, fencingAvailbilityAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(sourcaOfIrrigationQa, sourcaOfIrrigationAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(debrisCleaningQa, debrisCleaningAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(landpreprarationQa, landpreprarationAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(plantingDoneQa, plantingDoneAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(cctvQa, cctvAns, activity_Id, zone, ward, latitude, longitude, userId); + return saveFeedBackId; } @@ -1032,7 +1088,13 @@ public class ParksService { SaveFeedBack(weedingQa, weedingAns, activity_Id); SaveFeedBack(purningQa, purningans, activity_Id); + int saveFeedBackId = SaveFeedBack(gapFillingQa, gapFillingAns, activity_Id); + + saveComplaintFeedback(improvmetReqQa, improvmetReqAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(sourceOfirrigationQa, sourceOfirrigationAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(weedingQa, weedingAns, activity_Id, zone, ward, latitude, longitude, userId); + saveComplaintFeedback(purningQa, purningans, activity_Id, zone, ward, latitude, longitude, userId); return saveFeedBackId; } @@ -1408,9 +1470,14 @@ public class ParksService { */ public List> getZoneCount(String fromdate, String todate, String enumeration_type, String userId ) throws Exception { + /* StringBuilder sql = new StringBuilder("SELECT zone,count(enumeration_Id) as count FROM enumeration_master" + " where enumeration_type=(?) and DATE(cdate) BETWEEN STR_TO_DATE(? , '%d-%m-%Y') " + "AND STR_TO_DATE(? , '%d-%m-%Y') "); + */ + StringBuilder sql = new StringBuilder("SELECT `feedback_zone` as zone ,count(activity_id) as count FROM activity" + + " where feedback_enumeration_Type=(?) and DATE(cdate) BETWEEN STR_TO_DATE(? , '%d-%m-%Y') " + + "AND STR_TO_DATE(? , '%d-%m-%Y') "); List params = new ArrayList<>(); params.add(enumeration_type); @@ -1431,9 +1498,9 @@ public class ParksService { public List> getwardCount(String zone, String fromdate, String todate, String enumeration_type, String userId) { - StringBuilder sql = new StringBuilder(" SELECT ward,count(enumeration_Id) as count FROM enumeration_master " - + "where zone=(?) and date(cdate) between STR_TO_DATE(? , '%d-%m-%Y') " - + "and STR_TO_DATE(? , '%d-%m-%Y') And enumeration_type =(?)"); + StringBuilder sql = new StringBuilder(" SELECT ward,count(activity_id) as count FROM `activity` " + + "where feedback_zone=(?) and date(cdate) between STR_TO_DATE(? , '%d-%m-%Y') " + + "and STR_TO_DATE(? , '%d-%m-%Y') And `feedback_enumeration_Type` =(?)"); List params = new ArrayList<>(); params.add(zone); @@ -1458,35 +1525,28 @@ public class ParksService { StringBuilder sql = new StringBuilder("SELECT " - + " em.enumeration_Id AS feedback_enumeration_Id, " - + " em.ward, " + + " act.feedback_enumeration_Id AS feedback_enumeration_Id, " + + " act.ward, " + " COALESCE(em.park_name, em.location) AS location_Park, " + " COUNT(act.feedback_enumeration_Id) AS count " + "FROM " - + " enumeration_master em " + + " activity act " + "LEFT JOIN " - + " activity act ON act.feedback_enumeration_Id = em.enumeration_Id " - + " AND em.enumeration_Type = ?" - + " AND DATE(act.cdate) BETWEEN STR_TO_DATE( '"+fromdate+"' , '%d-%m-%Y') " - + " AND STR_TO_DATE('"+todate+"', '%d-%m-%Y') " + + " enumeration_master em " + + " ON em.enumeration_Id = act.feedback_enumeration_Id " + "WHERE " - + " em.ward = ? " - + " AND em.zone = ? " - + " AND DATE(em.cdate) BETWEEN STR_TO_DATE('"+fromdate+"', '%d-%m-%Y') " - + " AND STR_TO_DATE('"+todate+"' , '%d-%m-%Y') " ); + + " act.ward = ? " + + " AND act.feedback_zone = ? " + + " AND DATE(act.cdate) BETWEEN STR_TO_DATE('"+fromdate+"', '%d-%m-%Y') " + + " AND STR_TO_DATE('"+todate+"', '%d-%m-%Y') " + + " AND act.`feedback_enumeration_Type` = ? " + + "GROUP BY " + + " act.feedback_enumeration_Id, act.ward, em.location"); List params = new ArrayList<>(); - params.add(enumeration_type); params.add(ward); params.add(zone); - - sql.append(" GROUP BY em.enumeration_Id, em.ward, em.park_name, em.location"); - -// if (userId != null) { -// sql.append(" and act.user_Id = ?"); -// params.add(userId); -// } - + params.add(enumeration_type); return jdbcParkseTemplate.queryForList(sql.toString(), params.toArray()); @@ -1532,8 +1592,8 @@ public class ParksService { List> getParkDetails = new ArrayList<>(); // Fetch images and feedback - List> feedback = getEnumfeedback(activityId, fromdate, todate); - List> image = getEnumImage(enumerationId, fromdate, todate); + List> feedback = getEnumfeedback(activityId); + List> image = getEnumImage(enumerationId); // Prepare maps for images and feedback Map imageMap = new HashMap<>(); @@ -1552,21 +1612,21 @@ public class ParksService { return getEnumDetails1; } - private List> getEnumfeedback(String activityId, String fromdate, String todate) { + private List> getEnumfeedback(String activityId) { String sql = "select eqm.qa_name, fb.feedback_Name from feedback fb " + "left join enu_question_master eqm on eqm.qa_id = fb.feedback_qa_id " + "left join activity act on act.activity_id = fb.activity_id " - + "where fb.activity_id =? and date(act.cdate) between STR_TO_DATE(' "+ fromdate + " ','%d-%m-%Y') and STR_TO_DATE('"+todate+"','%d-%m-%Y')"; + + "where fb.activity_id =?"; return jdbcParkseTemplate.queryForList(sql, new Object[] { activityId }); } - private List> getEnumImage(String enumerationId, String fromdate, String todate) { + private List> getEnumImage(String enumerationId) { String sql = "select *,coalesce(em.park_name,em.location) as parkName, " + "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', eimg.photos_enu) AS imageUrl, em.latitude, em.longitude from enumertion_images eimg " + "left join enumeration_master em on em.enumeration_Id = eimg.enumerationImg_Id_master " - + "where eimg.enumerationImg_Id_master = ? and date(eimg.cdate) between STR_TO_DATE(' "+ fromdate + " ','%d-%m-%Y') and STR_TO_DATE('"+todate+"','%d-%m-%Y')"; + + "where eimg.enumerationImg_Id_master = ?"; return jdbcParkseTemplate.queryForList(sql, new Object[] { enumerationId }); } @@ -2049,5 +2109,162 @@ public class ParksService { return jdbcParkseTemplate.queryForList(sql.toString(), params.toArray()); } + + private void saveComplaintFeedback(String QuestionId, String Ans, int activityId, String zone, String ward, String latitude, String longitude, String userId) { + + if (QuestionId != null && !QuestionId.isEmpty()) { + + String sql = "SELECT qa_name, raise_compliance, positive_ans " + + "FROM enu_question_master " + + "WHERE qa_id = ? " + + "AND raise_compliance = 1 " + + "AND positive_ans <> ?"; + + try { + Map result = jdbcParkseTemplate.queryForMap(sql, QuestionId,Ans); + + String qaName = (String) result.get("qa_name"); + + String positiveAns = (String) result.get("positive_ans"); + + String feedComplaint = qaName + ":" + Ans; + + if (qaName != null && !qaName.isEmpty() && !Ans.equals(positiveAns)) { + + String saveComplaintQuery = "INSERT INTO feed_complaint (`feed_question`, `⁠feed_ans`, `activity_id`, `zone`, `ward`, `⁠latitude`, " + + "`⁠longitude`, `userId`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; + + jdbcParkseTemplate.update(saveComplaintQuery, feedComplaint, Ans, activityId, zone, ward, latitude, longitude, userId); + } + } catch (EmptyResultDataAccessException e) { + System.out.println("No record found for QA_ID: " + QuestionId); + } + } + } + + public List> getComplaintListforFeedback(String userid) { + String sqlQuery = "select fc.comp_id, fc.activity_id, et.enumerationName, fc.zone, fc.ward, " + + "fc.`⁠latitude` AS latitude, fc.`⁠longitude` AS longitude, coalesce(em.park_name, em.location) as parkName, " + + "fc.feed_question as complaintName, " + + "date_format(fc.cdate,'%d-%m-%Y %l:%i %p') as complaintDate, " + + "ifnull(fs.status,'Pending') as ReplyStatus, " + + "ifnull(fs.remarks,'yet to be Resolved') as remarks, " + + "ifnull(CONCAT('" + fileBaseUrl + "/gccofficialapp/files',fs.comp_img_path),'Image Not Uploaded') as ReplyImg, " + + "ifnull(date_format(fs.cdate,'%d-%m-%Y %l:%i %p'),'Complaint yet to be resolved') as complaintClosedDate, " + + "ifnull(fs.userId,'yet to be resolved') as closedBy "+ + "from feed_complaint fc " + + "left join feed_complaint_status fs on fc.comp_id = fs.comp_id " + + "left join activity ac on fc.activity_id = ac.activity_id " + + "left join enumeration_master em on ac.feedback_enumeration_Id = em.enumeration_Id " + + "left join enumerationtype et on em.enumeration_type = et.enumeration_type_id "+ + "where fc.userId =? and fc.is_active = 1 order by fc.cdate asc"; + + return jdbcParkseTemplate.queryForList(sqlQuery, userid); + } + + public List> updateComplaintDetails(String compId, String remarks, MultipartFile compImg, String latitude, String longitude, String userId) throws Exception { + + String name = "feedback_Complaint"; + int comp_status_id = 0; + + try { + if (compImg != null && !compImg.isEmpty()) { + String imagePath = fileUpload(name, compId, compImg); + System.out.println("Image Path: " + imagePath); + comp_status_id = saveComplaintDetails(compId, remarks, imagePath, latitude, longitude, userId); + } /*else { + comp_status_id = saveComplaintDetails(compId, remarks, null, userId); + }*/ + + if (comp_status_id > 0) { + String fetchQuery = "select fc.comp_id, fc.activity_id, fc.feed_question as complaintName, date_format(fc.cdate,'%d-%m-%Y %l:%i %p') as complaintDate, " + + "ifnull(fs.status,'Pending') as ReplyStatus, " + + "ifnull(fs.remarks,'yet to be Resolved') as remarks, " + + "ifnull(CONCAT('" +fileBaseUrl+ "/gccofficialapp/files',fs.comp_img_path),'Image Not Uploaded') as ReplyImg, " + + "ifnull(date_format(fs.cdate,'%d-%m-%Y %l:%i %p'),'Complaint yet to be resolved') as complaintClosedDate, " + + "ifnull(fs.userId,'yet to be resolved') as closedBy " + + "from feed_complaint fc " + + "left join feed_complaint_status fs on fc.comp_id = fs.comp_id " + + "where fc.comp_id =? and fc.is_active = 1"; + return jdbcParkseTemplate.queryForList(fetchQuery, compId); + } + + } catch (Exception e) { + throw new Exception("Error in image saving: " + e.getMessage(), e); + } + + return Collections.emptyList(); + } + + + private int saveComplaintDetails(String compId, String remarks, String imagePath, String latitude, String longitude, String userId) { + + System.out.println("saveComplaintDetails: \n" + + "compId:"+compId + + "\nremarks:"+remarks + + "\nimagePath:"+imagePath + + "\nlatitude:"+latitude + + "\nlongitude:"+longitude + + "\nuserId:"+userId + ); + + String sqlQuery = "INSERT INTO feed_complaint_status " + + "(comp_id, status, remarks, comp_img_path, ⁠latitude, " + + "longitude, userId) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)"; + + String status = "Completed"; + + return jdbcParkseTemplate.update(sqlQuery, compId, status, remarks, imagePath, latitude, longitude, userId); + } + + public boolean confirmLocationforComplaint(String compId, String latitude, String longitude) { + + String sqlQuery ="select `comp_id` from `feed_complaint` where " + + "`comp_id` = ? " + + "AND ((6371008.8 * acos(ROUND(cos(radians(?)) * cos(radians(`⁠latitude`)) * cos(radians(`⁠longitude`) - radians(?)) + sin(radians(?)) * sin(radians(`⁠latitude`)), 9))) < 500)"; + Integer count = jdbcParkseTemplate.queryForObject(sqlQuery, Integer.class, compId, latitude, longitude, latitude); + + return count != null && count > 0; + } + + public String getZoneByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `zone` FROM gcc_penalty_hoardings.hoading_user_list WHERE userid = ? AND type = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcParkseTemplate.queryForList(sqlQuery, loginid, type); + + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + System.out.println("zone....."+results); + // Extract the ward value from the first result + return (String) results.get(0).get("zone"); + } + + // Handle the case where no result is found + return "00"; // or return null based on your needs + } + + public List> getZoneComplaintListforFeedback(String loginid) { + + String zone = getZoneByLoginId(loginid,"osr"); + + String sqlQuery = "select fc.comp_id, fc.activity_id, et.enumerationName, fc.zone, " + + "fc.ward, fc.`⁠latitude` AS latitude, fc.`⁠longitude` AS longitude, coalesce(em.park_name, em.location) as parkName, " + + "fc.feed_question as complaintName, date_format(fc.cdate,'%d-%m-%Y %l:%i %p') as complaintDate, " + + "ifnull(fs.status,'Pending') as ReplyStatus, ifnull(fs.remarks,'yet to be Resolved') as remarks, " + + "ifnull(CONCAT('https://gccservices.in/gccofficialapp/files',fs.comp_img_path),'Image Not Uploaded') as ReplyImg, " + + "ifnull(date_format(fs.cdate,'%d-%m-%Y %l:%i %p'),'Complaint yet to be resolved') as complaintClosedDate, " + + "ifnull(fs.userId,'yet to be resolved') as closedBy " + + "from feed_complaint fc " + + "left join feed_complaint_status fs on fc.comp_id = fs.comp_id " + + "left join activity ac on fc.activity_id = ac.activity_id " + + "left join enumeration_master em on ac.feedback_enumeration_Id = em.enumeration_Id " + + "left join enumerationtype et on em.enumeration_type = et.enumeration_type_id " + + "where fc.zone =? and fc.is_active = 1 and fs.status is null order by fc.cdate asc"; + + return jdbcParkseTemplate.queryForList(sqlQuery, zone); + } } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java index 1dab6d3..9623e5c 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java @@ -308,6 +308,9 @@ public class SchoolUserController { @RequestParam String SeepageQa, @RequestParam String SeepageAns, @RequestParam(required = false) MultipartFile feedPhoto, + @RequestParam(required = false) MultipartFile utensilsPhoto, + @RequestParam(required = false) MultipartFile blockagePhoto, + @RequestParam(required = false) MultipartFile seepagePhoto, @RequestParam(required = false) int school_details_id, @RequestParam String zone, @RequestParam String division, @@ -326,7 +329,7 @@ public class SchoolUserController { SufficientNumberQa, SufficientNumberAns, BlockageInWashAreaQa, BlockageInWashAreaAns, SeepageQa, SeepageAns, - feedPhoto, school_details_id, zone, division,latitude,longitude,user_id + feedPhoto, utensilsPhoto, blockagePhoto, seepagePhoto, school_details_id, zone, division,latitude,longitude,user_id ); return new ResponseEntity<>("Feedback saved successfully.", HttpStatus.OK); @@ -437,7 +440,7 @@ public class SchoolUserController { @RequestParam String SeepageinSchoolAns, @RequestParam String HowmanyLocationsQa, @RequestParam String HowmanyLocationsAns, - //@RequestParam(required = false) MultipartFile feedPhoto, + @RequestParam(required = false) MultipartFile seepageinPhoto, @RequestParam(required = false) int school_details_id, @RequestParam String zone, @RequestParam String division, @@ -451,8 +454,9 @@ public class SchoolUserController { categoryId, SeepageinSchoolQa, SeepageinSchoolAns, HowmanyLocationsQa, HowmanyLocationsAns, - school_details_id, zone, division, - latitude,longitude,user_id // Pass latitude to the service + seepageinPhoto, + school_details_id, zone, division, + latitude,longitude,user_id ); return new ResponseEntity<>("Feedback saved successfully.", HttpStatus.OK); diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java index f3b53c4..c7692d5 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java @@ -196,10 +196,12 @@ public class SchoolUserActivity { private void updateSchoolInactive(String id, int schoolDetailsId) { String sql = "UPDATE `school_list` SET `gcc_app_updated`=? WHERE `school_name`=?"; jdbcSchoolsTemplate.update(sql, schoolDetailsId, id); + + // For education Web (gcc_schools_web Database) + String sql_web = "UPDATE `gcc_schools_web`.`school_list` SET `gcc_app_updated`=? WHERE `school_name`=?"; + jdbcSchoolsTemplate.update(sql_web, schoolDetailsId, id); } - - private int saveSchoolDetails(String latitude, String longitude, Integer schoolTypeId, String schoolName, String earmark, String zone, String division, String userId) { @@ -601,6 +603,9 @@ public class SchoolUserActivity { String SeepageQa, String SeepageAns, MultipartFile feedPhoto, + MultipartFile utensilsPhoto, + MultipartFile blockagePhoto, + MultipartFile seepagePhoto, int school_details_id, String zone, String division , @@ -609,6 +614,9 @@ public class SchoolUserActivity { String user_id) { String feedPhotoPath = null; + String utensilsPhotoPath = null; + String blockagePhotoPath = null; + String seepagePhotoPath = null; // Handle file upload if a file is provided if (feedPhoto != null && !feedPhoto.isEmpty()) { @@ -618,6 +626,27 @@ public class SchoolUserActivity { //feedPhotoPath = assetFileUpload(categoryId, feedPhoto, school_details_id); } + // Handle file upload if a file is provided + if (utensilsPhoto != null && !utensilsPhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + utensilsPhotoPath = fileUpload(id, sdid, utensilsPhoto); // Adjusted to use schoolDetailsId + } + + // Handle file upload if a file is provided + if (blockagePhoto != null && !blockagePhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + blockagePhotoPath = fileUpload(id, sdid, blockagePhoto); // Adjusted to use schoolDetailsId + } + + // Handle file upload if a file is provided + if (seepagePhoto != null && !seepagePhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + seepagePhotoPath = fileUpload(id, sdid, seepagePhoto); // Adjusted to use schoolDetailsId + } + String feedref = generateRandomString(); //generate feedback reference text // Save feedback for each question and answer pair saveFeedbackDetails(categoryId, NoonMealKitchenAvailableQa, NoonMealKitchenAvailableAns, school_details_id, zone, division,latitude,longitude,user_id,feedref); @@ -633,6 +662,21 @@ public class SchoolUserActivity { String qid="16"; saveCategoryPhoto(categoryId, feedPhotoPath, qid, feedref); } + // If a photo was uploaded, save it in the category_photos table + if (utensilsPhotoPath != null) { + String qid="19"; + saveCategoryPhoto(categoryId, utensilsPhotoPath, qid, feedref); + } + // If a photo was uploaded, save it in the category_photos table + if (blockagePhotoPath != null) { + String qid="21"; + saveCategoryPhoto(categoryId, blockagePhotoPath, qid, feedref); + } + // If a photo was uploaded, save it in the category_photos table + if (seepagePhotoPath != null) { + String qid="22"; + saveCategoryPhoto(categoryId, seepagePhotoPath, qid, feedref); + } } //////////////////////////////////////////////////////////// public void saveElectricityFeedback( @@ -755,7 +799,7 @@ public class SchoolUserActivity { String SeepageinSchoolAns, String HowmanyLocationsQa, String HowmanyLocationsAns, -// MultipartFile feedPhoto, + MultipartFile seepageinPhoto, int school_details_id, String zone, String division, @@ -763,11 +807,25 @@ public class SchoolUserActivity { double longitude, String user_id) { // Add latitude parameter + String seepageinPhotoPath = null; + + if (seepageinPhoto != null && !seepageinPhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + seepageinPhotoPath = fileUpload(id, sdid, seepageinPhoto); // Adjusted to use schoolDetailsId + } + String feedref = generateRandomString(); //generate feedback reference text // Save feedback for each question and answer pair saveFeedbackDetails(categoryId, SeepageinSchoolQa, SeepageinSchoolAns, school_details_id, zone, division, latitude,longitude,user_id,feedref); saveFeedbackDetails(categoryId, HowmanyLocationsQa, HowmanyLocationsAns, school_details_id, zone, division, latitude,longitude,user_id,feedref); - + + // If a photo was uploaded, save it in the category_photos table + if (seepageinPhotoPath != null) { + String qid="32"; + saveCategoryPhoto(categoryId,seepageinPhotoPath,qid,feedref); + } + } private void saveFeedbackDetails( diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/StreetVendorController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/StreetVendorController.java new file mode 100644 index 0000000..2d143e9 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/StreetVendorController.java @@ -0,0 +1,267 @@ +package in.gov.chennaicorporation.mobileservice.gccstreetvendor.controller; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import in.gov.chennaicorporation.mobileservice.configuration.AppConfig; +import in.gov.chennaicorporation.mobileservice.gccstreetvendor.service.StreetVendorService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; +import org.bytedeco.opencv.presets.opencv_core; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +@RequestMapping("/gccofficialapp/api/streetvendor") +@RestController("gccofficialappstreetvendor") + +public class StreetVendorController { + + @Autowired + StreetVendorService streetVendorService; + + @Autowired + AppConfig appConfig; + + //To fetch all social category + @GetMapping("/social-categories") + public List> getSocialCategories() { + return streetVendorService.getAllSocialCategories(); + } + + //To fetch all vending category + @GetMapping("/vending-categories") + public List> getVendingCategories() { + return streetVendorService.getAllVendingCategories(); + } + + // To save Vendor details + @PostMapping("/save-street-vendor") + public ResponseEntity saveStreetVendor( + @RequestParam("name") String name, + @RequestParam("fh_name") String fhname, + @RequestParam("gender") String gender, + @RequestParam("dob") String dob, + @RequestParam("social_category") String socialCategory, + @RequestParam("diff_abled") boolean diffAbled, + @RequestParam("mob_no") String mobileNo, + @RequestParam("aadhar_no") String aadharNo, + @RequestParam("present_address") String presentAddress, + @RequestParam("present_district") String presentDistrict, + @RequestParam("present_pincode") String presentPincode, + @RequestParam("vending_address") String vendingAddress, + @RequestParam("vending_district") String vendingDistrict, + @RequestParam("vending_pincode") String vendingPincode, + @RequestParam("vending_category") String vendingCategory, + @RequestParam("vending_space") String vendingSpace, + @RequestParam("bank_acc_status") boolean bankAccStatus, + @RequestParam("zone") String zone, + @RequestParam("ward") String ward, + @RequestParam("pm_svanidhi_loan") boolean pmSvanidhiLoan, + @RequestParam(required = false, name = "bank_passbook") MultipartFile bankPassbook, + @RequestParam("ration_card") MultipartFile rationCard, + @RequestParam("education_status") int education_status, + @RequestParam("marital_status") int marital_status, + @RequestParam("no_of_fam_mem") int no_of_fam_mem, + @RequestParam("fam_mem_invol_str_ven") boolean are_fam_mem_invol_str_ven, + @RequestParam("street_vendor_photo") MultipartFile streetVendorPhoto, + @RequestParam("aadhar_front_photo") MultipartFile aadharFrontPhoto, + @RequestParam("aadhar_back_photo") MultipartFile aadharBackPhoto) { + + // File upload paths + String bankPassbookPath = (bankPassbook != null) ? + streetVendorService.fileUpload(bankPassbook, "street_vendor_bank") : ""; + + String rationCardPath = (rationCard != null) ? + streetVendorService.fileUpload(rationCard, "street_vendor_ration") : ""; + + String streetVendorPhotoPath = (streetVendorPhoto != null) ? + streetVendorService.fileUpload(streetVendorPhoto, "street_vendor_photo") : ""; + + String aadharFrontPhotoPath = (aadharFrontPhoto != null) ? + streetVendorService.fileUpload(aadharFrontPhoto, "aadhar_front") : ""; + + String aadharBackPhotoPath = (aadharBackPhoto != null) ? + streetVendorService.fileUpload(aadharBackPhoto, "aadhar_back") : ""; + + // Save to DB + String saveStatus = streetVendorService.saveStreetVendorDetails( + name, fhname, gender, dob, socialCategory, diffAbled, mobileNo, aadharNo, + presentAddress, presentDistrict, presentPincode, + vendingAddress, vendingDistrict, vendingPincode, + vendingCategory, vendingSpace, bankAccStatus, zone, ward, pmSvanidhiLoan, + bankPassbookPath, rationCardPath, streetVendorPhotoPath, + aadharFrontPhotoPath, aadharBackPhotoPath, + education_status,marital_status,no_of_fam_mem,are_fam_mem_invol_str_ven + ); + + if (saveStatus == null || saveStatus.isEmpty() || saveStatus.equals("error")) { + return ResponseEntity.ok(Map.of( + "status", false, + "message", "failed", + "description", "Failed to save the details" + ).toString()); + } + + return ResponseEntity.ok(Map.of( + "status", true, + "message", "success", + "description", "Details were saved successfully" + ).toString()); + } + + @GetMapping(value = "/sendOTP") + @ResponseBody + public Map sendOtp(HttpServletRequest request, @RequestParam String mobile) { + Map response = new HashMap<>(); + String MobileNo = mobile; + Random rand = new Random(); + int otp = rand.nextInt(9000) + 1000;; + + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy%20HH:mm"); + LocalDateTime now = LocalDateTime.now(); + + String generatedToken = "Welcome to GCC! Your OTP for GCC Street Vendor Application is " + otp; + String key = "pfTEYN6H"; + String urlString = appConfig.otpurl + "from=GCCCRP&key=" + key + "&sender=GCCCRP&to=" + MobileNo + + "&body=" + generatedToken + "&entityid=1401572690000011081&templateid=1407174410515874750"; + + try { + RestTemplate restTemplate = new RestTemplate(); + String apiResponse = restTemplate.getForObject(urlString, String.class); + + // Parse the response using ObjectMapper + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(apiResponse); + + int statusCode = jsonNode.get("status").asInt(); + String description = jsonNode.get("description").asText(); + + if (statusCode == 100) { + HttpSession session = request.getSession(); + session.setAttribute("otp", otp); + response.put("status", true); + } else { + response.put("status", false); + } + + response.put("description", description); + response.put("otp", otp); // Optional: for debugging only (don't include in production) + } catch (Exception e) { + response.put("status", false); + response.put("description", "Error sending OTP: " + e.getMessage()); + } + + return response; + } + + @GetMapping(value = "/verifyOTP") + @ResponseBody + public Map verifyOtp(HttpServletRequest request, @RequestParam String otp) { + Map response = new HashMap<>(); + HttpSession session = request.getSession(); + + try { + Integer session_otp = (Integer) session.getAttribute("otp"); + Integer entered_otp = Integer.parseInt(otp); + + //System.out.println("session_otp---:" + session_otp); + //System.out.println("entered_otp---:" + entered_otp); + + if (session_otp != null && session_otp.equals(entered_otp)) { + session.setAttribute("verifiedotp", "success"); + response.put("status", true); + response.put("message", "Success"); + } else { + session.setAttribute("verifiedotp", "error"); + response.put("status", false); + response.put("message", "Incorrect OTP"); + } + } catch (NumberFormatException e) { + //System.out.println("Invalid OTP format: " + otp); + response.put("status", false); + response.put("message", "Invalid OTP format"); + } catch (Exception e) { + //System.out.println("Error verifying OTP: " + e.getMessage()); + response.put("status", false); + response.put("message", "Error verifying OTP"); + } + + return response; + } + + @GetMapping("/getvendorlist") + public List> getVendorList( + @RequestParam(value = "loginId", required = false) String loginid + ) { + return streetVendorService.getAllVendorDetails(loginid); + } + + @GetMapping("/getvendingtimes") + public List> getVendingTimes() { + return streetVendorService.getAllVendingTimes(); + } + + @GetMapping("/getmaritalstatus") + public List> getMaritalStatus() { + return streetVendorService.getAllMaritalStatus(); + } + + @GetMapping("/gettransactionmodes") + public List> getTransactionMode() { + return streetVendorService.getAllTransactionModes(); + } + + @GetMapping("/geteducationstatus") + public List> getEducationSatus() { + return streetVendorService.getAllEducationSatus(); + } + + // save the entered li details + @PostMapping("/saveFirstApproval") + public ResponseEntity saveFirstApproval( + @RequestParam(required = true, name = "loginId") String loginid, + @RequestParam(required = true, name = "vdid") String vdid, + @RequestParam(required = false, name = "vendor_type") String vendor_type, + @RequestParam(required = true, name = "latitude") String latitude, + @RequestParam(required = true, name = "longitude") String longitude, + @RequestParam(required = false, name = "vendor_id_card") boolean vendor_id_card, + @RequestParam(required = false, name = "vending_nature") String vending_nature, + @RequestParam(required = false, name = "vending_time") String vending_time, + //@RequestParam(required = false, name = "education_status") String education_status, + //@RequestParam(required = false, name = "marital_status") String marital_status, + //@RequestParam(required = false, name = "no_of_family_mem") String no_of_family_mem, + //@RequestParam(required = false, name = "fam_mem_street_vendor") boolean fam_mem_street_vendor, + @RequestParam(required = false, name = "transaction_mode") String transaction_mode, + @RequestParam(required = false, name = "svanidhi_loan_amount") String svanidhi_loan_amount, + @RequestParam(required = false, name = "vendor_space_photo") MultipartFile vendor_space_photo, + @RequestParam(required = true, name = "status") String status, + @RequestParam(required = true, name = "remarks") String remarks){ + + + String vendor_space_path = ""; + if ( vendor_space_photo != null) { + vendor_space_path = streetVendorService.fileUpload(vendor_space_photo, "vendor_space_photo"); + } + //String status = "Approved"; + + String saveStatus = streetVendorService.saveFirstApproval(loginid,vdid,vendor_type, latitude, longitude, vendor_id_card, vending_nature, + vending_time, transaction_mode, + svanidhi_loan_amount, status, remarks, vendor_space_path); + + if (saveStatus ==null || saveStatus.isEmpty()) { + return ResponseEntity.ok(Map + .of("status", false, "message", "failed", "description", "Failed to save the details").toString()); + } + + return ResponseEntity.ok(Map + .of("status", true, "message", "success", "description", "Details were saved successfully").toString()); + + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/package-info.java new file mode 100644 index 0000000..ae917f9 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.gccstreetvendor.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/StreetVendorService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/StreetVendorService.java new file mode 100644 index 0000000..6382091 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/StreetVendorService.java @@ -0,0 +1,337 @@ +package in.gov.chennaicorporation.mobileservice.gccstreetvendor.service; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; +import jakarta.transaction.Transactional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +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.web.multipart.MultipartFile; + + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.Random; + +@Service +public class StreetVendorService { + + @Autowired + private JdbcTemplate jdbcStreetVendorTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlGccStreetVendorDataSource") DataSource streetVendorDataSource) { + this.jdbcStreetVendorTemplate = new JdbcTemplate(streetVendorDataSource); + } + + public StreetVendorService(Environment environment) { + this.environment = environment; + this.fileBaseUrl = environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(MultipartFile file, String name) { + + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("street_vendor_foldername"); + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + month; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + String fileName = name + "_" + datetimetxt + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/" + serviceFolderName + year + "/" + month + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, compressedBytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public String getWardByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `ward` FROM `gcc_penalty_hoardings`.`hoading_user_list` WHERE `userid` = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcStreetVendorTemplate.queryForList(sqlQuery, loginid); + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + // Extract the ward value from the first result + return (String) results.get(0).get("ward"); + } + + // Handle the case where no result is found + return "000"; // or return null based on your needs + } + + //To fetch all social category + public List> getAllSocialCategories() { + String sql = "SELECT id, category_name FROM social_category_master WHERE is_active = true AND is_delete = false"; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + //To fetch all vending category + public List> getAllVendingCategories() { + String sql = "SELECT id, vending_category_name FROM vending_category_master WHERE is_active = true AND is_delete = false"; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + // To save Vendor details + public String saveStreetVendorDetails(String name, String fhname, String gender, String dob, String socialCategory, + boolean diffAbled, String mobNo, String aadharNo, String presentAddress, String presentDistrict, + String presentPincode, String vendingAddress, String vendingDistrict, String vendingPincode, + String vendingCategory, String vendingSpace, boolean bankAccStatus, String zone, String ward, + boolean pmSvanidhiLoan, String bankPassbookPath, String rationCardPath, String streetVendorPhotoPath, + String aadharFrontPhotoPath, String aadharBackPhotoPath, + int educationStatus, int maritalStatus, int noOfFamMem,boolean areAnyFamMemInvolStrVen) { + + String sql = "INSERT INTO vendor_details (" + + "name, f_h_name, gender, dob, social_category, diff_abled, mob_no, aadhar_no, " + + "present_address, present_district, present_pincode, vending_address, vending_district, vending_pincode, " + + "vending_category, vending_space, bank_acc_status, zone, ward, pm_svanidhi_loan, " + + "bank_passbook, ration_card_photo, street_vendor_photo, aadhar_front_photo, aadhar_back_photo, " + + "education_status, marital_status, no_of_fam_mem, are_any_fam_mem_invol_str_ven" + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int result = jdbcStreetVendorTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" }); + ps.setString(1, name); + ps.setString(2, fhname); + ps.setString(3, gender); + ps.setString(4, dob); + ps.setString(5, socialCategory); + ps.setBoolean(6, diffAbled); + ps.setString(7, mobNo); + ps.setString(8, aadharNo); + ps.setString(9, presentAddress); + ps.setString(10, presentDistrict); + ps.setString(11, presentPincode); + ps.setString(12, vendingAddress); + ps.setString(13, vendingDistrict); + ps.setString(14, vendingPincode); + ps.setString(15, vendingCategory); + ps.setString(16, vendingSpace); + ps.setBoolean(17, bankAccStatus); + ps.setString(18, zone); + ps.setString(19, ward); + ps.setBoolean(20, pmSvanidhiLoan); + ps.setString(21, bankPassbookPath); + ps.setString(22, rationCardPath); + ps.setString(23, streetVendorPhotoPath); + ps.setString(24, aadharFrontPhotoPath); + ps.setString(25, aadharBackPhotoPath); + ps.setInt(26, educationStatus); + ps.setInt(27, maritalStatus); + ps.setInt(28, noOfFamMem); + ps.setBoolean(29, areAnyFamMemInvolStrVen); + return ps; + }, keyHolder); + //return keyHolder.getKey().intValue(); + if (result > 0) { + int generatedId = keyHolder.getKey().intValue(); + String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String refId = prefix + generatedId; + + String updateSql = " UPDATE vendor_details SET vendor_req_id = ? WHERE id = ? "; + jdbcStreetVendorTemplate.update(updateSql,refId, generatedId); + return refId; + } + //return "error"; + } catch (Exception e) { + e.printStackTrace(); + } + return "error"; + } + + // To fetch street vendor details + @Transactional + public List> getAllVendorDetails(String loginid) { + + String ward = getWardByLoginId(loginid,"li"); + + StringBuilder query = new StringBuilder( + " SELECT vd.id, vd.name, vd.f_h_name, vd.gender, vd.zone, vd.ward," + + " vd.dob,vd.mob_no, vd.vending_space, vd.pm_svanidhi_loan, vd.bank_acc_status, " + + " vd.diff_abled, scm.category_name, vcm.vending_category_name," + + " em.education, msm.marital_status, vd.no_of_fam_mem, CASE " + + " WHEN vd.are_any_fam_mem_invol_str_ven = TRUE THEN 'Yes' " + + " ELSE 'No' " + + " END AS family_member_involved, " + + " CONCAT(vd.present_district, ', ', vd.present_pincode, ', ', vd.present_address) AS residental_address," + + " CONCAT(vd.vending_district, ', ', vd.vending_pincode, ', ', vd.vending_address) AS business_address," + + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.street_vendor_photo) as street_vendor_photo," + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.aadhar_front_photo) as aadhar_front_photo," + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.aadhar_back_photo) as aadhar_back_photo," + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.ration_card_photo) as ration_card_photo," + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files',vd.bank_passbook) as bank_passbook," + + + " DATE_FORMAT(vd.cdate, '%d-%m-%Y') as request_date" + + " FROM vendor_details vd" + + " LEFT JOIN social_category_master scm ON vd.social_category=scm.id" + + " LEFT JOIN vending_category_master vcm ON vd.vending_category=vcm.id " + + " LEFT JOIN `education_master` em ON vd.education_status=em.id " + + " LEFT JOIN `marital_status_master` msm ON vd.marital_status=msm.id " + + " WHERE vd.ward IN (?)"); + + return jdbcStreetVendorTemplate.queryForList(query.toString(),ward); + } + + + public List> getAllVendingTimes() { + String sql = " SELECT id, vending_time FROM vending_time_master WHERE is_active = 1 AND is_delete = 0 "; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + public List> getAllMaritalStatus() { + String sql = " SELECT id, marital_status FROM marital_status_master WHERE is_active = 1 AND is_delete = 0 "; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + public List> getAllTransactionModes() { + String sql = "SELECT id, transaction_mode FROM transaction_mode_master WHERE is_active = 1 AND is_delete = 0"; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + public List> getAllEducationSatus() { + String sql = "SELECT id, education FROM education_master WHERE is_active = 1 AND is_delete = 0"; + return jdbcStreetVendorTemplate.queryForList(sql); + } + + public String saveFirstApproval(String loginid, String vdid, String vendor_type, String latitude, String longitude, + boolean vendor_id_card, String vending_nature, String vending_time, + String transaction_mode,String svanidhi_loan_amount, + String status, String remarks, String vendor_space_path) { + + String sql = "INSERT INTO vendor_approval (" + + "vendor_type, latitude, longitude, vendor_id_card, vending_nature, vendor_timing_id, transaction_mode_id, swanidi_loan_amount, status, remarks, " + + "vendor_space_photo, vdid, cby" + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + + int result = jdbcStreetVendorTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + ps.setString(1, vendor_type); + ps.setString(2, latitude); + ps.setString(3, longitude); + ps.setBoolean(4, vendor_id_card); + ps.setString(5, vending_nature); + ps.setString(6, vending_time); + + ps.setString(7, transaction_mode); + ps.setString(8, svanidhi_loan_amount); + ps.setString(9, status); + ps.setString(10, remarks); + ps.setString(11, vendor_space_path); + ps.setString(12, vdid); + ps.setString(13, loginid); + // ps.setString(16, vendingSpace); add the additional flag variable + + return ps; + }, keyHolder); + + if (result > 0) { + int generatedId = keyHolder.getKey().intValue(); + String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); + String refId = prefix + generatedId; + + String updateSql = " UPDATE vendor_details SET vendor_req_id = ? WHERE id = ? "; + jdbcStreetVendorTemplate.update(updateSql,refId, generatedId); + return refId; + } + + return "error"; + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/package-info.java new file mode 100644 index 0000000..e76a5f7 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccstreetvendor/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.gccstreetvendor.service; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java index 7c512f7..fd7b88a 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java @@ -297,13 +297,11 @@ public class HoardingsService { Number generatedId = keyHolder.getKey(); lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; int asset_id = lastInsertId; - response.put("insertId", lastInsertId); - response.put("status", "success"); - response.put("message", "New Hoardings added successfully!"); + System.out.println("New Hoardings added successfully! Insert ID: " + generatedId); System.out.println("test:"+case_no); - updateHoardingLicenseInactive(licenses_no,asset_id); + //updateHoardingLicenseInactive(licenses_no,asset_id); int getUpdateStatus=insertHoardingInfo( asset_id, @@ -321,6 +319,21 @@ public class HoardingsService { fine_to, loginId); + if(getUpdateStatus>0) { + updateHoardingLicenseInactive(licenses_no,asset_id); + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Hoardings added successfully!"); + } + else { + String sqlQueryDelete= "DELETE FROM `asset_list` WHERE id = ?"; + jdbcHoardingsTemplate.update(sqlQueryDelete,lastInsertId); + + response.put("status", "error"); + response.put("message", "Failed to insert a new hoardings (Asset)."); + } + } else { response.put("status", "error"); response.put("message", "Failed to insert a new hoardings (Asset)."); @@ -1717,7 +1730,7 @@ public class HoardingsService { + " `hoarding_ae_update` haeu ON haeu.asset_id = hi.asset_id " + "WHERE " + " (al.`isactive` = 1 AND al.`isdelete` = 0) "; - + /* String sqlQuery_where=" AND 1=0 AND haeu.`cby`= ?"; if("materail".equals(pendingType)) { @@ -1729,7 +1742,7 @@ public class HoardingsService { } sqlQuery = sqlQuery + sqlQuery_where; - + */ List> result = jdbcHoardingsTemplate.queryForList(sqlQuery,loginid); Map response = new HashMap<>(); response.put("status", 200); diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_FoggingController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_FoggingController.java new file mode 100644 index 0000000..d461220 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_FoggingController.java @@ -0,0 +1,213 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.mosquitosurvey.service.FoggingService; + +@RequestMapping("/gccofficialapp/mosquito/api") +@RestController("apiFoggingRest") +public class API_FoggingController { + @Autowired + private FoggingService foggingService; + + @GetMapping("/getMaintainByList") + public List getMaintainByList() { + return foggingService.getMaintainByList(); + } + + @GetMapping("/getCanalsList") + public List getCanalsList( + @RequestParam(value = "maintainedby", required = true) String maintainedby, + @RequestParam(value = "zone", required = true) String zone + ) { + return foggingService.getCanalsList(maintainedby, zone); + } + + @PostMapping(value="/saveCanalFlow") + public List saveCanalFlow(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "maintainedby", required = true) String maintainedby, + @RequestParam(value = "canalid", required = true) String canalid, + @RequestParam(value = "sprayingmedium", required = true) String q4, + @RequestParam(value = "sprayingtype", required = true) String q5, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveCanalFlow(cid,scid,maintainedby,canalid,q4,q5,file,remarks,cby,zone,ward,latitude,longitude,"pending"); + } + + @GetMapping("/checkHasCanalPending") + public List checkHasPending( + @RequestParam(value = "loginId", required = true) String cby + ) { + return foggingService.checkHasCanalPending(cby); + } + + @GetMapping("/getCanalPendingList") + public List getCanalPendingList( + @RequestParam(value = "loginId", required = true) String cby + ) { + return foggingService.getCanalPendingList(cby); + } + + @GetMapping("/checkCanalPendingUpdateLocation") + public List checkPendingUpdateLocation( + @RequestParam(value = "activityid", required = true) String canalactivityid, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.checkCanalPendingUpdateLocation(canalactivityid,latitude,longitude); + } + + @PostMapping(value="/saveCanalData") + public List saveCanalFlow(@RequestParam MultiValueMap formData, + @RequestParam(value = "activityid", required = true) String canalactivityid, + @RequestParam(value = "isfinal", required = true) String isfinal, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveCanalActivityData(canalactivityid,isfinal,file,remarks,cby,zone,ward,latitude,longitude); + } + + + // ************************************************************************************************************************* // + // For SWD Activity + + @PostMapping(value="/saveSWDFlow") + public List saveSWDFlow(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "streetname", required = true) String streetname, + @RequestParam(value = "streetid", required = true) String streetid, + @RequestParam(value = "breedfound", required = true) String q2, + @RequestParam(value = "sprayingmedium", required = true) String q4, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveSWDFlow(cid,scid,streetname,streetid,q2,q4,file,remarks,cby,zone,ward,latitude,longitude,"pending"); + } + + @GetMapping("/checkHasSWDPending") + public List checkHasSWDPending( + @RequestParam(value = "loginId", required = true) String cby + ) { + return foggingService.checkHasSWDPending(cby); + } + + @GetMapping("/getSWDPendingList") + public List getSWDPendingList( + @RequestParam(value = "loginId", required = true) String cby + ) { + return foggingService.getSWDPendingList(cby); + } + + @GetMapping("/checkSWDPendingUpdateLocation") + public List checkSWDPendingUpdateLocation( + @RequestParam(value = "activityid", required = true) String swdactivityid, + @RequestParam(value = "streetid", required = true) String streetid + ) { + return foggingService.checkSWDPendingUpdateLocation(swdactivityid,streetid); + } + + @PostMapping(value="/updateSWDPendingStatus") + public List updatePendingStatus(@RequestParam MultiValueMap formData, + @RequestParam(value = "activityid", required = true) String swdactivityid, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "streetname", required = true) String streetname, + @RequestParam(value = "streetid", required = true) String streetid, + @RequestParam(value = "q2", required = true) String q2, + @RequestParam(value = "q4", required = true) String q4, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "did", required = true) String did + ) { + return foggingService.updateSWDPendingStatus(swdactivityid, file, streetname, streetid, + q2, q4, remarks, cby, zone, ward, latitude, longitude, "close", did); + } + + @PostMapping(value="/saveStreetData") + public List saveStreetData(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "streetid", required = true) String streetid, + @RequestParam(value = "streetname", required = true) String streetname, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveStreetData(cid, scid, streetid, streetname, file, remarks, cby, zone, ward, latitude, longitude, "close"); + } + + @PostMapping(value="/saveVacantLandData") + public List saveVacantLandData(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "name", required = true) String name, + @RequestParam(value = "breedfound", required = true) String q2, + @RequestParam(value = "action", required = false) String q3, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveVacantLandData(cid, scid, name, q2, q3, file, remarks, cby, zone, ward, latitude, longitude, "close"); + } + + // SAMPLE COLLECTION + @PostMapping(value="/saveLarvalAdultCollectionFlow") + public List saveLarvalAdultCollectionFlow(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "maintainedby", required = true) String maintainedby, + @RequestParam(value = "canalid", required = true) String canalid, + @RequestParam(value = "breedfound", required = true) String q2, + @RequestParam(value = "lavasample", required = false) String q6, + @RequestParam(value = "action", required = false) String q7, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return foggingService.saveLarvalAdultCollectionFlow(cid,maintainedby,canalid,q2,q6,q7, + file,remarks,cby,zone,ward,latitude,longitude,"close"); + } + +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_MosquitoController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_MosquitoController.java new file mode 100644 index 0000000..474cf08 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/API_MosquitoController.java @@ -0,0 +1,136 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.mosquitosurvey.service.MosquitoService; + +@RequestMapping("/gccofficialapp/mosquito/api") +@RestController("apiMosquitoRest") +public class API_MosquitoController { + @Autowired + private MosquitoService mosquitoService; + + @GetMapping("/getCategoryList") + public List getCategoryList( + ) { + return mosquitoService.getCategoryList(); + } + + @GetMapping("/getSubCategoryList") + public List getSubCategoryList( + @RequestParam(value = "cid", required = true) String cid + ) { + return mosquitoService.getSubCategoryList(cid); + } + + @GetMapping("/getTreatmentList") + public List getTreatmentList( + ) { + return mosquitoService.getTreatmentList(); + } + + @GetMapping("/getBreadingSourceCategoryList") + public List getBreadingSourceCategoryList( + ) { + return mosquitoService.getBreadingSourceCategoryList(); + } + + @GetMapping("/getBreadingSourceList") + public List getBreadingSourceList( + ) { + return mosquitoService.getBreadingSourceList(); + } + + // ************************************************************************************************************************* // + // For House, Companies & Education Institution + + @PostMapping(value="/saveSurveyFlow1") + public List saveSurveyFlow1(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "visitstatus", required = true) String visitstatus, + @RequestParam(value = "feverfound", required = true) String q1, + @RequestParam(value = "treatment", required = false) String treatment, + @RequestParam(value = "breedfound", required = true) String q2, + @RequestParam(value = "sourcetype", required = false) String sourcetype, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "name", required = true) String name, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + //@RequestParam(value = "file", required = true) MultipartFile file, + + ) { + return mosquitoService.saveSurveyFlow1(cid,scid,q1,treatment,q2,sourcetype,cby,name,zone,ward,latitude,longitude,visitstatus); + } + + @GetMapping("/checkHasPending") + public List checkHasPending( + @RequestParam(value = "loginId", required = true) String cby + ) { + return mosquitoService.checkHasPending(cby); + } + + @GetMapping("/getHousePendingList") + public List getHousePendingList( + @RequestParam(value = "loginId", required = true) String cby + ) { + return mosquitoService.getHousePendingList(cby); + } + + @GetMapping("/checkPendingUpdateLocation") + public List checkPendingUpdateLocation( + @RequestParam(value = "id", required = true) String id, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return mosquitoService.checkPendingUpdateLocation(id,latitude,longitude); + } + + @PostMapping(value="/updateSurveyFlow1Pending") + public List updatePendingStatus(@RequestParam MultiValueMap formData, + @RequestParam(value = "sid", required = true) String sid, + @RequestParam(value = "action", required = true) String q3, + @RequestParam(value = "file", required = true) MultipartFile file, + @RequestParam(value = "remarks", required = true) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return mosquitoService.updateFlow1PendingStatus("close", q3, file, remarks, cby, zone, ward, latitude, longitude, sid); + } + + // ************************************************************************************************************************* // + + // For Construction Site & Vacant Land + + @PostMapping(value="/saveSurveyFlow2") + public List saveSurveyFlow2(@RequestParam MultiValueMap formData, + @RequestParam(value = "category", required = true) String cid, + @RequestParam(value = "typeofsite", required = true) String scid, + @RequestParam(value = "name", required = true) String name, + @RequestParam(value = "breedfound", required = true) String q2, + @RequestParam(value = "action", required = false) String q3, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return mosquitoService.saveSurveyFlow2(cid, scid, name, q2, q3, file, remarks, cby, zone, ward, latitude, longitude, "close"); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/package-info.java new file mode 100644 index 0000000..bd7357f --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/package-info.java new file mode 100644 index 0000000..f281e71 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/FoggingService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/FoggingService.java new file mode 100644 index 0000000..64fdf50 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/FoggingService.java @@ -0,0 +1,1404 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class FoggingService { + private JdbcTemplate jdbcMosquitoTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlMosquitoDataSource") DataSource mosquitoDataSource) { + this.jdbcMosquitoTemplate = new JdbcTemplate(mosquitoDataSource); + } + + @Autowired + public FoggingService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("mosquito_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + var date =DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public List> getMaintainByList() { + String sql = "SELECT * FROM `maintained_by` WHERE isactive=1"; + return jdbcMosquitoTemplate.queryForList(sql); + } + + // ************************************************************************************************************************* // + // For Canal Activity + + public List> getCanalsList(String maintainedby, String zone) { + String sql = "SELECT * FROM `canals_list` WHERE `isactive`=1 AND (`maintainedby`=? AND `zone`=?) ORDER BY `name`"; + return jdbcMosquitoTemplate.queryForList(sql,maintainedby,zone ); + } + + @Transactional + public List> saveCanalFlow( + String cid, + String scid, + String maintainedby, + String canalid, + String q4, + String q5, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String filetxt = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload("canal_"+cid+"_"+scid, cby, file); + } + + String finalfile = filetxt; + + String sqlQuery = "INSERT INTO `fogging_of_canal` " + + "(`cid`, `scid`, `maintainedby`, `canalid`, `q4`, `q5`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, maintainedby); + ps.setString(4, canalid); + ps.setString(5, q4); + ps.setString(6, q5); + ps.setString(7, finalfile); + ps.setString(8, remarks); + ps.setString(9, cby); + ps.setString(10, zone); + ps.setString(11, ward); + ps.setString(12, latitude); + ps.setString(13, longitude); + ps.setString(14, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + addCanalActivityData(surveyid,finalfile,"Start Image",cby,zone,ward,latitude,longitude); + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> addCanalActivityData( + String canalactivityid, + String activityfile, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String sqlQuery = "INSERT INTO `fogging_of_canal_data` " + + "(`canalactivityid`, `activityfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`) " + + "VALUES (?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, canalactivityid); + ps.setString(2, activityfile); + ps.setString(3, remarks); + ps.setString(4, cby); + ps.setString(5, zone); + ps.setString(6, ward); + ps.setString(7, latitude); + ps.setString(8, longitude); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New canal data inserted successfully!"); + System.out.println("A new canal data was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new canal data."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + + public List> checkHasCanalPending(String cby) { + + String pending = "true"; + String message = "Pending found"; + + String sql = "SELECT `id` FROM `fogging_of_canal` WHERE (isactive=1 AND `status`='pending') AND `cby`=?"; + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + // Check if result is empty or not + if (result.isEmpty()) { + pending = "false"; + message = "No Pending"; + } + + Map response = new HashMap<>(); + response.put("status", "success"); + response.put("message", message); + response.put("pending", pending); + + return Collections.singletonList(response); + } + + public List> getCanalPendingList(String cby) { + + String sql = "SELECT " + + "foc.`id` AS activityid, " + + "foc.`maintainedby`, " + + "foc.`canalid`, " + + "cl.`name`, " + + "cl.`maintainedby`, " + + "mby.`name`, " + + "mby.`code`, " + + "foc.`remarks`, " + + "foc.`cby`, " + + "DATE_FORMAT(foc.`cdate`, '%d-%m-%Y %r') AS createddate, " + + "foc.`zone`, " + + "foc.`ward`, " + + "foc.`latitude`, " + + "foc.`longitude`, " + + "foc.`status` " + + "FROM `fogging_of_canal` foc " + + "JOIN `canals_list` AS cl ON foc.canalid = cl.id " + + "JOIN `maintained_by` AS mby ON cl.maintainedby = mby.id " + + "WHERE foc.`isactive` = 1 AND foc.`status`='pending' AND foc.cby = ?"; + + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + List> canalData = new ArrayList<>(); + + for (Map row : result) { + + Object activityidObj = row.get("activityid"); + + // Check if the value is an Integer and convert it to String + String activityid = ""; + if (activityidObj instanceof Integer) { + activityid = String.valueOf(activityidObj); // Converts Integer to String + } else if (activityidObj instanceof String) { + activityid = (String) activityidObj; // Already a String, so cast + } + + // Query for the images related to the current activity + String sqlForImage = "SELECT `did`, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', activityfile) AS activityfile, " + + "`remarks`, " + + "DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS createddate, " + + "`zone`, " + + "`ward`, " + + "`latitude`, " + + "`longitude` " + + "FROM `fogging_of_canal_data` WHERE `canalactivityid`=?"; + + List> imageresult = jdbcMosquitoTemplate.queryForList(sqlForImage, activityid); + + + if (!imageresult.isEmpty()) { + row.put("fileData", imageresult); + } + + // Add the row to canalData + canalData.add(row); + } + + // Prepare the response + Map response = new HashMap<>(); + response.put("CanalData", canalData); + response.put("message", "Canal Activity Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + public List> checkCanalPendingUpdateLocation(String canalactivityid, String latitude, String longitude) { + String sql = "SELECT `did`, `canalactivityid`, `cdate`, `latitude`, `longitude` " + + "FROM `fogging_of_canal_data` " + + "WHERE `isactive` = 1 " + + "AND `canalactivityid` = ? " + + "ORDER BY `cdate` DESC " + + "LIMIT 1"; + + // Retrieve the most recent row based on cdate + List> result = jdbcMosquitoTemplate.queryForList(sql, canalactivityid); + + // If result is empty, return early + if (result.isEmpty()) { + Map response = new HashMap<>(); + response.put("status", false); + response.put("distance", 0); + return Collections.singletonList(response); + } + + // Extract latitude and longitude from the result + Map lastRow = result.get(0); + String latitudedataStr = (String) lastRow.get("latitude"); + String longitudedataStr = (String) lastRow.get("longitude"); + + // Convert the String latitude and longitude to Double + Double latitudedata = Double.parseDouble(latitudedataStr); + Double longitudedata = Double.parseDouble(longitudedataStr); + + // Convert input latitude and longitude from String to Double + double inputLatitude = Double.parseDouble(latitude); + double inputLongitude = Double.parseDouble(longitude); + + // Fixed coordinates (for comparison) + double fixedLatitude = inputLatitude; + double fixedLongitude = inputLongitude; + + // Haversine formula to calculate distance + double radius = 6371008.8; // Earth's radius in meters + double latDistance = Math.toRadians(latitudedata - fixedLatitude); + double lonDistance = Math.toRadians(longitudedata - fixedLongitude); + double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + + Math.cos(Math.toRadians(fixedLatitude)) * Math.cos(Math.toRadians(latitudedata)) * + Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); + double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + double distance = radius * c; // Distance in meters + + // Check if distance is between 30 and 50 meters + //boolean isWithinRange = (distance >= 30 && distance <= 50); + + // Check if distance above 30 meters + boolean isWithinRange = (distance > 30); + + // Response based on whether the distance is within the range + Map response = new HashMap<>(); + response.put("status", isWithinRange); + response.put("distance", distance); + + return Collections.singletonList(response); + } + + @Transactional + public List> saveCanalActivityData( + String canalactivityid, + String isfinal, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String filetxt = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload(canalactivityid, cby, file); + } + String activityfile = filetxt; + + String sqlQuery = "INSERT INTO `fogging_of_canal_data` " + + "(`canalactivityid`, `activityfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`) " + + "VALUES (?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, canalactivityid); + ps.setString(2, activityfile); + ps.setString(3, remarks); + ps.setString(4, cby); + ps.setString(5, zone); + ps.setString(6, ward); + ps.setString(7, latitude); + ps.setString(8, longitude); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New canal data inserted successfully!"); + System.out.println("A new canal data was inserted successfully! Insert ID: " + generatedId); + + if(isfinal.equals("yes")){ + if(updateCanalActivityStatus(canalactivityid)) { + System.out.println("Canal final status updated successfully!. Activity ID: " + canalactivityid); + }else { + System.out.println("Canal final status update failed!. Activity ID: " + canalactivityid); + } + } + + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new canal data."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public Boolean updateCanalActivityStatus(String id) { + + String sqlQuery = "UPDATE `fogging_of_canal` SET `status`='close' WHERE `id`=?"; + int rowsAffected = jdbcMosquitoTemplate.update(sqlQuery, new Object[]{ id }); + + return rowsAffected>0; + } + + // ************************************************************************************************************************* // + // For SWD Activity + + @Transactional + public List> saveSWDFlow( + String cid, + String scid, + String streetname, + String streetid, + String q2, + String q4, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String filetxt = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload("SWD_"+cid+"_"+scid, cby, file); + } + + String finalfile = filetxt; + + String sqlQuery = "INSERT INTO `fogging_of_swd` " + + "(`cid`, `scid`, `streetname`, `streetid`, `q2`, `q4`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, streetname); + ps.setString(4, streetid); + ps.setString(5, q2); + ps.setString(6, q4); + ps.setString(7, finalfile); + ps.setString(8, remarks); + ps.setString(9, cby); + ps.setString(10, zone); + ps.setString(11, ward); + ps.setString(12, latitude); + ps.setString(13, longitude); + ps.setString(14, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + //addSWDActivityData(surveyid,finalfile,streetname,streetid,q2,q4,remarks,cby,zone,ward,latitude,longitude,"close"); + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> addSWDActivityData( + String swdactivityid, + String activityfile, + String streetname, + String streetid, + String q2, + String q4, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String sqlQuery = "INSERT INTO `fogging_of_swd_data` " + + "(`swdactivityid`, `activityfile`, `streetname`, `streetid`, `q2`, `q4`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`,`status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "did" }); + ps.setString(1, swdactivityid); + ps.setString(2, activityfile); + ps.setString(3, streetname); + ps.setString(4, streetid); + ps.setString(5, q2); + ps.setString(6, q4); + ps.setString(7, remarks); + ps.setString(8, cby); + ps.setString(9, zone); + ps.setString(10, ward); + ps.setString(11, latitude); + ps.setString(12, longitude); + ps.setString(13, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New SWD data inserted successfully!"); + System.out.println("A new SWD data was inserted successfully! Insert ID: " + generatedId); + + addSWDExtraActivityData(2,swdactivityid,"","","","","","",cby,zone,ward,"","","pending"); + + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new SWD data."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> addSWDExtraActivityData( + int totaltaskrequired, + String swdactivityid, + String activityfile, + String streetname, + String streetid, + String q2, + String q4, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String sqlQuery = "INSERT INTO `fogging_of_swd_data` " + + "(`swdactivityid`, `activityfile`, `streetname`, `streetid`, `q2`, `q4`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`,`status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + + // Insert the data the required number of times + for (int i = 0; i < totaltaskrequired; i++) { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "did" }); + ps.setString(1, swdactivityid); + ps.setString(2, activityfile); + ps.setString(3, streetname); + ps.setString(4, streetid); + ps.setString(5, q2); + ps.setString(6, q4); + ps.setString(7, remarks); + ps.setString(8, cby); + ps.setString(9, zone); + ps.setString(10, ward); + ps.setString(11, latitude); + ps.setString(12, longitude); + ps.setString(13, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New SWD data inserted successfully!"); + System.out.println("A new SWD data was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new SWD data."); + } + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public List> checkHasSWDPending(String cby) { + + String pending = "true"; + String message = "Pending found"; + + String sql = "SELECT `id` FROM `fogging_of_swd` WHERE (isactive=1 AND `status`='pending') AND `cby`=?"; + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + // Check if result is empty or not + if (result.isEmpty()) { + pending = "false"; + message = "No Pending"; + } + + pending = "false"; + message = "No Pending"; + + Map response = new HashMap<>(); + response.put("status", "success"); + response.put("message", message); + response.put("pending", pending); + + return Collections.singletonList(response); + } + + public List> getSWDPendingList(String cby) { + + String sql = "SELECT " + + "swd.`id` AS activityid, " + + "swd.`streetname`, " + + "swd.`streetid`, " + + "swd.`cby`, " + //+ "DATE_FORMAT(foc.`cdate`, '%d-%m-%Y %r') AS createddate, " + + "swd.`zone`, " + + "swd.`ward`, " + + "swd.`latitude`, " + + "swd.`longitude`, " + + "swd.`status` " + + "FROM `fogging_of_swd` swd " + + "WHERE swd.`isactive` = 1 AND swd.`status`='pending' AND swd.cby = ?"; + + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + List> SWDData = new ArrayList<>(); + + for (Map row : result) { + + Object activityidObj = row.get("activityid"); + + // Check if the value is an Integer and convert it to String + String activityid = ""; + if (activityidObj instanceof Integer) { + activityid = String.valueOf(activityidObj); // Converts Integer to String + } else if (activityidObj instanceof String) { + activityid = (String) activityidObj; // Already a String, so cast + } + + // Query for the task related to the current activity + String sqlForTask = "SELECT `did`, `swdactivityid`, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', activityfile) AS activityfile, " + + "`streetname`, " + + "`streetid`, " + + "`q2`, " + + "`q4`, " + + "`remarks`, " + + "DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS createddate, " + + "`zone`, " + + "`ward`, " + + "`latitude`, " + + "`longitude`, " + + "`status` " + + "FROM `fogging_of_swd_data` WHERE `swdactivityid`=?"; + + List> taskresult = jdbcMosquitoTemplate.queryForList(sqlForTask, activityid); + + + if (!taskresult.isEmpty()) { + row.put("tasklist", taskresult); + } + + // Add the row to SWDData + SWDData.add(row); + } + + // Prepare the response + Map response = new HashMap<>(); + response.put("SWDData", SWDData); + response.put("message", "SWD Activity Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + public List> checkSWDPendingUpdateLocation(String swdactivityid, String streetid) { + String sql = "SELECT `did`, `swdactivityid` " + + "FROM `fogging_of_swd_data` " + + "WHERE `isactive` = 1 " + + "AND `swdactivityid` = ? AND `streetid`=? " + + "ORDER BY `cdate` DESC " + + "LIMIT 1"; + + // Retrieve the most recent row based on cdate + List> result = jdbcMosquitoTemplate.queryForList(sql, swdactivityid, streetid); + + Map response = new HashMap<>(); + // If result is empty, return early + if (result.isEmpty()) { + response.put("status", true); + } + else { + response.put("status", false); + } + return Collections.singletonList(response); + } + + public List> updateSWDPendingStatus( + String swdactivityid, + MultipartFile file, + String streetname, + String streetid, + String q2, + String q4, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status, + String did + ) { + + // Create a response map + Map response = new HashMap<>(); + + if(!checkupdateSWDPendingStreetid(streetid,swdactivityid)) { + // Wrap the response in a list as required + response.put("status", false); + return Collections.singletonList(response); + } + + String filetxt =""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload("SWD_"+"_"+did+"_"+swdactivityid, cby, file); + } + + String finalactivityfile = filetxt; + + LocalDateTime updateDate = LocalDateTime.now(); + + String formattedDate = updateDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sqlQuery = "UPDATE `fogging_of_swd_data` SET " + + "`activityfile`=?,`streetname`=?,`streetid`=?,`q2`=?,`q4`=?,`remarks`=?," + + "`cdate`=?,`latitude`=?,`longitude`=?,`status`=?" + + "WHERE `did`=? AND `swdactivityid`=? AND `zone`=? AND `ward`=? AND cby=?"; + + // Execute the update query + int rowsAffected = jdbcMosquitoTemplate.update(sqlQuery, new Object[]{ + finalactivityfile, streetname, streetid, q2, q4, remarks, formattedDate, latitude, longitude, status, + did, swdactivityid, zone, ward, cby + }); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + if(updateSWDStatus(swdactivityid)) { + System.out.println("SWD PARENT Status Updated from `pending` -> `close` (swdactivityid (id):"+ swdactivityid + ")"); + } + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + public boolean checkupdateSWDPendingStreetid(String swdactivityid,String streetid) { + String sql = "SELECT `did` FROM `fogging_of_swd_data` WHERE (`isactive`=1 AND `streetid`=?) AND `swdactivityid`=?"; + List> result = jdbcMosquitoTemplate.queryForList(sql, streetid, swdactivityid); + return result.isEmpty(); + } + + public boolean updateSWDStatus(String swdactivityid) { + String sql = "SELECT `did` FROM `fogging_of_swd_data` WHERE (`isactive`=1 AND `status`='pending') AND `swdactivityid`=?"; + List> result = jdbcMosquitoTemplate.queryForList(sql, swdactivityid); + + int rowsAffected = 0; + // Check if result is empty or not + if (result.isEmpty()) { + String sqlQuery = "UPDATE `fogging_of_swd` SET `status`=? WHERE `id`=?"; + rowsAffected = jdbcMosquitoTemplate.update(sqlQuery, new Object[]{"close",swdactivityid}); + } + return rowsAffected > 0; + } + + @Transactional + public List> saveStreetData( + String cid, + String scid, + String streetid, + String streetname, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String treatedfile = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + treatedfile = fileUpload(cid+"_"+scid, cby, file); + } + + String finaltreatedfile = treatedfile; + + String sqlQuery = "INSERT INTO `fogging_of_street_data` " + + "(`cid`, `scid`, `streetid`, `streetname`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, streetid); + ps.setString(4,streetname); + ps.setString(5, finaltreatedfile); + ps.setString(6, remarks); + ps.setString(7, cby); + ps.setString(8, zone); + ps.setString(9, ward); + ps.setString(10, latitude); + ps.setString(11, longitude); + ps.setString(12, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> saveVacantLandData( + String cid, + String scid, + String name, + String q2, + String q3, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String treatedfile = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + treatedfile = fileUpload(cid+"_"+scid, cby, file); + } + + String finaltreatedfile = treatedfile; + + String sqlQuery = "INSERT INTO `fogging_of_vacantland_data` " + + "(`cid`, `scid`, `name`, `q2`, `q3`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, name); + ps.setString(4, q2); + ps.setString(5, q3); + ps.setString(6, finaltreatedfile); + ps.setString(7, remarks); + ps.setString(8, cby); + ps.setString(9, zone); + ps.setString(10, ward); + ps.setString(11, latitude); + ps.setString(12, longitude); + ps.setString(13, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + + // SAMPLE COLLECTION + + @Transactional + public List> saveLarvalAdultCollectionFlow( + String cid, + String maintainedby, + String canalid, + String q2, + String q6, + String q7, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String filetxt = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload("lavasample_"+cid+"_"+canalid, cby, file); + } + + String finalfile = filetxt; + + String sqlQuery = "INSERT INTO `larval_adult_collection_data` " + + "(`cid`, `maintainedby`, `canalid`, `q2`, `q6`, `q7`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, maintainedby); + ps.setString(3, canalid); + ps.setString(4, q2); + ps.setString(5, q6); + ps.setString(6, q7); + ps.setString(7, finalfile); + ps.setString(8, remarks); + ps.setString(9, cby); + ps.setString(10, zone); + ps.setString(11, ward); + ps.setString(12, latitude); + ps.setString(13, longitude); + ps.setString(14, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + // Reports + /* + public List> summaryReport(String cby) { + + String sql = ""; + + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + List> reportData = new ArrayList<>(); + + row.put("tasklist", taskresult); + // Add the row to SWDData + reportData.add(row); + + // Prepare the response + Map response = new HashMap<>(); + response.put("ReportData", reportData); + response.put("message", "Summary Data."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + */ +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/MosquitoService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/MosquitoService.java new file mode 100644 index 0000000..91308e1 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/MosquitoService.java @@ -0,0 +1,570 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class MosquitoService { + private JdbcTemplate jdbcMosquitoTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlMosquitoDataSource") DataSource mosquitoDataSource) { + this.jdbcMosquitoTemplate = new JdbcTemplate(mosquitoDataSource); + } + + @Autowired + public MosquitoService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("mosquito_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + var date =DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, compressedBytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public List> getCategoryList() { + String sql = "SELECT * FROM `category` WHERE isactive=1 ORDER BY `orderby`"; + return jdbcMosquitoTemplate.queryForList(sql); + } + + public List> getSubCategoryList(String cid) { + String sql = "SELECT * FROM `subcategory` WHERE `cid`=? AND isactive=1 ORDER BY `orderby`"; + return jdbcMosquitoTemplate.queryForList(sql, cid); + } + + public List> getTreatmentList() { + String sql = "SELECT * FROM `treatment` WHERE isactive=1 ORDER BY `orderby`"; + return jdbcMosquitoTemplate.queryForList(sql); + } + + public List> getBreadingSourceCategoryList() { + String sql = "SELECT * FROM `breadingsource_category` WHERE isactive=1 ORDER BY `orderby`"; + return jdbcMosquitoTemplate.queryForList(sql); + } + + public List> getBreadingSourceList() { + String sql = "SELECT * FROM `breadingsource` WHERE isactive=1 ORDER BY `orderby`"; + return jdbcMosquitoTemplate.queryForList(sql); + } + + // ************************************************************************************************************************* // + // For House, Companies & Education Institution + + @Transactional + public List> saveSurveyFlow1( + String cid, + String scid, + String q1, + String treatment, + String q2, + String sourcetype, + String cby, + String name, + String zone, + String ward, + String latitude, + String longitude, + String visitstatus) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; +/* + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload("Created", cby, file); + } + + String storeIMG = image; +*/ + String sqlQuery = "INSERT INTO `survey_of_house`" + + "(`cid`, `scid`, `q1`, `treatment`, `q2`, `sourcetype`, `cby`, " + + "`name`, `zone`, `ward`, `latitude`, `longitude`,`visitstatus`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, q1); + ps.setString(4, treatment); + ps.setString(5, q2); + ps.setString(6, sourcetype); + ps.setString(7, cby); + ps.setString(8, name); + ps.setString(9, zone); + ps.setString(10, ward); + ps.setString(11, latitude); + ps.setString(12, longitude); + ps.setString(13, visitstatus); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + // Split the sourcetype string by comma + String[] sourcetypeArray = sourcetype.split(","); + + // Loop through the array and process each value + for (String type : sourcetypeArray) { + System.out.println("Sourcetype: " + type); + createSurveyPending(surveyid, type, "pending",cby); + } + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New House Survey inserted successfully!"); + System.out.println("A new House Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> createSurveyPending( + String surveyid, + String sourceid, + String status, + String cby) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String sqlQuery = "INSERT INTO `survey_of_house_data`" + + "(`surveyid`, `sourceid`, `status`, `q3`, `treatedfile`, `remarks`, `cby`, " + + "`zone`, `ward`, `latitude`, `longitude`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String q3 = ""; + String treatedfile = ""; + String remarks = ""; + + String zone = ""; + String ward = ""; + String latitude = ""; + String longitude = ""; + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "sid" }); + ps.setString(1, surveyid); + ps.setString(2, sourceid); + ps.setString(3, status); + ps.setString(4, q3); + ps.setString(5, treatedfile); + ps.setString(6, remarks); + ps.setString(7, cby); + ps.setString(8, zone); + ps.setString(9, ward); + ps.setString(10, latitude); + ps.setString(11, longitude); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New House Survey inserted successfully!"); + System.out.println("A new House Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public List> checkHasPending(String cby) { + + String pending = "true"; + + String sql = "SELECT `sid` FROM `survey_of_house_data` WHERE (isactive=1 AND `status`='pending') AND `cby`=?"; + List> result = jdbcMosquitoTemplate.queryForList(sql, cby); + + // Check if result is empty or not + if (result.isEmpty()) { + pending = "false"; // If no rows are found, set pending to "true" + } + + Map response = new HashMap<>(); + response.put("status", "success"); + response.put("message", "Pending found"); + response.put("pending", pending); + + return Collections.singletonList(response); + } + + public List> getHousePendingList(String cby) { + + String sql = "SELECT shd.sid, sh.id, sh.name, bs.name AS sourcetype, sc.name AS sitetype, " + + "sh.zone, sh.ward, sh.latitude, sh.longitude, " + + "bsc.actiontype AS actionrequired, " + + "DATE_FORMAT(sh.`cdate`, '%d-%m-%Y %r') AS createddate " + + "FROM survey_of_house_data AS shd " + + "JOIN survey_of_house AS sh ON shd.surveyid = sh.id " + + "JOIN breadingsource AS bs ON shd.sourceid = bs.sid " + + "JOIN breadingsource_category AS bsc ON bs.scid = bsc.scid " + + "JOIN subcategory AS sc ON sc.scid = sh.scid " + + "WHERE shd.isactive = 1 AND shd.status='pending' AND sh.cby = ?"; + + return jdbcMosquitoTemplate.queryForList(sql, cby); + } + + public List> checkPendingUpdateLocation(String id, String latitude, String longitude) { + + String sql = "SELECT `id` FROM `survey_of_house` WHERE " + + "`isactive` = 1 AND `id` = ? " + + "AND ((6371008.8 * acos(ROUND(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)), 9))) < 50) " + + ""; + List> result = jdbcMosquitoTemplate.queryForList(sql, new Object[]{id, latitude, longitude, latitude}); + + Map response = new HashMap<>(); + response.put("status", !result.isEmpty()); + + return Collections.singletonList(response); + } + + public List> updateFlow1PendingStatus( + String status, String q3, + MultipartFile file, String remarks, + String cby, String zone, String ward, + String latitude, String longitude, + String sid + ) { + + String treatedfile =""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + treatedfile = fileUpload(sid, cby, file); + } + + String finaltreatedfile = treatedfile; + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + String sqlQuery = "UPDATE `survey_of_house_data` SET " + + "`status`=?, `q3`=?, `treatedfile`=?, `remarks`=?, `cby`=?, " + + "`zone`=?, `ward`=?, `latitude`=?, `longitude`=? ,`updatedate`=? " + + "WHERE `sid`=?"; + + // Execute the update query + int rowsAffected = jdbcMosquitoTemplate.update(sqlQuery, new Object[]{ + status, q3, finaltreatedfile, remarks, cby, zone, ward, latitude, longitude,formattedDate, sid + }); + + // Create a response map + Map response = new HashMap<>(); + + // If rows are affected, it means the update was successful + response.put("status", rowsAffected > 0); + + // Wrap the response in a list as required + return Collections.singletonList(response); + } + + // ************************************************************************************************************************* // + + // For Construction Site & Vacant Land + + @Transactional + public List> saveSurveyFlow2( + String cid, + String scid, + String name, + String q2, + String q3, + MultipartFile file, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String treatedfile = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + treatedfile = fileUpload(cid+"_"+scid, cby, file); + } + + String finaltreatedfile = treatedfile; + + String sqlQuery = "INSERT INTO `survey_of_construction_land_data` " + + "(`cid`, `scid`, `name`, `q2`, `q3`, `treatedfile`, " + + "`remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `status`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + int affectedRows = jdbcMosquitoTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, cid); + ps.setString(2, scid); + ps.setString(3, name); + ps.setString(4, q2); + ps.setString(5, q3); + ps.setString(6, finaltreatedfile); + ps.setString(7, remarks); + ps.setString(8, cby); + ps.setString(9, zone); + ps.setString(10, ward); + ps.setString(11, latitude); + ps.setString(12, longitude); + ps.setString(13, status); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String surveyid = lastInsertId+""; + + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Survey inserted successfully!"); + System.out.println("A new Survey was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new House Survey."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/package-info.java new file mode 100644 index 0000000..88729f7 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/mosquitosurvey/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.mosquitosurvey.service; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java index fc13cad..b9c09ca 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java @@ -439,15 +439,17 @@ public class CattleCatchService { String noofdays = noOfDayObject.toString(); // Assuming noOfDayObject is your object containing the days int days = Integer.parseInt(noofdays); // Convert String to integer - int amount = 5000; + + int baseAmount = 10000; + int extraChargePerDay = 1000; int extraDays = 0; int finalAmount; if (days <= 2) { - finalAmount = amount; // No extra charge + finalAmount = baseAmount; // No extra charge } else { extraDays = days - 2; // Calculate extra days - finalAmount = amount + (extraDays * 1000); // Add extra charges + finalAmount = baseAmount + (extraDays * extraChargePerDay); // Add extra charges } System.out.println("Final Amount: " + finalAmount); @@ -877,7 +879,7 @@ public class CattleCatchService { updatePaymentStatus(txnId, transactionResponseStatus); - // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` /* String sqlQuery_joined = "SELECT pc.category_id, CONCAT('" + fileBaseUrl + "/gccofficialapp/files', pc.image) as imageurl, " + "pc.latitude, pc.longitude, pc.zone, pc.ward, pc.challan_by, " @@ -976,7 +978,7 @@ public class CattleCatchService { + "`violator_phone`, `fine_amount`, `orderid`, `depotid`, " + "LENGTH(cinfoids) - LENGTH(REPLACE(cinfoids, ',', '')) + 1 AS cattlecount, " + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl " - + " From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND (`status`<> 'unpaid' AND `status`<> 'out')"; + + " From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND (`status`='Transaction success')"; if(loginid!=null && !loginid.isEmpty() && !loginid.isBlank()) { sqlQuery= sqlQuery +" AND `challan_by`='"+loginid+"'"; @@ -1158,6 +1160,7 @@ public class CattleCatchService { + " JOIN `cc_step4` s4 ON s3.`id` = s4.`cinfoid` " + " WHERE (s2.`isactive` = 1 AND s2.`isdelete` = 0) " + " AND (s2.`depotid` = ?) " + + " AND (s4.`isactive` = 1 AND s4.`isdelete` = 0) " + " AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + " " + ") temp"; @@ -1187,7 +1190,7 @@ public class CattleCatchService { return Collections.singletonList(response); } - + /* @Transactional public List> zoneReport( MultiValueMap formData, @@ -1225,12 +1228,7 @@ public class CattleCatchService { + "AND (s1.id=s2.cinfoid AND s1.zone=?) " + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y')"; List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total, depotid, zone, fromDate, toDate); -/* - // Fetch total paid count for this depot - String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3 " + - "WHERE (`isactive`=1 AND `isdelete`=0) AND (s3.`depotid`=? AND s3.`status`<>'unpaid') AND `zone`=?"; - List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_paid, depotid,zone); -*/ + // Fetch total out count for this depot String sqlQuery_out = "SELECT IFNULL(SUM(unique_cattle_count), 0) AS cattlecount " + "FROM ( SELECT COUNT(DISTINCT s1.id) AS unique_cattle_count " @@ -1242,13 +1240,7 @@ public class CattleCatchService { List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_out, depotid,zone,fromDate,toDate); System.out.println(sqlQuery_out); - /* - - // Fetch total paid count for this depot - String sqlQuery_pending = "SELECT count(s2.id) as TotalPending FROM `cc_step2` s2 " + - "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) AND (s2.`depotid`=? AND s2.`status`='in')"; - List> resultPending = jdbcPenaltyTemplate.queryForList(sqlQuery_pending, depotid); -*/ + // Add counts to the current depot details Map detailedDepot = new HashMap<>(depot); detailedDepot.put("Total", resultTotal.isEmpty() ? 0 : resultTotal.get(0).get("Total")); @@ -1268,7 +1260,99 @@ public class CattleCatchService { return Collections.singletonList(response); } + */ + + @Transactional + public List> zoneReport( + MultiValueMap formData, + String fromDate, + String toDate, + String depotid, + String loginid) { + + String sqlQuery = "SELECT zone, SUM(TotalIn) AS Total, SUM(TotalOut) AS TotalOut FROM ( " + + "SELECT s1.zone, COUNT(DISTINCT s2.id) AS TotalIn, 0 AS TotalOut " + + "FROM cc_step1 s1 " + + "JOIN cc_step2 s2 ON s1.id = s2.cinfoid " + + "WHERE s1.isactive = 1 AND s1.isdelete = 0 AND s2.isactive = 1 AND s2.isdelete = 0 " + + "AND s2.depotid = ? " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.zone " + + + "UNION ALL " + + + "SELECT s1.zone, 0 AS TotalIn, COUNT(DISTINCT s1.id) AS TotalOut " + + "FROM cc_step1 s1 " + + "JOIN cc_step3 s3 ON FIND_IN_SET(s1.id, s3.cinfoids) " + + "JOIN cc_step4 s4 ON s3.id = s4.cinfoid " + + "WHERE s1.isactive = 1 AND s1.isdelete = 0 AND s3.depotid = ? " + + "AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.zone " + + ") AS combined " + + "GROUP BY zone " + + "HAVING Total > 0 OR TotalOut > 0"; + + List> detailedResult = jdbcPenaltyTemplate.queryForList( + sqlQuery, + depotid, fromDate, toDate, // For IN part + depotid, fromDate, toDate // For OUT part + ); + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Zone List Details"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + + @Transactional + public List> wardReport( + MultiValueMap formData, + String fromDate, + String toDate, + String zone, + String depotid, + String loginid) { + + String sqlQuery = "SELECT zone, ward, SUM(TotalIn) AS Total, SUM(TotalOut) AS TotalOut FROM ( " + + "SELECT s1.zone, s1.ward, COUNT(DISTINCT s2.id) AS TotalIn, 0 AS TotalOut " + + "FROM cc_step1 s1 " + + "JOIN cc_step2 s2 ON s1.id = s2.cinfoid " + + "WHERE s1.zone=? AND s1.isactive = 1 AND s1.isdelete = 0 AND s2.isactive = 1 AND s2.isdelete = 0 " + + "AND s2.depotid = ? " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.zone, s1.ward " + + + "UNION ALL " + + + "SELECT s1.zone, s1.ward, 0 AS TotalIn, COUNT(DISTINCT s1.id) AS TotalOut " + + "FROM cc_step1 s1 " + + "JOIN cc_step3 s3 ON FIND_IN_SET(s1.id, s3.cinfoids) " + + "JOIN cc_step4 s4 ON s3.id = s4.cinfoid " + + "WHERE s1.zone=? AND s1.isactive = 1 AND s1.isdelete = 0 AND s3.depotid = ? " + + "AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.zone, s1.ward " + + ") AS combined " + + "GROUP BY zone, ward " + + "HAVING Total > 0 OR TotalOut > 0"; + + List> detailedResult = jdbcPenaltyTemplate.queryForList( + sqlQuery, + zone, depotid, fromDate, toDate, // For IN + zone, depotid, fromDate, toDate // For OUT + ); + + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Zone-Ward Wise Report"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + /* @Transactional public List> wardReport( MultiValueMap formData, @@ -1311,12 +1395,7 @@ public class CattleCatchService { + "AND (s1.id=s2.cinfoid AND s1.zone=? AND s1.ward=?) " + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y')"; List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total, depotid, zone, ward,fromDate, toDate); -/* - // Fetch total paid count for this depot - String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3 " + - "WHERE (`isactive`=1 AND `isdelete`=0) AND (s3.`depotid`=? AND s3.`status`<>'unpaid') AND `zone`=?"; - List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_paid, depotid,zone); -*/ + // Fetch total out count for this depot String sqlQuery_out = "SELECT IFNULL(SUM(unique_cattle_count), 0) AS cattlecount " + "FROM ( SELECT COUNT(DISTINCT s1.id) AS unique_cattle_count " @@ -1329,13 +1408,7 @@ public class CattleCatchService { List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_out, depotid,zone,ward,fromDate,toDate); System.out.println(sqlQuery_out); - /* - - // Fetch total paid count for this depot - String sqlQuery_pending = "SELECT count(s2.id) as TotalPending FROM `cc_step2` s2 " + - "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) AND (s2.`depotid`=? AND s2.`status`='in')"; - List> resultPending = jdbcPenaltyTemplate.queryForList(sqlQuery_pending, depotid); -*/ + // Add counts to the current depot details Map detailedDepot = new HashMap<>(depot); detailedDepot.put("Total", resultTotal.isEmpty() ? 0 : resultTotal.get(0).get("Total")); @@ -1355,7 +1428,7 @@ public class CattleCatchService { return Collections.singletonList(response); } - + */ @Transactional public List> inListReport( MultiValueMap formData, @@ -1427,6 +1500,8 @@ public class CattleCatchService { + " AND s1.zone = ? " + " AND s1.ward = ? " + " AND s3.depotid = ? " + + " AND s4.isactive = 1 " + + " AND s4.isdelete = 0 " + " AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') " + " AND STR_TO_DATE(?, '%d-%m-%Y')"; @@ -1441,7 +1516,7 @@ public class CattleCatchService { int days = (noOfDayObject != null) ? Integer.parseInt(noOfDayObject.toString()) : 0; - int baseAmount = 5000; + int baseAmount = 10000; int extraChargePerDay = 1000; int fineAmount = days <= 2 ? baseAmount : baseAmount + ((days - 2) * extraChargePerDay); diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java index 621a165..f068f03 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java @@ -42,11 +42,24 @@ public class APIController { return activity.getToiletsListWithButton(cby); } - @GetMapping(value="/getQuestionsList") + @GetMapping(value="/getQuestionsList") // Old App public List getQuestionsList(@RequestParam(value="loginId", required = false) String cby){ return activity.getQuestionsList(); } + @GetMapping(value="/getParentQuestionsList") + public List getParentQuestionsList(@RequestParam(value="loginId", required = false) String cby){ + return activity.getParentQuestionsList(); + } + + @GetMapping(value="/getChildQuestionsList") + public List getChildQuestionsList( + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value="pid", required = true) String pid + ){ + return activity.getChildQuestionsList(pid); + } + @PostMapping(value="/addNewToilet") public List addNewToilet( @RequestParam(value="latitude", required = true) String latitude, @@ -90,11 +103,23 @@ public class APIController { @RequestParam(value="q_10", required = false) String q_10, @RequestParam(value="q_11", required = false) String q_11, @RequestParam(value="remarks", required = false) String remarks, - @RequestParam(value = "file", required = true) MultipartFile filedata + @RequestParam(value = "file", required = true) MultipartFile filedata, + + @RequestParam(value="file_1", required = false) MultipartFile file_1, + @RequestParam(value="file_2", required = false) MultipartFile file_2, + @RequestParam(value="file_3", required = false) MultipartFile file_3, + @RequestParam(value="file_4", required = false) MultipartFile file_4, + @RequestParam(value="file_5", required = false) MultipartFile file_5, + @RequestParam(value="file_6", required = false) MultipartFile file_6, + @RequestParam(value="file_7", required = false) MultipartFile file_7, + @RequestParam(value="file_8", required = false) MultipartFile file_8, + @RequestParam(value="file_9", required = false) MultipartFile file_9, + @RequestParam(value="file_10", required = false) MultipartFile file_10, + @RequestParam(value="file_11", required = false) MultipartFile file_11 ){ return activity.saveFeedback(toilet_id, cby, latitude, longitude, zone, ward, - q_1, q_2, q_3, q_4, q_5, q_6, q_7, q_8, q_9, q_10, q_11, - remarks, filedata); + q_1, q_2, q_3, q_4, q_5, q_6, q_7, q_8, q_9, q_10, q_11, remarks, filedata, + file_1, file_2, file_3, file_4, file_5, file_6, file_7, file_8, file_9, file_10, file_11); } @GetMapping(value="/zoneReport") diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java index 68513c6..efe0846 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java @@ -11,7 +11,9 @@ import java.security.SecureRandom; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.time.LocalDate; import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -67,6 +69,14 @@ public class activity { } return result.toString(); } + + public static String generateRandomFileString(int lenthval) { + StringBuilder result = new StringBuilder(lenthval); + for (int i = 0; i < lenthval; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } private byte[] compressImage(BufferedImage image, float quality) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); @@ -97,8 +107,9 @@ public class activity { String serviceFolderName = environment.getProperty("toilets_foldername"); var year = DateTimeUtil.getCurrentYear(); var month = DateTimeUtil.getCurrentMonth(); + var date = DateTimeUtil.getCurrentDay(); - uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + month; + uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + month + "/" + date; try { // Create directory if it doesn't exist @@ -109,13 +120,16 @@ public class activity { // Datetime string String datetimetxt = DateTimeUtil.getCurrentDateTime(); + + datetimetxt = datetimetxt + "_"+ generateRandomFileString(6); // Attached Random text + // File name String fileName = name + "_" + id + "_" + datetimetxt + "_" + file.getOriginalFilename(); fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename String filePath = uploadDirectory + "/" + fileName; - String filepath_txt = "/" + serviceFolderName + year + "/" + month + "/" + fileName; + String filepath_txt = "/" + serviceFolderName + year + "/" + month + "/" + date + "/" + fileName; // Create a new Path object Path path = Paths.get(filePath); @@ -193,28 +207,7 @@ public class activity { } public List> getToiletsListWithButton(String loginid) { - /* - String sql = "SELECT " - + " `gcc_toilet_list`.*, " - + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `gcc_toilet_list`.`image`) AS photo, " - + " CASE " - + " WHEN `toilet_feedback`.`type` = 'morning' THEN true " - + " ELSE false " - + " END AS morning_feedback, " - + " CASE " - + " WHEN `toilet_feedback`.`type` = 'evening' THEN true " - + " ELSE false " - + " END AS evening_feedback " - + "FROM " - + " `gcc_toilet_list` " - + "LEFT JOIN " - + " `toilet_feedback` " - + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " - + " AND DATE(`toilet_feedback`.`cdate`) = CURDATE() " - + "WHERE " - + " `gcc_toilet_list`.`user_id` = ? " - + " AND `gcc_toilet_list`.`isactive` = 1"; - */ + String sql ="SELECT " + " `gcc_toilet_list`.*, " + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', " @@ -231,6 +224,7 @@ public class activity { + "LEFT JOIN " + " `toilet_feedback` " + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`isactive` = 1 " + " AND DATE(`toilet_feedback`.`cdate`) = CURDATE() " + "WHERE " + " `gcc_toilet_list`.`user_id` = ? " @@ -255,6 +249,28 @@ public class activity { response.put("message", "Toilet Question List."); response.put("data", result); + return Collections.singletonList(response); + } + + public List> getParentQuestionsList() { + String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=0"; + List> result = jdbcToiletsTemplate.queryForList(sql); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Toilet Parent Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getChildQuestionsList(String pid) { + String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?"; + List> result = jdbcToiletsTemplate.queryForList(sql,pid); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Toilet Child Question List."); + response.put("data", result); + return Collections.singletonList(response); } @@ -376,6 +392,14 @@ public class activity { return Collections.singletonList(response); } + public String inactiveFeedBack(String type, String toilet_id) { + + String sql = "UPDATE `toilet_feedback` SET `isactive`=0 WHERE DATE(`toilet_feedback`.`cdate`) = CURDATE() AND `type`= ? AND `toilet_id`=?"; + jdbcToiletsTemplate.update(sql,type,toilet_id); + + return "sussess"; + } + @Transactional public List> saveFeedback( String toilet_id, @@ -396,28 +420,122 @@ public class activity { String q_10, String q_11, String remarks, - MultipartFile file) { + MultipartFile file, + + MultipartFile file_1, + MultipartFile file_2, + MultipartFile file_3, + MultipartFile file_4, + MultipartFile file_5, + MultipartFile file_6, + MultipartFile file_7, + MultipartFile file_8, + MultipartFile file_9, + MultipartFile file_10, + MultipartFile file_11) { List> result = null; Map response = new HashMap<>(); int lastInsertId = 0; String image = ""; + String image_q1 = ""; + String image_q2 = ""; + String image_q3 = ""; + String image_q4 = ""; + String image_q5 = ""; + String image_q6 = ""; + String image_q7 = ""; + String image_q8 = ""; + String image_q9 = ""; + String image_q10 = ""; + String image_q11 = ""; + + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); // Handle file upload if a file is provided if (file != null && !file.isEmpty()) { - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - image = fileUpload(year, month, file); + image = fileUpload("feedback", "0", file); + } + + // Question Images + if (file_1 != null && !file_1.isEmpty()) { + image_q1 = fileUpload("1", "q1", file_1); + } + + if (file_2 != null && !file_2.isEmpty()) { + image_q2 = fileUpload("2", "q2", file_2); + } + + if (file_3 != null && !file_3.isEmpty()) { + image_q3 = fileUpload("3", "q3", file_3); + } + + if (file_4 != null && !file_4.isEmpty()) { + image_q4 = fileUpload("4", "q4", file_4); + } + + if (file_5 != null && !file_5.isEmpty()) { + image_q5 = fileUpload("5", "q5", file_5); + } + + if (file_6 != null && !file_6.isEmpty()) { + image_q6 = fileUpload("6", "q6", file_6); + } + + if (file_7 != null && !file_7.isEmpty()) { + image_q7 = fileUpload("7", "q7", file_7); + } + + if (file_8 != null && !file_8.isEmpty()) { + image_q8 = fileUpload("8", "q8", file_8); + } + + if (file_9 != null && !file_9.isEmpty()) { + image_q9 = fileUpload("9", "q9", file_9); + } + + if (file_10 != null && !file_10.isEmpty()) { + image_q10 = fileUpload("10", "q10", file_10); + } + + if (file_11 != null && !file_11.isEmpty()) { + image_q11 = fileUpload("11", "q11", file_11); } String feedbackimg = image; + + String q1_image = image_q1; + String q2_image = image_q2; + String q3_image = image_q3; + String q4_image = image_q4; + String q5_image = image_q5; + String q6_image = image_q6; + String q7_image = image_q7; + String q8_image = image_q8; + String q9_image = image_q9; + String q10_image = image_q10; + String q11_image = image_q11; + String type = getTypeBasedOnTime(); // Get Morning & Evening + // Get today's date + LocalDate today = LocalDate.now(); + + // Format it in the desired format (yyyy-MM-dd) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayDate = today.format(formatter); + + inactiveFeedBack(type, toilet_id); // Upadte already insert data. + String sqlQuery = "INSERT INTO `toilet_feedback`(" + "`toilet_id`, `cby`, " + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " - + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`," + + "`q1_image`, `q2_image`, `q3_image`, `q4_image`, `q5_image`, `q6_image`, " + + "`q7_image`, `q8_image`, `q9_image`, `q10_image`, `q11_image`" + + ") " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); @@ -446,6 +564,18 @@ public class activity { ps.setString(18, ward); ps.setString(19, type); ps.setString(20, feedbackimg); + + ps.setString(21, q1_image); + ps.setString(22, q2_image); + ps.setString(23, q3_image); + ps.setString(24, q4_image); + ps.setString(25, q5_image); + ps.setString(26, q6_image); + ps.setString(27, q7_image); + ps.setString(28, q8_image); + ps.setString(29, q9_image); + ps.setString(30, q10_image); + ps.setString(31, q11_image); return ps; } }, keyHolder); @@ -491,8 +621,6 @@ public class activity { String fromDate, String toDate, String loginid) { - - String sqlQuery = "SELECT " + " `gcc_toilet_list`.`zone`, " @@ -514,6 +642,7 @@ public class activity { + "LEFT JOIN " + " `toilet_feedback` " + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`isactive` = 1 " + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + "WHERE " //+ " `gcc_toilet_list`.`user_id` = ? AND " @@ -542,8 +671,6 @@ public class activity { String toDate, String zone, String loginid) { - - String sqlQuery = "SELECT " + " `gcc_toilet_list`.`ward`, " @@ -565,6 +692,7 @@ public class activity { + "LEFT JOIN " + " `toilet_feedback` " + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`isactive` = 1 " + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + "WHERE " + " `gcc_toilet_list`.`zone` = ? AND " @@ -616,6 +744,7 @@ public class activity { + "LEFT JOIN " + " `toilet_feedback` " + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`isactive` = 1 " + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + "WHERE " + " `gcc_toilet_list`.`ward` = ? AND " @@ -661,6 +790,7 @@ public class activity { + "RIGHT JOIN " + " `toilet_feedback` " + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`isactive` = 1 " + " AND `toilet_feedback`.`type` = ? " + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + "WHERE " diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/WorksController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/WorksController.java new file mode 100644 index 0000000..1eaa5f0 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/WorksController.java @@ -0,0 +1,98 @@ +package in.gov.chennaicorporation.mobileservice.works.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.works.service.WorksService; + +@RequestMapping("/gccofficialapp/works/api") +@RestController("worksRestapi") +public class WorksController { + + @Autowired + private WorksService worksService; + + /* + @GetMapping("/getESTList") + public List getTaskList( + @RequestParam(value = "typeofworkid", required = true) String typeofworkid + ) { + return worksService.getTaskList(typeofworkid); + } + */ + + @GetMapping("/getESTList") + public List getESTList( + @RequestParam(value = "typeofworkid", required = false) String typeofworkid, + @RequestParam(value = "loginId", required = true) String loginId + ) { + return worksService.getESTList(loginId); + } + + @GetMapping("/getESTWorkListData") + public List getESTWorkListData( + @RequestParam(value = "estid", required = true) String estid, + @RequestParam(value = "loginId", required = false) String cby + ) { + return worksService.getESTWorkListData(estid); + } + + @GetMapping("/getTaskDataListWithData") + public List getTaskDataListWithData( + @RequestParam(value = "worktasktid", required = true) String wtid, + @RequestParam(value = "estid", required = true) String estid, + @RequestParam(value = "typeofworkid", required = true) String typeofworkid + ) { + return worksService.getTaskDataListWithData(wtid, estid,typeofworkid); + } + + @PostMapping(value="/addTaskStageActivityData") + public List addTaskStageActivityData(@RequestParam MultiValueMap formData, + @RequestParam(value = "estid", required = true) String estid, + @RequestParam(value = "tmid", required = true) String tmid, + @RequestParam(value = "worktasktid", required = true) String wtid, + @RequestParam(value = "activityfile", required = true) MultipartFile activityfile, + @RequestParam(value = "percentage", required = true) String percentage, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "loginId", required = true) String cby, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude + ) { + return worksService.addTaskStageActivityData(estid, tmid, wtid, activityfile, percentage, remarks, cby, zone, ward, latitude, longitude,"open"); + } + + @GetMapping("/getZoneReport") + public List getZoneReport( + @RequestParam(value = "loginId", required = false) String cby + ) { + return worksService.getZoneReport(); + } + + @GetMapping("/getWardReport") + public List getWardReport( + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "loginId", required = false) String cby + ) { + return worksService.getWardReport(zone); + } + + @GetMapping("/getListReport") + public List getListReport( + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "statusFilter", required = true) String statusFilter, + @RequestParam(value = "loginId", required = false) String cby + ) { + return worksService.getListReport(ward, statusFilter); + } + +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/package-info.java new file mode 100644 index 0000000..6cbccd0 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.works.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/package-info.java new file mode 100644 index 0000000..c239d28 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.works; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/WorksService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/WorksService.java new file mode 100644 index 0000000..d31e137 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/WorksService.java @@ -0,0 +1,699 @@ +package in.gov.chennaicorporation.mobileservice.works.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class WorksService { + private JdbcTemplate jdbcWorksTemplate; + + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlWorksDataSource") DataSource worksDataSource) { + this.jdbcWorksTemplate = new JdbcTemplate(worksDataSource); + } + + @Autowired + public WorksService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + public static String generateRandomString() { + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + public static String generateRandomStringForFile(int String_Lenth) { + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } + + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, MultipartFile file) { + + int lastInsertId = 0; + // Set the file path where you want to save it + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("works_task_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + var date =DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality + + // Write the bytes to the file + Files.write(path, compressedBytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public String getWardByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `ward`, `works` FROM `gcc_penalty_hoardings`.`hoading_user_list` WHERE `userid` = ? LIMIT 1"; + + List> results = jdbcWorksTemplate.queryForList(sqlQuery, loginid); + + if (!results.isEmpty()) { + Map row = results.get(0); + String wardClause; + String departmentClause = ""; + + Object wardValue = row.get("ward"); + Object worksValue = row.get("works"); + + if (wardValue == null || wardValue.toString().equals("0")) { + wardClause = "wu.`ward` NOT IN (0)"; + } else { + wardClause = "wu.`ward` IN ('" + wardValue + "')"; + } + + if (worksValue != null) { + departmentClause = " AND wu.`department` IN (" + worksValue + ")"; + } + + return wardClause + departmentClause; + } + + return "wu.`ward` IN ('-')"; + } + + public List> getESTList(String loginid) { + /* + String sql = "SELECT wu.`Id` AS estid, `wu`.`sub_category` AS works, tw.id AS typeofworkid, `wu`.`estimate_no`, " + + "`wu`.`estimate_date`, `wu`.`zone`, `wu`.`ward`, `wu`.`project_name`, `wu`.`location`, `wu`.`department`, " + + "`wu`.`contractor_name`, `wu`.`contractor_period`, `wu`.`fund_source`, `wu`.`scheme`, `wu`.`category`, `wu`.`sub_category` AS `sub_category`, " + + "`wu`.`est_amount`, `wu`.`tech_sanc_date`, `wu`.`admin_sanc_date`, `wu`.`tender_call_date`, `wu`.`tender_fin_date`, " + + "`wu`.`loa_date`, `wu`.`agreement_date`, `wu`.`work_order_date`, `wu`.`work_comm_date` " + + "FROM `works_update` `wu` LEFT JOIN EGW_TYPEOFWORK `tw` ON trim(`tw`.description) = trim(`wu`.`sub_category`)"; + */ + + String where = getWardByLoginId(loginid,"ae"); + //System.out.println("ward: "+ward); + String sql = "SELECT " + + "wu.`estid` AS estid, " + + "tm.`description` AS works, " + + "tm.id AS typeofworkid, " + + "wu.`estimate_no`, " + + "wu.`estimate_date`, " + + "wu.`zone`, " + + "wu.`ward`, " + + "wu.`project_name`, " + + "wu.`location`, " + + "dm.`dept_name` AS `department`, " + + "wu.`contractor_name`, " + + "CAST(wu.contractor_period AS CHAR) AS contractor_period, " + + "fs.`name` AS `fund_source`, " + + "s.`name` AS `scheme`, " + + "wm.`name` AS `category`, " + + "tm.`description` AS `sub_category`, " + + "wu.`estimation_amount` AS `est_amount`, " + + "wu.`technical_sanction_date` AS `tech_sanc_date`, " + + "wu.`admin_sanction_date` AS `admin_sanc_date`, " + + "wu.`tender_called_date` AS `tender_call_date`, " + + "wu.`tender_finalized_date` AS `tender_fin_date`, " + + "wu.`loa_date` AS `loa_date`, " + + "wu.`agreement_date` AS `agreement_date`, " + + "wu.`work_order_date` AS `work_order_date`, " + + "wu.`work_commenced_date` AS `work_comm_date`, " + + "wu.`percentage` AS `percentage` " + + "FROM `erp_works` wu " + //+ "LEFT JOIN typeofwork_master tw ON trim(tw.description) = trim(wu.`sub_category`)" + + "LEFT JOIN department_master dm ON dm.id = wu.`department`" + + "LEFT JOIN fundsource_master fs ON fs.id = wu.`fund_source` " + + "LEFT JOIN scheme_master s ON s.id = wu.`scheme` " + + "LEFT JOIN workstype_master wm ON wm.id = wu.`category` " + + "LEFT JOIN typeofwork_master tm ON tm.id = wu.`sub_category` " + + "WHERE "+where; + + List> result = jdbcWorksTemplate.queryForList(sql); + /* + List> estWorklistData = new ArrayList<>(); + + for (Map row : result) { + // CHECK IN WORK_TASK + + // CHECK IN typeofwork_task_master + + // CHECK IN task_data last DATA for each typeofwork_task_master + } + */ + + return jdbcWorksTemplate.queryForList(sql); + } + + /* + public List> getTaskDataListWithData(String estid, String typeofworkid) { + String sql = "SELECT `tdid`, `estid`, `tmid`, `percentage`, `cdate`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `stage_file`, `status`, `isactive` FROM `task_data` WHERE 1"; + return jdbcWorksTemplate.queryForList(sql,typeofworkid); + } + */ + + public List> getESTWorkListData(String estid) { + + String sql = "SELECT `id` AS wtid, `estid`, `estimate_no`, `sub_cat_id`, `question_id`, `ans_id`," + + " `remarks`, `cdate`, `isactive`, `isdelete`, `percentage` " + + " FROM `erp_works_task` " + + " WHERE `isactive`=1 AND `isdelete`=0 AND `estid`= ?"; + + List> result = jdbcWorksTemplate.queryForList(sql, estid); + + // Prepare the response + Map response = new HashMap<>(); + response.put("estWorklistData", result); + response.put("message", "EST Activity Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + public List> getTaskDataListWithData(String wtid, String estid, String typeofworkid) { + + String sql = "SELECT `id`, `estid`, `estimate_no`, `sub_cat_id`, `question_id`, `ans_id`," + + " `remarks`, `cdate`, `isactive`, `isdelete`, `percentage` FROM `erp_works_task` " + + "WHERE `id`=? AND `estid`= ? AND `isactive`=1 AND `isdelete`=0"; + + List> result = jdbcWorksTemplate.queryForList(sql, wtid, estid); + + List> estTaskWorklistData = new ArrayList<>(); + + for (Map row : result) { + + // Query for the task related to the current activity + String sqlForTask = "SELECT `tmid`, `stagename` AS `taskname`, `isactive`, `isdelete`, `orderby`, " + + "(" + + " SELECT `percentage` " + + " FROM `erp_task_data` " + + " WHERE `tmid` = `erp_works_stages`.`tmid` AND wtid=? AND `isactive`=1 " + + " ORDER BY `cdate` DESC " + + " LIMIT 1 " + + " ) AS percentage " + + "FROM `erp_works_stages` WHERE `isactive`=1 AND `isdelete`=0 AND `estid`=? ORDER BY `orderby`"; + + List> taskresult = jdbcWorksTemplate.queryForList(sqlForTask, wtid, estid); + + if (!taskresult.isEmpty()) { + // For each task in the taskresult, add taskdataresult + for (Map task : taskresult) { + // Query for the task-related data + String tmid = ""+task.get("tmid"); // Assuming tmid is a field in task + String sqlForTaskData = "SELECT `tdid`, `estid`, `tmid`, `percentage`, `remarks`, " + + "DATE_FORMAT(`cdate`, '%d-%m-%Y %r') AS createddate, " + + "`cby`, `zone`, `ward`, `latitude`, `longitude`, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `stage_file`) AS image, " + + "`status`, `isactive` FROM `erp_task_data` WHERE `wtid`=? AND `tmid`=? AND `estid`=? AND `isactive`=1"; + + List> taskdataresult = jdbcWorksTemplate.queryForList(sqlForTaskData, wtid, tmid, estid); + + // Add taskdataresult to each task + task.put("taskdata", taskdataresult); + } + } + // Add tasklist (with taskdata) to the row + row.put("tasklist", taskresult); + + // Add the row to SWDData + estTaskWorklistData.add(row); + } + + // Prepare the response + Map response = new HashMap<>(); + response.put("estTaskWorklistData", estTaskWorklistData); + response.put("message", "EST Activity Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + @Transactional + public List> addTaskStageActivityData( + String estid, + String tmid, + String wtid, + MultipartFile file, + String percentage, + String remarks, + String cby, + String zone, + String ward, + String latitude, + String longitude, + String status) { + List> result = null; + Map response = new HashMap<>(); + + int lastInsertId = 0; + + String filetxt = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + filetxt = fileUpload(estid+"_"+tmid, cby, file); + } + String finalfile = filetxt; + String sqlQuery = "INSERT INTO `erp_task_data`" + + "(`estid`, `tmid`, `percentage`, `remarks`, `cby`, `zone`, `ward`, `latitude`, `longitude`, `stage_file`, `status`,`wtid`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + LocalDateTime approvedDate = LocalDateTime.now(); + + String formattedDate = approvedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + try { + status = "open"; + if(percentage.contains("100")) { + status = "close"; + } + + String statustxt = status; + + // Insert the data the required number of times + int affectedRows = jdbcWorksTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "did" }); + ps.setString(1, estid); + ps.setString(2, tmid); + ps.setString(3, percentage); + ps.setString(4, remarks); + ps.setString(5, cby); + ps.setString(6, zone); + ps.setString(7, ward); + ps.setString(8, latitude); + ps.setString(9, longitude); + ps.setString(10, finalfile); + ps.setString(11, statustxt); + ps.setString(12, wtid); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "Stage Task data inserted successfully!"); + System.out.println("Stage Task was inserted successfully! Insert ID: " + generatedId); + updateStatus(percentage, estid, wtid); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert stage task data."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } +/* + // Update Percentage of works progress + String sqlUpdateQuery ="UPDATE erp_works ew " + + "JOIN ( " + + " SELECT " + + " ew.estid, " + + " ROUND(SUM(COALESCE(etd.percentage, 0)) / COUNT(*), 0) AS physical_progress " + + " FROM erp_works ew " + + " JOIN erp_works_task ewt ON ewt.estid = ew.estid " + + " JOIN erp_works_stages ews ON ews.estid = ew.estid " + + " LEFT JOIN erp_task_data etd " + + " ON etd.estid = ew.estid " + + " AND etd.wtid = ewt.id " + + " AND etd.tmid = ews.tmid " + + " GROUP BY ew.estid " + + " HAVING physical_progress > 0 " + + ") AS prog " + + "ON ew.estid = prog.estid " + + "SET " + + " ew.percentage = prog.physical_progress, " + + " ew.update_status = CASE " + + " WHEN prog.physical_progress = 0 THEN 'pending' " + + " WHEN prog.physical_progress < 100 THEN 'Inprogress' " + + " ELSE 'Completed' " + + " END"; +*/ + String sqlUpdateQuery ="UPDATE erp_works ew " + + "JOIN ( " + + " SELECT " + + " ew.estid, " + + " ROUND(SUM(COALESCE(etd.percentage, 0)) / COUNT(*), 0) AS physical_progress " + + " FROM erp_works ew " + + " JOIN erp_works_task ewt ON ewt.estid = ew.estid " + + " JOIN erp_works_stages ews ON ews.estid = ew.estid " + + " LEFT JOIN ( " + //+ " -- Get only the latest active record per (estid, wtid, tmid) " + + " SELECT etd.* " + + " FROM erp_task_data etd " + + " INNER JOIN ( " + + " SELECT estid, wtid, tmid, MAX(tdid) AS max_tdid " + + " FROM erp_task_data " + + " WHERE isactive = 1 " + + " GROUP BY estid, wtid, tmid " + + " ) latest ON latest.estid = etd.estid " + + " AND latest.wtid = etd.wtid " + + " AND latest.tmid = etd.tmid " + + " AND latest.max_tdid = etd.tdid " + + " ) etd ON etd.estid = ew.estid " + + " AND etd.wtid = ewt.id " + + " AND etd.tmid = ews.tmid " + + " GROUP BY ew.estid " + + " HAVING physical_progress > 0 " + + ") AS prog " + + "ON ew.estid = prog.estid " + + "SET " + + " ew.percentage = prog.physical_progress, " + + " ew.update_status = CASE " + + " WHEN prog.physical_progress = 0 THEN 'pending' " + + " WHEN prog.physical_progress < 100 THEN 'Inprogress' " + + " ELSE 'Completed' " + + " END"; + + System.out.println("Percentage Update : " + sqlUpdateQuery + " --> ESTID : " + estid); + jdbcWorksTemplate.update(sqlUpdateQuery); + + return Collections.singletonList(response); + } + + public boolean updateStatus(String percentage,String estid, String wtid) { + int statusAffected = 0; + /* + String selectSql = "SELECT " + + " ewt.id," + + " ROUND(SUM(COALESCE(etd.percentage, 0)) / COUNT(*), 0) AS physical_progress" + + " FROM erp_works ew" + + " JOIN erp_works_task ewt ON ewt.estid = ew.estid" + + " JOIN erp_works_stages ews ON ews.estid = ew.estid" + + " LEFT JOIN erp_task_data etd " + + " ON etd.estid = ew.estid " + + " AND etd.wtid = ewt.id " + + " AND etd.tmid = ews.tmid" + + " AND ewt.id = ?" + + " GROUP BY ew.estid" + + " HAVING physical_progress > 0"; + */ + + String selectSql ="SELECT " + + " ewt.id, " + + " ROUND(SUM(COALESCE(etd.percentage, 0)) / COUNT(*), 0) AS physical_progress " + + "FROM " + + " erp_works ew " + + "JOIN " + + " erp_works_task ewt ON ewt.estid = ew.estid " + + "JOIN " + + " erp_works_stages ews ON ews.estid = ew.estid " + + "LEFT JOIN ( " + + " -- Subquery to get only latest entry per estid/wtid/tmid based on highest tdid " + + " SELECT etd.* " + + " FROM erp_task_data etd " + + " INNER JOIN ( " + + " SELECT estid, wtid, tmid, MAX(tdid) AS max_tdid " + + " FROM erp_task_data " + + " WHERE isactive = 1 " + + " GROUP BY estid, wtid, tmid " + + " ) latest ON latest.estid = etd.estid " + + " AND latest.wtid = etd.wtid " + + " AND latest.tmid = etd.tmid " + + " AND latest.max_tdid = etd.tdid " + + ") etd ON etd.estid = ew.estid " + + " AND etd.wtid = ewt.id " + + " AND etd.tmid = ews.tmid " + + "WHERE " + + " ewt.id = ? " + + "GROUP BY " + + " ew.estid " + + "HAVING " + + " physical_progress > 0"; + + List> rows = jdbcWorksTemplate.queryForList(selectSql, new Object[]{wtid}); + + for (Map row : rows) { + int physical_progress = ((Number) row.get("physical_progress")).intValue(); + + String updateSql = "UPDATE `erp_works_task` SET `percentage`=? WHERE `estid`=? AND `id`=?"; + statusAffected = jdbcWorksTemplate.update(updateSql, physical_progress, estid, wtid); + + System.out.println("Updated " + statusAffected + " row(s) for estid=" + estid + ", wtid=" + wtid); + } + + // System.out.println("UPDATE `erp_works_task` SET `percentage`="+percentage+" WHERE `estid`="+estid+" AND `id`="+wtid); + // System.out.println("UPDATE `erp_works_task` Status: " + statusAffected); + + int rowsAffected = 0; + if (statusAffected > 0) { + /* + sqlQuery = "UPDATE `works_update` SET `percentage`=? WHERE `id`=?"; + rowsAffected = jdbcWorksTemplate.update(sqlQuery, new Object[]{percentage,estid}); + + System.out.println("UPDATE `works_update` SET `percentage`="+percentage+" WHERE `id`="+estid); + System.out.println("UPDATE `works_update` Status: " + rowsAffected); + */ + } + return rowsAffected > 0; + } + + + public List> getZoneReport() { + + String sql = "SELECT " + + " CASE " + + " WHEN zone = '00' THEN 'HQ' " + + " ELSE zone " + + " END AS zone, " + + " COUNT(estid) AS Total, " + + " SUM(CASE WHEN percentage = 100 THEN 1 ELSE 0 END) AS CompletedTotal, " + + " SUM(CASE WHEN percentage > 0 AND percentage < 100 THEN 1 ELSE 0 END) AS OngoingTotal, " + + " SUM(CASE WHEN percentage = 0 THEN 1 ELSE 0 END) AS NotStartedTotal " + + "FROM " + + " `erp_works` " + + "GROUP BY " + + " zone " + + "ORDER BY " + + " zone;"; + + List> result = jdbcWorksTemplate.queryForList(sql); + + // Prepare the response + Map response = new HashMap<>(); + response.put("ZoneData", result); + response.put("message", "EST Activity Zone Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + public List> getWardReport(String zone) { + + String sql = "SELECT " + + " CASE " + + " WHEN zone = '00' THEN 'HQ' " + + " ELSE zone " + + " END AS zone, " + + " CASE " + + " WHEN ward = '000' THEN 'HQ' " + + " ELSE ward " + + " END AS ward, " + + " COUNT(estid) AS Total, " + + " SUM(CASE WHEN percentage = 100 THEN 1 ELSE 0 END) AS CompletedTotal, " + + " SUM(CASE WHEN percentage > 0 AND percentage < 100 THEN 1 ELSE 0 END) AS OngoingTotal, " + + " SUM(CASE WHEN percentage = 0 THEN 1 ELSE 0 END) AS NotStartedTotal " + + "FROM " + + " `erp_works` " + + "WHERE zone=? " + + "GROUP BY " + + " zone, ward " + + "ORDER BY " + + " ward"; + + List> result = jdbcWorksTemplate.queryForList(sql,zone); + + // Prepare the response + Map response = new HashMap<>(); + response.put("estWorklistData", result); + response.put("message", "EST Activity Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + public List> getListReport(String ward, String statusFilter) { + + + + StringBuilder sqlBuilder = new StringBuilder("SELECT " + + "wu.`estid` AS estid, " + + "tm.`description` AS works, " + + "tm.id AS typeofworkid, " + + "wu.`estimate_no`, " + + "wu.`estimate_date`, " + + "wu.`zone`, " + + "wu.`ward`, " + + "wu.`project_name`, " + + "wu.`location`, " + + "dm.`dept_name` AS `department`, " + + "wu.`contractor_name`, " + + "CAST(wu.contractor_period AS CHAR) AS contractor_period, " + + "fs.`name` AS `fund_source`, " + + "s.`name` AS `scheme`, " + + "wm.`name` AS `category`, " + + "tm.`description` AS `sub_category`, " + + "wu.`estimation_amount` AS `est_amount`, " + + "wu.`technical_sanction_date` AS `tech_sanc_date`, " + + "wu.`admin_sanction_date` AS `admin_sanc_date`, " + + "wu.`tender_called_date` AS `tender_call_date`, " + + "wu.`tender_finalized_date` AS `tender_fin_date`, " + + "wu.`loa_date` AS `loa_date`, " + + "wu.`agreement_date` AS `agreement_date`, " + + "wu.`work_order_date` AS `work_order_date`, " + + "wu.`work_commenced_date` AS `work_comm_date`, " + + "wu.`percentage` AS `percentage` " + + "FROM `erp_works` wu " + + "LEFT JOIN department_master dm ON dm.id = wu.`department` " + + "LEFT JOIN fundsource_master fs ON fs.id = wu.`fund_source` " + + "LEFT JOIN scheme_master s ON s.id = wu.`scheme` " + + "LEFT JOIN workstype_master wm ON wm.id = wu.`category` " + + "LEFT JOIN typeofwork_master tm ON tm.id = wu.`sub_category` " + + "WHERE wu.`ward` = '" + ward + "' "); + + switch (statusFilter) { + case "completed": + sqlBuilder.append("AND wu.percentage = 100 "); + break; + case "ongoing": + sqlBuilder.append("AND wu.percentage > 0 AND wu.percentage < 100 "); + break; + case "not_started": + sqlBuilder.append("AND wu.percentage = 0 "); + break; + // default is no filtering (all) + } + + String sql = sqlBuilder.toString(); + List> result = jdbcWorksTemplate.queryForList(sql); + + // Prepare the response + Map response = new HashMap<>(); + response.put("estWorklistData", result); + response.put("message", "EST Data List."); + + // Return the response wrapped in a singleton list + return Collections.singletonList(response); + } + + +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/package-info.java new file mode 100644 index 0000000..7187c5c --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/works/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.works.service; \ No newline at end of file diff --git a/mobileservice/src/main/resources/application-local.properties b/mobileservice/src/main/resources/application-local.properties index e999929..394aad6 100644 --- a/mobileservice/src/main/resources/application-local.properties +++ b/mobileservice/src/main/resources/application-local.properties @@ -1 +1,3 @@ -assets.base-url=/assets/ \ No newline at end of file +assets.base-url=/assets/ + +fileBaseUrl=http://localhost:8064 \ No newline at end of file diff --git a/mobileservice/src/main/resources/application-production.properties b/mobileservice/src/main/resources/application-production.properties index 210d765..029057f 100644 --- a/mobileservice/src/main/resources/application-production.properties +++ b/mobileservice/src/main/resources/application-production.properties @@ -1 +1,3 @@ -assets.base-url=/gccofficialapp/assets/ \ No newline at end of file +assets.base-url=/gccofficialapp/assets/ + +fileBaseUrl=https://gccservices.in \ No newline at end of file diff --git a/mobileservice/src/main/resources/application.properties b/mobileservice/src/main/resources/application.properties index c169002..4456708 100644 --- a/mobileservice/src/main/resources/application.properties +++ b/mobileservice/src/main/resources/application.properties @@ -24,12 +24,10 @@ spring.jackson.time-zone=Asia/Kolkata spring.servlet.multipart.max-file-size=20MB # Maximum request size (including all files) -spring.servlet.multipart.max-request-size=20MB +spring.servlet.multipart.max-request-size=120MB spring.mvc.favicon.enabled=false -fileBaseUrl=https://gccservices.in - file.upload.directory=${user.dir}/gcc_mobile_service_uploads/ activity_foldername = asset_activity/ @@ -44,4 +42,9 @@ swm_bwg_foldername = swm_bwg/ cattlecatch_foldername = cattlecatch_activity/ hoardings_foldername = hoardings_activity/ toilets_foldername = toilets_activity/ - +c_d_waste_foldername = c_d_waste_activity/ +mosquito_foldername = mosquito_activity/ +works_task_foldername = works_activity/ +street_vendor_foldername=street_vendor_files/ +gcceducation_foldername=education_schools_files/ +busshelter_foldername=bus_shelter_files/