This application is used for whatsapp governance, which contains the API for the several services provided by GCC.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

864 lines
45 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. package com.gcc.restapiservices.communityHall.service;
  2. import com.gcc.restapiservices.communityHall.configuration.PaymentConfig;
  3. import com.gcc.restapiservices.communityHall.util.TransactionNumberGenerator;
  4. import com.gcc.restapiservices.configuration.AppConfig;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.core.env.Environment;
  9. import org.springframework.dao.DataAccessException;
  10. import org.springframework.dao.EmptyResultDataAccessException;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.jdbc.support.GeneratedKeyHolder;
  13. import org.springframework.jdbc.support.KeyHolder;
  14. import org.springframework.stereotype.Service;
  15. import org.springframework.transaction.annotation.Transactional;
  16. import org.springframework.web.bind.annotation.RequestParam;
  17. import org.springframework.web.client.RestTemplate;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import java.util.Random;
  20. import com.gcc.restapiservices.configuration.AppConfig;
  21. import com.fasterxml.jackson.databind.ObjectMapper;
  22. import com.fasterxml.jackson.databind.node.ObjectNode;
  23. import jakarta.servlet.http.HttpServletRequest;
  24. import jakarta.servlet.http.HttpSession;
  25. import javax.sql.DataSource;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Random;
  29. import java.io.File;
  30. import java.io.FileOutputStream;
  31. import java.io.IOException;
  32. import java.math.BigInteger;
  33. import java.nio.file.Files;
  34. import java.nio.file.Path;
  35. import java.nio.file.Paths;
  36. import java.security.MessageDigest;
  37. import java.security.NoSuchAlgorithmException;
  38. import java.security.SecureRandom;
  39. import java.sql.PreparedStatement;
  40. import java.sql.Statement;
  41. import java.time.LocalDate;
  42. import java.time.LocalDateTime;
  43. import java.time.format.DateTimeFormatter;
  44. import java.util.ArrayList;
  45. import java.util.Collections;
  46. import java.util.HashMap;
  47. @Service
  48. public class communityHallService {
  49. private JdbcTemplate jdbcTemplate;
  50. @Autowired
  51. private AppConfig appConfig;
  52. @Autowired
  53. private Environment environment;
  54. @Autowired
  55. private PaymentConfig paymentConfig;
  56. @Autowired
  57. private TransactionNumberGenerator transactionNumberGenerator;
  58. private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  59. private static final int STRING_LENGTH = 15;
  60. private static final Random RANDOM = new SecureRandom();
  61. @Value("${file.upload.directory.communityhall}")
  62. private String uploadDirectory;
  63. @Value("${file.fullpath.communityhall}")
  64. private String serverPath;
  65. @Autowired
  66. public void setDataSource(@Qualifier("mysqlCommunityHallDataSource") DataSource dataSource) {
  67. this.jdbcTemplate = new JdbcTemplate(dataSource);
  68. }
  69. public List<Map<String, Object>> getHallList() {
  70. return jdbcTemplate.queryForList("SELECT * FROM hall_details WHERE is_active = 1 order by hall_name asc");
  71. }
  72. public List<Map<String, Object>> getReasonMaster() {
  73. String sql = "SELECT reason_id,reason,maxdays,reasoncode FROM reason_master";
  74. return jdbcTemplate.queryForList(sql);
  75. }
  76. public List<Map<String, Object>> getDocumentsByReasonId(Long reasonId) {
  77. String sql = "SELECT doc_field_name,field_name FROM reason_document_master WHERE reason_id = ?";
  78. return jdbcTemplate.queryForList(sql, reasonId);
  79. }
  80. public List<Map<String, String>> getRelationTypesAsMap() {
  81. List<Map<String, String>> relationList = new ArrayList<>();
  82. String[] relations = {"Self", "Son", "Daughter", "Granddaughter", "Grandson", "Brother", "Sister"};
  83. for (String rel : relations) {
  84. Map<String, String> map = new HashMap<>();
  85. map.put("relation_name", rel);
  86. map.put("value", rel);
  87. relationList.add(map);
  88. }
  89. return relationList;
  90. }
  91. public List<Map<String, Object>> getUserDetails(Long Mobilenumber) {
  92. String sql = "SELECT name,email,mobile_no,doorno,area,location,pin_code,user_status,usertype,profilephoto FROM users WHERE mobile_no = ?";
  93. return jdbcTemplate.queryForList(sql, Mobilenumber);
  94. }
  95. public Map<String, Object> getHallDetailsById(int hallId) {
  96. String sql = "SELECT * FROM hall_details WHERE hall_id = ?";
  97. List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, hallId);
  98. if (result.isEmpty()) {
  99. return null; // or Collections.emptyMap() if you prefer
  100. }
  101. return result.get(0);
  102. }
  103. public Map<String, Object> getHallConcessionByHallId(int hallId) {
  104. String sql = "SELECT * FROM hall_details_concession WHERE hall_id = ?";
  105. List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, hallId);
  106. if (result.isEmpty()) {
  107. return null; // or Collections.emptyMap()
  108. }
  109. return result.get(0); // ✅ safe return of first result
  110. }
  111. public List<Map<String, Object>> checkMobileExits(Long Mobilenumber) {
  112. String sql = "SELECT * FROM users WHERE mobile_no = ?";
  113. return jdbcTemplate.queryForList(sql, Mobilenumber);
  114. }
  115. public List<Map<String, Object>> checkEmployeeExits(String EmployeeID) {
  116. String sql = "SELECT * FROM users WHERE government_id= ?";
  117. return jdbcTemplate.queryForList(sql, EmployeeID);
  118. }
  119. /*
  120. * public Map<String, Object> getBookingDetailsById(int bookingId) { String sql
  121. * = "SELECT " +
  122. * "bd.booking_id, bd.booking_date, bd.start_date, bd.end_date, bd.comments, bd.booking_status, "
  123. * +
  124. * "bd.starting_slot, bd.ending_slot, bd.no_of_days, bd.reason, bd.gst, bd.deposit_amount, "
  125. * + "bd.hall_amount, bd.amount_received AS booking_amount_received, " +
  126. * "u.name, u.usertype, u.mobile_no, u.email, " +
  127. * "hd.zone, hd.division, hd.hall_incharge_name, hd.hall_incharge_no, hd.hall_name, "
  128. * + "CONCAT_WS(', ', hd.street, hd.area, hd.pin_code) AS address, " +
  129. * "p.transaction_id, p.payment_status, p.amount_received AS payment_amount_received "
  130. * + "FROM booking_details bd " +
  131. * "INNER JOIN users u ON bd.users_user_id = u.user_id " +
  132. * "INNER JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " +
  133. * "INNER JOIN payments p ON bd.booking_id = p.booking_details_booking_id " +
  134. * "WHERE bd.booking_id = ?";
  135. *
  136. * return jdbcTemplate.queryForMap(sql, bookingId); }
  137. */
  138. public Map<String, Object> getBookingDetailsById(int bookingId) {
  139. String sql = "SELECT "
  140. + "bd.booking_id, DATE_FORMAT(bd.booking_date, '%d-%m-%Y') AS booking_date, "
  141. + " DATE_FORMAT(bd.start_date, '%d-%m-%Y') AS start_date, "
  142. + " DATE_FORMAT(bd.end_date, '%d-%m-%Y') AS end_date, "
  143. + " bd.comments, bd.booking_status, "
  144. + "bd.starting_slot, bd.ending_slot, bd.no_of_days, bd.reason, bd.gst, bd.deposit_amount, "
  145. + "bd.hall_amount, bd.amount_received AS total_amount, " + "u.name, u.usertype, u.mobile_no, u.email, "
  146. + "hd.zone, hd.division, hd.hall_incharge_name as caretaker_name, hd.hall_incharge_no as caretaker_mobileno, hd.hall_name, "
  147. + "CONCAT_WS(', ', hd.street, hd.area, hd.pin_code) AS hall_address, "
  148. + "p.transaction_id, p.payment_status, p.amount_received AS payment_amount_received "
  149. + "FROM booking_details bd " + "INNER JOIN users u ON bd.users_user_id = u.user_id "
  150. + "INNER JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "
  151. + "INNER JOIN payments p ON bd.booking_id = p.booking_details_booking_id " + "WHERE bd.booking_id = ?";
  152. Map<String, Object> result = jdbcTemplate.queryForMap(sql, bookingId);
  153. // Add the acknowledgement URL to the result
  154. String acknowledgementUrl = "https://gccservices.chennaicorporation.gov.in/communityhall/user/acknowledgement?bookingId=" + bookingId;
  155. result.put("acknowledgement_url", acknowledgementUrl);
  156. return result;
  157. }
  158. // pdf
  159. /*
  160. * public List<Map<String, Object>> getBookingsByMobile(Long mobileNumber) {
  161. * String sql =
  162. * "SELECT bd.booking_id, bd.booking_date, bd.start_date, bd.end_date, " +
  163. * "bd.starting_slot, bd.ending_slot, bd.reason, bd.booking_status, " +
  164. * "p.payment_status AS payment_status " +
  165. * "FROM testcommunityhall.booking_details bd " +
  166. * "INNER JOIN testcommunityhall.users u ON bd.users_user_id = u.user_id " +
  167. * "INNER JOIN testcommunityhall.payments p ON bd.booking_id = p.booking_details_booking_id "
  168. * + "WHERE u.mobile_no = ? " + "AND bd.booking_status NOT IN ('PENDING')";
  169. *
  170. * return jdbcTemplate.queryForList(sql, mobileNumber); }
  171. */
  172. public List<Map<String, Object>> getBookingsByMobile(Long mobileNumber) {
  173. String sql = "SELECT bd.booking_id , DATE_FORMAT(bd.booking_date, '%d-%m-%Y') AS booking_date,"
  174. + " DATE_FORMAT(bd.start_date, '%d-%m-%Y') AS start_date,"
  175. + " DATE_FORMAT(bd.end_date, '%d-%m-%Y') AS end_date, "
  176. + "bd.starting_slot, bd.ending_slot, bd.reason, bd.booking_status, "
  177. + "p.payment_status AS payment_status " + "FROM booking_details bd "
  178. + "INNER JOIN users u ON bd.users_user_id = u.user_id "
  179. + "INNER JOIN payments p ON bd.booking_id = p.booking_details_booking_id "
  180. + "WHERE u.mobile_no = ? " + "AND bd.booking_status NOT IN ('PENDING')";
  181. List<Map<String, Object>> bookings = jdbcTemplate.queryForList(sql, mobileNumber);
  182. // Add acknowledgement URL to each booking
  183. for (Map<String, Object> booking : bookings) {
  184. Object bookingId = booking.get("booking_id");
  185. if (bookingId != null) {
  186. String acknowledgementUrl = "https://gccservices.chennaicorporation.gov.in/communityhall/user/acknowledgement?bookingId="
  187. + bookingId;
  188. booking.put("acknowledgement_url", acknowledgementUrl);
  189. }
  190. }
  191. return bookings;
  192. }
  193. public List<Map<String, Object>> checkPenionerExits(String PensionerID) {
  194. String sql = "SELECT * FROM users WHERE government_id= ?";
  195. return jdbcTemplate.queryForList(sql, PensionerID);
  196. }
  197. //
  198. public List<Map<String, Object>> findCounsellorByMobile(long mobileNo) {
  199. String sql = "SELECT * FROM counsellor_details WHERE mobile1 = ? OR mobile2 = ?";
  200. return jdbcTemplate.queryForList(sql, mobileNo, mobileNo);
  201. }
  202. public void registerUser(String userType, String name, long mobileNumber, String aadharNumber,
  203. MultipartFile profilePhoto, String emailId, String doorNo, String street, String area, String location,
  204. String pincode, String pensionerID, String pensionerDepartment, String employeeID,
  205. String employeeDepartment) throws IOException {
  206. String uploadPhotoUrl = null;
  207. if (profilePhoto != null && !profilePhoto.isEmpty()) {
  208. uploadPhotoUrl = saveFile(profilePhoto);
  209. }
  210. // Default values for government_id and department
  211. String governmentId = null;
  212. String department = null;
  213. String userstatus = "APPROVED";
  214. // Logic for conditional insertion based on userType
  215. if ("GCC PENSIONER".equalsIgnoreCase(userType)) {
  216. governmentId = pensionerID;
  217. department = pensionerDepartment;
  218. userstatus = "PENDING";
  219. } else if ("GCC EMPLOYEE".equalsIgnoreCase(userType)) {
  220. governmentId = employeeID;
  221. department = employeeDepartment;
  222. userstatus = "PENDING";
  223. }
  224. String sql = "INSERT INTO users (usertype, name, mobile_no, aadhar_number, profilephoto, email, "
  225. + "doorno, street, area, location, pin_code, government_id, department,user_status) "
  226. + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
  227. jdbcTemplate.update(sql, userType, name, mobileNumber, aadharNumber, uploadPhotoUrl, emailId, doorNo, street,
  228. area, location, pincode, governmentId, department, userstatus);
  229. }
  230. public String saveFile(MultipartFile file) throws IOException {
  231. String order_copy_url = "";
  232. // Handle file upload if a file is provided
  233. if (file == null || file.isEmpty()) {
  234. return order_copy_url;
  235. }
  236. // Get the base upload directory from properties
  237. String uploadDirectory = environment.getProperty("file.upload.directory"); // e.g., /opt/myapp/uploads
  238. // Define the subdirectory structure
  239. String serviceFolderName = "images/userPhoto"; // You can also get from properties if needed
  240. // Build the full folder path
  241. String fullUploadPath = uploadDirectory + File.separator + serviceFolderName;
  242. Path directoryPath = Paths.get(fullUploadPath);
  243. if (!Files.exists(directoryPath)) {
  244. Files.createDirectories(directoryPath);
  245. }
  246. // Generate unique file name
  247. // String datetimetxt = DateTimeUtil.getCurrentDateTime();
  248. String fileName = generateRandomStringForFile(10) + "_" + file.getOriginalFilename();
  249. // Physical file path
  250. Path filePath = directoryPath.resolve(fileName);
  251. // Write the file to the physical path
  252. Files.write(filePath, file.getBytes());
  253. // Relative path for storing in DB
  254. String filepath_txt = "/" + serviceFolderName + "/" + fileName;
  255. return filepath_txt;
  256. }
  257. public static String generateRandomStringForFile(int String_Lenth) {
  258. StringBuilder result = new StringBuilder(String_Lenth);
  259. for (int i = 0; i < STRING_LENGTH; i++) {
  260. result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
  261. }
  262. return result.toString();
  263. }
  264. @Transactional("mysqlCommunityHallTransactionManager")
  265. public Map<String, Object> saveBookingDetails(Map<String, Object> formData) {
  266. Map<String, Object> hs = new HashMap<>();
  267. Map<String, Object> userMaster = jdbcTemplate.queryForMap("SELECT * FROM users WHERE mobile_no = ?",
  268. (formData.get("mobNo").toString()));
  269. Integer userId = (Integer) userMaster.get("user_id");
  270. Map<String, Object> reasonMaster = jdbcTemplate.queryForMap("SELECT * FROM reason_master WHERE reason_id = ?",
  271. Integer.parseInt(formData.get("reasonId").toString()));
  272. Map<String, Object> hallDetails = jdbcTemplate.queryForMap("SELECT * FROM hall_details WHERE hall_id = ?",
  273. Integer.parseInt(formData.get("hallId").toString()));
  274. // Fetch User
  275. Map<String, Object> user = jdbcTemplate.queryForMap("SELECT * FROM users WHERE user_id = ?", userId);
  276. String bookingId = formData.get("bookingId").toString();
  277. Map<String, Object> bookingDetails = null;
  278. if (bookingId != null && bookingId.equals("0")) {
  279. } else {
  280. List<Map<String, Object>> bookings = jdbcTemplate
  281. .queryForList("SELECT * FROM booking_details WHERE booking_id = ?", Integer.parseInt(bookingId));
  282. if (!bookings.isEmpty()) {
  283. bookingDetails = bookings.get(0);
  284. jdbcTemplate.update("DELETE FROM booking_documents WHERE booking_id = ?", Integer.parseInt(bookingId));
  285. }
  286. }
  287. if (user != null) {
  288. String startDate = formData.get("startDate").toString();
  289. String endDate = formData.get("endDate").toString();
  290. String relation = formData.get("relation").toString();
  291. double days = Double.parseDouble(formData.get("days").toString());
  292. int daysrange = Integer.parseInt(formData.get("daysrange").toString());
  293. String usertype = user.get("usertype").toString();
  294. String reason = reasonMaster.get("reason").toString();
  295. int startingSlot = Integer.parseInt(formData.get("startingSlot").toString());
  296. int endingSlot = Integer.parseInt(formData.get("endingSlot").toString());
  297. String startingSlot_txt = formData.get("startingSlot").toString();
  298. String endingSlot_txt = formData.get("endingSlot").toString();
  299. Map<String, Object> discountrange = jdbcTemplate
  300. .queryForMap("SELECT * FROM discount_range WHERE usertype = ?", usertype);
  301. float discount = Float.parseFloat(discountrange.get("discount_range").toString());
  302. double hallAmount = calcHallAmountJdbc(hallDetails, daysrange, startingSlot, endingSlot);
  303. hs.put("actualhallamount", hallAmount);
  304. double depositeamount = Double.parseDouble(hallDetails.get("deposit_amount").toString());
  305. double halfDepositAmount = Double.parseDouble(hallDetails.get("half_deposit_amount").toString());
  306. double Totaldepositeamount = calculateDepositAmountJdbc(daysrange, startingSlot_txt, endingSlot_txt,
  307. depositeamount, halfDepositAmount);
  308. depositeamount = Totaldepositeamount;
  309. double discountAmount = 0;
  310. double gstAmount = 0.00;
  311. String reasoncode = reasonMaster.get("reasoncode") != null ? reasonMaster.get("reasoncode").toString() : "";
  312. hs.put("reasoncode", reasoncode);
  313. /*Map<String, Object> governmentevents = jdbcTemplate.queryForMap(
  314. "SELECT * FROM hall_details_concession WHERE hall_id = ?",
  315. Integer.parseInt(hallDetails.get("hall_id").toString()));*/
  316. List<Map<String, Object>> rows = jdbcTemplate.queryForList(
  317. "SELECT * FROM hall_details_concession WHERE hall_id = ?",
  318. Integer.parseInt(hallDetails.get("hall_id").toString())
  319. );
  320. Map<String, Object> governmentevents = rows.isEmpty()
  321. ? Collections.emptyMap() // or null, your call
  322. : rows.get(0);
  323. if (reasoncode.equals("SGE")) {
  324. if (startingSlot == 1 && endingSlot == 2) {
  325. discountAmount = (Double.parseDouble(governmentevents.get("fulldayhallamount").toString())
  326. * Double.parseDouble(hallDetails.get("sgediscount").toString())) / 100;
  327. hallAmount = Double.parseDouble(governmentevents.get("fulldayhallamount").toString());
  328. hs.put("discount", hallDetails.get("sgediscount"));
  329. double cleaningCharges = Double
  330. .parseDouble(governmentevents.get("full_day_cleaningcharges").toString());
  331. double PASystem = Double.parseDouble(governmentevents.get("fulldaypasystem").toString());
  332. double EB = Double.parseDouble(governmentevents.get("fulldayebcharges").toString());
  333. double additionalcharges = cleaningCharges + PASystem + EB;
  334. gstAmount = Math.round(additionalcharges * Double.parseDouble(hallDetails.get("gst").toString()))
  335. / 100.0;
  336. double depositAmount = Double.parseDouble(hallDetails.get("deposit_amount").toString()) * daysrange;
  337. double totalAmount = additionalcharges + gstAmount + depositAmount;
  338. double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0;
  339. hs.put("actualhallamount", hallAmount);
  340. hs.put("additionalcharges", additionalcharges);
  341. hs.put("totalAmount", truncatedTotalAmount);
  342. bookingId = insertOrUpdateBookingDetailsJdbc(jdbcTemplate, bookingId, user, hallDetails, startDate,
  343. endDate, days, startingSlot, endingSlot, depositeamount, additionalcharges, gstAmount,
  344. truncatedTotalAmount, reason, relation, "WAITING", "Booking Slot not Confirmed.", "ONLINE");
  345. } else {
  346. hallAmount = Double.parseDouble(governmentevents.get("halfdayhallamount").toString());
  347. discountAmount = (hallAmount * Double.parseDouble(hallDetails.get("sgediscount").toString())) / 100;
  348. hs.put("discount", hallDetails.get("sgediscount"));
  349. double cleaningCharges = Double
  350. .parseDouble(governmentevents.get("halfdaycleaningcharges").toString());
  351. double PASystem = Double.parseDouble(governmentevents.get("halfdaypasystem").toString());
  352. double EB = Double.parseDouble(governmentevents.get("halfdayebcharges").toString());
  353. double additionalcharges = cleaningCharges + PASystem + EB;
  354. gstAmount = Math.round(additionalcharges * Double.parseDouble(hallDetails.get("gst").toString()))
  355. / 100.0;
  356. double depositAmount = Double.parseDouble(hallDetails.get("deposit_amount").toString()) * daysrange;
  357. double totalAmount = additionalcharges + gstAmount + depositAmount;
  358. double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0;
  359. hs.put("actualhallamount", hallAmount);
  360. hs.put("additionalcharges", additionalcharges);
  361. hs.put("totalAmount", truncatedTotalAmount);
  362. bookingId = insertOrUpdateBookingDetailsJdbc(jdbcTemplate, bookingId, user, hallDetails, startDate,
  363. endDate, days, startingSlot, endingSlot, depositeamount, additionalcharges, gstAmount,
  364. truncatedTotalAmount, reason, relation, "WAITING", "Booking Slot not Confirmed.", "ONLINE");
  365. }
  366. } else if (reasoncode.equals("CGE")) {
  367. double rentAmount, netAmount, depositAmount, totalAmount, truncatedTotalAmount, additionalcharges;
  368. if (startingSlot == 1 && endingSlot == 2) {
  369. discountAmount = (Double.parseDouble(hallDetails.get("full_day_rent").toString())
  370. * Double.parseDouble(hallDetails.get("cgediscount").toString())) / 100;
  371. hallAmount = Double.parseDouble(hallDetails.get("full_day_rent").toString());
  372. hs.put("discount", hallDetails.get("cgediscount"));
  373. double cleaningCharges = Double
  374. .parseDouble(governmentevents.get("full_day_cleaningcharges").toString());
  375. double PASystem = Double.parseDouble(governmentevents.get("fulldaypasystem").toString());
  376. double EB = Double.parseDouble(governmentevents.get("fulldayebcharges").toString());
  377. additionalcharges = cleaningCharges + PASystem + EB;
  378. rentAmount = hallAmount - discountAmount;
  379. netAmount = rentAmount + additionalcharges;
  380. gstAmount = Math.round(netAmount * Double.parseDouble(hallDetails.get("gst").toString())) / 100.0;
  381. depositAmount = Double.parseDouble(hallDetails.get("deposit_amount").toString()) * daysrange;
  382. totalAmount = netAmount + gstAmount + depositAmount;
  383. truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0;
  384. hs.put("actualhallamount", hallAmount);
  385. hs.put("rentAmount", rentAmount);
  386. hs.put("gstAmount", gstAmount);
  387. hs.put("netAmount", netAmount);
  388. hs.put("additionalcharges", additionalcharges);
  389. hs.put("totalAmount", truncatedTotalAmount);
  390. bookingId = insertOrUpdateBookingDetailsJdbc(jdbcTemplate, bookingId, user, hallDetails, startDate,
  391. endDate, days, startingSlot, endingSlot, depositeamount, netAmount, gstAmount,
  392. truncatedTotalAmount, reason, relation, "WAITING", "Booking Slot not Confirmed.", "ONLINE");
  393. } else {
  394. discountAmount = (Double.parseDouble(hallDetails.get("half_day_rent").toString())
  395. * Double.parseDouble(hallDetails.get("cge_discount").toString())) / 100;
  396. hallAmount = Double.parseDouble(hallDetails.get("half_day_rent").toString());
  397. hs.put("discount", hallDetails.get("cgediscount"));
  398. double cleaningCharges = Double
  399. .parseDouble(governmentevents.get("half_day_cleaningcharges").toString());
  400. double PASystem = Double.parseDouble(governmentevents.get("halfdaypasystem").toString());
  401. double EB = Double.parseDouble(governmentevents.get("halfdayebcharges").toString());
  402. additionalcharges = cleaningCharges + PASystem + EB;
  403. rentAmount = hallAmount - discountAmount;
  404. netAmount = rentAmount + additionalcharges;
  405. gstAmount = Math.round(netAmount * Double.parseDouble(hallDetails.get("gst").toString())) / 100.0;
  406. depositAmount = Double.parseDouble(hallDetails.get("deposit_amount").toString()) * daysrange;
  407. totalAmount = netAmount + gstAmount + depositAmount;
  408. truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0;
  409. hs.put("actualhallamount", hallAmount);
  410. hs.put("rentAmount", rentAmount);
  411. hs.put("gstAmount", gstAmount);
  412. hs.put("netAmount", netAmount);
  413. hs.put("additionalcharges", additionalcharges);
  414. hs.put("totalAmount", truncatedTotalAmount);
  415. bookingId = insertOrUpdateBookingDetailsJdbc(jdbcTemplate, bookingId, user, hallDetails, startDate,
  416. endDate, days, startingSlot, endingSlot, depositeamount, netAmount, gstAmount,
  417. truncatedTotalAmount, reason, relation, "WAITING", "Booking Slot not Confirmed.", "ONLINE");
  418. }
  419. } else {
  420. if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE")
  421. || usertype.equals("PUBLIC")) {
  422. discountAmount = (hallAmount * discount) / 100;
  423. hallAmount = hallAmount - discountAmount;
  424. gstAmount = Math.round(hallAmount * Double.parseDouble(hallDetails.get("gst").toString())) / 100.0;
  425. double totalAmount = hallAmount + gstAmount + depositeamount;
  426. double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0;
  427. hs.put("totalAmount", truncatedTotalAmount);
  428. bookingId = insertOrUpdateBookingDetailsJdbc(jdbcTemplate, bookingId, user, hallDetails, startDate,
  429. endDate, days, startingSlot, endingSlot, depositeamount, hallAmount, gstAmount,
  430. truncatedTotalAmount, reason, relation, "WAITING", "Booking Slot not Confirmed.", "ONLINE");
  431. }
  432. }
  433. System.out.println("bookingId...." + bookingId);
  434. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  435. LocalDate start = LocalDate.parse(startDate, formatter);
  436. LocalDate end = LocalDate.parse(endDate, formatter);
  437. int hallId = Integer.parseInt(hallDetails.get("hall_id").toString());
  438. int i = 0;
  439. for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
  440. Map<String, Object> bookingCalendar = null;
  441. List<Map<String, Object>> calList = jdbcTemplate.queryForList(
  442. "SELECT * FROM booking_calendar WHERE bdate = ? AND hall_id = ?", date.toString(), hallId);
  443. if (!calList.isEmpty())
  444. bookingCalendar = calList.get(0);
  445. if (bookingCalendar != null) {
  446. boolean morningSlot = Boolean.TRUE.equals(bookingCalendar.get("morning_slot"));
  447. boolean eveningSlot = Boolean.TRUE.equals(bookingCalendar.get("evening_slot"));
  448. if ((date.equals(start) && startingSlot == 1 && morningSlot)
  449. || (date.equals(start) && startingSlot == 2 && eveningSlot)
  450. || (date.equals(end) && endingSlot == 1 && morningSlot)
  451. || (date.equals(end) && endingSlot == 2 && eveningSlot)) {
  452. return Collections.singletonMap("status", "slotOccupied");
  453. } else if (morningSlot && eveningSlot) {
  454. return Collections.singletonMap("status", "slotOccupied");
  455. } else if (!date.equals(end) && i != 0 && i != Math.round(days - 1)
  456. && (morningSlot || eveningSlot)) {
  457. return Collections.singletonMap("status", "slotOccupied");
  458. } else if (date.equals(end) && endingSlot == 2 && morningSlot && i != 0
  459. && i == Math.round(days - 1)) {
  460. return Collections.singletonMap("status", "slotOccupied");
  461. }
  462. }
  463. i++;
  464. }
  465. List<Map<String, Object>> reasonDocMaster = jdbcTemplate.queryForList(
  466. "SELECT * FROM reason_document_master WHERE reason_id = ?",
  467. Integer.parseInt(formData.get("reasonId").toString()));
  468. List<Map<String, Object>> uploadedDocs = new ArrayList<>();
  469. for (Map<String, Object> rm : reasonDocMaster) {
  470. Map<String, Object> docMap = new HashMap<>();
  471. String fieldName = "";
  472. String value = "";
  473. String fileName = "";
  474. String fileUrl = "";
  475. String filePath = "";
  476. if (Boolean.TRUE.equals(rm.get("add_text_field"))) {
  477. fieldName = rm.get("field_name").toString();
  478. value = formData.get(fieldName).toString();
  479. jdbcTemplate.update(
  480. "INSERT INTO booking_documents (booking_details_booking_id, booking_label, name) VALUES (?, ?, ?)",
  481. Integer.parseInt(bookingId), fieldName, value);
  482. docMap.put("booking_label", fieldName);
  483. docMap.put("name", value);
  484. }
  485. if (Boolean.TRUE.equals(rm.get("add_document_field"))) {
  486. String docFieldName = rm.get("doc_field_name").toString();
  487. MultipartFile file = (MultipartFile) formData.get(docFieldName);
  488. fileName = bookingId + "_" + file.getOriginalFilename();
  489. fileUrl = serverPath + "images/" + reason + "/" + fileName;
  490. filePath = uploadDirectory + "/" + reason + "/" + fileName;
  491. // Create directory if it doesn't exist
  492. File directory = new File(uploadDirectory + "/" + reason);
  493. if (!directory.exists()) {
  494. directory.mkdirs(); // Creates parent directories if needed
  495. }
  496. docMap.put("documentName", file.getOriginalFilename());
  497. docMap.put("documentType", file.getContentType());
  498. docMap.put("bookingDocUrl", fileUrl);
  499. // Save file to disk
  500. try (FileOutputStream fos = new FileOutputStream(filePath)) {
  501. byte[] bytes = file.getBytes();
  502. fos.write(bytes);
  503. } catch (Exception e) {
  504. throw new RuntimeException(e);
  505. }
  506. jdbcTemplate.update(
  507. "INSERT INTO booking_documents (booking_details_booking_id, booking_doc_url, document_name, document_type, booking_label, name) VALUES (?, ?, ?, ?, ?, ?)",
  508. Integer.parseInt(bookingId), fileUrl, file.getOriginalFilename(), file.getContentType(),
  509. fieldName, value);
  510. }
  511. uploadedDocs.add(docMap);
  512. }
  513. hs.put("bookingId", bookingId);
  514. hs.put("hallName", hallDetails.get("hall_name"));
  515. hs.put("NoOfDay", days);
  516. hs.put("startDate", startDate);
  517. hs.put("endDate", endDate);
  518. hs.put("startingSlot", startingSlot);
  519. hs.put("endingSlot", endingSlot);
  520. hs.put("hallAmount", hallAmount);
  521. hs.put("gst", gstAmount);
  522. hs.put("depositAmount", depositeamount);
  523. hs.put("username", user.get("name"));
  524. hs.put("userId", user.get("user_id"));
  525. hs.put("mobileNo", user.get("mobile_no"));
  526. hs.put("userType", user.get("usertype"));
  527. hs.put("reason", reason);
  528. hs.put("bookingId", bookingId);
  529. hs.put("uploadedDocs", uploadedDocs);
  530. }
  531. return hs;
  532. }
  533. private double calcHallAmountJdbc(Map<String, Object> hallDetails, int daysrange, int startPeriod, int endPeriod) {
  534. double fullDayRent = Double.parseDouble(hallDetails.get("full_day_rent").toString());
  535. double halfDayRent = Double.parseDouble(hallDetails.get("half_day_rent").toString());
  536. if (daysrange == 1) {
  537. if (startPeriod == 1 && endPeriod == 2)
  538. return fullDayRent;
  539. else if (startPeriod == 1 && endPeriod == 1)
  540. return halfDayRent;
  541. else if (startPeriod == 2 && endPeriod == 2)
  542. return halfDayRent;
  543. else if (startPeriod == 2 && endPeriod == 1)
  544. return fullDayRent;
  545. } else {
  546. if (startPeriod == 1 && endPeriod == 2)
  547. return fullDayRent * daysrange;
  548. else if (startPeriod == 1 && endPeriod == 1)
  549. return fullDayRent * (daysrange - 1) + halfDayRent;
  550. else if (startPeriod == 2 && endPeriod == 2)
  551. return fullDayRent * (daysrange - 1) + halfDayRent;
  552. else if (startPeriod == 2 && endPeriod == 1)
  553. return fullDayRent * (daysrange - 2) + halfDayRent * 2;
  554. }
  555. return 0;
  556. }
  557. private double calculateDepositAmountJdbc(double numDays, String startPeriod, String endPeriod,
  558. double depositAmount, double HalfDepositAmount) {
  559. double damount = 0;
  560. if (numDays == 1) {
  561. if ("1".equals(startPeriod) && "2".equals(endPeriod))
  562. damount = depositAmount;
  563. else if ("1".equals(startPeriod) && "1".equals(endPeriod))
  564. damount = HalfDepositAmount;
  565. else if ("2".equals(startPeriod) && "2".equals(endPeriod))
  566. damount = HalfDepositAmount;
  567. else
  568. damount = numDays;
  569. } else {
  570. if ("1".equals(startPeriod) && "2".equals(endPeriod))
  571. damount = depositAmount * numDays;
  572. else if ("1".equals(startPeriod) && "1".equals(endPeriod))
  573. damount = depositAmount * (numDays - 1) + HalfDepositAmount;
  574. else if ("2".equals(startPeriod) && "2".equals(endPeriod))
  575. damount = depositAmount * (numDays - 1) + HalfDepositAmount;
  576. else if ("2".equals(startPeriod) && "1".equals(endPeriod))
  577. damount = depositAmount * (numDays - 2) + depositAmount;
  578. else
  579. damount = numDays;
  580. }
  581. return damount;
  582. }
  583. private String insertOrUpdateBookingDetailsJdbc(JdbcTemplate jdbcTemplate, String bookingId,
  584. Map<String, Object> user, Map<String, Object> hallDetails, String startDate, String endDate, double days,
  585. int startingSlot, int endingSlot, double depositAmount, double hallAmount, double gst, double totalAmount,
  586. String reason, String relation, String refundStatus, String comments, String bookingType) {
  587. if (bookingId == null || bookingId.equals("0")) {
  588. // Insert with KeyHolder
  589. KeyHolder keyHolder = new GeneratedKeyHolder();
  590. jdbcTemplate.update(connection -> {
  591. PreparedStatement ps = connection.prepareStatement(
  592. "INSERT INTO booking_details (users_user_id, hall_details_hall_id, start_date, end_date, no_of_days, starting_slot, ending_slot, deposit_amount, hall_amount, gst, amount_received, reason, refund_status, comments, booking_type, relationship, booking_date, schedule_count, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  593. Statement.RETURN_GENERATED_KEYS);
  594. ps.setObject(1, user.get("user_id"));
  595. ps.setObject(2, hallDetails.get("hall_id"));
  596. ps.setString(3, startDate);
  597. ps.setString(4, endDate);
  598. ps.setDouble(5, days);
  599. ps.setInt(6, startingSlot);
  600. ps.setInt(7, endingSlot);
  601. ps.setDouble(8, depositAmount);
  602. ps.setDouble(9, hallAmount);
  603. ps.setDouble(10, gst);
  604. ps.setDouble(11, totalAmount);
  605. ps.setString(12, reason);
  606. ps.setString(13, refundStatus);
  607. ps.setString(14, comments);
  608. ps.setString(15, bookingType);
  609. ps.setString(16, relation);
  610. ps.setString(17, java.time.LocalDate.now().toString());
  611. ps.setInt(18, 0);
  612. ps.setInt(19, 2);
  613. return ps;
  614. }, keyHolder);
  615. Number generatedId = keyHolder.getKey();
  616. return generatedId != null ? generatedId.toString() : null;
  617. } else {
  618. // Update
  619. jdbcTemplate.update(
  620. "UPDATE booking_details SET users_user_id=?, hall_details_hall_id=?, start_date=?, end_date=?, no_of_days=?, starting_slot=?, ending_slot=?, deposit_amount=?, hall_amount=?, gst=?, amount_received=?, reason=?, refund_status=?, comments=?, booking_type=?, relationship=?, booking_date=?, schedule_count=? WHERE booking_id=?",
  621. user.get("user_id"), hallDetails.get("hall_id"), startDate, endDate, days, startingSlot, endingSlot,
  622. depositAmount, hallAmount, gst, totalAmount, reason, refundStatus, comments, bookingType, relation,
  623. java.time.LocalDate.now().toString(), 0, Integer.parseInt(bookingId));
  624. return bookingId;
  625. }
  626. }
  627. public HashMap<String, Object> startPayment(int bookingId) {
  628. HashMap<String, Object> hs = new HashMap<>();
  629. String bookingSql = "SELECT b.amount_received, b.users_user_id, b.hall_details_hall_id, "
  630. + " u.user_id, u.mobile_no, u.email " + " FROM booking_details b "
  631. + " JOIN users u ON b.users_user_id = u.user_id " + " WHERE b.booking_id = ?";
  632. try {
  633. Map<String, Object> data = jdbcTemplate.queryForMap(bookingSql, bookingId);
  634. double amountReceived = (double) data.get("amount_received");
  635. int UserId = (int) data.get("user_id");
  636. long mobileNo = (long) data.get("mobile_no");
  637. String email = (String) data.get("email");
  638. int hallId = (int) data.get("hall_details_hall_id");
  639. String txnId = "CHB" + transactionNumberGenerator.generateTransactionNumber()
  640. + String.format("%05d", UserId);
  641. String totalAmt = String.valueOf(amountReceived);
  642. String insertSql = "INSERT INTO transaction_response (txansaction_id, hall_id, user_id, status_code, booking_id) "
  643. + " VALUES (?, ?, ?, ?, ?)";
  644. jdbcTemplate.update(insertSql, txnId, hallId, String.valueOf(UserId), "temp", bookingId);
  645. String merchantId = paymentConfig.getMerchantId();
  646. String consumerId = String.format("%05d", UserId);
  647. String encryptedToken = getToken(merchantId + "|", txnId + "|", totalAmt + "|", "|", consumerId + "|",
  648. mobileNo + "|", email + "|", "|", "|", "|", "|", "|", "|", "|", "|", "|",
  649. paymentConfig.getEncryptionKey());
  650. hs.put("txansactionId", txnId);
  651. hs.put("token", encryptedToken);
  652. hs.put("amount", totalAmt);
  653. /*
  654. * hs.put("merchantId", merchantId); hs.put("consumerMobileNo", mobileNo);
  655. * hs.put("consumerEmailId", email); hs.put("consumerId", consumerId);
  656. * hs.put("error", false);
  657. */
  658. } catch (EmptyResultDataAccessException | NoSuchAlgorithmException e) {
  659. hs.put("error", true);
  660. hs.put("message", "Invalid booking ID or no user data found. ");
  661. e.printStackTrace();
  662. }
  663. return hs;
  664. }
  665. public String getToken(String merchantId, String txnId, String totalAmt, String accountNo, String consumerId,
  666. String consumerMobileNo, String consumerEmailId, String debitStartDate, String debitEndDate,
  667. String maxAmount, String amountType, String frequency, String cardNumber, String expMonth, String expYear,
  668. String cvvCode, String salt) throws NoSuchAlgorithmException {
  669. String token = merchantId + txnId + totalAmt + accountNo + consumerId + consumerMobileNo + consumerEmailId
  670. + debitStartDate + debitEndDate + maxAmount + amountType + frequency + cardNumber + expMonth + expYear
  671. + cvvCode + salt;
  672. return generateToken(token);
  673. }
  674. public String generateToken(String token) throws NoSuchAlgorithmException {
  675. // System.out.println("Token:-" + token);
  676. MessageDigest md = MessageDigest.getInstance("SHA-512");
  677. md.update(token.getBytes());
  678. byte[] bytes = md.digest();
  679. BigInteger bigInt = new BigInteger(1, bytes);
  680. String encryptedtoken = bigInt.toString(16);
  681. while (encryptedtoken.length() < 128) {
  682. encryptedtoken = "0" + encryptedtoken;
  683. }
  684. // System.out.println("Encryption :- " + encryptedtoken);
  685. return encryptedtoken;
  686. }
  687. public Map<String, Object> checkSlotAvailability(int hallId, String startDate, String endDate, int startingSlot, int endingSlot) {
  688. // Validate slot numbers
  689. if (startingSlot < 1 || startingSlot > 2 || endingSlot < 1 || endingSlot > 2) {
  690. throw new IllegalArgumentException("Slot values must be 1 (morning) or 2 (evening).");
  691. }
  692. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  693. LocalDate start;
  694. LocalDate end;
  695. try {
  696. start = LocalDate.parse(startDate, formatter);
  697. end = LocalDate.parse(endDate, formatter);
  698. } catch (Exception e) {
  699. throw new IllegalArgumentException("Invalid date format. Use yyyy-MM-dd.");
  700. }
  701. if (end.isBefore(start)) {
  702. throw new IllegalArgumentException("End date cannot be before start date.");
  703. }
  704. long days = java.time.temporal.ChronoUnit.DAYS.between(start, end) + 1;
  705. int i = 0;
  706. try {
  707. for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
  708. List<Map<String, Object>> calList = jdbcTemplate.queryForList(
  709. "SELECT * FROM booking_calendar WHERE bdate = ? AND hall_id = ?",
  710. date.toString(), hallId
  711. );
  712. if (!calList.isEmpty()) {
  713. Map<String, Object> bookingCalendar = calList.get(0);
  714. boolean morningSlot = Boolean.TRUE.equals(bookingCalendar.get("morning_slot"));
  715. boolean eveningSlot = Boolean.TRUE.equals(bookingCalendar.get("evening_slot"));
  716. if ((date.equals(start) && startingSlot == 1 && morningSlot)
  717. || (date.equals(start) && startingSlot == 2 && eveningSlot)
  718. || (date.equals(end) && endingSlot == 1 && morningSlot)
  719. || (date.equals(end) && endingSlot == 2 && eveningSlot)) {
  720. return Map.of("status", "slotOccupied");
  721. } else if (morningSlot && eveningSlot) {
  722. return Map.of("status", "slotOccupied");
  723. } else if (!date.equals(end) && i != 0 && i != Math.round(days - 1)
  724. && (morningSlot || eveningSlot)) {
  725. return Map.of("status", "slotOccupied");
  726. } else if (date.equals(end) && endingSlot == 2 && morningSlot && i != 0
  727. && i == Math.round(days - 1)) {
  728. return Map.of("status", "slotOccupied");
  729. }
  730. }
  731. i++;
  732. }
  733. } catch (DataAccessException e) {
  734. e.printStackTrace();
  735. throw new RuntimeException("Database error occurred while checking slot availability.");
  736. }
  737. return Map.of("status", "slotAvailable");
  738. }
  739. }