Browse Source

GCC Mobile Service updated code initial commit

master
KaNi-04 4 months ago
commit
cf9f7c157d
  1. 33
      .gitignore
  2. 259
      mvnw
  3. 149
      mvnw.cmd
  4. 139
      pom.xml
  5. BIN
      src/.DS_Store
  6. BIN
      src/main/.DS_Store
  7. BIN
      src/main/java/.DS_Store
  8. BIN
      src/main/java/in/.DS_Store
  9. BIN
      src/main/java/in/gov/.DS_Store
  10. BIN
      src/main/java/in/gov/chennaicorporation/.DS_Store
  11. BIN
      src/main/java/in/gov/chennaicorporation/mobileservice/.DS_Store
  12. 78
      src/main/java/in/gov/chennaicorporation/mobileservice/ImageUrlValidator.java
  13. 18
      src/main/java/in/gov/chennaicorporation/mobileservice/MobileServiceApplication.java
  14. 28
      src/main/java/in/gov/chennaicorporation/mobileservice/UpdateResponse.java
  15. 162
      src/main/java/in/gov/chennaicorporation/mobileservice/abandonedVehicle/controller/VehicleController.java
  16. 829
      src/main/java/in/gov/chennaicorporation/mobileservice/abandonedVehicle/service/VehicleService.java
  17. 95
      src/main/java/in/gov/chennaicorporation/mobileservice/boatService/controller/BoatController.java
  18. 513
      src/main/java/in/gov/chennaicorporation/mobileservice/boatService/service/BoatService.java
  19. 147
      src/main/java/in/gov/chennaicorporation/mobileservice/buildingDemolition/controller/BuildingDemolitionController.java
  20. 641
      src/main/java/in/gov/chennaicorporation/mobileservice/buildingDemolition/service/BuildingDemolitionActivity.java
  21. 92
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController.java
  22. 115
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController_renovation.java
  23. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java
  24. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java
  25. 507
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterActivity.java
  26. 879
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterRenovationActivity.java
  27. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java
  28. 42
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/Scheduler/C_D_WasteScheduler.java
  29. 406
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java
  30. 69
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java
  31. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/package-info.java
  32. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java
  33. 2123
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java
  34. 1333
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java
  35. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/package-info.java
  36. 64
      src/main/java/in/gov/chennaicorporation/mobileservice/component/ApiLoggingFilter.java
  37. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java
  38. 22
      src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java
  39. 687
      src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java
  40. 20
      src/main/java/in/gov/chennaicorporation/mobileservice/configuration/JacksonConfiguration.java
  41. 26
      src/main/java/in/gov/chennaicorporation/mobileservice/configuration/WebConfig.java
  42. 191
      src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/controller/APIController.java
  43. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/controller/package-info.java
  44. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/package-info.java
  45. 1624
      src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/service/GuidelinesService.java
  46. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/service/package-info.java
  47. 205
      src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIOfficialController.java
  48. 22
      src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIPetController.java
  49. 78
      src/main/java/in/gov/chennaicorporation/mobileservice/controller/FileController.java
  50. 64
      src/main/java/in/gov/chennaicorporation/mobileservice/controller/MainController.java
  51. 114
      src/main/java/in/gov/chennaicorporation/mobileservice/controller/PdfTemplateController.java
  52. 111
      src/main/java/in/gov/chennaicorporation/mobileservice/disposalPoint/controller/DisposalPointController.java
  53. 773
      src/main/java/in/gov/chennaicorporation/mobileservice/disposalPoint/service/DisposalPointService.java
  54. 187
      src/main/java/in/gov/chennaicorporation/mobileservice/election/controller/ElectionApiController.java
  55. 366
      src/main/java/in/gov/chennaicorporation/mobileservice/election/service/ElectionService.java
  56. 5
      src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/erppostdataController.java
  57. 191
      src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/erppostdataService.java
  58. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/package-info.java
  59. 49
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/Scheduler/DailyRequestScheduler.java
  60. 163
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/DistributionController.java
  61. 144
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/DriverController.java
  62. 408
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java
  63. 1691
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/DistributionService.java
  64. 750
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/DriverService.java
  65. 3804
      src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java
  66. 143
      src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java
  67. 648
      src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java
  68. 98
      src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java
  69. 579
      src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java
  70. BIN
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/.DS_Store
  71. BIN
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Controller/.DS_Store
  72. 172
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Controller/DomesticWasteController.java
  73. 28
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Scheduler/DomesticWasteScheduler.java
  74. BIN
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Service/.DS_Store
  75. 797
      src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Service/DomesticWasteService.java
  76. 157
      src/main/java/in/gov/chennaicorporation/mobileservice/gccHealthCamp/controller/HealthCampController.java
  77. 385
      src/main/java/in/gov/chennaicorporation/mobileservice/gccHealthCamp/service/HealthCampService.java
  78. 169
      src/main/java/in/gov/chennaicorporation/mobileservice/gccHomeLessSurveyNew/Controller/HomeLessSurveyApiController.java
  79. 974
      src/main/java/in/gov/chennaicorporation/mobileservice/gccHomeLessSurveyNew/Service/HomeLessSurveyService.java
  80. 48
      src/main/java/in/gov/chennaicorporation/mobileservice/gccMobileMenus/controller/MobileMenusApiController.java
  81. 88
      src/main/java/in/gov/chennaicorporation/mobileservice/gccMobileMenus/service/MobileMenusService.java
  82. 80
      src/main/java/in/gov/chennaicorporation/mobileservice/gccSCP/controller/SCPController.java
  83. 461
      src/main/java/in/gov/chennaicorporation/mobileservice/gccSCP/service/SCPService.java
  84. 72
      src/main/java/in/gov/chennaicorporation/mobileservice/gccSpecialVehicle/controller/VehicleController.java
  85. 494
      src/main/java/in/gov/chennaicorporation/mobileservice/gccSpecialVehicle/service/VehicleService.java
  86. 313
      src/main/java/in/gov/chennaicorporation/mobileservice/gccTenements/controller/TenementController.java
  87. 2785
      src/main/java/in/gov/chennaicorporation/mobileservice/gccTenements/service/TenementService.java
  88. 181
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIActivityController.java
  89. 153
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIMassActivityController.java
  90. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/package-info.java
  91. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/package-info.java
  92. 1896
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java
  93. 34
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/DateTimeUtil.java
  94. 712
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/MassClearn.java
  95. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/package-info.java
  96. 149
      src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/EducationController.java
  97. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java
  98. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java
  99. 1127
      src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java
  100. 1
      src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java

33
.gitignore

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

259
mvnw

@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
mvnw.cmd

@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

139
pom.xml

@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>in.gov.chennaicorporation</groupId>
<artifactId>mobileservice</artifactId>
<version>1</version>
<name>Mobile Service</name>
<description>Common Mobile Service</description>
<!-- Repositories for Bytecode and Central -->
<repositories>
<repository>
<id>central</id>
<url>https://repo1.maven.org/maven2/</url>
</repository>
<repository>
<id>bytedeco</id>
<url>https://raw.githubusercontent.com/bytedeco/javacpp-presets/master/artifacts/</url>
</repository>
</repositories>
<properties>
<java.version>17</java.version>
<bootstrap.version>4.0.0-2</bootstrap.version>
<webjars-locator.version>0.30</webjars-locator.version>
<lombok.version>1.18.2</lombok.version>
</properties>
<dependencies>
<!-- Spring Boot Starters -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
<!-- Oracle JDBC Driver -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Jakarta Persistence API -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency>
<!-- Spring Boot Test Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot DevTools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.5.7</version> <!-- Use the latest version available -->
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>opencv-platform</artifactId>
<version>4.5.5-1.5.7</version> <!-- Use the latest version available -->
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacpp</artifactId>
<version>1.5.7</version> <!-- Use the latest version available -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version> <!-- or the latest version -->
</dependency>
<!-- For HTML to PDF conversion -->
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-java2d</artifactId>
<version>1.0.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

BIN
src/.DS_Store

BIN
src/main/.DS_Store

BIN
src/main/java/.DS_Store

BIN
src/main/java/in/.DS_Store

BIN
src/main/java/in/gov/.DS_Store

BIN
src/main/java/in/gov/chennaicorporation/.DS_Store

BIN
src/main/java/in/gov/chennaicorporation/mobileservice/.DS_Store

78
src/main/java/in/gov/chennaicorporation/mobileservice/ImageUrlValidator.java

@ -0,0 +1,78 @@
package in.gov.chennaicorporation.mobileservice;
import java.sql.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.HttpURLConnection;
import java.net.URL;
@RequestMapping("/gccofficialapp/api/imgval/")
@RestController("imgval")
public class ImageUrlValidator {
// JDBC connection details
private static final String DB_URL = "jdbc:mysql://localhost:3306/cmdashboard";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "";
@GetMapping("/imagecheck")
public String imagecheck(){
String query = "SELECT data_id, abs_est_number, regionname, typeofwork, imageurl, zonename, wardname FROM tbl_cmdashboard"
+ " WHERE abs_est_number LIKE '%2024-25%'";
String updateQuery = "UPDATE tbl_cmdashboard SET image_status = ? WHERE data_id = ?";
try (
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);
PreparedStatement updateStmt = conn.prepareStatement(updateQuery);
ResultSet rs = stmt.executeQuery()
) {
while (rs.next()) {
int dataId = rs.getInt("data_id");
String estNumber = rs.getString("abs_est_number");
String region = rs.getString("regionname");
String typeOfWork = rs.getString("typeofwork");
String imageUrl = rs.getString("imageurl");
String zone = rs.getString("zonename");
String ward = rs.getString("wardname");
boolean isValid = isImageUrlValid(imageUrl);
updateStmt.setBoolean(1, isValid ? true : false);
updateStmt.setInt(2, dataId);
updateStmt.executeUpdate();
System.out.printf("ID: %d | Estimate: %s | URL: %s | Valid: %s%n",
dataId, estNumber, imageUrl, isValid ? "✅" : "❌");
}
System.out.println("All image statuses updated.");
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
// Checks if the image URL is valid and accessible
private static boolean isImageUrlValid(String imageUrl) {
if (imageUrl == null || imageUrl.isBlank()) return false;
try {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
int statusCode = conn.getResponseCode();
String contentType = conn.getContentType();
return statusCode == 200 && contentType != null && contentType.startsWith("image/");
} catch (Exception e) {
return false;
}
}
}

18
src/main/java/in/gov/chennaicorporation/mobileservice/MobileServiceApplication.java

@ -0,0 +1,18 @@
package in.gov.chennaicorporation.mobileservice;
import java.util.TimeZone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MobileServiceApplication {
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata"));
SpringApplication.run(MobileServiceApplication.class, args);
}
}

28
src/main/java/in/gov/chennaicorporation/mobileservice/UpdateResponse.java

@ -0,0 +1,28 @@
package in.gov.chennaicorporation.mobileservice;
public class UpdateResponse {
private int status;
private String message;
public UpdateResponse(int status, String message) {
this.status = status;
this.message = message;
}
// Getters and Setters
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

162
src/main/java/in/gov/chennaicorporation/mobileservice/abandonedVehicle/controller/VehicleController.java

@ -0,0 +1,162 @@
package in.gov.chennaicorporation.mobileservice.abandonedVehicle.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
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.abandonedVehicle.service.VehicleService;
@RequestMapping("/gccofficialapp/api/abandonedvehicle")
@RestController("gccofficialappabandonedvehicle")
public class VehicleController {
@Autowired
VehicleService vehicleService;
@PostMapping("/saveIdentfiedVehicle")
public List<?> saveIdentfiedVehicle(
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "frontFile", required = true) MultipartFile frontFile,
@RequestParam(value = "backFile", required = true) MultipartFile backFile,
@RequestParam(value = "sideFile", required = true) MultipartFile sideFile) {
return vehicleService.saveIdentfiedVehicle(
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
frontFile,
backFile,
sideFile);
}
@GetMapping(value = "/getRemovePendingList")
public List<?> getRemovePendingList(
@RequestParam(value = "loginId", required = true) String loginId) {
return vehicleService.getRemovePendingList(loginId);
}
@PostMapping("/saveRemovedVehicle")
public List<?> saveRemovedVehicle(
@RequestParam(value = "vid", required = true) String vid,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "address", required = false) String address,
@RequestParam(value = "removeFile", required = true) MultipartFile removeFile) {
return vehicleService.saveRemovedVehicle(
vid,
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
address,
removeFile);
}
@GetMapping(value = "/getYardPendingList")
public List<?> getYardPendingList(
@RequestParam(value = "loginId", required = true) String loginId) {
return vehicleService.getYardPendingList(loginId);
}
@PostMapping("/saveYardVehicle")
public List<?> saveYardVehicle(
@RequestParam(value = "vid", required = true) String vid,
@RequestParam(value = "yardid", required = true) String yardid,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "address", required = false) String address,
@RequestParam(value = "removeFile", required = true) MultipartFile removeFile) {
return vehicleService.saveYardVehicle(
vid,
yardid,
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
address,
removeFile);
}
// Reports
@GetMapping(value = "/getZoneSummary")
public List<?> getZoneSummary(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate) {
return vehicleService.getZoneSummary(fromDate, toDate);
}
@GetMapping(value = "/getWardSummary")
public List<?> getWardSummary(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate,
@RequestParam(value = "zone", required = true) String zone) {
return vehicleService.getWardSummary(fromDate, toDate, zone);
}
@GetMapping(value = "/getVehicleSummary")
public List<?> getVehicleSummary(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate,
@RequestParam(value = "ward", required = true) String ward) {
return vehicleService.getVehicleSummary(fromDate, toDate, ward);
}
// New
@GetMapping(value = "/getZoneSummary_")
public List<?> getZoneSummary_(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate) {
return vehicleService.getZoneSummary_(fromDate, toDate);
}
@GetMapping(value = "/getWardSummary_")
public List<?> getWardSummary_(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate,
@RequestParam(value = "zone", required = true) String zone) {
return vehicleService.getWardSummary_(fromDate, toDate, zone);
}
@GetMapping(value = "/getVehicleSummary_")
public List<?> getVehicleSummary_(
@RequestParam(value = "fromDate", required = true) String fromDate,
@RequestParam(value = "toDate", required = true) String toDate,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "filterType", required = true) String filterType) {
// filterType : IDENTIFIED | REMOVED | YARD | REMOVED_PENDING | YARD_PENDING
return vehicleService.getVehicleSummary_(fromDate, toDate, ward, filterType);
}
}

829
src/main/java/in/gov/chennaicorporation/mobileservice/abandonedVehicle/service/VehicleService.java

@ -0,0 +1,829 @@
package in.gov.chennaicorporation.mobileservice.abandonedVehicle.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.PreparedStatement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service("abandonedVehicleService")
public class VehicleService {
private JdbcTemplate jdbcTemplate;
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("mysqlGccAbandonedVehicleSource") DataSource AbandonedVehicleDataSource) {
this.jdbcTemplate = new JdbcTemplate(AbandonedVehicleDataSource);
}
@Autowired
public VehicleService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, String id, MultipartFile file, String filetype) {
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("abandonedvehicle_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + filetype + "/" + 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();
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 + filetype + "/" + year + "/" + month + "/" + date + "/"
+ fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
if (filetype.equalsIgnoreCase("image")) {
// 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);
} else {
// Write the bytes to the file
Files.write(path, bytes);
}
// Get current date & time
LocalDateTime now = LocalDateTime.now();
// Format date-time (optional)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println("Date: " + now.format(formatter));
System.out.println("Activity: " + serviceFolderName);
System.out.println("File Type: " + filetype);
System.out.println("File Upload Path: " + filePath);
System.out.println("File Path: " + filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save file " + file.getOriginalFilename());
return "error";
}
}
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<Map<String, Object>> results = jdbcTemplate.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
}
@Transactional
public List<Map<String, Object>> saveIdentfiedVehicle(
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
MultipartFile frontFile,
MultipartFile backFile,
MultipartFile sideFile) {
String filetxt = inby;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
// for front Image
String action = "front";
String frontimg = fileUpload(action, filetxt, frontFile, filetype);
if ("error".equalsIgnoreCase(frontimg)) {
response.put("status", "error");
response.put("message", "Front image insert failed.");
result.add(response);
return result;
}
// for side Image
action = "side";
String sideimg = fileUpload(action, filetxt, sideFile, filetype);
if ("error".equalsIgnoreCase(sideimg)) {
response.put("status", "error");
response.put("message", "Side image insert failed.");
result.add(response);
return result;
}
// for back Image
action = "back";
String backimg = fileUpload(action, filetxt, backFile, filetype);
if ("error".equalsIgnoreCase(backimg)) {
response.put("status", "error");
response.put("message", "Back image insert failed.");
result.add(response);
return result;
}
String insertSqltxt = "INSERT INTO `vehicle_identified` (`zone`, `ward`, `street_name`, `streetid`, `latitude`, `longitude`, `inby`, `front_img`,`side_img`,`back_img`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "vid" });
int i = 1;
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
ps.setString(i++, frontimg);
ps.setString(i++, sideimg);
ps.setString(i++, backimg);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Abandoned Vehicle", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", "Abandoned Vehicle data inserted successfully.");
} else {
response.put("Abandoned Vehicle", action + " error!");
response.put("status", "error");
response.put("message", "Abandoned Vehicle data insert failed.");
}
result.add(response);
return result;
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getRemovePendingList(String userid) {
String ward = getWardByLoginId(userid, "ae");
String sql = "SELECT *, "
+ "date_format(cdate,'%d-%m-%Y %l:%i %p') as created_date,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `front_img`) AS front_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `side_img`) AS side_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `back_img`) AS back_img_url "
+ "FROM vehicle_identified "
+ "WHERE isactive = 1 AND isdelete = 0 AND status_id = 1 "
+ "AND `ward` = ? "
+ "ORDER BY `ward`";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Pending List");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveRemovedVehicle(
String vid,
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
String address,
MultipartFile removeFile) {
String filetxt = inby;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
// for front Image
String action = "Remove";
String removeimg = fileUpload(action, filetxt, removeFile, filetype);
if ("error".equalsIgnoreCase(removeimg)) {
response.put("status", "error");
response.put("message", "Remove image insert failed.");
result.add(response);
return result;
}
String insertSqltxt = "INSERT INTO `vehicle_removed` (`vid`, `zone`, `ward`, `street_name`, `streetid`, `latitude`, `longitude`, `inby`, `remove_img`,`address`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "vrid" });
int i = 1;
ps.setString(i++, vid);
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
ps.setString(i++, removeimg);
ps.setString(i++, address);
return ps;
}, keyHolder);
if (affectedRows > 0) {
// Update on vehicle status
String updateSQL = "UPDATE `vehicle_identified` SET status_id=2 WHERE vid=?";
jdbcTemplate.update(updateSQL, vid);
int lastInsertId = keyHolder.getKey().intValue();
response.put("Abandoned Vehicle", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", "Abandoned Vehicle removed data inserted successfully.");
} else {
response.put("Abandoned Vehicle", action + " error!");
response.put("status", "error");
response.put("message", "Abandoned Vehicle removed data insert failed.");
}
result.add(response);
return result;
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getYardPendingList(String userid) {
String ward = getWardByLoginId(userid, "ae");
String sql = "SELECT *, "
+ "date_format(cdate,'%d-%m-%Y %l:%i %p') as created_date,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `front_img`) AS front_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `side_img`) AS side_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `back_img`) AS back_img_url "
+ "FROM vehicle_identified "
+ "WHERE isactive = 1 AND isdelete = 0 AND status_id = 2 "
+ "AND `ward` = ? "
+ "ORDER BY `ward`";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Pending List");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveYardVehicle(
String vid,
String yardid,
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
String address,
MultipartFile yardFile) {
String filetxt = inby;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
// for front Image
String action = "Yard";
String yardimg = fileUpload(action, filetxt, yardFile, filetype);
if ("error".equalsIgnoreCase(yardimg)) {
response.put("status", "error");
response.put("message", "Yard drop image insert failed.");
result.add(response);
return result;
}
String insertSqltxt = "INSERT INTO `vehicle_yard` (`vid`, `zone`, `ward`, `street_name`, `streetid`, `latitude`, `longitude`, `inby`, `drop_img`, `yard`,`address`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "vyid" });
int i = 1;
ps.setString(i++, vid);
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
ps.setString(i++, yardimg);
ps.setString(i++, yardid);
ps.setString(i++, address);
return ps;
}, keyHolder);
if (affectedRows > 0) {
// Update on vehicle status
String updateSQL = "UPDATE `vehicle_identified` SET status_id=3 WHERE vid=?";
jdbcTemplate.update(updateSQL, vid);
int lastInsertId = keyHolder.getKey().intValue();
response.put("Abandoned Vehicle", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", "Yard drop data inserted successfully.");
} else {
response.put("Abandoned Vehicle", action + " error!");
response.put("status", "error");
response.put("message", "Yard drop data insert failed.");
}
result.add(response);
return result;
}
// Reports OLD
@Transactional(readOnly = true)
public List<Map<String, Object>> getZoneSummary(String fromDate, String toDate) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
String sql = "SELECT zone, COUNT(vid) AS total " +
"FROM vehicle_identified " +
"WHERE isactive = 1 AND isdelete = 0 " +
"AND cdate >= ? " +
"AND cdate < ? " +
"GROUP BY `zone` ORDER BY `zone` ";
String fromDateTime = fromDate + " 00:00:00";
String toDateTime = toDate + " 00:00:00";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, fromDateTime, toDateTime);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Zone List.");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getWardSummary(String fromDate, String toDate, String zone) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
String sql = "SELECT ward, COUNT(vid) AS total " +
"FROM vehicle_identified " +
"WHERE isactive = 1 AND isdelete = 0 " +
"AND cdate >= ? " +
"AND cdate < ? " +
"AND `zone` = ? " +
"GROUP BY `ward` ORDER BY `ward` ";
String fromDateTime = fromDate + " 00:00:00";
String toDateTime = toDate + " 00:00:00";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, fromDateTime, toDateTime, zone);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Ward List.");
response.put("data", results);
return Collections.singletonList(response);
}
// Reports
@Transactional(readOnly = true)
public List<Map<String, Object>> getZoneSummary_(String fromDate, String toDate) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
String sql = "SELECT IFNULL(zone, 'TOTAL') AS zone, " +
"COUNT(*) AS total_identified, " +
"SUM(CASE WHEN status_id = 2 THEN 1 ELSE 0 END) AS total_removed, " +
"SUM(CASE WHEN status_id = 3 THEN 1 ELSE 0 END) AS total_yard, " +
"SUM(CASE WHEN status_id = 1 THEN 1 ELSE 0 END) AS removed_pending, " +
"SUM(CASE WHEN status_id = 2 THEN 1 ELSE 0 END) AS yard_pending " +
"FROM vehicle_identified " +
"WHERE isactive = 1 " +
"AND isdelete = 0 " +
"AND cdate >= ? " +
"AND cdate < ? " +
"GROUP BY zone WITH ROLLUP";
String fromDateTime = fromDate + " 00:00:00";
String toDateTime = toDate + " 00:00:00";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, fromDateTime, toDateTime);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Zone List.");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getWardSummary_(String fromDate, String toDate, String zone) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
String sql = "SELECT IFNULL(ward, 'TOTAL') AS ward, " +
"COUNT(*) AS total_identified, " +
"SUM(CASE WHEN status_id = 2 THEN 1 ELSE 0 END) AS total_removed, " +
"SUM(CASE WHEN status_id = 3 THEN 1 ELSE 0 END) AS total_yard, " +
"SUM(CASE WHEN status_id = 1 THEN 1 ELSE 0 END) AS removed_pending, " +
"SUM(CASE WHEN status_id = 2 THEN 1 ELSE 0 END) AS yard_pending " +
"FROM vehicle_identified " +
"WHERE isactive = 1 " +
"AND isdelete = 0 " +
"AND cdate >= ? " +
"AND cdate < ? " +
"AND `zone` = ? " +
"GROUP BY ward WITH ROLLUP";
String fromDateTime = fromDate + " 00:00:00";
String toDateTime = toDate + " 00:00:00";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, fromDateTime, toDateTime, zone);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Ward List.");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getVehicleSummary(String fromDate, String toDate, String ward) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
String sql = "SELECT *, "
+ "date_format(cdate,'%d-%m-%Y %l:%i %p') as created_date,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `front_img`) AS front_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `side_img`) AS side_img_url,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `back_img`) AS back_img_url "
+ "FROM vehicle_identified " +
"WHERE isactive = 1 AND isdelete = 0 " +
"AND cdate >= ? " +
"AND cdate < ? " +
"AND `ward` = ? " +
"ORDER BY `ward` ";
String fromDateTime = fromDate + " 00:00:00";
String toDateTime = toDate + " 00:00:00";
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, fromDateTime, toDateTime, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Vehicle List.");
response.put("data", results);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getVehicleSummary_(
String fromDate,
String toDate,
String ward,
String filterType) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 1);
StringBuilder sql = new StringBuilder(
"SELECT vi.*, " +
"DATE_FORMAT(vi.cdate,'%d-%m-%Y %l:%i %p') AS created_date, " +
"CONCAT(?, vi.front_img) AS front_img_url, " +
"CONCAT(?, vi.side_img) AS side_img_url, " +
"CONCAT(?, vi.back_img) AS back_img_url ");
// 🔹 Conditional extra columns
if ("REMOVED".equals(filterType) || "YARD_PENDING".equals(filterType)) {
sql.append(
", DATE_FORMAT(vr.cdate,'%d-%m-%Y %l:%i %p') AS removed_date, " +
"CONCAT(?, vr.remove_img) AS remove_img_url ");
}
if ("YARD".equals(filterType)) {
sql.append(
", DATE_FORMAT(vy.cdate,'%d-%m-%Y %l:%i %p') AS yard_date, " +
"vy.yard, " +
"CONCAT(?, vy.drop_img) AS drop_img_url ");
}
sql.append(" FROM vehicle_identified vi ");
// 🔹 Conditional JOINs
if ("REMOVED".equals(filterType) || "YARD_PENDING".equals(filterType)) {
sql.append(
" LEFT JOIN vehicle_removed vr " +
" ON vr.vid = vi.vid ");
}
if ("YARD".equals(filterType)) {
sql.append(
" LEFT JOIN vehicle_yard vy " +
" ON vy.vid = vi.vid ");
}
sql.append(
" WHERE vi.isactive = 1 AND vi.isdelete = 0 " +
" AND vi.cdate >= ? " +
" AND vi.cdate < ? " +
" AND vi.ward = ? ");
// 🔹 Status filter
if (filterType != null) {
switch (filterType) {
case "IDENTIFIED":
case "REMOVED_PENDING":
sql.append(" AND vi.status_id = 1 ");
break;
case "REMOVED":
case "YARD_PENDING":
sql.append(" AND vi.status_id = 2 ");
break;
case "YARD":
sql.append(" AND vi.status_id = 3 ");
break;
}
}
sql.append(" ORDER BY vi.cdate DESC ");
// 🔹 Parameters
List<Object> params = new ArrayList<>();
// base images
params.add(fileBaseUrl + "/gccofficialapp/files");
params.add(fileBaseUrl + "/gccofficialapp/files");
params.add(fileBaseUrl + "/gccofficialapp/files");
// removed images
if ("REMOVED".equals(filterType) || "YARD_PENDING".equals(filterType)) {
params.add(fileBaseUrl + "/gccofficialapp/files");
}
// yard images
if ("YARD".equals(filterType)) {
params.add(fileBaseUrl + "/gccofficialapp/files");
}
params.add(fromDate + " 00:00:00");
params.add(toDate + " 00:00:00");
params.add(ward);
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql.toString(), params.toArray());
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Vehicle List");
response.put("data", results);
return Collections.singletonList(response);
}
/*
* @Transactional(readOnly = true)
* public List<Map<String, Object>> getVehicleSummary_(
* String fromDate,
* String toDate,
* String ward,
* String filterType
* ) {
*
* fromDate = convertDateFormat(fromDate, 0);
* toDate = convertDateFormat(toDate, 1);
*
* StringBuilder sql = new StringBuilder(
* "SELECT *, " +
* "DATE_FORMAT(cdate,'%d-%m-%Y %l:%i %p') AS created_date, " +
* "CONCAT(?, front_img) AS front_img_url, " +
* "CONCAT(?, side_img) AS side_img_url, " +
* "CONCAT(?, back_img) AS back_img_url " +
* "FROM vehicle_identified " +
* "WHERE isactive = 1 AND isdelete = 0 " +
* "AND cdate >= ? " +
* "AND cdate < ? " +
* "AND ward = ? "
* );
*
* List<Object> params = new ArrayList<>();
* params.add(fileBaseUrl + "/gccofficialapp/files");
* params.add(fileBaseUrl + "/gccofficialapp/files");
* params.add(fileBaseUrl + "/gccofficialapp/files");
*
* params.add(fromDate + " 00:00:00");
* params.add(toDate + " 00:00:00");
* params.add(ward);
*
* // 🔹 Status filter based on click
* if (filterType != null) {
* switch (filterType) {
* case "IDENTIFIED":
* case "REMOVED_PENDING":
* sql.append(" AND status_id = 1 ");
* break;
*
* case "REMOVED":
* case "YARD_PENDING":
* sql.append(" AND status_id = 2 ");
* break;
*
* case "YARD":
* sql.append(" AND status_id = 3 ");
* break;
* }
* }
*
* sql.append(" ORDER BY cdate DESC ");
*
* List<Map<String, Object>> results =
* jdbcTemplate.queryForList(sql.toString(), params.toArray());
*
* Map<String, Object> response = new HashMap<>();
* response.put("status", "Success");
* response.put("message", "Vehicle List");
* response.put("data", results);
*
* return Collections.singletonList(response);
* }
*/
}

95
src/main/java/in/gov/chennaicorporation/mobileservice/boatService/controller/BoatController.java

@ -0,0 +1,95 @@
package in.gov.chennaicorporation.mobileservice.boatService.controller;
import java.util.List;
import java.util.Map;
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.RequestBody;
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.boatService.service.BoatService;
@RequestMapping("/gccofficialapp/api/boat/pos")
@RestController("apiBoatPOSRest")
public class BoatController {
@Autowired
private BoatService boatService;
@PostMapping("/devicelogin")
public List<?> devicelogin(
@RequestParam(value = "device_username", required = true) String device_username,
@RequestParam(value = "device_password", required = true) String device_password
) {
return boatService.devicelogin(device_username,device_password);
}
@PostMapping("/getuserinfo")
public List<?> getuserinfo(
@RequestParam(value = "loginId", required = true) String loginId
) {
return boatService.getuserinfo(loginId);
}
@GetMapping("/getBoatServiceLocation")
public List<?> getBoatServiceLocation(
@RequestParam(value = "lid", required = true) String lid
) {
return boatService.getBoatServiceLocation(lid);
}
@GetMapping("/getBoatConfigInfo")
public List<?> getBoatConfigInfo(
@RequestParam(value = "lid", required = true) String lid
) {
return boatService.getBoatConfigInfo(lid);
}
@PostMapping(value="/generateBoatTicketPOS")
public List<?> generateBoatTicketPOS(@RequestParam MultiValueMap<String, String> formData,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "lid", required = false) String lid,
@RequestParam(value = "bcid", required = false) String bcid,
@RequestParam(value = "boat_name", required = false) String boat_name,
@RequestParam(value = "visitorName", required = false) String visitorName,
@RequestParam(value = "visitorPhone", required = false) String visitorPhone,
@RequestParam(value = "adult_count", required = false) String adult_count,
@RequestParam(value = "child_count", required = false) String child_count,
@RequestParam(value = "adult_price", required = false) String adult_price,
@RequestParam(value = "child_price", required = false) String child_price,
@RequestParam(value = "raid_time", required = false) String raid_time,
@RequestParam(value = "total_ticket", required = false) String total_ticket,
@RequestParam(value = "ticket_amount", required = false) String ticket_amount,
@RequestParam(value = "tid", required = false) String tid,
@RequestParam(value = "mid", required = false) String mid,
@RequestParam(value = "serialNumber", required = false) String serialNumber
) {
return boatService.generateBoatTicketPOS(formData, loginId, lid, bcid, boat_name, visitorName,
visitorPhone, adult_count, child_count, adult_price, child_price, raid_time,total_ticket,ticket_amount, tid, mid, serialNumber);
}
@GetMapping("/getTicketData")
public List<?> getTicketData(
@RequestParam MultiValueMap<String, String> formData,
@RequestParam(value = "orderid", required = false) String orderid,
@RequestParam(value = "ticketid", required = false) String ticketid
) {
return boatService.getTicketData(formData, orderid, ticketid);
}
@PostMapping("/storeBankTransaction")
public List<?> storeBankTransaction(@RequestBody Map<String, Object> transactionData) {
return boatService.storeBankTransaction(transactionData);
}
@PostMapping("/storeFailedBankTransaction")
public List<?> storeFailedBankTransaction(@RequestBody Map<String, Object> transactionData) {
return boatService.storeFailedBankTransaction(transactionData);
}
}

513
src/main/java/in/gov/chennaicorporation/mobileservice/boatService/service/BoatService.java

@ -0,0 +1,513 @@
package in.gov.chennaicorporation.mobileservice.boatService.service;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.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;
@Service
public class BoatService {
private JdbcTemplate jdbcTemplate;
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("mysqlBoatSource") DataSource BoatDataSource) {
this.jdbcTemplate = new JdbcTemplate(BoatDataSource);
}
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 List<Map<String, Object>> devicelogin(String device_username, String device_password) {
String sql = "SELECT `uid`, `lid`, `device_username` FROM `device_user` "
+ "WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`device_username` = ? AND `device_password` = ?) "
+ "LIMIT 1";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,device_username, device_password);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Login Info");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getuserinfo(String loginId) {
String sql = "SELECT `userid`, `lid`, `device_username` FROM `device_user` "
+ "WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`userid` = ? ) "
+ "LIMIT 1";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,loginId);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Login Info");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getBoatServiceLocation(String lid) {
String sql = "SELECT `lid`, `name`, `zone`, `ward`, `incharge_name`, `incharge_mobile`, `open_time`, `close_time` "
+ " FROM `service_location` "
+ "WHERE "
+ "`isactive` = 1 "
+ " AND `isdelete` = 0 "
+ " AND `lid` = ?";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,lid);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Boat Service Loaction");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getBoatConfigInfo(String lid) {
String sql = "SELECT `bcid`, `name`, `type`, `noofseats`, "
+ "`adult_price`, `child_price`, "
+ "`raid_time`, `holiday`, "
+ "`lid` "
+ "FROM `boat_config` "
+ "WHERE "
+ "`isactive` = 1 "
+ "AND `isdelete` = 0 "
+ "AND `lid` = ?";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,lid);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Boat details");
response.put("data", result);
return Collections.singletonList(response);
}
@Transactional
public void updateTicketNo(int ticketId, String lid) {
String sql = """
SELECT COALESCE(MAX(ticketno), 0) + 1
FROM tickets
WHERE lid = ?
AND DATE(ticketdatetime) = CURDATE()
""";
Integer nextTicketNo = jdbcTemplate.queryForObject(sql, Integer.class, lid);
String updateSql = """
UPDATE tickets
SET ticketno = ?
WHERE ticketid = ?
""";
jdbcTemplate.update(updateSql, nextTicketNo, ticketId);
}
@Transactional
public List<Map<String, Object>> generateBoatTicketPOS(
MultiValueMap<String, String> formData,
String loginId,
String lid,
String bcid,
String boat_name,
String visitorName,
String visitorPhone,
String adult_count,
String child_count,
String adult_price,
String child_price,
String raid_time,
String total_ticket,
String ticket_amount,
String tid,
String mid,
String serialNumber) {
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
String orderid = generateRandomString();
String sqlQuery = "INSERT INTO `tickets`(`lid`, `bcid`, `boat_name`, `visitorName`, "
+ "`visitorPhone`, `adult_count`, `child_count`, "
+ "`adult_price`, `child_price`, `raid_time`, `total_ticket`,`ticket_amount`,`orderid`,"
+ "`tid`, `mid`, `serialNumber`,`ticket_by`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"ticketid"});
int i = 1;
ps.setString(i++, lid);
ps.setString(i++, bcid);
ps.setString(i++, boat_name);
ps.setString(i++, visitorName);
ps.setString(i++, visitorPhone);
ps.setString(i++, adult_count);
ps.setString(i++, child_count);
ps.setString(i++, adult_price);
ps.setString(i++, child_price);
ps.setString(i++, raid_time);
ps.setString(i++, total_ticket);
ps.setString(i++, ticket_amount);
ps.setString(i++, orderid);
ps.setString(i++, tid);
ps.setString(i++, mid);
ps.setString(i++, serialNumber);
ps.setString(i++, loginId);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
updateTicketNo(lastInsertId, lid);
String sqlQuery_txt = "SELECT * From `tickets` WHERE ticketid='"+lastInsertId+"' LIMIT 1";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery_txt);
response.put("status", 200);
response.put("message", "A new ticket (Boat) was generated successfully!");
response.put("data", result);
System.out.println("A new Ticket (Boat) was generated successfully! Insert ID: " + generatedId);
} else {
response.put("status", 201);
response.put("message", "Failed to insert a new ticket (Boat).");
response.put("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", 500);
response.put("message", "Database error while storing new ticket (Boat).");
response.put("error", e.getMessage());
} else {
System.out.println("Message: " + rootCause.getMessage());
response.put("status", 400);
response.put("message", "Failed to insert a new ticket (Boat).");
}
}
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> getTicketData(
MultiValueMap<String, String> formData,
String orderid,
String ticketid) {
String sqlQuery = "SELECT * From `tickets` WHERE (`isactive`=1 AND `isdelete`=0) ";
if(orderid!=null && !orderid.isEmpty() && !orderid.isBlank()) {
sqlQuery= sqlQuery +" AND `orderid`='"+orderid+"'";
}
if(ticketid!=null && !ticketid.isEmpty() && !ticketid.isBlank()) {
sqlQuery= sqlQuery +" AND `ticketid`='"+ticketid+"'";
}
sqlQuery = sqlQuery + " LIMIT 1";
//System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Ticket Details");
response.put("data", result);
return result;
}
@Transactional
public List<Map<String, Object>> storeBankTransaction(Map<String, Object> transactionData) {
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
// Extract data from the JSON object
String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus");
// Check if the transaction was successful
if ("Transaction success".equalsIgnoreCase(transactionResponseStatus)) {
String mid = (String) transactionData.get("mid");
String tid = (String) transactionData.get("tid");
String txnId = (String) transactionData.get("txnId");
// Fetch nested transaction response data
Map<String, Object> txnResponseData = (Map<String, Object>) transactionData.get("txnResponseData");
String bankName = (String) txnResponseData.get("bankName");
String batchNumber = (String) txnResponseData.get("batchNumber");
String transactionTitle = (String) txnResponseData.get("transactionTitle");
String txnAID = (String) txnResponseData.get("txnAID");
String txnApprCode = (String) txnResponseData.get("txnApprCode");
String txnCardNo = (String) txnResponseData.get("txnCardNo");
String txnCardType = (String) txnResponseData.get("txnCardType");
String txnDate = (String) txnResponseData.get("txnDate");
String txnInvoice = (String) txnResponseData.get("txnInvoice");
String txnMode = (String) txnResponseData.get("txnMode");
String txnRefNo = (String) txnResponseData.get("txnRefNo");
String txnTC = (String) txnResponseData.get("txnTC");
String txnTSI = (String) txnResponseData.get("txnTSI");
String txnTVR = (String) txnResponseData.get("txnTVR");
String txnTime = (String) txnResponseData.get("txnTime");
// Convert transaction amount properly
Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount"));
String sqlQuery = "INSERT INTO bank_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, "
+ "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, "
+ "txnTC, txnTSI, txnTVR, txnTime) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, mid);
ps.setString(2, tid);
ps.setString(3, txnId);
ps.setString(4, bankName);
ps.setString(5, batchNumber);
ps.setDouble(6, transactionAmount);
ps.setString(7, transactionTitle);
ps.setString(8, txnAID);
ps.setString(9, txnApprCode);
ps.setString(10, txnCardNo);
ps.setString(11, txnCardType);
ps.setString(12, txnDate);
ps.setString(13, txnInvoice);
ps.setString(14, txnMode);
ps.setString(15, txnRefNo);
ps.setString(16, txnTC);
ps.setString(17, txnTSI);
ps.setString(18, txnTVR);
ps.setString(19, txnTime);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
updatePaymentStatus(txnId, transactionResponseStatus);
// Fetch inserted data for response, joining `penalty_challan` and `bank_transactions`
String sqlQuery_joined = "SELECT ts.*, "
+ "bt.mid, bt.tid, bt.txnId, bt.bankName, bt.batchNumber, bt.transactionAmount, bt.transactionTitle, "
+ "bt.txnCardNo, bt.txnDate, bt.txnInvoice, bt.txnMode, bt.txnRefNo "
+ "FROM tickets ts "
+ "LEFT JOIN bank_transactions bt ON ts.orderid = bt.txnId "
+ "WHERE ts.isactive = 1 AND ts.isdelete = 0 AND bt.id = ? LIMIT 1";
System.out.println(sqlQuery_joined);
// Execute the query
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery_joined, lastInsertId);
response.put("status", 200);
response.put("message", "Transaction stored successfully!");
response.put("data", result);
} else {
response.put("status", 201);
response.put("message", "Failed to store the transaction.");
response.put("data", "");
}
} catch (DataAccessException e) {
response.put("status", 500);
response.put("message", "Database error while storing transaction.");
response.put("error", e.getMessage());
e.printStackTrace(); // This will give you more detail in logs
}
} else {
response.put("status", 400);
response.put("message", "Transaction failed or invalid status.");
}
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> storeFailedBankTransaction(Map<String, Object> transactionData) {
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
// Extract data from the JSON object
String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus");
// Check if the transaction was successful
if ("Transaction cancelled".equalsIgnoreCase(transactionResponseStatus)) {
String mid = (String) transactionData.get("mid");
String tid = (String) transactionData.get("tid");
String txnId = (String) transactionData.get("txnId");
// Fetch nested transaction response data
Map<String, Object> txnResponseData = (Map<String, Object>) transactionData.get("txnResponseData");
String bankName = (String) txnResponseData.get("bankName");
String batchNumber = (String) txnResponseData.get("batchNumber");
String transactionTitle = (String) txnResponseData.get("transactionTitle");
String txnAID = (String) txnResponseData.get("txnAID");
String txnApprCode = (String) txnResponseData.get("txnApprCode");
String txnCardNo = (String) txnResponseData.get("txnCardNo");
String txnCardType = (String) txnResponseData.get("txnCardType");
String txnDate = (String) txnResponseData.get("txnDate");
String txnInvoice = (String) txnResponseData.get("txnInvoice");
String txnMode = (String) txnResponseData.get("txnMode");
String txnRefNo = (String) txnResponseData.get("txnRefNo");
String txnTC = (String) txnResponseData.get("txnTC");
String txnTSI = (String) txnResponseData.get("txnTSI");
String txnTVR = (String) txnResponseData.get("txnTVR");
String txnTime = (String) txnResponseData.get("txnTime");
// Convert transaction amount properly
//Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount"));
// Get the transactionAmount from txnResponseData
String transactionAmountStr = (String) txnResponseData.get("transactionAmount");
// Check if the transactionAmount is not null and not empty before converting
Double transactionAmountTemp = null;
if (transactionAmountStr != null && !transactionAmountStr.trim().isEmpty()) {
try {
// Convert the valid string to a Double
transactionAmountTemp = Double.valueOf(transactionAmountStr);
} catch (NumberFormatException e) {
// Handle the case where the string cannot be parsed to a Double // Log the error or throw a custom exception
System.out.println("Error: Unable to parse transactionAmount to Double. " + e.getMessage());
transactionAmountTemp = 0.0; // Set to a default value or handle as needed
}
} else {
// Handle the case where transactionAmount is empty or null
transactionAmountTemp = 0.0; // Default value or handle as needed
}
Double transactionAmount = transactionAmountTemp;
String sqlQuery = "INSERT INTO bank_failed_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, "
+ "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, "
+ "txnTC, txnTSI, txnTVR, txnTime) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, mid);
ps.setString(2, tid);
ps.setString(3, txnId);
ps.setString(4, bankName);
ps.setString(5, batchNumber);
ps.setDouble(6, transactionAmount);
ps.setString(7, transactionTitle);
ps.setString(8, txnAID);
ps.setString(9, txnApprCode);
ps.setString(10, txnCardNo);
ps.setString(11, txnCardType);
ps.setString(12, txnDate);
ps.setString(13, txnInvoice);
ps.setString(14, txnMode);
ps.setString(15, txnRefNo);
ps.setString(16, txnTC);
ps.setString(17, txnTSI);
ps.setString(18, txnTVR);
ps.setString(19, txnTime);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
updatePaymentStatus(txnId, transactionResponseStatus);
// Fetch inserted data for response, joining `penalty_challan` and `bank_transactions`
String sqlQuery_joined = "SELECT ts.*, "
+ "bt.mid, bt.tid, bt.txnId, bt.bankName, bt.batchNumber, bt.transactionAmount, bt.transactionTitle, "
+ "bt.txnCardNo, bt.txnDate, bt.txnInvoice, bt.txnMode, bt.txnRefNo "
+ "FROM tickets ts "
+ "LEFT JOIN bank_transactions bt ON ts.orderid = bt.txnId "
+ "WHERE ts.isactive = 1 AND ts.isdelete = 0 AND bt.txnId = ? LIMIT 1";
System.out.println(sqlQuery_joined);
// Execute the query
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery_joined, txnId);
response.put("status", 200);
response.put("message", "Transaction stored successfully!");
response.put("data", result);
} else {
response.put("status", 201);
response.put("message", "Failed to store the transaction.");
response.put("data", "");
}
} catch (DataAccessException e) {
response.put("status", 500);
response.put("message", "Database error while storing transaction.");
response.put("error", e.getMessage());
e.printStackTrace(); // This will give you more detail in logs
}
} else {
response.put("status", 400);
response.put("message", "Transaction failed or invalid status.");
}
return Collections.singletonList(response);
}
public String updatePaymentStatus(String orderid, String status) {
String sqlQuery = "UPDATE tickets SET status = ? WHERE orderid = ? LIMIT 1";
jdbcTemplate.update(sqlQuery, status, orderid);
return "success";
}
}

147
src/main/java/in/gov/chennaicorporation/mobileservice/buildingDemolition/controller/BuildingDemolitionController.java

@ -0,0 +1,147 @@
package in.gov.chennaicorporation.mobileservice.buildingDemolition.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.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.buildingDemolition.service.BuildingDemolitionActivity;
@RequestMapping("/gccofficialapp/api/buildingdemolition/")
@RestController("buildingDemolitionRest")
public class BuildingDemolitionController {
@Autowired
BuildingDemolitionActivity buildingDemolitionService;
@GetMapping("/list")
public ResponseEntity<List<Map<String, Object>>> getBuildingList(
@RequestParam String loginId) {
return ResponseEntity.ok(buildingDemolitionService.getBuildingList(loginId));
}
@PostMapping("/update")
public ResponseEntity<List<Map<String, Object>>> updateDetails(
@RequestParam String id,
@RequestParam String status,
@RequestParam String cby,
@RequestParam(required = true) String latitude,
@RequestParam(required = true) String longitude,
@RequestParam(required = true) String remarks,
@RequestParam(required = true) MultipartFile file) {
return ResponseEntity
.ok(buildingDemolitionService.updateDetails(id, status, cby, latitude, longitude, remarks, file));
}
// Zone wise Report
@GetMapping("/report/zone")
public ResponseEntity<List<Map<String, Object>>> zoneReport() {
return ResponseEntity.ok(buildingDemolitionService.zoneReport());
}
// Ward wise Report (filter by zone)
@GetMapping("/report/ward")
public ResponseEntity<List<Map<String, Object>>> wardReport(@RequestParam String zone) {
return ResponseEntity.ok(buildingDemolitionService.wardReport(zone));
}
// Pending list Report (filter by ward)
@GetMapping("/report/pending")
public ResponseEntity<List<Map<String, Object>>> pendingReport(@RequestParam String ward) {
return ResponseEntity.ok(buildingDemolitionService.pendingReport(ward));
}
// Completed list Report (filter by ward)
@GetMapping("/report/completed")
public ResponseEntity<List<Map<String, Object>>> completedReport(@RequestParam String ward) {
return ResponseEntity.ok(buildingDemolitionService.completedReport(ward));
}
// --- New Endpoints Replicated from Construction Guidelines ---
@PostMapping("/saveFeedback")
public ResponseEntity<List<Map<String, Object>>> saveDemolitionFeedback(
@RequestParam(required = true) String bdid,
@RequestParam(required = true) String bdsid,
@RequestParam(required = true) String cby,
@RequestParam(required = true) String latitude,
@RequestParam(required = true) String longitude,
@RequestParam(required = true) String zone,
@RequestParam(required = true) String ward,
@RequestParam(required = true) String q1,
@RequestParam(required = true) String q2,
@RequestParam(required = true) String q3,
@RequestParam(required = true) String q4,
@RequestParam(required = true) String q5,
@RequestParam(required = true) String q6,
@RequestParam(required = true) String q7,
@RequestParam(required = true) String q8,
@RequestParam(required = true) String q9,
@RequestParam(required = true) String q10,
@RequestParam(required = true) String q11,
@RequestParam(required = true) String q12,
@RequestParam(required = true) String q13,
@RequestParam(required = true) String q14,
@RequestParam(required = true) String q15,
@RequestParam(required = true) String q16,
@RequestParam(required = true) String q17,
@RequestParam(required = true) String q18,
@RequestParam(required = true) MultipartFile image1,
@RequestParam(required = true) MultipartFile image2,
@RequestParam(required = true) MultipartFile image3,
@RequestParam(required = true) MultipartFile image4,
@RequestParam(required = true) MultipartFile image5) {
return ResponseEntity.ok(buildingDemolitionService.saveDemolitionFeedback(
bdid, bdsid, cby, latitude, longitude, zone, ward,
q1, q2, q3, q4, q5, q6, q7, q8, q9, q10,
q11, q12, q13, q14, q15, q16, q17, q18,
image1, image2, image3, image4, image5));
}
@GetMapping("/getRevisitList")
public ResponseEntity<List<Map<String, Object>>> getRevisitDemolitionList(
@RequestParam String loginId,
@RequestParam String latitude,
@RequestParam String longitude) {
return ResponseEntity.ok(buildingDemolitionService.getRevisitDemolitionList(loginId, latitude, longitude));
}
@PostMapping("/saveAfterNoticeDetails")
public ResponseEntity<List<Map<String, Object>>> saveDemolitionAfterNotice(
@RequestParam String bdid,
@RequestParam String bdsid,
@RequestParam String bdgiid,
@RequestParam String remarks,
@RequestParam String status,
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String loginId,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam MultipartFile mainfile) {
return ResponseEntity.ok(buildingDemolitionService.saveDemolitionAfterNotice(
bdid, bdsid, bdgiid, remarks, status, zone, ward, loginId, latitude, longitude, mainfile));
}
@PostMapping("/saveFinalNoticeDetails")
public ResponseEntity<List<Map<String, Object>>> saveDemolitionFinalNotice(
@RequestParam String bdid,
@RequestParam String bdsid,
@RequestParam String bdgiid,
@RequestParam String remarks,
@RequestParam String status,
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String loginId,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam MultipartFile mainfile) {
return ResponseEntity.ok(buildingDemolitionService.saveDemolitionFinalNotice(
bdid, bdsid, bdgiid, remarks, status, zone, ward, loginId, latitude, longitude, mainfile));
}
}

641
src/main/java/in/gov/chennaicorporation/mobileservice/buildingDemolition/service/BuildingDemolitionActivity.java

@ -0,0 +1,641 @@
package in.gov.chennaicorporation.mobileservice.buildingDemolition.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.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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class BuildingDemolitionActivity {
private JdbcTemplate jdbcBuildingDemolitionTemplate;
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("mysqlGccBuildingDemolitionSource") DataSource BuildingDemolitionDataSource) {
this.jdbcBuildingDemolitionTemplate = new JdbcTemplate(BuildingDemolitionDataSource);
}
@Autowired
public BuildingDemolitionActivity(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("buildingdemolition_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 List<Map<String, Object>> getBuildingList(String aeUserId) {
String sql = "SELECT zone, ward FROM gcc_penalty_hoardings.`hoading_user_list` WHERE userid = ? AND type='ae'";
List<Map<String, Object>> userList = jdbcBuildingDemolitionTemplate.queryForList(sql, aeUserId);
if (userList.isEmpty()) {
// You can return an empty list or throw a custom exception
return Collections.emptyList(); // or handle as needed
}
Map<String, Object> vendorData = userList.get(0);
String ward = String.valueOf(vendorData.get("ward"));
sql = "SELECT "
+ " bd.* "
+ "FROM building_demolition bd "
+ "LEFT JOIN building_demolition_status bds ON bd.id = bds.bdid "
+ "WHERE bds.bdid IS NULL "
+ " AND bd.ward = ?";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Building Demolition List.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> updateDetails(
String id,
String status,
String cby,
String latitude,
String longitude,
String remarks,
MultipartFile file) {
String filepath = null;
// 1. Fetch building details
String sql = "SELECT `id` as bdid, `council_resolution_date`, `year`, `zone`, `ward`, " +
"`description`, `category_of_building`, `area_sqm` " +
"FROM `building_demolition` WHERE id=?";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sql, id);
if (result.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", "Failed");
response.put("message", "No record found for id " + id);
return Collections.singletonList(response);
}
Map<String, Object> building = result.get(0);
// 2. Check if record already exists in building_demolition_status
String checkSql = "SELECT COUNT(*) FROM `building_demolition_status` WHERE bdid = ?";
Integer count = jdbcBuildingDemolitionTemplate.queryForObject(checkSql, Integer.class, building.get("bdid"));
if (count != null && count > 0) {
Map<String, Object> response = new HashMap<>();
response.put("status", "Failed");
response.put("message", "Duplicate entry: Demolition status already exists for building id " + id);
return Collections.singletonList(response);
}
// 2.1. Handle file upload (optional)
if (file != null && !file.isEmpty()) {
filepath = fileUpload(id, cby, file);
}
// 3. Insert into building_demolition_status
String insertSql = "INSERT INTO `building_demolition_status` " +
"(`bdid`, `council_resolution_date`, `year`, `zone`, `ward`, `description`, " +
"`category_of_building`, `area_sqm`, `status`, `inby`, " +
" `file1`, `remarks`, `latitude`, `longitude`) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
jdbcBuildingDemolitionTemplate.update(insertSql,
building.get("bdid"),
building.get("council_resolution_date"),
building.get("year"),
building.get("zone"),
building.get("ward"),
building.get("description"),
building.get("category_of_building"),
building.get("area_sqm"),
status,
cby,
filepath,
remarks,
latitude,
longitude);
// 4. Build response
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Building Demolition Status inserted successfully.");
response.put("data", building);
return Collections.singletonList(response);
}
// Reports
public List<Map<String, Object>> zoneReport() {
String sqlQuery = "SELECT "
+ " bd.zone, "
+ " COUNT(bd.id) AS total_building, "
+ " SUM(CASE WHEN bds.bdid IS NULL THEN 1 ELSE 0 END) AS pending, "
+ " SUM(CASE WHEN bds.bdid IS NOT NULL THEN 1 ELSE 0 END) AS completed "
+ "FROM building_demolition bd "
+ "LEFT JOIN building_demolition_status bds ON bd.id = bds.bdid "
+ "GROUP BY bd.zone "
+ "ORDER BY bd.zone";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Zone list report.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> wardReport(String zone) {
String sqlQuery = "SELECT "
+ " bd.ward, "
+ " COUNT(bd.id) AS total_building, "
+ " SUM(CASE WHEN bds.bdid IS NULL THEN 1 ELSE 0 END) AS pending, "
+ " SUM(CASE WHEN bds.bdid IS NOT NULL THEN 1 ELSE 0 END) AS completed "
+ "FROM building_demolition bd "
+ "LEFT JOIN building_demolition_status bds ON bd.id = bds.bdid "
+ "WHERE bd.zone = ? "
+ "GROUP BY bd.ward "
+ "ORDER BY bd.ward";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sqlQuery, zone);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Ward list report.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> pendingReport(String ward) {
String sqlQuery = "SELECT "
+ " bd.* "
+ "FROM building_demolition bd "
+ "LEFT JOIN building_demolition_status bds ON bd.id = bds.bdid "
+ "WHERE bds.bdid IS NULL "
+ " AND bd.ward = ?";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sqlQuery, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Pending list report.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> completedReport(String ward) {
String sqlQuery = "SELECT "
+ " bds.*,"
+ " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bds.file1) AS image_url "
+ "FROM building_demolition bd "
+ "INNER JOIN building_demolition_status bds ON bd.id = bds.bdid "
+ "WHERE bd.ward = ?";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sqlQuery, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "Completed list report.");
response.put("data", result);
return Collections.singletonList(response);
}
// --- New Methods Replicated from Construction Guidelines ---
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT ward FROM gcc_penalty_hoardings.hoading_user_list WHERE userid = ? LIMIT 1";
List<Map<String, Object>> results = jdbcBuildingDemolitionTemplate.queryForList(sqlQuery, loginid);
if (!results.isEmpty()) {
return (String) results.get(0).get("ward");
}
return "000";
}
public String sendMessage(String tempid, String bdid) {
String sendTo = "";
String datetxt = "";
String name = "";
String Nos = "";
String fineAmount = "";
// Assuming send_msg_to table is shared or similar exists
String sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);";
List<Map<String, Object>> mobileResult = jdbcBuildingDemolitionTemplate.queryForList(sql, tempid);
StringBuilder sendToBuilder = new StringBuilder();
for (Map<String, Object> mobileRow : mobileResult) {
String mobile = String.valueOf(mobileRow.get("mobile"));
if (sendToBuilder.length() > 0) {
sendToBuilder.append(",");
}
sendToBuilder.append(mobile);
}
sendTo = sendToBuilder.toString();
System.out.println("Mobile Numbers: " + sendTo);
// NOTE: Credentials and URL structure copied from GuidelinesService
String urlString = "";
String username = "2000233507";
String password = "h2YjFNcJ";
// Note: Messages adapted slightly or kept generic if specific building
// demolition context is needed
switch (tempid) {
case "1":
System.out.println("TempID is 1 (Initial Notice)");
urlString = "https://media.smsgupshup.com/GatewayAPI/rest?"
+ "userid=" + username
+ "&password=" + password
+ "&send_to=" + sendTo
+ "&v=1.1"
+ "&format=json"
+ "&msg_type=TEXT"
+ "&method=SENDMEDIAMESSAGE"
+ "&msg=Your+Demolition+Site+%28" + name + "%29+has+violations.+Please+rectify+within+15+days."
+ "&isTemplate=true"
+ "&header=GCC+Building+Demolition"
+ "&footer=GCC+-+IT+Cell";
break;
case "2": // Compliance resolved
// ... (Similar logic)
break;
case "3": // Penalty
// ...
break;
// Add other cases as needed
default:
System.out.println("TempID (" + tempid + ") is unknown or not fully implemented for Demolition");
}
if (!urlString.isBlank() && !sendTo.isEmpty()) {
// String response = sendWhatsAppMessage(urlString);
// System.out.println("WhatsApp response: " + response);
}
return "success";
}
@org.springframework.transaction.annotation.Transactional
public List<Map<String, Object>> saveDemolitionFeedback(
String bdid,
String bdsid, // Building Demolition Status ID
String cby,
String latitude,
String longitude,
String zone,
String ward,
String q1, String q2, String q3, String q4, String q5, String q6, String q7, String q8, String q9,
String q10,
String q11, String q12, String q13, String q14, String q15, String q16, String q17, String q18,
MultipartFile image1, MultipartFile image2, MultipartFile image3, MultipartFile image4,
MultipartFile image5) {
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = java.util.ArrayList.class.cast(new java.util.ArrayList<>());
MultipartFile[] files = { image1, image2, image3, image4, image5 };
String[] imagePaths = new String[5];
for (int i = 0; i < files.length; i++) {
if (files[i] != null && !files[i].isEmpty()) {
imagePaths[i] = fileUpload(bdid, "_" + bdsid + "_" + (i + 1), files[i]);
} else {
imagePaths[i] = "";
}
}
String insertSql = "INSERT INTO `building_demolition_guidelines_inspection` "
+ "(`bdid`, `bdsid`, `cby`, `latitude`, `longitude`, `zone`, `ward`,"
+ "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, "
+ "`q11`, `q12`, `q13`, `q14`, `q15`, `q16`, `q17`, `q18`, "
+ "`img1`, `img2`, `img3`, `img4`, `img5`) " +
"VALUES (" + "?,".repeat(7 + 18 + 5).replaceAll(",$", "") + ")";
org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder();
int affectedRows = jdbcBuildingDemolitionTemplate.update(connection -> {
java.sql.PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "bdgiid" });
int i = 1;
ps.setString(i++, bdid);
ps.setString(i++, bdsid);
ps.setString(i++, cby);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, zone);
ps.setString(i++, ward);
for (String q : new String[] { q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17,
q18 }) {
ps.setString(i++, q);
}
for (String path : imagePaths) {
ps.setString(i++, path);
}
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("insertId", lastInsertId);
String penalty = findPenaltyType(q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17,
q18);
// Calculate fine amount based on building area (from building_demolition table)
double areaSqm = getAreaSqm(bdid);
int fineAmount = 0;
// Logic replicated from Construction Guidelines (Area based)
// Assuming 'area_sqm' is comparable to 'buildup_area'
if (areaSqm > 20000) {
fineAmount = "High".equalsIgnoreCase(penalty) ? 500000 : 100000;
} else if (areaSqm > 500) {
fineAmount = "High".equalsIgnoreCase(penalty) ? 25000 : 10000;
} else if (areaSqm >= 300) {
fineAmount = "High".equalsIgnoreCase(penalty) ? 10000 : 1000;
}
if (updateDemolitionStatus(bdsid, bdid, penalty, String.valueOf(fineAmount))) {
response.put("status", "success");
response.put("message", "Feedback inserted successfully.");
} else {
response.put("status", "error");
response.put("message", "Feedback Insert failed (Status Update).");
}
} else {
response.put("status", "error");
response.put("message", "Insert failed.");
}
result.add(response);
return result;
}
private double getAreaSqm(String bdid) {
String sql = "SELECT area_sqm FROM building_demolition WHERE id = ?";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sql, bdid);
if (result.isEmpty())
return 0.0;
Object val = result.get(0).get("area_sqm");
if (val == null)
return 0.0;
try {
return Double.parseDouble(val.toString());
} catch (Exception e) {
return 0.0;
}
}
private String findPenaltyType(String q1, String q2, String q3, String q4, String q5, String q6, String q7,
String q8,
String q9, String q10,
String q11, String q12, String q13, String q14, String q15, String q16, String q17, String q18) {
if ("No".equalsIgnoreCase(q1) || "No".equalsIgnoreCase(q2) || "No".equalsIgnoreCase(q3) ||
"No".equalsIgnoreCase(q4) || "No".equalsIgnoreCase(q5) || "No".equalsIgnoreCase(q6) ||
"No".equalsIgnoreCase(q7) || "No".equalsIgnoreCase(q8) || "No".equalsIgnoreCase(q9) ||
"No".equalsIgnoreCase(q10) || "No".equalsIgnoreCase(q11) || "No".equalsIgnoreCase(q12) ||
"No".equalsIgnoreCase(q13) || "No".equalsIgnoreCase(q14)) {
return "High";
}
if ("No".equalsIgnoreCase(q15) || "No".equalsIgnoreCase(q16) || "No".equalsIgnoreCase(q17)) {
return "Medium";
}
return "Low";
}
public boolean updateDemolitionStatus(String bdsid, String bdid, String penalty, String fineAmount) {
// Assuming 'id' is key for building_demolition_status
// Wait, user might not have 'id' in status table if it's 1-to-1 with 'bdid'?
// Code in updateDetails does NOT use bdsid, but we need to update the row we
// created.
// If bdsid (ciid) is passed, we use it. If not, we map by bdid (as duplicate
// check ensures 1 row).
String updateSql = "UPDATE `building_demolition_status` SET `penalty` = ?, `fine_amount` = ? WHERE bdid = ?";
// Using bdid (id from building_demolition) as the foreign key reference
int affectedRows = jdbcBuildingDemolitionTemplate.update(updateSql, penalty, fineAmount, bdid);
return affectedRows > 0;
}
public List<Map<String, Object>> getRevisitDemolitionList(String loginid, String latitude, String longitude) {
String ward = getWardByLoginId(loginid, "");
String sql = "SELECT bd.*, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bds.file1) AS photo, " + // Assuming file1 is image
"bds.id as bdsid, bds.penalty " +
"FROM building_demolition bd " +
"LEFT JOIN building_demolition_status bds ON bds.bdid = bd.id " +
"WHERE bd.ward = ? AND bds.penalty IN ('High','Medium','Low') " +
"AND bd.id NOT IN (SELECT bdid FROM building_demolition_after_notice WHERE isactive = 1)";
List<Map<String, Object>> result = jdbcBuildingDemolitionTemplate.queryForList(sql, ward);
java.time.LocalDate today = java.time.LocalDate.now();
java.time.format.DateTimeFormatter dtf = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (Map<String, Object> row : result) {
boolean allowRevisit = false;
Object cdateObj = row.get("cdate"); // Assuming cdate column exists
if (cdateObj != null) {
try {
java.time.LocalDate cdate = null;
if (cdateObj instanceof java.sql.Timestamp) {
cdate = ((java.sql.Timestamp) cdateObj).toLocalDateTime().toLocalDate();
} else if (cdateObj instanceof String) {
cdate = java.time.LocalDateTime.parse((String) cdateObj, dtf).toLocalDate();
}
if (cdate != null) {
java.time.LocalDate finalDate = cdate.plusDays(15);
allowRevisit = !today.isBefore(finalDate);
}
} catch (Exception e) {
// Ignore parse error
}
}
row.put("allowRevisit", allowRevisit);
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Revisit List");
response.put("data", result);
return Collections.singletonList(response);
}
@org.springframework.transaction.annotation.Transactional
public List<Map<String, Object>> saveDemolitionAfterNotice(
String bdid, String bdsid, String bdgiid, String remarks, String status,
String zone, String ward, String cby, String latitude, String longitude, MultipartFile mainfile) {
Map<String, Object> response = new HashMap<>();
String imagePath = fileUpload(bdid, "after_notice", mainfile);
String sql = "INSERT INTO `building_demolition_after_notice` (bdid, bdsid, bdgiid, remarks, status, zone, ward, cby, latitude, longitude, mainfile) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
int rows = jdbcBuildingDemolitionTemplate.update(sql, bdid, bdsid, bdgiid, remarks, status, zone, ward, cby,
latitude, longitude, imagePath);
if (rows > 0) {
response.put("status", "success");
response.put("message", "After notice details saved");
} else {
response.put("status", "error");
response.put("message", "Failed to save");
}
return Collections.singletonList(response);
}
@org.springframework.transaction.annotation.Transactional
public List<Map<String, Object>> saveDemolitionFinalNotice(
String bdid, String bdsid, String bdgiid, String remarks, String status,
String zone, String ward, String cby, String latitude, String longitude, MultipartFile mainfile) {
Map<String, Object> response = new HashMap<>();
String imagePath = fileUpload(bdid, "final_notice", mainfile);
String sql = "INSERT INTO `building_demolition_final_notice` (bdid, bdsid, bdgiid, remarks, status, zone, ward, cby, latitude, longitude, mainfile) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
int rows = jdbcBuildingDemolitionTemplate.update(sql, bdid, bdsid, bdgiid, remarks, status, zone, ward, cby,
latitude, longitude, imagePath);
if (rows > 0) {
response.put("status", "success");
response.put("message", "Final notice details saved");
} else {
response.put("status", "error");
response.put("message", "Failed to save");
}
return Collections.singletonList(response);
}
private String sendWhatsAppMessage(String urlString) {
String response = "";
try {
java.net.URL url = new java.net.URL(urlString);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
response = String.valueOf(responseCode);
System.out.println("Response Code for URL: " + urlString + " is " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}

92
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController.java

@ -0,0 +1,92 @@
package in.gov.chennaicorporation.mobileservice.busshelters.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.busshelters.service.BusShelterActivity;
@RequestMapping("/gccofficialapp/api/busshelter/")
@RestController("busshelterRest")
public class BusShelterController {
@Autowired
private JdbcTemplate jdbcBusShelterTemplate;
@Autowired
private BusShelterActivity busShelterActivity;
@GetMapping(value="/getBusShelterList")
public List<?> getBusShelterList(@RequestParam MultiValueMap<String, String> 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);
}
}

115
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/BusShelterController_renovation.java

@ -0,0 +1,115 @@
package in.gov.chennaicorporation.mobileservice.busshelters.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.busshelters.service.BusShelterRenovationActivity;
@RequestMapping("/gccofficialapp/api/busshelter/renovation/")
@RestController("busshelterRenovationRest")
public class BusShelterController_renovation {
@Autowired
private JdbcTemplate jdbcBusShelterTemplate;
@Autowired
private BusShelterRenovationActivity busShelterRenovationActivity;
@GetMapping(value="/getBusShelterList")
public List<?> getBusShelterList(@RequestParam MultiValueMap<String, String> formData,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginid", required = false) String loginid){
return busShelterRenovationActivity.getBusShelterList(formData, latitude, longitude, loginid);
}
@GetMapping(value="/getBusCompletedShelterList")
public List<?> getBusCompletedShelterList(@RequestParam MultiValueMap<String, String> formData,
@RequestParam(value = "latitude", required = false) String latitude,
@RequestParam(value = "longitude", required = false) String longitude,
@RequestParam(value = "loginid", required = true) String loginid){
return busShelterRenovationActivity.getBusCompletedShelterList(formData, latitude, longitude, loginid);
}
@GetMapping(value="/getStageList") // Old App
public List<?> getQuestionsList(@RequestParam(value="loginId", required = false) String cby){
return busShelterRenovationActivity.getStageList();
}
@GetMapping(value="/getBusShelterDetails")
public List<?> getBusShelterDetails(
@RequestParam MultiValueMap<String, String> formData,
@RequestParam(value="id", required = true) String id,
@RequestParam(value="latitude", required = true) String latitude,
@RequestParam(value="longitude", required = true) String longitude,
@RequestParam(value="loginid", required = false) String loginid,
@RequestParam(value="renovation_required_condition", required = false) String renovation_required_condition){
return busShelterRenovationActivity.getBusShelterDetails(formData,id,loginid, latitude, longitude, renovation_required_condition);
}
@PostMapping(value="/saveStageActivityData")
public List<?> saveStageActivityData(
@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="zone", required = true) String zone,
@RequestParam(value="ward", required = true) String ward,
@RequestParam(value="streetname", required = false) String streetname,
@RequestParam(value="streetid", required = false) String streetid,
@RequestParam(value="stageid", required = true) String stageid,
@RequestParam(value="remarks", required = true) String remarks,
@RequestParam(value="weightage", required = true) String weightage,
@RequestParam(value="renovation_required", required = false) String renovation_required,
@RequestParam(value = "file", required = false) MultipartFile file,
@RequestParam(value="stagefile", required = false) MultipartFile stage_file
){
return busShelterRenovationActivity.saveStageActivityData(shelter_id, cby, latitude, longitude, zone, ward,
streetname, streetid, stageid, remarks, weightage, file, stage_file, renovation_required);
}
// Reports
@GetMapping(value="/getZoneList")
public List<?> getZoneList(){
return busShelterRenovationActivity.getZoneList();
}
@GetMapping(value="/getWardList")
public List<?> getWardList(@RequestParam(value="zone", required = true) String zone){
return busShelterRenovationActivity.getWardList(zone);
}
@GetMapping(value="/getVistPendingList")
public List<?> getVistPendingList(@RequestParam(value="ward", required = true) String ward){
return busShelterRenovationActivity.getVistPendingList(ward);
}
@GetMapping(value="/getRenovationRequiredList")
public List<?> getRenovationRequiredList(@RequestParam(value="ward", required = true) String ward){
return busShelterRenovationActivity.getRenovationRequiredList(ward);
}
@GetMapping(value="/getRenovationNotRequiredList")
public List<?> getRenovationNotRequiredList(@RequestParam(value="ward", required = true) String ward){
return busShelterRenovationActivity.getRenovationNotRequiredList(ward);
}
@GetMapping(value="/getWorkPendingList")
public List<?> getWorkPendingList(@RequestParam(value="ward", required = true) String ward){
return busShelterRenovationActivity.getWorkPendingList(ward);
}
@GetMapping(value="/getWorkCompletedList")
public List<?> getWorkCompletedList(@RequestParam(value="ward", required = true) String ward){
return busShelterRenovationActivity.getWorkCompletedList(ward);
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/controller/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.busshelters.controller;

1
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.busshelters;

507
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<Map<String, Object>> results = jdbcBusShelterTemplate.queryForList(sqlQuery);
if (!results.isEmpty()) {
Map<String, Object> row = results.get(0);
value = String.valueOf(row.get("lat_long_radius")); // corrected key name
}
return value;
}
//////////////////////////////
public List<Map<String, Object>> getBusShelterList(
MultiValueMap<String, String> 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<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter List.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getQuestionsList() {
String sql = "SELECT * FROM question_list WHERE isactive=1";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter Question List.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> 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<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql,"%" + qtype + "%");
ObjectMapper mapper = new ObjectMapper();
for (Map<String, Object> row : result) {
Object optionsRaw = row.get("options");
if (optionsRaw != null && optionsRaw instanceof String) {
try {
List<Map<String, Object>> optionsParsed = mapper.readValue((String) optionsRaw, List.class);
row.put("options", optionsParsed);
} catch (Exception e) {
row.put("options", null); // fallback if malformed
}
}
}
Map<String, Object> 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<Map<String, Object>> getChildQuestionsList(String pid) {
String sql = "SELECT * FROM question_list WHERE isactive=1 AND `pid`=?";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql,pid);
Map<String, Object> 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<Map<String, Object>> 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<Map<String, Object>> result = null;
Map<String, Object> 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);
}
}

879
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/BusShelterRenovationActivity.java

@ -0,0 +1,879 @@
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.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.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class BusShelterRenovationActivity {
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 BusShelterRenovationActivity(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_renovation_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<Map<String, Object>> results = jdbcBusShelterTemplate.queryForList(sqlQuery);
if (!results.isEmpty()) {
Map<String, Object> row = results.get(0);
value = String.valueOf(row.get("lat_long_radius")); // corrected key name
}
return value;
}
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT `ward` FROM gcc_penalty_hoardings.`hoading_user_list` WHERE `userid` = ? AND `type` = ? LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcBusShelterTemplate.queryForList(sqlQuery, loginid, type);
// 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<Map<String, Object>> getBusShelterList(
MultiValueMap<String, String> 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((cos(radians(" + latitude
+ ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude
+ ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude))))) < "+radius+")"
+ " ORDER BY"
+ " bsl.`id` DESC";
}
*/
String ward = getWardByLoginId(loginid,"ae");
sqlWhere = " AND (bsr.`stage_status` <> 'Completed' OR bsr.`stage_status` is NULL) ORDER BY bsl.`id` DESC";
String sql = "SELECT "
+ " bsl.`id`, "
+ " bsl.`zone`, "
+ " bsl.`ward`, "
+ " bsl.`latitude`, "
+ " bsl.`longitude`, "
+ " bsl.`road`, "
+ " bsl.`category`, "
+ " bsr.renovation_required, "
+ " IF(bsr.shelter_image IS NOT NULL AND bsr.shelter_image != '', "
+ " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bsr.shelter_image), "
+ " NULL) AS shelter_image, "
+ " COALESCE(bsr.stage_status,'Pending') AS stage_status "
+ "FROM `bus_shelter_list` bsl "
+ "LEFT JOIN `bus_shelter_renovation` bsr "
+ " ON bsr.bsid = bsl.id AND bsr.isactive = 1 "
+ "WHERE bsl.isactive = 1 AND bsl.ward = ? "+sqlWhere;
//System.out.println(sql);
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql,ward);
ObjectMapper mapper = new ObjectMapper();
for (Map<String, Object> row : result) {
Object renovation_required = row.get("renovation_required");
if (renovation_required != null) {
sql = "SELECT COALESCE(SUM(`weightage`), 0) AS total_weightage "
+ "FROM `bus_shelter_renovation_data` "
+ "WHERE bsid = ?";
List<Map<String, Object>> presentage = jdbcBusShelterTemplate.queryForList(sql, row.get("id"));
// Safely get the first result
if (!presentage.isEmpty()) {
row.put("stage_presentage", presentage.get(0).get("total_weightage"));
} else {
row.put("stage_presentage", 0);
}
} else {
row.put("stage_presentage", 0);
}
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter List.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getBusCompletedShelterList(
MultiValueMap<String, String> 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((cos(radians(" + latitude
+ ")) * cos(radians(bsl.latitude)) * cos(radians(bsl.longitude) - radians(" + longitude
+ ")) + sin(radians(" + latitude + ")) * sin(radians(bsl.latitude))))) < "+radius+")"
+ " ORDER BY"
+ " bsl.`id` DESC";
}
*/
String sql = "SELECT "
+ " bsl.`id`, "
+ " bsl.`zone`, "
+ " bsl.`ward`, "
+ " bsl.`latitude`, "
+ " bsl.`longitude`, "
+ " bsl.`road`, "
+ " bsl.`category`, "
+ " bsr.renovation_required, "
+ " IF(bsr.shelter_image IS NOT NULL AND bsr.shelter_image != '', "
+ " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bsr.shelter_image), "
+ " NULL) AS shelter_image, "
+ " COALESCE(bsr.stage_status,'Pending') AS stage_status "
+ "FROM `bus_shelter_list` bsl "
+ "LEFT JOIN `bus_shelter_renovation` bsr "
+ " ON bsr.bsid = bsl.id AND bsr.isactive = 1 "
+ "WHERE bsl.isactive = 1 AND bsr.stage_status='Completed'"; // +sqlWhere;
System.out.println(sql);
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql);
ObjectMapper mapper = new ObjectMapper();
for (Map<String, Object> row : result) {
Object renovation_required = row.get("renovation_required");
if (renovation_required != null) {
sql = "SELECT COALESCE(SUM(`weightage`), 0) AS total_weightage "
+ "FROM `bus_shelter_renovation_data` "
+ "WHERE bsid = ?";
List<Map<String, Object>> presentage = jdbcBusShelterTemplate.queryForList(sql, row.get("id"));
// Safely get the first result
if (!presentage.isEmpty()) {
row.put("stage_presentage", presentage.get(0).get("total_weightage"));
} else {
row.put("stage_presentage", 0);
}
} else {
row.put("stage_presentage", 0);
}
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter Completed List.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getStageList() {
String sql = "SELECT * FROM `renovation_statge` WHERE isactive=1 ORDER BY orderby";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter Stages.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getBusShelterDetails(
MultiValueMap<String, String> formData,
String id,
String loginid,
String latitude,
String longitude,
String renovation_required_condition
) {
String sqlWhere = "";
//String radius = getConfigValue();
String sql = "SELECT "
+ " bsl.`id`, "
+ " bsl.`zone`, "
+ " bsl.`ward`, "
+ " bsl.`latitude`, "
+ " bsl.`longitude`, "
+ " bsl.`road`, "
+ " bsl.`category`, "
+ " bsr.renovation_required, "
+ " IF(bsr.shelter_image IS NOT NULL AND bsr.shelter_image != '', "
+ " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', bsr.shelter_image), "
+ " NULL) AS shelter_image, "
+ " COALESCE(bsr.stage_status,'Pending') AS stage_status "
+ "FROM `bus_shelter_list` bsl "
+ "LEFT JOIN `bus_shelter_renovation` bsr "
+ " ON bsr.bsid = bsl.id AND bsr.isactive = 1 "
+ "WHERE bsl.id = ? ";
System.out.println(sql);
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, id);
ObjectMapper mapper = new ObjectMapper();
for (Map<String, Object> row : result) {
Object renovation_required = row.get("renovation_required");
if (renovation_required != null) {
sql = "SELECT COALESCE(SUM(`weightage`), 0) AS total_weightage "
+ "FROM `bus_shelter_renovation_data` "
+ "WHERE bsid = ?";
List<Map<String, Object>> presentage = jdbcBusShelterTemplate.queryForList(sql, row.get("id"));
// Safely get the first result
if (!presentage.isEmpty()) {
row.put("stage_presentage", presentage.get(0).get("total_weightage"));
} else {
row.put("stage_presentage", 0);
}
} else {
row.put("stage_presentage", 0);
}
// Location Check
double shelterLat = Double.parseDouble(row.get("latitude").toString());
double shelterLng = Double.parseDouble(row.get("longitude").toString());
double userLat = Double.parseDouble(latitude);
double userLng = Double.parseDouble(longitude);
// Calculate distance using Haversine formula
double earthRadius = 6371008.8; // in meters
double dLat = Math.toRadians(userLat - shelterLat);
double dLng = Math.toRadians(userLng - shelterLng);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(shelterLat)) * Math.cos(Math.toRadians(userLat))
* Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
double radiusInMeters = Double.parseDouble(getConfigValue());
row.put("user_on_correct_location", distance <= radiusInMeters); // true if within radius meters
////////
if(!"0".equals(renovation_required_condition)) {
// Stages
List<Map<String, Object>> stageListRaw = getStageList();
List<Map<String, Object>> stageList = (List<Map<String, Object>>) stageListRaw.get(0).get("data");
List<Map<String, Object>> stagedata = new ArrayList<>();
for (Map<String, Object> stage : stageList) {
Map<String, Object> stageEntry = new HashMap<>(stage); // Clone base stage info
stageEntry.put("stageid", stage.get("sid"));
stageEntry.put("stage_name", stage.get("name"));
stageEntry.put("weightage", stage.get("weightage"));
stageEntry.put("orderby", stage.get("orderby"));
sql = "SELECT `dataid`, `bsid`, `stageid`, "
+ "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `image`) AS `image`, "
+ "`remarks`, `weightage`, "
+ "`zone`, `ward`, `latitude`, `longitude`, `streetname`, `streetid`, "
+ " DATE_FORMAT(`cdate`, '%d-%m-%Y') AS `cdate`, "
+ "`cby`, `isactive` FROM `bus_shelter_renovation_data` "
+ "WHERE `bsid` = ? AND `stageid` = ? AND isactive = 1";
List<Map<String, Object>> resultStageData = jdbcBusShelterTemplate.queryForList(sql, row.get("id"), stage.get("sid"));
if (!resultStageData.isEmpty()) {
Map<String, Object> stageDataRow = resultStageData.get(0);
stageEntry.put("stage_image", stageDataRow.get("image"));
stageEntry.put("stage_remarks", stageDataRow.get("remarks"));
stageEntry.put("stage_date", stageDataRow.get("cdate"));
stageEntry.put("stage_status", "Completed");
stageEntry.put("stage_presentage", stageDataRow.get("weightage"));
} else {
// Defaults if no data available
stageEntry.put("stage_image", null);
stageEntry.put("stage_remarks", null);
stageEntry.put("stage_date", null);
stageEntry.put("stage_status", "Pending");
stageEntry.put("stage_presentage", 0);
}
stagedata.add(stageEntry);
}
row.put("stages", stagedata);
}
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter With Stage Details.");
response.put("data", result);
return Collections.singletonList(response);
}
@Transactional
public String addRenovationBaseData(
String shelter_id, String renovation_required, String image,
String latitude, String longitude, String zone, String ward,
String streetname, String streetid, String stage_status
) {
String sql ="INSERT INTO `bus_shelter_renovation`("
+ "`bsid`, `renovation_required`, `shelter_image`, "
+ "`latitude`, `longitude`, `zone`, `ward`, `streetname`, `streetid`, "
+ "`stage_status`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
jdbcBusShelterTemplate.update(sql, shelter_id, renovation_required, image, latitude, longitude , zone, ward, streetname, streetid, stage_status);
return "success";
}
public String updateStageStatus(String shelter_id, String stage_status, String datetxt) {
String sql = "UPDATE `bus_shelter_renovation` SET `stage_status`=?,`lastcdate` =? WHERE `bsid`=?";
jdbcBusShelterTemplate.update(sql,stage_status, datetxt, shelter_id);
return "sussess";
}
@Transactional
public List<Map<String, Object>> saveStageActivityData(
String shelter_id,
String cby,
String latitude,
String longitude,
String zone,
String ward,
String streetname,
String streetid,
String stageid,
String remarks,
String weightage,
MultipartFile file,
MultipartFile stage_file,
String renovation_required) {
List<Map<String, Object>> result = null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
String image = "";
String stage_image = "";
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
// Handle file upload if a file is provided
if (file != null && !file.isEmpty()) {
image = fileUpload("bushshelter", shelter_id, file);
}
// Question Images
if (stage_file != null && !stage_file.isEmpty()) {
stage_image = fileUpload("stage", stageid, stage_file);
}
String baseimg = image;
String stage_image_txt = stage_image;
//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);
String stage_status = "Pending";
if("0".equals(renovation_required) || "1".equals(renovation_required)) {
addRenovationBaseData(shelter_id, renovation_required, image, latitude, longitude , zone, ward, streetname, streetid, stage_status);
}
if("0".equals(renovation_required)) {
stage_status = "Completed";
updateStageStatus(shelter_id, stage_status, todayDate);
}
if(!"0".equals(renovation_required)) {
String sqlQuery = "INSERT INTO `bus_shelter_renovation_data`("
+ "`bsid`, `stageid`, `image`, `remarks`, `weightage`, `zone`, "
+ "`ward`, `latitude`, `longitude`, `streetname`, `streetid`, `cby`"
+ ") "
+ "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[] { "dataid" });
ps.setString(1, shelter_id);
ps.setString(2, stageid);
ps.setString(3, stage_image_txt);
ps.setString(4, remarks);
ps.setString(5, weightage);
ps.setString(6, zone);
ps.setString(7, ward);
ps.setString(8, latitude);
ps.setString(9, longitude);
ps.setString(10, streetname);
ps.setString(11, streetid);
ps.setString(12, cby);
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 Bus Shelter stage data was inserted successfully!");
System.out.println("A Bus Shelter stage data was inserted successfully! Bus Shelter ID: " + generatedId);
String sql = "SELECT COALESCE(SUM(`weightage`), 0) AS total_weightage "
+ "FROM `bus_shelter_renovation_data` "
+ "WHERE bsid = ?";
List<Map<String, Object>> resultStageData = jdbcBusShelterTemplate.queryForList(sql, shelter_id );
Object totalWeightageObj = resultStageData.get(0).get("total_weightage");
double totalWeightage = totalWeightageObj != null ? Double.parseDouble(totalWeightageObj.toString()) : 0;
if (totalWeightage >= 100) {
stage_status = "Completed";
}
updateStageStatus(shelter_id, stage_status, todayDate);
} else {
response.put("status", "error");
response.put("message", "Failed to insert a Bus Shelter stage data. Bus Shelter 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());
}
}
}
else {
response.put("insertId", 0);
response.put("status", "success");
response.put("message", "0 - A Bus Shelter stage data was inserted successfully!");
}
return Collections.singletonList(response);
}
// Reports
public List<Map<String, Object>> getZoneList() {
String sql = "SELECT "
+ " bsl.zone, "
+ " COUNT(DISTINCT bsl.id) AS total_shelters, "
+ " COUNT(DISTINCT CASE WHEN bsr.bsid IS NULL THEN bsl.id END) AS total_not_visited, "
+ " COUNT(DISTINCT CASE WHEN bsr.renovation_required = 1 THEN bsr.bsid END) AS total_need_improvement, "
+ " COUNT(DISTINCT CASE WHEN bsr.renovation_required = 0 THEN bsr.bsid END) AS total_no_improvement, "
+ " COUNT(DISTINCT CASE WHEN bsr.stage_status != 'Completed' AND bsr.stage_status IS NOT NULL THEN bsr.bsid END) AS total_pending, "
+ " COUNT(DISTINCT CASE WHEN bsr.stage_status = 'Completed' THEN bsr.bsid END) AS total_completed "
+ "FROM "
+ " bus_shelter_list bsl "
+ "LEFT JOIN "
+ " bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 "
+ "WHERE "
+ " bsl.isactive = 1 "
+ "GROUP BY "
+ " bsl.zone "
+ "ORDER BY "
+ " bsl.zone";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql);
// Compute totals
Map<String, Object> totals = new HashMap<>();
totals.put("zone", "Total");
String[] keys = {
"total_shelters", "total_not_visited",
"total_need_improvement", "total_no_improvement",
"total_pending", "total_completed"
};
for (String key : keys) {
int sum = result.stream()
.mapToInt(row -> row.get(key) != null ? ((Number) row.get(key)).intValue() : 0)
.sum();
totals.put(key, sum);
}
// Add totals row at the end
result.add(totals);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter Zone Report.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getWardList(String zone) {
String sql = "SELECT "
+ " bsl.ward,"
+ " COUNT(DISTINCT bsl.id) AS total_shelters,"
+ " COUNT(DISTINCT CASE WHEN bsr.bsid IS NULL THEN bsl.id END) AS total_not_visited,"
+ " COUNT(DISTINCT CASE WHEN bsr.renovation_required = 1 THEN bsr.bsid END) AS total_need_improvement,"
+ " COUNT(DISTINCT CASE WHEN bsr.renovation_required = 0 THEN bsr.bsid END) AS total_no_improvement,"
+ " COUNT(DISTINCT CASE WHEN bsr.stage_status != 'Completed' AND bsr.stage_status IS NOT NULL THEN bsr.bsid END) AS total_pending,"
+ " COUNT(DISTINCT CASE WHEN bsr.stage_status = 'Completed' THEN bsr.bsid END) AS total_completed "
+ "FROM "
+ " bus_shelter_list bsl "
+ "LEFT JOIN "
+ " bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 "
+ "WHERE "
+ " bsl.isactive = 1 "
+ " AND bsl.zone = ? "
+ "GROUP BY "
+ " bsl.ward "
+ "ORDER BY "
+ " bsl.ward";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql,zone);
// Compute totals
Map<String, Object> totals = new HashMap<>();
totals.put("ward", "Total");
String[] keys = {
"total_shelters", "total_not_visited",
"total_need_improvement", "total_no_improvement",
"total_pending", "total_completed"
};
for (String key : keys) {
int sum = result.stream()
.mapToInt(row -> row.get(key) != null ? ((Number) row.get(key)).intValue() : 0)
.sum();
totals.put(key, sum);
}
// Add totals row at the end
result.add(totals);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter Ward Report.");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getVistPendingList(String ward) {
String sql = "SELECT bsl.id, bsl.zone, bsl.ward, bsl.road, bsl.latitude, bsl.longitude " +
"FROM bus_shelter_list bsl " +
"LEFT JOIN bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 " +
"WHERE bsl.isactive = 1 " +
"AND bsl.ward = ? AND bsr.bsid IS NULL";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelters not yet visited (pending) in ward " + ward);
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getRenovationRequiredList(String ward) {
String sql = "SELECT bsl.id, bsl.zone, bsl.ward, bsl.road, bsl.latitude, bsl.longitude, bsr.stage_status " +
"FROM bus_shelter_list bsl " +
"LEFT JOIN bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 " +
"WHERE bsl.isactive = 1 " +
"AND bsl.ward = ? AND bsr.renovation_required=1";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelters not yet visited (pending) in ward " + ward);
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getRenovationNotRequiredList(String ward) {
String sql = "SELECT bsl.id, bsl.zone, bsl.ward, bsl.road, bsl.latitude, bsl.longitude, bsr.stage_status " +
"FROM bus_shelter_list bsl " +
"LEFT JOIN bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 " +
"WHERE bsl.isactive = 1 " +
"AND bsl.ward = ? AND bsr.renovation_required=0";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelters improvement Needed List in ward " + ward);
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getWorkPendingList(String ward) {
String sql = "SELECT bsl.id, bsl.zone, bsl.ward, bsl.road, bsl.latitude, bsl.longitude, bsr.stage_status " +
"FROM bus_shelter_list bsl " +
"INNER JOIN bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 " +
"WHERE bsl.isactive = 1 " +
"AND bsl.ward = ? AND COALESCE(bsr.stage_status, 'Pending') != 'Completed'";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter improvement Not Needed List for ward " + ward);
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getWorkCompletedList(String ward) {
String sql = "SELECT bsl.id, bsl.zone, bsl.ward, bsl.road, bsl.latitude, bsl.longitude, bsr.stage_status " +
"FROM bus_shelter_list bsl " +
"INNER JOIN bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1 " +
"WHERE bsl.isactive = 1 " +
"AND bsl.ward = ? AND COALESCE(bsr.stage_status, 'Pending') = 'Completed'";
List<Map<String, Object>> result = jdbcBusShelterTemplate.queryForList(sql, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Bus Shelter work pending list for ward " + ward);
response.put("data", result);
return Collections.singletonList(response);
}
/*
Zone wise:
SELECT
bsl.zone,
COUNT(DISTINCT bsl.id) AS total_shelters,
COUNT(DISTINCT CASE WHEN bsr.bsid IS NULL THEN bsl.id END) AS total_not_visited,
COUNT(DISTINCT CASE WHEN bsr.renovation_required = 1 THEN bsr.bsid END) AS total_need_improvement,
COUNT(DISTINCT CASE WHEN bsr.renovation_required = 0 THEN bsr.bsid END) AS total_no_improvement,
COUNT(DISTINCT CASE WHEN bsr.stage_status != 'Completed' AND bsr.stage_status IS NOT NULL THEN bsr.bsid END) AS total_pending,
COUNT(DISTINCT CASE WHEN bsr.stage_status = 'Completed' THEN bsr.bsid END) AS total_completed
FROM
bus_shelter_list bsl
LEFT JOIN
bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1
WHERE
bsl.isactive = 1
GROUP BY
bsl.zone
ORDER BY
bsl.zone;
// ward wise
SELECT
bsl.ward,
COUNT(DISTINCT bsl.id) AS total_shelters,
COUNT(DISTINCT CASE WHEN bsr.bsid IS NULL THEN bsl.id END) AS total_not_visited,
COUNT(DISTINCT CASE WHEN bsr.renovation_required = 1 THEN bsr.bsid END) AS total_need_improvement,
COUNT(DISTINCT CASE WHEN bsr.renovation_required = 0 THEN bsr.bsid END) AS total_no_improvement,
COUNT(DISTINCT CASE WHEN bsr.stage_status != 'Completed' AND bsr.stage_status IS NOT NULL THEN bsr.bsid END) AS total_pending,
COUNT(DISTINCT CASE WHEN bsr.stage_status = 'Completed' THEN bsr.bsid END) AS total_completed
FROM
bus_shelter_list bsl
LEFT JOIN
bus_shelter_renovation bsr ON bsr.bsid = bsl.id AND bsr.isactive = 1
WHERE
bsl.isactive = 1 AND bsl.isdelete = 0
AND bsl.zone = '01'
GROUP BY
bsl.ward
ORDER BY
bsl.ward;
*/
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/busshelters/service/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.busshelters.service;

42
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/Scheduler/C_D_WasteScheduler.java

@ -0,0 +1,42 @@
package in.gov.chennaicorporation.mobileservice.c_d_waste.Scheduler;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import in.gov.chennaicorporation.mobileservice.c_d_waste.service.c_d_WasteService;
import in.gov.chennaicorporation.mobileservice.c_d_waste.service.c_d_WasteUserService;
@Component
@EnableScheduling
public class C_D_WasteScheduler {
@Autowired
private c_d_WasteService c_d_WasteService;
@Autowired
private c_d_WasteUserService c_d_WasteUserService;
//@Scheduled(cron = "0 0 * * * *", zone = "Asia/Kolkata") for hour
// @Scheduled(cron = "0 * * * * *", zone = "Asia/Kolkata") for minute
@Scheduled(cron = "0 0 * * * *", zone = "Asia/Kolkata")
public void cd_wasteScheduler() {
System.out.println("CD_wasteScheduler Started......");
Map<String,Object> result= c_d_WasteService.updateCDWasteEscalationStatus("1");
System.out.println("Scheduler Result: " + result);
}
@Scheduled(cron = "0 0 * * * *", zone = "Asia/Kolkata")
public void cd_userwasteScheduler() {
System.out.println("CD_userwasteScheduler Started......");
Map<String,Object> result= c_d_WasteUserService.updateCDWasteUserEscalationStatus("1");
System.out.println("Scheduler Result: " + result);
}
}

406
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/APIC_D_WasteController.java

@ -0,0 +1,406 @@
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<String, String> 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,
@RequestParam(value = "StreetType", required = false) String StreetType
) {
return c_d_WasteService.saveWaste(cby,latitude,longitude,zone,ward,address,tonage,file, type, StreetType);
}
@PostMapping(value="/saveVendorWaste")
public List<?> saveVendorWaste(@RequestParam MultiValueMap<String, String> 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,
@RequestParam(value = "StreetType", required = false) String StreetType
) {
return c_d_WasteService.saveVendorWaste(latitude,longitude,zone,ward,address,tonage,file,type,ref_id, StreetType);
}
@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<String, String> 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,
// @RequestParam(value = "fromDate", required = false) String fromDATE,
// @RequestParam(value = "toDate", required = false) String toDATE
// ) {
// return c_d_WasteService.getMyticketllist(loginId,fromDATE,toDATE);
// }
//
// @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("/getMyticketllist")
public List<?> getMyticketllist(
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "fromDate", required = false) String fromDATE,
@RequestParam(value = "toDate", required = false) String toDATE,
@RequestParam(value = "type", required = false) String type
) {
return c_d_WasteService.getMyticketllist(loginId,fromDATE,toDATE,type);
}
@GetMapping("/getApprovalPendingList")
public List<?> getApprovalPendingList(
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "type", required = false) String type
) {
return c_d_WasteService.getApprovalPendingList(loginId,ward,type);
}
@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<String, String> 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<String, String> 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','councillor','IE'";
// }
// 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','councillor','IE'";
// }
// 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','councillor','IE'";
// }
// else {
// //requestBy = "'"+requestBy+"'";
// }
//
// return c_d_WasteService.getListByStatus(fromDATE,toDATE, zone, ward, status,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,
@RequestParam(value = "type", required = false) String type
) {
if (requestBy == null || requestBy.isBlank()) {
requestBy = "'Officer'";
}
else {
requestBy = "'"+requestBy+"'";
}
return c_d_WasteService.getOfficerZoneWiseCount(fromDATE,toDATE,requestBy,type);
}
@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,
@RequestParam(value = "type", required = false) String type
) {
if (requestBy == null || requestBy.isBlank()) {
requestBy = "'Officer'";
}
else {
requestBy = "'"+requestBy+"'";
}
return c_d_WasteService.getOfficerWardWiseCount(fromDATE,toDATE, zone,requestBy,type);
}
@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,
@RequestParam(value = "type", required = false) String type
) {
if (requestBy == null || requestBy.isBlank()) {
requestBy = "'Vendor','councillor','IE'";
}
else {
requestBy = "'"+requestBy+"'";
}
return c_d_WasteService.getVendorZoneWiseCount(fromDATE,toDATE,requestBy,type);
}
@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,
@RequestParam(value = "type", required = false) String type
) {
if (requestBy == null || requestBy.isBlank()) {
requestBy = "'Vendor','councillor','IE'";
}
else {
requestBy = "'"+requestBy+"'";
}
return c_d_WasteService.getVendorWardWiseCount(fromDATE,toDATE, zone,requestBy,type);
}
@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,
@RequestParam(value = "type", required = false) String type
) {
if (requestBy == null || requestBy.isBlank()) {
requestBy = "'Vendor','Officer','councillor','IE'";
}
else {
//requestBy = "'"+requestBy+"'";
}
return c_d_WasteService.getListByStatus(fromDATE,toDATE, zone, ward, status,requestBy,type);
}
@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);
}
}

69
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/controller/API_C_D_WasteUserController.java

@ -0,0 +1,69 @@
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<String, String> 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);
// }
@GetMapping("/getUserApprovalPendingList")
public List<?> getApprovalPendingList(
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "type", required = false) String type
) {
return c_d_WasteUserService.getApprovalPendingList(loginId,ward,type);
}
@PostMapping(value="/saveUserApproval")
public List<?> saveApproval(@RequestParam MultiValueMap<String, String> 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);
}
}

1
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;

1
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.c_d_waste;

2123
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteService.java
File diff suppressed because it is too large
View File

1333
src/main/java/in/gov/chennaicorporation/mobileservice/c_d_waste/service/c_d_WasteUserService.java
File diff suppressed because it is too large
View File

1
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;

64
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
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/component/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.component;

22
src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java

@ -0,0 +1,22 @@
package in.gov.chennaicorporation.mobileservice.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
public String qrAssetFeedback = "http://117.232.67.158:8063";
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 = "";
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

687
src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java

@ -0,0 +1,687 @@
package in.gov.chennaicorporation.mobileservice.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
// private static String host = "localhost:3306";
// private static String dbpassword = "root";
// private static String dbpassword = "gccroot";
// AWS
private static String host = "gcc-facial-db-instance-1.cf48eqcciziq.ap-south-1.rds.amazonaws.com:3306";
private static String dbpassword = "gcc-facial-password";
////////////////////////////// (For GCC APP) ////////////////////////
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "appEntityManagerFactory", transactionManagerRef = "appTransactionManager", basePackages = {
"in.gov.chennaicorporation" })
public static class MysqlAppDataSourceConfig {
@Primary
@Bean(name = "mysqlAppDataSource")
public DataSource mysqlAppDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_apps");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
@Primary
@Bean(name = "appEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier("mysqlAppDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan("in.gov.chennaicorporation");
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
@Primary
@Bean(name = "appTransactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("appEntityManagerFactory") jakarta.persistence.EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
////////////////////////////// (For GCC Activity Master)
////////////////////////////// ////////////////////////
@Bean(name = "mysqlActivityDataSource")
public DataSource mysqlActivityDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_activity");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Penalty Master) ////////////////////////
@Bean(name = "mysqlPenaltyDataSource")
public DataSource mysqlPenaltyDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_penalty_pos");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Cattle Catch Master)
////////////////////////////// ////////////////////////
@Bean(name = "mysqlCattleCatchDataSource")
public DataSource mysqlCattleCatchDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_penalty");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (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;
}
////////////////////////////// (For PGR Master) ////////////////////////
@Bean(name = "mysqlPGRMasterDataSource")
public DataSource mysqlPGRMasterDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/erp_pgr");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For PGR Master) ////////////////////////
@Bean(name = "mysqlGCCUserDataSource")
public DataSource mysqlGCCUserDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_users");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For PGR Master) ////////////////////////
@Bean(name = "mysqlGccSOSDataSource")
public DataSource mysqlGccSOSDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_sos");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For NULM Staff) ////////////////////////
@Bean(name = "mysqlNulmDataSource")
public DataSource mysqlNulmDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_nulm");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Stray Dog (veterinary))
////////////////////////////// ////////////////////////
@Bean(name = "mysqlGccStraydogsDataSource")
public DataSource mysqlGccStraydogsDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_stray_dogs");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Schools) ////////////////////////
@Bean(name = "mysqlGccSchoolsDataSource")
public DataSource mysqlGccSchoolsDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_schools");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Parks and Playground)
////////////////////////////// ////////////////////////
@Bean(name = "mysqlGccParksDataSource")
public DataSource mysqlGccParksDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_parks_playground");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Toilets) ////////////////////////
@Bean(name = "mysqlToiletsDataSource")
public DataSource mysqlToiletsDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_toilets");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
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 domestic_waste_management )
////////////////////////////// ////////////////////////
@Bean(name = "mysqlGccDomesticWasteManagementDataSource")
public DataSource domesticwastemanagement() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/domestic_waste_management");
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;
}
////////////////////////////// (For Toilets) ////////////////////////
@Bean(name = "mysqlPrivateToiletsDataSource")
public DataSource mysqlPrivateToiletsDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_private_toilets");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Toilets) ////////////////////////
@Bean(name = "mysqlRoadCutDataSource")
public DataSource mysqlRoadCutDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_roadcut");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For PotHole) ////////////////////////
@Bean(name = "mysqlGccPotHoleDataSource")
public DataSource mysqlGccPotHoleDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_pothole");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Construction Guidelines)
////////////////////////////// ////////////////////////
@Bean(name = "mysqlGccConstructionGuidelinesSource")
public DataSource mysqlGccConstructionGuidelinesSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_construction_guidelines");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For View Cutter) ////////////////////////
@Bean(name = "mysqlViewCutterDataSource")
public DataSource mysqlViewCutterDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_view_cutter");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For SpeedBrake ) ////////////////////////
@Bean(name = "mysqlGccSpeedBrakeSource")
public DataSource mysqlGccSpeedBrakeSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_speedbrake");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For Construction Guidelines)
////////////////////////////// ////////////////////////
@Bean(name = "mysqlGccBuildingDemolitionSource")
public DataSource mysqlGccBuildingDemolitionSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_building_demolition");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Construction Guidelines)
///////////////////////////// ////////////////////////
@Bean(name = "mysqlGccRoadWarSource")
public DataSource mysqlGccRoadWarSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_roadwar");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For ManHole) ////////////////////////
@Bean(name = "mysqlGccManHoleSource")
public DataSource mysqlGccManHoleSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_manholes");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Disposal Point) ////////////////////////
@Bean(name = "mysqlGccDisposalPointSource")
public DataSource mysqlGccDisposalPointSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_disposalpoint");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Street Cleaning) ////////////////////////
@Bean(name = "mysqlGccStreetCleaningSource")
public DataSource mysqlGccStreetCleaningSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_street_cleaning");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Pumps & Sumps) ////////////////////////
@Bean(name = "mysqlGccPumpSource")
public DataSource mysqlGccPumpSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_pumps");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Special Vehicles) ////////////////////////
@Bean(name = "mysqlGccSpecialVehicleSource")
public DataSource mysqlGccSpecialVehicleSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_special_vehicle");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Sluice Point) ////////////////////////
@Bean(name = "mysqlGccSluicePointSource")
public DataSource mysqlGccSluicePointSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_sluicepoint");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Railway Culverts) ////////////////////////
@Bean(name = "mysqlGccRailwayCulvertSource")
public DataSource mysqlGccRailwayCulvertSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_railway_culvert");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
///////////////////////////// (For Food Distribution) ////////////////////////
@Bean(name = "mysqlGccFoodDistributionSource")
public DataSource mysqlGccFoodDistributionSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_food_distribution");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For FlagPole) ////////////////////////
@Bean(name = "mysqlGccFlagPoleDataSource")
public DataSource mysqlGccFlagPoleDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_flag_pole");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Medical Camp ////////////////////////
@Bean(name = "mysqlGccMedicalCampDataSource")
public DataSource mysqlGccMedicalCampDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_health_camp");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Home Less ////////////////////////
@Bean(name = "mysqlGccHomelessDataSource")
public DataSource mysqlGccHomelessDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/homeless_survey");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Abandoned Vehicle ////////////////////////
@Bean(name = "mysqlGccAbandonedVehicleSource")
public DataSource mysqlGccAbandonedVehicleSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/abandoned_vehicle");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Green Committee ////////////////////////
@Bean(name = "mysqlGccGreenCommitteeSource")
public DataSource mysqlGccGreenCommitteeSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/green_committee");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Thooimai Mission ////////////////////////
@Bean(name = "mysqlThooimaiMissionSource")
public DataSource mysqlThooimaiMissionSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/thooimai_mission");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Boat Service ////////////////////////
@Bean(name = "mysqlBoatSource")
public DataSource mysqlBoatSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/boat_service");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// (For V-Track (jTrack)) ////////////////////////
@Bean(name = "mysqlVehiclTrackingDataSource")
public DataSource mysqlVehiclTrackingDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_vtrack");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Abandoned Vehicle ////////////////////////
@Bean(name = "mysqlillegalDebrisVehicleSource")
public DataSource mysqlillegalDebrisVehicleSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/illegal_debris_vehicle");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Abandoned Vehicle ////////////////////////
@Bean(name = "mysqlElectionDataSource")
public DataSource mysqlElectionDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_election");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For IE Complaints ////////////////////////
@Bean(name = "mysqlIEComplaintsDataSource")
public DataSource mysqlIEComplaintsDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_ie_complaints");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Construction Payment ////////////////////////
@Bean(name = "mysqlConstructionPaymentDataSource")
public DataSource mysqlConstructionPaymentDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/construction_payment");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For Child Survey ////////////////////////
@Bean(name = "mysqlChildSurveyDataSource")
public DataSource mysqlChildSurveyDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_children_survey");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// For homeless Survey ////////////////////////
@Bean(name = "mysqlHomeLessSurveyDataSource")
public DataSource mysqlHomeLessSurveyDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_homeless_survey");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////// Tenements//////////////////////
@Bean(name = "mysqlTenementDataSource")
public DataSource mysqlTenementDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_tenements");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////// Cattle Survey//////////////////////
@Bean(name = "mysqlCattleSurveyGccDataSource")
public DataSource mysqlCattleSurveyGccDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_cattle_survey");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////// GCC Mobile Menu //////////////////////
@Bean(name = "mysqlGccMobileMenuDataSource")
public DataSource mysqlGccMobileMenuDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://" + host + "/gcc_mobile_menus");
dataSource.setUsername("root");
dataSource.setPassword(dbpassword);
return dataSource;
}
////////////////////////////// ORACLE ////////////////////////
@Bean(name = "oracleERPDataSource")
public DataSource oracleERPDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@10.1.0.14:1521:chncorp");
dataSource.setUsername("FAS");
dataSource.setPassword("FAS");
return dataSource;
}
}

20
src/main/java/in/gov/chennaicorporation/mobileservice/configuration/JacksonConfiguration.java

@ -0,0 +1,20 @@
package in.gov.chennaicorporation.mobileservice.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // Do not fail on empty beans during serialization
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Serialize dates as Strings
objectMapper.registerModule(new JavaTimeModule()); // Register JavaTimeModule for Java 8 Date/Time support
return objectMapper;
}
}

26
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<ApiLoggingFilter> loggingFilter() {
FilterRegistrationBean<ApiLoggingFilter> 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;
}
}

191
src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/controller/APIController.java

@ -0,0 +1,191 @@
package in.gov.chennaicorporation.mobileservice.constructionGuidelines.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.constructionGuidelines.service.GuidelinesService;
@RequestMapping("/gccofficialapp/api/constructionguidelines/")
@RestController("gccofficialappsconstructionguidelines")
public class APIController {
@Autowired
private GuidelinesService guidelinesService;
@GetMapping(value = "/getConstructionList")
public List<?> getToiletsList(
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude) {
return guidelinesService.getConstructionList(cby, latitude, longitude);
}
@GetMapping(value = "/getUnitOfficeList")
public List<?> getUnitOfficeList(
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward) {
return guidelinesService.getUnitOfficeList(zone, ward);
}
@GetMapping(value = "/getBuildingType")
public List<?> getBuildingTypeList() {
return guidelinesService.getBuildingTypeList();
}
@PostMapping(value = "/saveDetails")
public List<Map<String, Object>> saveConstructionDetails(
@RequestParam(value = "contractor_name", required = true) String contractorName,
@RequestParam(value = "contractor_mobile", required = true) String contractorMobile,
@RequestParam(value = "buildup_area", required = true) String buildupArea,
@RequestParam(value = "building_type", required = true) String buildingType,
@RequestParam(value = "high_rise", required = true) String highRise,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "unit", required = true) String unit,
@RequestParam(value = "under_guidelines", required = true) String underGuidelines,
@RequestParam(value = "site_address", required = true) String siteAddress,
@RequestParam(value = "cby", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "mainfile", required = true) MultipartFile mainFile) {
return guidelinesService.saveConstructionDetails(
contractorName, contractorMobile, buildupArea, buildingType, highRise,
zone, ward, unit, underGuidelines, siteAddress, cby, latitude, longitude, mainFile);
}
@GetMapping(value = "/getguidelines")
public List<?> getGuidelinesList() {
return guidelinesService.getGuidelinesList();
}
@PostMapping(value = "/saveFeedback")
public List<?> saveGuidelinesFeedback(
@RequestParam(value = "cdid", required = true) String cdid,
@RequestParam(value = "ciid", required = true) String ciid,
@RequestParam(value = "cby", required = true) String cby,
@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 = "q1", required = true) String q1,
@RequestParam(value = "q2", required = true) String q2,
@RequestParam(value = "q3", required = true) String q3,
@RequestParam(value = "q4", required = true) String q4,
@RequestParam(value = "q5", required = true) String q5,
@RequestParam(value = "q6", required = true) String q6,
@RequestParam(value = "q7", required = true) String q7,
@RequestParam(value = "q8", required = true) String q8,
@RequestParam(value = "q9", required = true) String q9,
@RequestParam(value = "q10", required = true) String q10,
@RequestParam(value = "q11", required = true) String q11,
@RequestParam(value = "q12", required = true) String q12,
@RequestParam(value = "q13", required = true) String q13,
@RequestParam(value = "q14", required = true) String q14,
@RequestParam(value = "q15", required = true) String q15,
@RequestParam(value = "q16", required = true) String q16,
@RequestParam(value = "q17", required = true) String q17,
@RequestParam(value = "q18", required = true) String q18,
@RequestParam(value = "image1", required = true) MultipartFile image1,
@RequestParam(value = "image2", required = true) MultipartFile image2,
@RequestParam(value = "image3", required = true) MultipartFile image3,
@RequestParam(value = "image4", required = true) MultipartFile image4,
@RequestParam(value = "image5", required = true) MultipartFile image5) {
return guidelinesService.saveGuidlinesFeedback(
cdid, ciid, cby, latitude, longitude, zone, ward,
q1, q2, q3, q4, q5, q6, q7, q8, q9, q10,
q11, q12, q13, q14, q15, q16, q17, q18,
image1, image2, image3, image4, image5);
}
@GetMapping(value = "/getRevisitConstructionList")
public List<?> getRevisitConstructionList(
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude) {
return guidelinesService.getRevisitConstructionList(cby, latitude, longitude);
}
@GetMapping(value = "/getRevisitConstructionListWithFeedback")
public List<?> getRevisitConstructionListWithFeedback(
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "cdid", required = true) String cdid,
@RequestParam(value = "ciid", required = true) String ciid) {
return guidelinesService.getRevisitConstructionListWithFeedback(cby, cdid, ciid);
}
@GetMapping(value = "/get7thRevisitConstructionList")
public List<?> get7RevisitConstructionList(
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude) {
return guidelinesService.get7thRevisitConstructionList(cby, latitude, longitude);
}
@PostMapping(value = "/saveAfterNoticeDetails")
public List<Map<String, Object>> saveAfterNoticeDetails(
@RequestParam(value = "cdid", required = true) String cdid,
@RequestParam(value = "ciid", required = true) String ciid,
@RequestParam(value = "giid", required = true) String giid,
@RequestParam(value = "remarks", required = true) String remarks,
@RequestParam(value = "status", required = true) String status,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "mainfile", required = true) MultipartFile mainfile) {
return guidelinesService.saveAfterNoticeDetails(
cdid, ciid, giid, remarks, status, zone, ward, cby, latitude, longitude, mainfile);
}
@PostMapping(value = "/saveFinalNoticeDetails")
public List<Map<String, Object>> saveFinalNoticeDetails(
@RequestParam(value = "cdid", required = true) String cdid,
@RequestParam(value = "ciid", required = true) String ciid,
@RequestParam(value = "giid", required = true) String giid,
@RequestParam(value = "remarks", required = true) String remarks,
@RequestParam(value = "status", required = true) String status,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "mainfile", required = true) MultipartFile mainfile) {
return guidelinesService.saveFinalNoticeDetails(
cdid, ciid, giid, remarks, status, zone, ward, cby, latitude, longitude, mainfile);
}
// yogi
@PostMapping(value = "/saveFinalNoticeDetailsLockAndSealed")
public List<Map<String, Object>> saveFinalNoticeDetailsLockAndSealed(
@RequestParam(value = "cdid", required = true) String cdid,
@RequestParam(value = "ciid", required = true) String ciid,
@RequestParam(value = "giid", required = true) String giid,
@RequestParam(value = "remarks", required = true) String remarks,
@RequestParam(value = "status", required = true) String status,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "mainfile", required = true) MultipartFile mainfile) {
return guidelinesService.saveFinalNoticeDetailLockAndSealed(
cdid, ciid, giid, remarks, status, zone, ward, cby, latitude, longitude, mainfile);
}
// yogi
@GetMapping(value = "/getLockAndSealedList")
public List<?> getLockAndSealedList(
@RequestParam(value = "loginId", required = true) String cby,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude) {
return guidelinesService.getLockAndSealedList(cby, latitude, longitude);
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/controller/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.constructionGuidelines.controller;

1
src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.constructionGuidelines;

1624
src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/service/GuidelinesService.java
File diff suppressed because it is too large
View File

1
src/main/java/in/gov/chennaicorporation/mobileservice/constructionGuidelines/service/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.constructionGuidelines.service;

205
src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIOfficialController.java

@ -0,0 +1,205 @@
package in.gov.chennaicorporation.mobileservice.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.service.DataSyncService;
import in.gov.chennaicorporation.mobileservice.service.OTPGenerator;
import in.gov.chennaicorporation.mobileservice.service.OfficialAPIService;
import jakarta.servlet.http.HttpServletRequest;
@RequestMapping("/gccofficialapp/api/")
@RestController("gccofficialappRest")
public class APIOfficialController {
@Autowired
private OfficialAPIService officialAPIService;
@Autowired
private DataSyncService dataSyncService;
@GetMapping(value="")
public String index() {
return "Invalid Url";
}
@GetMapping({"/versionCheck"}) // Template
public List <?> versionCheck() {
return officialAPIService.versionCheck();
}
@GetMapping({"/nammaVersionCheck"}) // Template
public List <?> nammaVersionCheck() {
return officialAPIService.nammaVersionCheck();
}
// API FOR TOTHER APP
@GetMapping(value="/sendOTP")
public List sendOTP(HttpServletRequest request,
@RequestParam("mobileNo") String mobileNo,
@RequestParam("otpLength") Integer OTP_LENGTH,
@RequestParam(value = "mobilenocheck", required = false) String checkmobileno) {
String generatedToken = OTPGenerator.generateOTP(OTP_LENGTH);
return officialAPIService.sendOTP(request, mobileNo, generatedToken, checkmobileno);
}
@PostMapping(value="/savePassword")
public List savePetition(
@RequestParam("username") String username,
@RequestParam("password") String password
) {
return officialAPIService.updatePassword(username,password);
}
@GetMapping(value="login")
public List login(@RequestParam("username") String username, @RequestParam("password") String Password, @RequestParam("usertype") String usertype) {
return officialAPIService.getloginList(username, Password, usertype);
}
@GetMapping(value="getUserByMobile")
public List getUserByMobile(@RequestParam("mobileNo") String mobileNo) {
return officialAPIService.getUserListByMobileNumber(mobileNo);
}
@GetMapping(value="getUserinfo")
public List getUserinfo(@RequestParam("username") String username) {
return officialAPIService.getUserinfo(username);
}
@GetMapping(value="getUserList")
public List getUserList() {
return officialAPIService.getUserList();
}
@GetMapping(value="getUserGroups")
public List getUserGroups(@RequestParam String loginId) {
return officialAPIService.getUserGroups(loginId);
}
@GetMapping(value="getUserModules")
public List getUserModules(@RequestParam String loginId) {
return officialAPIService.getUserModules(loginId);
}
@GetMapping(value="getUserMenuItem")
public List getUserMenuItem(@RequestParam String loginId) {
return officialAPIService.getUserMenuItem(loginId);
}
// For Menu ////////////////////////////////////////
@GetMapping(value="/getMainMenu")
public List getMainMenu(@RequestParam String loginId){
return officialAPIService.getMainMenu(loginId);
}
@GetMapping(value="/getMenu")
public List getMenu(
@RequestParam String loginId,
@RequestParam(value = "departmentId", required = false) String departmentId){
return officialAPIService.getMenu(loginId,departmentId);
}
@GetMapping(value="/getSubMenu")
public List getSubMenu(@RequestParam String loginId,@RequestParam String menuId){
return officialAPIService.getSubMenu(loginId,menuId);
}
@GetMapping(value="/getSubSubMenu")
public List getSubSubMenu(@RequestParam String loginId,@RequestParam String menuId,@RequestParam String submenuId){
return officialAPIService.getSubSubMenu(loginId,menuId,submenuId);
}
// Menu End ////////////////////////////////////////
@GetMapping(value="/syncERPtoLocal")
public String syncERPtoLocal(@RequestParam("syncType") String syncType) {
return syncData(syncType);
}
public String syncData(String syncType) {
switch (syncType) {
case "egUser":
System.out.println("Starting Syning EG_USER Table Data.\n");
dataSyncService.syncEgUserData();
System.out.println("EG_USER Table Data synchronization completed.\n");
break;
case "EgDepartment":
System.out.println("Starting Syning EG_DEPARTMENT Table Data.\n");
dataSyncService.syncEgDepartmentData();
System.out.println("EG_DEPARTMENT Table Data synchronization completed.\n");
break;
case "EgBoundary":
System.out.println("Starting Syning EG_BOUNDARY Table Data.\n");
dataSyncService.syncEgBoundaryData();
System.out.println("EG_BOUNDARY Table Data synchronization completed.\n");
break;
case "EggrComplaintStatus":
System.out.println("Starting Syning EGGR_COMPLAINTSTATUS Table Data.\n");
dataSyncService.syncEggrComplaintStatusData();
System.out.println("EGGR_COMPLAINTSTATUS Table Data synchronization completed.\n");
break;
case "EggrComplaintTypes":
System.out.println("Starting Syning EGGR_COMPLAINTTYPES Table Data.\n");
dataSyncService.syncEggrComplaintTypesData();
System.out.println("EGGR_COMPLAINTTYPES Table Data synchronization completed.\n");
break;
case "EggrComplaintGroup":
System.out.println("Starting Syning EGGR_COMPLAINTGROUP Table Data.\n");
dataSyncService.syncEggrComplaintGroupData();
System.out.println("EGGR_COMPLAINTGROUP Table Data synchronization completed.\n");
break;
case "EggrComplaintDetails":
System.out.println("Starting Syning EGGR_COMPLAINTDETAILS Table Data.\n");
dataSyncService.syncEggrComplaintDetailsData();
System.out.println("EGGR_COMPLAINTDETAILS Table Data synchronization completed.\n");
break;
case "EggrRedressalDetails":
System.out.println("Starting Syning EGGR_REDRESSALDETAILS Table Data.\n");
dataSyncService.syncEggrRedressalDetailsData();
System.out.println("EGGR_REDRESSALDETAILS Table Data synchronization completed.\n");
break;
// additional cases
default:
System.out.println("Starting Syning EG_USER Table Data.\n");
dataSyncService.syncEgUserData();
System.out.println("EG_USER Table Data synchronization completed.\n");
System.out.println("Starting Syning EG_DEPARTMENT Table Data.\n");
dataSyncService.syncEgDepartmentData();
System.out.println("EG_DEPARTMENT Table Data synchronization completed.\n");
System.out.println("Starting Syning EG_BOUNDARY Table Data.\n");
dataSyncService.syncEgBoundaryData();
System.out.println("EG_BOUNDARY Table Data synchronization completed.\n");
System.out.println("Starting Syning EGGR_COMPLAINTSTATUS Table Data.\n");
dataSyncService.syncEggrComplaintStatusData();
System.out.println("EGGR_COMPLAINTSTATUS Table Data synchronization completed.\n");
System.out.println("Starting Syning EGGR_COMPLAINTTYPES Table Data.\n");
dataSyncService.syncEggrComplaintTypesData();
System.out.println("EGGR_COMPLAINTTYPES Table Data synchronization completed.\n");
System.out.println("Starting Syning EGGR_COMPLAINTGROUP Table Data.\n");
dataSyncService.syncEggrComplaintGroupData();
System.out.println("EGGR_COMPLAINTGROUP Table Data synchronization completed.\n");
System.out.println("Starting Syning EGGR_COMPLAINTDETAILS Table Data.\n");
dataSyncService.syncEggrComplaintDetailsData();
System.out.println("EGGR_COMPLAINTDETAILS Table Data synchronization completed.\n");
System.out.println("Starting Syning EGGR_REDRESSALDETAILS Table Data.\n");
dataSyncService.syncEggrRedressalDetailsData();
System.out.println("EGGR_REDRESSALDETAILS Table Data synchronization completed.\n");
}
return "ERP -> All PGR Data synchronization completed!";
}
}

22
src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIPetController.java

@ -0,0 +1,22 @@
package in.gov.chennaicorporation.mobileservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import in.gov.chennaicorporation.mobileservice.service.PetAPIService;
@RequestMapping("/gccofficialapp/pet/api")
@RestController("petapicontroller")
public class APIPetController {
@Autowired
private PetAPIService petAPIService;
@GetMapping(value="/paymentinfo")
public List<Map<String, Object>> getApiData(@RequestParam("fromDate") String fromDate, @RequestParam("toDate") String toDate ) {
return petAPIService.fetchApiData(fromDate, toDate);
}
}

78
src/main/java/in/gov/chennaicorporation/mobileservice/controller/FileController.java

@ -0,0 +1,78 @@
package in.gov.chennaicorporation.mobileservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.file.Path;
import java.nio.file.Paths;
@RequestMapping("/gccofficialapp")
@Controller("FileController")
public class FileController {
@Value("${file.upload.directory}")
private String uploadDirectory;
@GetMapping("/files/{directoryPath}/**")
public ResponseEntity<Resource> serveFile(@PathVariable String directoryPath, HttpServletRequest request) {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
//System.out.println(fullPath.toString()+"\n"+directoryPath.length()+"\n directoryPath:"+directoryPath);
//String relativePath = fullPath.substring(directoryPath.length() + 1); // Adding 1 for the trailing '/'
String relativePath = fullPath.replace("/gccofficialapp/files", "");
String filePath = uploadDirectory + "/" + relativePath;
Path path = Paths.get(filePath).normalize();
//System.out.println(path.toString());
Resource resource;
try {
resource = new UrlResource(path.toUri());
if (resource.exists() || resource.isReadable()) {
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
// Determine content type based on file extension
String fileName = resource.getFilename();
if (fileName != null) {
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
switch (fileExtension.toLowerCase()) {
case "jpg":
case "jpeg":
mediaType = MediaType.IMAGE_JPEG;
break;
case "png":
mediaType = MediaType.IMAGE_PNG;
break;
case "gif":
mediaType = MediaType.IMAGE_GIF;
break;
case "pdf":
mediaType = MediaType.APPLICATION_PDF;
break;
// Add more cases for other file types if needed
}
}
return ResponseEntity.ok()
.contentType(mediaType)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
//.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}

64
src/main/java/in/gov/chennaicorporation/mobileservice/controller/MainController.java

@ -0,0 +1,64 @@
package in.gov.chennaicorporation.mobileservice.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import in.gov.chennaicorporation.mobileservice.service.MainService;
import in.gov.chennaicorporation.mobileservice.service.OfficialAPIService;
@RequestMapping("/gccofficialapp")
@Controller("mainController")
public class MainController {
@Autowired
private MainService mainService;
private final Environment environment;
@Autowired
public MainController(Environment environment) {
this.environment = environment;
}
@GetMapping({ "", "/", "/index" })
public String main(Model model) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
model.addAttribute("assetsBaseUrl", assetsBaseUrl);
return "error";
}
@GetMapping({ "/support" })
public String support(Model model) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
model.addAttribute("assetsBaseUrl", assetsBaseUrl);
return "modules/gccofficialapp/support";
}
@GetMapping({ "/policy" })
public String main2(Model model) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
model.addAttribute("assetsBaseUrl", assetsBaseUrl);
return "modules/gccofficialapp/policy";
}
@GetMapping({ "/foodschemepolicy" })
public String foodschemepolicy(Model model) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
model.addAttribute("assetsBaseUrl", assetsBaseUrl);
return "modules/gccofficialapp/foodschemepolicy";
}
@GetMapping({ "/electionsupport" })
public String electionsupport(Model model) {
String assetsBaseUrl = environment.getProperty("assets.base-url");
model.addAttribute("assetsBaseUrl", assetsBaseUrl);
return "modules/gccofficialapp/electionsupport";
}
}

114
src/main/java/in/gov/chennaicorporation/mobileservice/controller/PdfTemplateController.java

@ -0,0 +1,114 @@
package in.gov.chennaicorporation.mobileservice.controller;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.mobileservice.constructionGuidelines.service.GuidelinesService;
import in.gov.chennaicorporation.mobileservice.service.PdfGeneratorService;
@RestController
@RequestMapping("/gccofficialapp/api/pdf")
public class PdfTemplateController {
@Autowired
private PdfGeneratorService pdfGeneratorService;
@Autowired
private GuidelinesService guidelinesService;
/*
* @GetMapping("/template")
* public ResponseEntity<byte[]> generateFromTemplate(
*
* @RequestParam(value = "cdid", required = false) String cdid,
*
* @RequestParam(value = "ciid", required = false) String ciid
* ) {
* //Map<String, Object> data = new HashMap<>();
*
* //data.put("siteLocation", siteLocation);
* //data.put("violations", violations);
* //data.put("violationLevel", violationLevel);
* //data.put("clause", clause);
* //data.put("fineAmount", fineAmount);
* //data.put("date", LocalDate.now().toString());
*
*
* String
* attachmentFileName="UNDER_CLEAN_AND_SAFE_CONSTRUCTION_GUIDELINES_NOTICE_"+
* LocalDate.now().toString()+"pdf";
*
* byte[] pdfBytes =
* pdfGeneratorService.generatePdf(guidelinesService.getNoticeData(cdid, ciid));
*
* HttpHeaders headers = new HttpHeaders();
* headers.setContentType(MediaType.APPLICATION_PDF);
* headers.setContentDispositionFormData("attachment", attachmentFileName);
*
* return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
* }
*/
@GetMapping("/template")
public ResponseEntity<byte[]> generateFromTemplate(
@RequestParam(value = "cdid", required = false) String cdid,
@RequestParam(value = "ciid", required = false) String ciid) {
String attachmentFileName = "UNDER_CLEAN_AND_SAFE_CONSTRUCTION_GUIDELINES_NOTICE_" + LocalDate.now()
+ ".pdf";
// Generate PDF content
byte[] pdfBytes = pdfGeneratorService.generatePdf(
guidelinesService.getNoticeData(cdid, ciid));
// Prepare response headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", attachmentFileName);
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
}
@GetMapping("/secondnotice")
public ResponseEntity<byte[]> generateSecondNoticeFromTemplate(
@RequestParam(value = "cdid", required = false) String cdid,
@RequestParam(value = "ciid", required = false) String ciid) {
String attachmentFileName = "SECOND_NOTICE_UNDER_CLEAN_AND_SAFE_CONSTRUCTION_GUIDELINES_NOTICE_"
+ LocalDate.now() + ".pdf";
byte[] pdfBytes = pdfGeneratorService.generatePdfSecondNotice(
guidelinesService.getNoticeData(cdid, ciid));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", attachmentFileName);
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
}
@GetMapping("/finalnotice")
public ResponseEntity<byte[]> generateFinalNoticeFromTemplate(
@RequestParam(value = "cdid", required = false) String cdid,
@RequestParam(value = "ciid", required = false) String ciid) {
String attachmentFileName = "FINAL_NOTICE_UNDER_CLEAN_AND_SAFE_CONSTRUCTION_GUIDELINES_NOTICE_"
+ LocalDate.now() + ".pdf";
byte[] pdfBytes = pdfGeneratorService.generatePdfFinalNotice(
guidelinesService.getNoticeData(cdid, ciid));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", attachmentFileName);
return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
}
}

111
src/main/java/in/gov/chennaicorporation/mobileservice/disposalPoint/controller/DisposalPointController.java

@ -0,0 +1,111 @@
package in.gov.chennaicorporation.mobileservice.disposalPoint.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.disposalPoint.service.DisposalPointService;
@RequestMapping("/gccofficialapp/api/disposalpoint/")
@RestController("gccofficialappsdisposalpoint")
public class DisposalPointController {
@Autowired
private DisposalPointService disposalPointService;
@GetMapping(value="/getDisposalPointListForMap")
public List<?> getDisposalPointListFormap(
@RequestParam(value="loginId", required = true) String cby
){
return disposalPointService.getDisposalPointListForMap(cby);
}
@GetMapping(value="/getDisposalPointList")
public List<?> getDisposalPointList(
@RequestParam(value="loginId", required = true) String cby
){
return disposalPointService.getDisposalPointList(cby);
}
@PostMapping("/saveDisposalPoint")
public List<?> saveDisposalPoint(
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "file", required = true) MultipartFile file
) {
return disposalPointService.saveDisposalPoint(
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
file
);
}
@PostMapping("/saveActivity")
public List<?> saveActivity(
@RequestParam(value = "disposalpoint_id", required = true) String disposalpoint_id,
@RequestParam(value = "file", required = true) MultipartFile file,
@RequestParam(value = "video", required = true) MultipartFile video,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId
) {
return disposalPointService.saveActivity(
disposalpoint_id,
file,
video,
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
"before"
);
}
@GetMapping(value="/getZoneSummary")
public List<?> getZoneSummary(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate
){
return disposalPointService.getZoneSummary(fromDate, toDate);
}
@GetMapping(value="/getWardSummary")
public List<?> getWardSummary(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate,
@RequestParam(value="zone", required = true) String zone
){
return disposalPointService.getWardSummary(fromDate, toDate, zone);
}
@GetMapping(value="/getDisposalPointSummary")
public List<?> getDisposalPointSummary(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate,
@RequestParam(value="ward", required = true) String ward
){
return disposalPointService.getDisposalPointSummary(fromDate, toDate, ward);
}
}

773
src/main/java/in/gov/chennaicorporation/mobileservice/disposalPoint/service/DisposalPointService.java

@ -0,0 +1,773 @@
package in.gov.chennaicorporation.mobileservice.disposalPoint.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.PreparedStatement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class DisposalPointService {
private JdbcTemplate jdbcDisposalPointTemplate;
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("mysqlGccDisposalPointSource") DataSource DisposalPointDataSource) {
this.jdbcDisposalPointTemplate = new JdbcTemplate(DisposalPointDataSource);
}
@Autowired
public DisposalPointService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, String id, MultipartFile file, String filetype) {
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("disposalpoint_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + filetype + "/" + 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();
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 + filetype + "/" + year + "/" + month + "/" + date + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
if(filetype.equalsIgnoreCase("image"))
{
// 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);
}
else {
// Write the bytes to the file
Files.write(path, bytes);
}
// Get current date & time
LocalDateTime now = LocalDateTime.now();
// Format date-time (optional)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Date: "+ now.format(formatter));
System.out.println("Activity: DisposalPoint");
System.out.println("File Type: " + filetype);
System.out.println("File Upload Path: " + filePath);
System.out.println("File Path: " + filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save file " + file.getOriginalFilename());
return "error";
}
}
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT `ward` FROM gcc_penalty_hoardings.`hoading_user_list` WHERE `userid` = ? AND `type` = ? LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(sqlQuery, loginid, type);
// 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
}
@Transactional
public List<Map<String, Object>> saveDisposalPoint(
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
MultipartFile file
) {
String filetxt = inby;
String action = "new_mapping";
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
String activityimg = fileUpload(action, filetxt, file, filetype);
if ("error".equalsIgnoreCase(activityimg)) {
response.put("status", "error");
response.put("message", "Disposal Point new mapping image insert failed.");
result.add(response);
return result;
}
String insertSqltxt = "INSERT INTO disposalpoint_mapped_master(`zone`, `ward`, `road_name`, `road_gisid`, `latitude`, `longitude`, `inby`, `file`) "
+ "VALUES (?,?,?,?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcDisposalPointTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"disposalpoint_id"});
int i = 1;
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
ps.setString(i++, activityimg);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Disposal Point", action + " insertId: " +lastInsertId);
response.put("status", "success");
response.put("message", "Disposal Point " + action + " data inserted successfully.");
} else {
response.put("Disposal Point", action + " insertId error!");
response.put("status", "error");
response.put("message", "Disposal Point " + action + " data insert failed.");
}
result.add(response);
return result;
}
public List<Map<String, Object>> getDisposalPointListForMap(String loginid) {
String ward = getWardByLoginId(loginid,"ae");
String sqlManhole = "SELECT "
+ " d.zone,"
+ " d.ward,"
+ " COUNT(*) AS total_disposal_points,"
+ " (SELECT COUNT(*) "
+ " FROM disposalpoint_mapped_master m"
+ " WHERE m.isactive = 1 AND m.isdelete = 0 AND m.ward = d.ward) AS total_mapped_points,"
+ " (COUNT(*) - "
+ " (SELECT COUNT(*) "
+ " FROM disposalpoint_mapped_master m"
+ " WHERE m.isactive = 1 AND m.isdelete = 0 AND m.ward = d.ward)"
+ " ) AS total_pending_points "
+ "FROM disposalpoint_master d "
+ "WHERE d.isactive = 1 AND d.isdelete = 0"
+ " AND d.ward = ? "
+ "GROUP BY d.ward "
+ "ORDER BY d.ward";
List<Map<String, Object>> disposalpoints = jdbcDisposalPointTemplate.queryForList(sqlManhole, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Dispoasl Map List.");
response.put("data", disposalpoints);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getDisposalPointList(String loginid) {
String ward = getWardByLoginId(loginid,"ae");
// 1. Fetch all Disposal Points for the given SWDID
String sqlManhole = "SELECT *, "
+ "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `file`) AS img_file_url "
+ " FROM disposalpoint_mapped_master WHERE ward = ? AND `isactive`=1 AND `isdelete`=0";
List<Map<String, Object>> disposalpoints = jdbcDisposalPointTemplate.queryForList(sqlManhole, ward);
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> disposalpoint : disposalpoints) {
Map<String, Object> disposalpointResponse = new HashMap<>();
disposalpointResponse.putAll(disposalpoint); // add all Disposal point columns
// 2. Fetch before activity
String sqlBefore = "SELECT *,"
+ "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `img_file`) AS img_file_url,"
+ "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `video_file`) AS video_file_url "
+ "FROM before_activity WHERE disposalpoint_id = ? "
+ "AND indate >= CURDATE() "
+ "AND indate < CURDATE() + INTERVAL 1 DAY "
+ "AND isactive=1 AND isdelete=0";
List<Map<String, Object>> beforeActivities = jdbcDisposalPointTemplate.queryForList(sqlBefore,
disposalpoint.get("disposalpoint_id"));
Map<String, Object> beforeData = new HashMap<>();
if (!beforeActivities.isEmpty()) {
beforeData.put("status", "Completed");
beforeData.put("details", beforeActivities);
} else {
beforeData.put("status", "Pending");
beforeData.put("details", Collections.emptyList());
}
// 4. Overall Disposal Point status
String overallStatus = (!beforeActivities.isEmpty()) ? "Completed" : "Pending";
disposalpointResponse.put("status", overallStatus);
disposalpointResponse.put("before", beforeData);
finalList.add(disposalpointResponse);
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Dispoasl List.");
response.put("data", finalList);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveActivity(
String disposalpoint_id,
MultipartFile file,
MultipartFile video,
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
String action
) {
String filetxt =disposalpoint_id;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
String activityimg = fileUpload(action, filetxt, file, filetype);
if ("error".equalsIgnoreCase(activityimg)) {
response.put("status", "error");
response.put("message", "Disposal Point activity image insert failed.");
result.add(response);
return result;
}
// For Video
filetype = "video";
String activityvideo = fileUpload(action, filetxt, video, filetype);
if ("error".equalsIgnoreCase(activityvideo)) {
response.put("status", "error");
response.put("message", "Disposal Point activity video insert failed.");
result.add(response);
return result;
}
String insertBeforeSql = "INSERT INTO before_activity(disposalpoint_id, img_file, video_file, zone, ward, street_name, street_id, latitude, longitude, inby) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
/*
String insertAfterSql = "INSERT INTO after_activity(disposalpoint_id, file, zone, ward, street_name, street_id, latitude, longitude, inby, before_activity_id, clean_type) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
String insertSql = "before".equalsIgnoreCase(action) ? insertBeforeSql : insertAfterSql;
*/
String insertSql = insertBeforeSql;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcDisposalPointTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"activity_id"});
int i = 1;
ps.setString(i++, disposalpoint_id);
ps.setString(i++, activityimg);
ps.setString(i++, activityvideo);
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
/*
if ("after".equalsIgnoreCase(action)) {
ps.setString(i++, beforeActivityId);
ps.setString(i++, clean_type);
}
*/
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Disposal Point", action + " insertId: " +lastInsertId);
response.put("status", "success");
response.put("message", "Disposal Point " + action + " activity inserted successfully.");
} else {
response.put("Disposal Point", action + " insertId error!");
response.put("status", "error");
response.put("message", "Disposal Point " + action + " activity insert failed.");
}
result.add(response);
return result;
}
/*
public List<Map<String, Object>> getZoneSummary(String fromDate, String toDate) {
fromDate = convertDateFormat(fromDate,0);
toDate = convertDateFormat(toDate,0);
// SQL: count completed days per zone
String sql = "SELECT d.zone, COUNT(DISTINCT DATE(b.indate)) AS completedDays "
+ "FROM disposalpoint_mapped_master d "
+ "LEFT JOIN before_activity b ON d.disposalpoint_id = b.disposalpoint_id "
+ "AND b.indate >= ? AND b.indate < DATE_ADD(?, INTERVAL 1 DAY) "
+ "AND b.isactive=1 AND b.isdelete=0 "
+ "WHERE d.isactive=1 AND d.isdelete=0 "
+ "GROUP BY d.zone ORDER BY d.zone";
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(sql, fromDate, toDate);
long totalDays = ChronoUnit.DAYS.between(
LocalDate.parse(fromDate),
LocalDate.parse(toDate)
) + 1;
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> row : results) {
Map<String, Object> Report = new HashMap<>();
long completed = ((Number) row.get("completedDays")).longValue();
Report.put("zone", row.get("zone"));
Report.put("totalDays", totalDays);
Report.put("completed", completed);
Report.put("pending", totalDays - completed);
finalList.add(Report);
}
return finalList;
}
*/
@Transactional(readOnly = true)
public List<Map<String, Object>> getZoneSummary(String fromDate, String toDate) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 0);
String sql =
"SELECT " +
" z.zone, " +
" COALESCE(dm.total_disposal_points, 0) AS total_disposal_points, " +
" COALESCE(mm.total_mapped_points, 0) AS total_mapped_points, " +
" COALESCE(COUNT(DISTINCT (b.disposalpoint_id), 0)) AS completed_days " +
"FROM (" +
" SELECT DISTINCT zone FROM disposalpoint_master WHERE isactive=1 AND isdelete=0" +
") z " +
"LEFT JOIN (" +
" SELECT zone, COUNT(*) AS total_disposal_points " +
" FROM disposalpoint_master " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY zone" +
") dm ON z.zone = dm.zone " +
"LEFT JOIN (" +
" SELECT zone, COUNT(*) AS total_mapped_points " +
" FROM disposalpoint_mapped_master " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY zone" +
") mm ON z.zone = mm.zone " +
"LEFT JOIN disposalpoint_mapped_master dmm ON dmm.zone = z.zone AND dmm.isactive=1 AND dmm.isdelete=0 " +
"LEFT JOIN before_activity b ON dmm.disposalpoint_id = b.disposalpoint_id " +
" AND b.isactive=1 AND b.isdelete=0 " +
" AND b.indate >= ? AND b.indate < DATE_ADD(?, INTERVAL 1 DAY) " +
"GROUP BY z.zone, dm.total_disposal_points, mm.total_mapped_points " +
"ORDER BY z.zone";
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(sql, fromDate, toDate);
long totalDays = ChronoUnit.DAYS.between(
LocalDate.parse(fromDate),
LocalDate.parse(toDate)
) + 1;
List<Map<String, Object>> finalList = new ArrayList<>();
long grandTotalDisposalPoints = 0;
long grandTotalMappedPoints = 0;
long grandCompletedDays = 0;
long grandPendingDays = 0;
for (Map<String, Object> row : results) {
Map<String, Object> report = new LinkedHashMap<>();
long completed = ((Number) row.get("completed_days")).longValue();
long totalDisposalPoints = ((Number) row.get("total_disposal_points")).longValue();
long totalMappedPoints = ((Number) row.get("total_mapped_points")).longValue();
long totalDays_final = (totalDays*totalMappedPoints);
report.put("zone", row.get("zone"));
report.put("totalDisposalPoints", totalDisposalPoints);
report.put("totalMappedPoints", totalMappedPoints);
report.put("totalDays", totalDays_final);
report.put("completedDays", completed);
report.put("pendingDays", (totalDays_final - completed));
finalList.add(report);
// accumulate grand totals
grandTotalDisposalPoints += totalDisposalPoints;
grandTotalMappedPoints += totalMappedPoints;
grandCompletedDays += completed;
grandPendingDays +=(totalDays_final - completed);
}
// add grand total row
Map<String, Object> grandTotalRow = new LinkedHashMap<>();
grandTotalRow.put("zone", "TOTAL");
grandTotalRow.put("totalDisposalPoints", grandTotalDisposalPoints);
grandTotalRow.put("totalMappedPoints", grandTotalMappedPoints);
grandTotalRow.put("totalDays", totalDays);
grandTotalRow.put("completedDays", grandCompletedDays);
grandTotalRow.put("pendingDays", grandPendingDays); // total pending across all wards
finalList.add(grandTotalRow);
return finalList;
}
/*
public List<Map<String, Object>> getWardSummary(String fromDate, String toDate, String zone) {
fromDate = convertDateFormat(fromDate,0);
toDate = convertDateFormat(toDate,0);
// SQL: count completed days per ward
String sql = "SELECT d.ward, COUNT(DISTINCT DATE(b.indate)) AS completedDays "
+ "FROM disposalpoint_mapped_master d "
+ "LEFT JOIN before_activity b ON d.disposalpoint_id = b.disposalpoint_id "
+ "AND b.indate >= ? AND b.indate < DATE_ADD(?, INTERVAL 1 DAY) "
+ "AND b.isactive=1 AND b.isdelete=0 "
+ "WHERE d.isactive=1 AND d.isdelete=0 AND d.zone=?"
+ "GROUP BY d.ward ORDER BY d.ward";
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(sql, fromDate, toDate, zone);
long totalDays = ChronoUnit.DAYS.between(
LocalDate.parse(fromDate),
LocalDate.parse(toDate)
) + 1;
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> row : results) {
Map<String, Object> Report = new HashMap<>();
long completed = ((Number) row.get("completedDays")).longValue();
Report.put("ward", row.get("ward"));
Report.put("totalDays", totalDays);
Report.put("completed", completed);
Report.put("pending", totalDays - completed);
finalList.add(Report);
}
return finalList;
}
*/
@Transactional(readOnly = true)
public List<Map<String, Object>> getWardSummary(String fromDate, String toDate, String zone) {
fromDate = convertDateFormat(fromDate, 0);
toDate = convertDateFormat(toDate, 0);
String sql =
"SELECT " +
" w.ward, " +
" COALESCE(dm.total_disposal_points, 0) AS total_disposal_points, " +
" COALESCE(mm.total_mapped_points, 0) AS total_mapped_points, " +
" COALESCE(COUNT(DISTINCT (b.disposalpoint_id), 0)) AS completed_days " +
"FROM (" +
" SELECT DISTINCT ward FROM disposalpoint_master WHERE isactive=1 AND isdelete=0 AND zone=?" +
") w " +
"LEFT JOIN (" +
" SELECT ward, COUNT(*) AS total_disposal_points " +
" FROM disposalpoint_master " +
" WHERE isactive=1 AND isdelete=0 AND zone=? " +
" GROUP BY ward" +
") dm ON w.ward = dm.ward " +
"LEFT JOIN (" +
" SELECT ward, COUNT(*) AS total_mapped_points " +
" FROM disposalpoint_mapped_master " +
" WHERE isactive=1 AND isdelete=0 AND zone=? " +
" GROUP BY ward" +
") mm ON w.ward = mm.ward " +
"LEFT JOIN disposalpoint_mapped_master dmm ON dmm.ward = w.ward AND dmm.isactive=1 AND dmm.isdelete=0 " +
"LEFT JOIN before_activity b ON dmm.disposalpoint_id = b.disposalpoint_id " +
" AND b.isactive=1 AND b.isdelete=0 " +
" AND b.indate >= ? AND b.indate < DATE_ADD(?, INTERVAL 1 DAY) " +
"GROUP BY w.ward, dm.total_disposal_points, mm.total_mapped_points " +
"ORDER BY w.ward";
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(
sql, zone, zone, zone, fromDate, toDate
);
long totalDays = ChronoUnit.DAYS.between(
LocalDate.parse(fromDate),
LocalDate.parse(toDate)
) + 1;
List<Map<String, Object>> finalList = new ArrayList<>();
long grandTotalDisposalPoints = 0;
long grandTotalMappedPoints = 0;
long grandCompletedDays = 0;
long grandPendingDays = 0;
for (Map<String, Object> row : results) {
Map<String, Object> report = new LinkedHashMap<>();
long completed = ((Number) row.get("completed_days")).longValue();
long totalDisposalPoints = ((Number) row.get("total_disposal_points")).longValue();
long totalMappedPoints = ((Number) row.get("total_mapped_points")).longValue();
long totalDays_final = (totalDays*totalMappedPoints);
report.put("ward", row.get("ward"));
report.put("totalDisposalPoints", totalDisposalPoints);
report.put("totalMappedPoints", totalMappedPoints);
report.put("totalDays", totalDays_final);
report.put("completedDays", completed);
report.put("pendingDays", (totalDays_final - completed));
finalList.add(report);
// accumulate grand totals
grandTotalDisposalPoints += totalDisposalPoints;
grandTotalMappedPoints += totalMappedPoints;
grandCompletedDays += completed;
grandPendingDays +=(totalDays_final - completed);
}
// add grand total row
Map<String, Object> grandTotalRow = new LinkedHashMap<>();
grandTotalRow.put("ward", "TOTAL");
grandTotalRow.put("totalDisposalPoints", grandTotalDisposalPoints);
grandTotalRow.put("totalMappedPoints", grandTotalMappedPoints);
grandTotalRow.put("totalDays", totalDays);
grandTotalRow.put("completedDays", grandCompletedDays);
grandTotalRow.put("pendingDays", grandPendingDays); // total pending across all wards
finalList.add(grandTotalRow);
return finalList;
}
public List<Map<String, Object>> getDisposalPointSummary(String fromDate, String toDate, String ward) {
fromDate = convertDateFormat(fromDate,0);
toDate = convertDateFormat(toDate,0);
// SQL: count completed days per Disposal point
String sql = "SELECT d.road_name, d.disposalpoint_id, COUNT(DISTINCT DATE(b.indate)) AS completedDays "
+ "FROM disposalpoint_mapped_master d "
+ "LEFT JOIN before_activity b ON d.disposalpoint_id = b.disposalpoint_id "
+ "AND b.indate >= ? AND b.indate < DATE_ADD(?, INTERVAL 1 DAY) "
+ "AND b.isactive=1 AND b.isdelete=0 "
+ "WHERE d.isactive=1 AND d.isdelete=0 AND d.ward=? "
+ "GROUP BY d.road_name, d.disposalpoint_id ORDER BY d.road_name";
List<Map<String, Object>> results = jdbcDisposalPointTemplate.queryForList(sql, fromDate, toDate, ward);
long totalDays = ChronoUnit.DAYS.between(
LocalDate.parse(fromDate),
LocalDate.parse(toDate)
) + 1;
List<Map<String, Object>> finalList = new ArrayList<>();
//long grandTotalDisposalPoints = 0;
//long grandTotalMappedPoints = 0;
long grandCompletedDays = 0;
long grandPendingDays = 0;
for (Map<String, Object> row : results) {
Map<String, Object> Report = new HashMap<>();
long completed = ((Number) row.get("completedDays")).longValue();
//long totalDisposalPoints = ((Number) row.get("total_disposal_points")).longValue();
//long totalMappedPoints = ((Number) row.get("total_mapped_points")).longValue();
long totalDays_final = (totalDays*1);
Report.put("road_name", row.get("road_name"));
Report.put("disposalpoint_id", row.get("disposalpoint_id"));
Report.put("totalDays", totalDays_final);
Report.put("completed", completed);
Report.put("pending", totalDays_final - completed);
finalList.add(Report);
// accumulate grand totals
//grandTotalDisposalPoints += totalDisposalPoints;
//grandTotalMappedPoints += totalMappedPoints;
grandCompletedDays += completed;
grandPendingDays +=(totalDays_final - completed);
}
// add grand total row
Map<String, Object> grandTotalRow = new LinkedHashMap<>();
grandTotalRow.put("road_name", "TOTAL");
//grandTotalRow.put("totalDisposalPoints", grandTotalDisposalPoints);
//grandTotalRow.put("totalMappedPoints", grandTotalMappedPoints);
grandTotalRow.put("disposalpoint_id", 0);
grandTotalRow.put("totalDays", totalDays);
grandTotalRow.put("completed", grandCompletedDays);
grandTotalRow.put("pending", grandPendingDays); // total pending across all wards
//finalList.add(grandTotalRow);
return finalList;
}
}

187
src/main/java/in/gov/chennaicorporation/mobileservice/election/controller/ElectionApiController.java

@ -0,0 +1,187 @@
package in.gov.chennaicorporation.mobileservice.election.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import in.gov.chennaicorporation.mobileservice.election.service.ElectionService;
@RequestMapping("/gccofficialapp/api/election")
@RestController("gccofficialappelection")
public class ElectionApiController {
@Autowired
ElectionService electionService;
@GetMapping("/getPollPersonDetailsByMobile")
public ResponseEntity<Map<String, Object>> getPollPersonDetails(
@RequestParam(required = false) String slno) {
Map<String, Object> response = new HashMap<>();
// Validation
if (slno == null || slno.trim().isEmpty()) {
response.put("status", HttpStatus.BAD_REQUEST.value());
response.put("message", "slno number is required");
response.put("data", null);
return ResponseEntity.ok(response);
}
// if (!slno.matches("^[1-9][0-9]{9}$")) {
// response.put("status", HttpStatus.BAD_REQUEST.value());
// response.put("message", "Mobile number must be 10 digits and should not start
// with 0");
// response.put("data", null);
// return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
// }
// 🔹 Fetch data
List<Map<String, Object>> applicants = electionService.getApplicantsByMobile(slno);
if (applicants == null || applicants.isEmpty()) {
response.put("status", HttpStatus.NOT_FOUND.value());
response.put("message", "No records found for given mobile number");
return ResponseEntity.ok(response);
}
// 🔹 Success response
response.put("status", HttpStatus.OK.value());
response.put("message", "Poll person details fetched successfully");
response.put("data", applicants);
return ResponseEntity.ok(response);
}
@GetMapping("/getLoginSuccess")
public ResponseEntity<Map<String, Object>> getLoginSuccess(
@RequestParam String mobileNo) {
Map<String, Object> response = new HashMap<>();
try {
// Validation FIRST
if (mobileNo == null || mobileNo.trim().isEmpty()) {
response.put("status", false);
response.put("message", "Mobile number is required");
response.put("data", null);
return ResponseEntity.ok(response);
}
if (!mobileNo.matches("^[1-9][0-9]{9}$")) {
response.put("status", false);
response.put("message", "Mobile number must be 10 digits and should not start with 0");
response.put("data", null);
return ResponseEntity.ok(response);
}
List<Map<String, Object>> result = electionService.getBatchDetails(mobileNo);
// No records
if (result.isEmpty()) {
response.put("status", false);
response.put("message", "No records found");
response.put("data", new ArrayList<>());
return ResponseEntity.ok(response);
}
// Multiple records
if (result.size() > 1) {
response.put("status", false);
response.put("message",
"You have multiple records. Please contact IT Cell.");
response.put("data", null);
return ResponseEntity.ok(response);
}
// 🔹 Single record success
response.put("status", true);
response.put("message", "Batch details fetched successfully");
response.put("data", result);
return ResponseEntity.ok(response);
} catch (Exception e) {
e.printStackTrace();
response.put("status", false);
response.put("message", "Something went wrong");
response.put("data", null);
return ResponseEntity.ok(response);
}
}
@PostMapping("/savePollPersonUpdate")
public ResponseEntity<?> savePollPersonUpdate(
@RequestParam(required = false) Integer slno,
@RequestParam(required = false) String name,
@RequestParam(required = false) String designationId,
@RequestParam(required = false) String sex,
@RequestParam(required = false) String address1,
@RequestParam(required = false) String address2,
@RequestParam(required = false) String address3,
@RequestParam(required = false) String pincode,
@RequestParam(required = false) String nearPolicesta,
@RequestParam(required = false) String phoneNo,
@RequestParam(required = false) String mobileNo,
@RequestParam(required = false) Integer homeDist,
@RequestParam(required = false) Integer nativeAcNo,
@RequestParam(required = false) Integer resideAcNo,
@RequestParam(required = false) Integer electorAcNo,
@RequestParam(required = false) Integer electorPartNo,
@RequestParam(required = false) Integer electorSlNo,
@RequestParam(required = false) String electorEpicNo,
@RequestParam(required = false) String updatedBy,
@RequestParam(required = false) MultipartFile photo) {
try {
// SLNO validation
if (slno == null) {
return ResponseEntity.badRequest().body(Map.of(
"status", "Failed",
"message", "SLNO is mandatory"));
}
// Mobile validation
if (mobileNo == null || !mobileNo.matches("\\d{10}")) {
return ResponseEntity.badRequest().body(Map.of(
"status", "Failed",
"message", "Mobile number must be 10 digits"));
}
// Call service
Map<String, Object> result = electionService.savePollPersonUpdate(
slno, name, designationId, sex,
address1, address2, address3,
pincode, nearPolicesta, phoneNo, mobileNo,
homeDist, nativeAcNo, resideAcNo,
electorAcNo, electorPartNo, electorSlNo,
electorEpicNo, updatedBy, photo);
return ResponseEntity.ok(result);
} catch (Exception e) {
e.printStackTrace();
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("status", "Failed");
errorResponse.put("message", e.getMessage() != null ? e.getMessage() : "Failed to save data");
return ResponseEntity.status(HttpStatus.OK).body(errorResponse);
}
}
}

366
src/main/java/in/gov/chennaicorporation/mobileservice/election/service/ElectionService.java

@ -0,0 +1,366 @@
package in.gov.chennaicorporation.mobileservice.election.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.util.HashMap;
import java.util.List;
import java.util.Map;
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.jdbc.core.JdbcTemplate;
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 ElectionService {
@Autowired
JdbcTemplate jdbcElectionTemplate;
private Environment environment;
private String fileBaseUrl;
@Autowired
public void setDataSource(@Qualifier("mysqlElectionDataSource") DataSource electionDataSource) {
this.jdbcElectionTemplate = new JdbcTemplate(electionDataSource);
}
public ElectionService(Environment environment) {
this.environment = environment;
this.fileBaseUrl = environment.getProperty("fileBaseUrl");
}
@Transactional
public List<Map<String, Object>> getApplicantsByMobile(String slno) {
try {
String sql = "SELECT " +
/* Person Details */
"ppn.slno AS slno, " +
"UPPER(ppn.name) AS name, " +
"ppn.age, " +
"ppn.sex, " +
"ppn.r_mobile_no, " +
"ppn.r_phone_no, " +
"ppn.r_address1, " +
"ppn.r_address2, " +
"ppn.r_address3, " +
"ppn.r_pincode, " +
/* Department */
"ppn.dept AS dept_name, " +
"dm.dept_id, " +
/* Designation */
// "ppn.designation_id AS designation_id, " +
// "d.new_designation AS designation_name, " +
"ppn.designation AS designation_name, " +
/* Office */
// "ppn.office_id AS office_id, " +
// "od.office_name, " +
"ppn.office as office_name, " +
/* Image */
"CONCAT('" + fileBaseUrl + "/election/files', ppm.image_path) AS img_full_path, " +
/* Office Full Address */
"CONCAT( " +
"COALESCE(ppn.address1, ''), ' ', " +
"COALESCE(ppn.address2, ''), ' ', " +
"COALESCE(ppn.address3, ''), ' ', " +
"COALESCE(ppn.pincode, '') " +
") AS office_address, " +
/* Constituencies */
"ppn.native_ac_no, ac_native.ac_name AS native_constituency, " +
"ppn.reside_ac_no, ac_reside.ac_name AS residential_constituency, " +
"ppn.elector_ac_no, ac_elector.ac_name AS elector_constituency, " +
"ppn.work_ac_no, ac_work.ac_name AS working_constituency, " +
"ppn.epic_no AS elector_epic_no, " +
"ppn.elector_part_no AS elector_part_no, " +
"ppn.elector_sl_no AS elector_sl_no, " +
"ppn.elector_ac_no AS elector_ac_no " +
"FROM poll_person ppn " +
"LEFT JOIN poll_person_images ppm ON ppm.slno = ppn.slno " +
"LEFT JOIN dept_master dm ON ppn.dept = dm.dept_id " +
// "LEFT JOIN designation d ON ppn.designation_id = d.desig_id " +
// "LEFT JOIN office_details od ON ppn.office_id = od.id " +
"LEFT JOIN ac_list_all ac_native ON ac_native.ac_no = ppn.native_ac_no " +
"LEFT JOIN ac_list_all ac_reside ON ac_reside.ac_no = ppn.reside_ac_no " +
"LEFT JOIN ac_list_all ac_elector ON ac_elector.ac_no = ppn.elector_ac_no " +
"LEFT JOIN ac_list_all ac_work ON ac_work.ac_no = ppn.work_ac_no " +
"WHERE ppn.slno = ? ";
// "AND ppn.is_active = 1 AND ppn.is_delete = 0";
List<Map<String, Object>> data = jdbcElectionTemplate.queryForList(sql, slno);
// if (data.isEmpty()) {
// throw new RuntimeException("Your details are not registered");
// }
/* Convert all NULL values to empty string */
// for (Map<String, Object> row : data) {
// for (Map.Entry<String, Object> entry : row.entrySet()) {
// if (entry.getValue() == null) {
// entry.setValue("");
// }
// }
// }
for (Map<String, Object> row : data) {
for (Map.Entry<String, Object> entry : row.entrySet()) {
// Convert NULL → empty string
if (entry.getValue() == null) {
entry.setValue("");
continue;
}
String key = entry.getKey();
Object value = entry.getValue();
// Convert slno → String
if ("slno".equalsIgnoreCase(key)) {
entry.setValue(String.valueOf(value));
}
// Convert AC numbers → Integer
if ("native_ac_no".equalsIgnoreCase(key) ||
"reside_ac_no".equalsIgnoreCase(key)) {
try {
entry.setValue(Integer.parseInt(value.toString()));
} catch (Exception ex) {
entry.setValue(0); // fallback if invalid
}
}
}
}
return data;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error fetching applicant details: " + e.getMessage());
}
}
public List<Map<String, Object>> getBatchDetails(String mobileNo) {
try {
String sql = "SELECT r_mobile_no AS mobile_number, slno " +
"FROM poll_person " +
"WHERE r_mobile_no = ?";
List<Map<String, Object>> data = jdbcElectionTemplate.queryForList(sql, mobileNo);
for (Map<String, Object> row : data) {
Object slnoObj = row.get("slno");
// Convert null → ""
String slno = (slnoObj == null) ? "" : slnoObj.toString().trim();
row.put("slno", slno);
// hasLogin flag
boolean hasLogin = !slno.isEmpty();
row.put("hasLogin", hasLogin);
// Convert mobile_number null → ""
Object mobileObj = row.get("mobile_number");
row.put("mobile_number",
mobileObj == null ? "" : mobileObj.toString());
}
return data;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error fetching batch details: " + e.getMessage());
}
}
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();
}
private String saveimage(MultipartFile file, String slno) {
// String uploadDirectory = environment.getProperty("file.upload.directory");
String uploadDirectory = environment.getProperty("file.upload.directory.web");
String serviceFolderName = environment.getProperty("polling_person_images_foldername");
var year = DateTimeUtil.getCurrentYear();
// var month = DateTimeUtil.getCurrentMonth();
uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + "photo";
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 = slno + ".jpg";
fileName = fileName.replaceAll("\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + fileName;
String filepath_txt = "/" + serviceFolderName + year + "/" + "photo" + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality
Files.write(path, compressedBytes);
System.out.println(filePath);
// System.out.println(" filepath_txt=="+ filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
return "Failed to save file " + file.getOriginalFilename();
}
}
public Map<String, Object> savePollPersonUpdate(
Integer slno,
String name,
String designationId,
String sex,
String address1,
String address2,
String address3,
String pincode,
String nearPolicesta,
String phoneNo,
String mobileNo,
Integer homeDist,
Integer nativeAcNo,
Integer resideAcNo,
Integer electorAcNo,
Integer electorPartNo,
Integer electorSlNo,
String electorEpicNo,
String updatedBy,
MultipartFile photo) {
Map<String, Object> response = new HashMap<>();
try {
// Validate SLNO exists in main table
String checkSql = "SELECT COUNT(*) FROM poll_person_new WHERE slno=?";
Integer count = jdbcElectionTemplate.queryForObject(checkSql, Integer.class, slno);
if (count == null || count == 0) {
throw new RuntimeException("Invalid SLNO. No record found.");
}
// Prevent duplicate request (optional)
String checkReqSql = "SELECT COUNT(*) FROM poll_person_updation_request WHERE slno=? AND is_delete=0";
Integer existing = jdbcElectionTemplate.queryForObject(checkReqSql, Integer.class, slno);
if (existing != null && existing > 0) {
throw new RuntimeException("Update request already exists for this person");
}
// Save Image
String photoUrl = null;
if (photo != null && !photo.isEmpty()) {
photoUrl = saveimage(photo, String.valueOf(slno));
if ("error".equals(photoUrl)) {
throw new RuntimeException("Image upload failed");
}
}
String insertSql = """
INSERT INTO poll_person_updation_request (
slno, name, designation_id, sex,
address1, address2, address3,
pincode, near_policesta, phone_no, mobile_no,
home_dist, native_ac_no, reside_ac_no,
elector_ac_no, elector_part_no, elector_sl_no,
elector_epic_no, photo_upload_url,
cdate, updated_date, updated_by,
is_active, is_delete
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),?,1,0)
""";
jdbcElectionTemplate.update(insertSql,
slno, name, designationId, sex,
address1, address2, address3,
pincode, nearPolicesta, phoneNo, mobileNo,
homeDist, nativeAcNo, resideAcNo,
electorAcNo, electorPartNo, electorSlNo,
electorEpicNo, photoUrl,
updatedBy);
response.put("status", "success");
response.put("message",
"Your profile update request have submitted succesfully. The requested changes will be updated within a week");
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error while saving: " + e.getMessage());
}
return response;
}
}

5
src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/erppostdataController.java

@ -0,0 +1,5 @@
package in.gov.chennaicorporation.mobileservice.erpPostData;
public class erppostdataController {
}

191
src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/erppostdataService.java

@ -0,0 +1,191 @@
package in.gov.chennaicorporation.mobileservice.erpPostData;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class erppostdataService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlPenaltyDataSource") DataSource penaltyDataSource) {
this.jdbcTemplate = new JdbcTemplate(penaltyDataSource);
}
// This method runs every 1 hour (3600000 ms)
@Scheduled(fixedRate = 60 * 60 * 1000)
//@Scheduled(cron = "0 0 * * * *") // every hour at 0th minute
public void postDataToERP() {
// Call the logic you currently expose through controller
// System.out.println("Posting data to ERP at " + java.time.LocalDateTime.now());
postPOStoERP(); // FOR PENALTY POS (gcc_penalty_pos)
}
private String postPOStoERP() {
// System.out.println("ERP txn: Started");
String sql = "SELECT "
+ " bt.id, "
+ " bt.txnDate, "
+ " DATE_FORMAT(bt.txnDate, '%Y') AS TRANSACTIONYEAR, "
+ " DATE_FORMAT(bt.txnDate, '%d/%m/%Y') AS TRANSACTIONDATE, "
+ " bt.txnId AS TRANSACTIONNO, "
+ " bt.transactionAmount AS TOTALTRANSACTIONAMOUNT, "
+ " bt.txnRefNo AS TRANSACTIONREFNO, "
+ " '450310000' AS TOTALTRANSACTIONCODE, "
+ " pcat.erpcode AS MSTRCODEONE, "
+ " 0 AS SPLITAMOUNTONE, "
+ " pc.violator_name AS PARTYNAME, "
+ " pc.violator_company AS PARTYADDRESS, "
+ " pc.violator_phone AS PARTYMOBILE, "
+ " pc.id AS UNIQUERECEIPTID "
+ "FROM "
+ " `bank_transactions` bt "
+ "LEFT JOIN "
+ " `penalty_challan` pc ON bt.txnId = pc.orderid "
+ " AND pc.isactive = 1 "
+ " AND pc.isdelete = 0 "
+ " AND bt.txnMode NOT IN ('Hand cash','Cheque','DD') "
+ "LEFT JOIN "
+ " `penalty_category` pcat ON pcat.id = pc.category_id "
+ "WHERE bt.erp_post_status IS NULL OR bt.erp_post_status != 'posted' "
+ " AND bt.erp_post_message != 'Already Updated this collection' "
+ "ORDER BY `bt`.`id` ASC";
try {
// System.out.println("Running ERP sync...");
// System.out.println("Using SQL:\n" + sql);
// System.out.println("Connecting to: " + jdbcTemplate.getDataSource().getConnection().getMetaData().getURL());
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
// System.out.println("ERP txt Total records: : "+result.size());
for (Map<String, Object> row : result) {
String ID = String.valueOf(row.get("id"));
//System.out.println("ERP TXT DATA : "+ID);
String ASSESSMENTNO = row.get("TRANSACTIONYEAR")+"/Fine/"+row.get("id");
String UNIQUERECEIPTID = String.valueOf(row.get("UNIQUERECEIPTID"));
String TRANSACTIONNO = String.valueOf(row.get("TRANSACTIONNO"));
String TRANSACTIONREFNO = String.valueOf(row.get("TRANSACTIONREFNO")); // optional mapping
String TRANSACTIONDATE = String.valueOf(row.get("TRANSACTIONDATE"));
String TOTALTRANSACTIONAMOUNT = String.valueOf(row.get("TOTALTRANSACTIONAMOUNT"));
String TOTALTRANSACTIONCODE = String.valueOf(row.get("TOTALTRANSACTIONCODE"));
String MSTRCODEONE = String.valueOf(row.get("MSTRCODEONE"));
String SPLITAMOUNTONE = String.valueOf(row.get("SPLITAMOUNTONE"));
String PARTYNAME = String.valueOf(row.get("PARTYNAME"));
String PARTYADDRESS = String.valueOf(row.get("PARTYADDRESS"));
String PARTYMOBILE = String.valueOf(row.get("PARTYMOBILE"));
String response = postToErp(
ID,
ASSESSMENTNO,
UNIQUERECEIPTID,
TRANSACTIONNO,
TRANSACTIONREFNO,
TRANSACTIONDATE,
TOTALTRANSACTIONAMOUNT,
TOTALTRANSACTIONCODE,
MSTRCODEONE,
SPLITAMOUNTONE,
PARTYNAME,
PARTYADDRESS,
PARTYMOBILE
);
// ✅ Exit loop immediately if ERP server down or response is not "success"
if ("server_down".equalsIgnoreCase(response)) {
System.out.println("ERP server is down or unreachable. Halting current loop...");
break; // stop further processing in this cycle
}
// Optionally log response
// System.out.println("ERP Response for txn: " + TRANSACTIONNO + " → " + response);
}
return "success";
} catch (Exception e) {
e.printStackTrace();
return "erp error: " + e.getMessage();
}
}
private String postToErp(
String id,
String ASSESSMENTNO,
String UNIQUERECEIPTID,
String TRANSACTIONNO,
String TRANSACTIONREFNO,
String TRANSACTIONDATE,
String TOTALTRANSACTIONAMOUNT,
String TOTALTRANSACTIONCODE,
String MSTRCODEONE,
String SPLITAMOUNTONE,
String PARTYNAME,
String PARTYADDRESS,
String PARTYMOBILE) {
// System.out.println("ERP txn request: ERP");
String erpURL = "http://coc-staging.egovernments.org:9980/pgr/external/mobileservice?serviceId=getOtherCollection"
+ "&COLLECTION_TYPE=Fine Collection"
+ "&ASSESSMENTNO=" + ASSESSMENTNO
+ "&UNIQUERECEIPTID=" + UNIQUERECEIPTID
+ "&TRANSACTIONNO=" + TRANSACTIONNO
+ "&TRANSACTIONREFNO=" + TRANSACTIONREFNO
+ "&TRANSACTIONDATE=" + TRANSACTIONDATE
+ "&TOTALTRANSACTIONAMOUNT=" + TOTALTRANSACTIONAMOUNT
+ "&TOTALTRANSACTIONCODE=" + TOTALTRANSACTIONCODE
+ "&MSTRCODEONE=" + MSTRCODEONE
+ "&SPLITAMOUNTONE=" + SPLITAMOUNTONE
+ "&PARTYNAME=" + PARTYNAME
+ "&PARTYADDRESS=" + PARTYADDRESS
+ "&PARTYMOBILE=" + PARTYMOBILE;
RestTemplate restTemplate = new RestTemplate();
//System.out.println("ERP URL:" + erpURL);
try {
ResponseEntity<String> response = restTemplate.exchange(erpURL, HttpMethod.GET, null, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(response.getBody());
boolean resultStatus = jsonNode.path("ResultStatus").asBoolean(); // this is already a boolean
String message = jsonNode.path("Message").asText(); // capture the message string
if (resultStatus) {
String updateSql = "UPDATE bank_transactions SET erp_post_status = 'posted', erp_post_message = ?, erp_post_date = ? WHERE id = ?";
jdbcTemplate.update(updateSql, message, Timestamp.valueOf(LocalDateTime.now()), id);
} else {
String updateSql = "UPDATE bank_transactions SET erp_post_status = 'failed', erp_post_message = ?, erp_post_date = ? WHERE id = ?";
jdbcTemplate.update(updateSql, message, Timestamp.valueOf(LocalDateTime.now()), id);
}
return resultStatus ? "success" : "failed";
} else {
return "failed"; // Non-200 response from server
}
} catch (Exception ex) {
System.out.println("Error contacting ERP server: " + ex.getMessage());
return "server_down";
}
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/erpPostData/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.erpPostData;

49
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/Scheduler/DailyRequestScheduler.java

@ -0,0 +1,49 @@
package in.gov.chennaicorporation.mobileservice.foodDistribution.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import in.gov.chennaicorporation.mobileservice.foodDistribution.service.DistributionService;
@Component
@EnableScheduling
public class DailyRequestScheduler {
@Autowired
private DistributionService distributionService;
//@Scheduled(cron = "0 * * * * *", zone = "Asia/Kolkata") // for minute
@Scheduled(cron = "0 0 14 * * ?", zone = "Asia/Kolkata") // 2:00 PM daily
public void runAutoInsert() {
System.out.println("Food Daily Request Scheduler Started......");
distributionService.autoInsertNextDayRequest();
System.out.println("Food Daily Request Scheduler Ended......");
}
@Scheduled(cron = "0 0 13 * * ?", zone = "Asia/Kolkata") // 1 PM
public void runAutoAcceptFoodswingShift1() {
System.out.println("Shift-A Automatic Fine Accept Scheduler Started......");
distributionService.autoInsertForFineShift1();
System.out.println("Shift-A Automatic Fine Accept Scheduler Ended......");
}
@Scheduled(cron = "0 0 20 * * ?", zone = "Asia/Kolkata") // 8 PM
public void runAutoAcceptFoodswingShift2() {
System.out.println("Shift-B Automatic Fine Accept Scheduler Started......");
distributionService.autoInsertForFineShift2();
System.out.println("Shift-B Automatic Fine Accept Scheduler Ended......");
}
@Scheduled(cron = "0 0 5 * * ?", zone = "Asia/Kolkata") // 5 AM
public void runAutoAcceptFoodswingShift3() {
System.out.println("Shift-C Automatic Fine Accept Scheduler Started......");
distributionService.autoInsertForFineShift3();
System.out.println("Shift-C Automatic Fine Accept Scheduler Ended......");
}
}

163
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/DistributionController.java

@ -0,0 +1,163 @@
package in.gov.chennaicorporation.mobileservice.foodDistribution.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.foodDistribution.service.DistributionService;
@RequestMapping("/gccofficialapp/api/fooddistribution/")
@RestController("gccofficialappsfooddistribution")
public class DistributionController {
@Autowired
private DistributionService distributionService;
// -------------------- GET CONFIG --------------------
@GetMapping("/getConfig")
public List<?> getConfig(@RequestParam("loginId") String loginId) {
return distributionService.getConfig(loginId);
}
// -------------------- GET SHIFT COUNT --------------------
@GetMapping("/getShiftCount")
public List<?> getShiftCount(
@RequestParam("loginId") String loginId,
@RequestParam("shiftid") String shiftid
) {
return distributionService.getShiftCount(loginId, shiftid);
}
// -------------------- SAVE DAILY REQUEST --------------------
@PostMapping("/saveRequest")
public List<?> saveRequest(
@RequestParam String ward,
@RequestParam String required_date,
@RequestParam String permanent,
@RequestParam String nulm,
@RequestParam String private_,
@RequestParam String others,
@RequestParam(value = "nmr", required = false) String nmr,
@RequestParam String weeklyoff_permanent,
@RequestParam String weeklyoff_nulm,
@RequestParam String weeklyoff_private,
@RequestParam String weeklyoff_others,
@RequestParam(value = "weeklyoff_nmr", required = false) String weeklyoff_nmr,
@RequestParam String absentees_permanent,
@RequestParam String absentees_nulm,
@RequestParam String absentees_private,
@RequestParam String absentees_others,
@RequestParam(value = "absentees_nmr", required = false) String absentees_nmr,
@RequestParam String shiftid,
@RequestParam String request_by,
@RequestParam String hub_id
) {
return distributionService.saveRequest(
ward,
required_date,
permanent,
nulm,
private_,
others,
nmr,
weeklyoff_permanent,
weeklyoff_nulm,
weeklyoff_private,
weeklyoff_others,
weeklyoff_nmr,
absentees_permanent,
absentees_nulm,
absentees_private,
absentees_others,
absentees_nmr,
shiftid,
request_by,
hub_id
);
}
// -------------------- GET PENDING LIST --------------------
@GetMapping("/getPending")
public List<?> getPending(@RequestParam("loginId") String loginId) {
return distributionService.getPending(loginId);
}
// -------------------- GET PENDING DETAILS --------------------
@GetMapping("/getPendingDetails")
public List<?> getPendingDetails(
@RequestParam("loginId") String loginId,
@RequestParam("requestid") String requestid,
@RequestParam("shiftid") String shiftid
) {
return distributionService.getPendingDetails(loginId, requestid, shiftid);
}
// -------------------- SAVE FEEDBACK AND RECEVIED INFORMATION --------------------
@PostMapping("/saveFeedbackAndReceived")
public List<?> saveFeedbackAndReceived(
@RequestParam String requestid,
@RequestParam String shiftid,
// Feedback
@RequestParam String q1,
@RequestParam(value = "q1_img", required = false) MultipartFile q1_img,
@RequestParam String q2,
@RequestParam(value = "q2_img", required = false) MultipartFile q2_img,
@RequestParam String q3,
@RequestParam(value = "q3_img", required = false) MultipartFile q3_img,
@RequestParam String feedback_by,
// Received Update
@RequestParam String total_box_shortfall,
@RequestParam String return_today,
@RequestParam String total_food_requested,
@RequestParam String total_food_received,
@RequestParam String today_absentees_permanent,
@RequestParam String today_absentees_nulm,
@RequestParam String today_absentees_private,
@RequestParam String today_absentees_others,
@RequestParam String received_by,
@RequestParam(value = "today_absentees_nmr", required = false) String today_absentees_nmr,
@RequestParam(value = "remarks", required = false) String remarks
) {
return distributionService.saveFullFeedbackAndReceived(
requestid, shiftid,
q1, q1_img, q2, q2_img, q3, q3_img, feedback_by,
total_box_shortfall, return_today, total_food_requested, total_food_received,
today_absentees_permanent, today_absentees_nulm,
today_absentees_private, today_absentees_others,
received_by,today_absentees_nmr,remarks
);
}
// For Reports
@GetMapping("/getZoneSummary")
public List<?> getZoneSummary(
@RequestParam("fromDate") String fromDate,
@RequestParam("toDate") String toDate
) {
return distributionService.getZoneSummary(fromDate, toDate);
}
@GetMapping("/getWardSummary")
public List<?> getWardSummary(
@RequestParam("fromDate") String fromDate,
@RequestParam("toDate") String toDate,
@RequestParam("zone") String zone
) {
return distributionService.getWardSummary(fromDate, toDate, zone);
}
}

144
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/DriverController.java

@ -0,0 +1,144 @@
package in.gov.chennaicorporation.mobileservice.foodDistribution.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.foodDistribution.service.DriverService;
@RequestMapping("/gccofficialapp/api/fooddistribution/driver")
@RestController("gccofficialappsfooddistributiondriver")
public class DriverController {
@Autowired
private DriverService driverService;
@GetMapping({"/versionCheck"}) // Template
public List <?> versionCheck() {
return driverService.versionCheck();
}
@GetMapping(value="login")
public List login(@RequestParam("username") String username, @RequestParam("password") String Password, @RequestParam("usertype") String usertype) {
return driverService.getloginList(username, Password, usertype);
}
// ---------------------------------------------------------
//️⃣ GET LIVE TRACK
// ---------------------------------------------------------
@GetMapping("/getDeliveryLocation")
public List<?> getDeliveryLocation(
@RequestParam String loginid
) {
return driverService.getDeliveryLocation(loginid);
}
// ---------------------------------------------------------
// GET LIVE TRACK OF Driver BY SI Login
// ---------------------------------------------------------
@GetMapping("/getDriverStatus")
public List<?> getDriverStatus(
@RequestParam String siloginid
) {
return driverService.getDriverStatus(siloginid);
}
// ---------------------------------------------------------
// 1️⃣ GET LIVE TRACK BY SI Login
// ---------------------------------------------------------
@GetMapping("/getLiveTrack")
public List<?> getLiveTrack(
@RequestParam String siloginid,
@RequestParam String date
) {
return driverService.getLiveTrack(siloginid, date);
}
// ---------------------------------------------------------
// 2️⃣ GET DRIVER LAST START/STOP STATUS
// ---------------------------------------------------------
@GetMapping("/getDriverLastStartStop")
public List<?> getDriverLastStartStop(
@RequestParam String loginid
) {
return driverService.getDriverLastStartStop(loginid);
}
// ---------------------------------------------------------
// 3️⃣ SAVE DRIVER START / STOP WITH IMAGE
// ---------------------------------------------------------
@PostMapping(value = "/saveStartStop", consumes = {"multipart/form-data"})
public List<?> saveStartStop(
@RequestParam String loginid,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String action,
@RequestParam String startid,
@RequestParam String driver_live_mobile,
@RequestParam(required = false) MultipartFile image,
@RequestParam(required = false) String address,
@RequestParam(required = false) String driver_name
) {
return driverService.saveStartStop(
loginid, latitude, longitude,
action, startid, driver_live_mobile, image, address, driver_name
);
}
// ---------------------------------------------------------
// 4️⃣ SAVE LIVE LOCATION POINT
// ---------------------------------------------------------
@PostMapping("/saveLiveLocation")
public List<?> saveLiveLocation(
@RequestParam String loginid,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam(required = false) String address
) {
return driverService.saveLiveLocation(loginid, latitude, longitude, address);
}
// Vendor
@GetMapping("/getMenuDetails")
public List<?> getMenuDetails(
@RequestParam String loginid
) {
return driverService.getMenuDetails(loginid);
}
@GetMapping("/getPendingDetails")
public List<?> getPendingDetails(
@RequestParam String loginid,
@RequestParam String shiftid,
@RequestParam String date,
@RequestParam String hub_id
) {
return driverService.getPendingDetails(loginid, shiftid, date, hub_id);
}
@GetMapping("/getRequestUpdated")
public List<?> getRequestUpdated(
@RequestParam String loginid,
@RequestParam String shiftid,
@RequestParam String date
) {
return driverService.getRequestUpdated(loginid, shiftid, date);
}
@PostMapping("/saveRequestUpadte")
public List<?> saveRequestUpadte(
@RequestParam String loginid,
@RequestParam String shiftid,
@RequestParam String total_food_request_recived,
@RequestParam String total_food_transported,
@RequestParam String foodid
) {
return driverService.saveRequestUpadte(loginid, shiftid, total_food_request_recived, total_food_transported, foodid);
}
}

408
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/controller/PmcController.java

@ -0,0 +1,408 @@
package in.gov.chennaicorporation.mobileservice.foodDistribution.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.foodDistribution.service.PmcService;
@RequestMapping("/gccofficialapp/api/fooddistribution/pmc")
@RestController("gccofficialappsfooddistributionpmc")
public class PmcController {
@Autowired
private PmcService pmcservice;
// kitchen
@GetMapping("/getConfig")
public List<?> getConfig(@RequestParam("loginId") String loginId) {
return pmcservice.getConfig(loginId);
}
// @GetMapping("/getFinalFoodCount")
// public List<Map<String, Object>> getZoneCount(
// @RequestParam int shiftid,
// @RequestParam int loginid,
// @RequestParam String date) {
//
// return pmcservice.getFinalFoodCount(shiftid, loginid, date);
// }
// @GetMapping("/getfeedbackquestions")
// public List<Map<String, Object>> getFeedbackQuestions(
// @RequestParam(value = "loginId", required = false) String loginId) {
// return pmcservice.getParentQuestionsList(loginId);
// }
// @PostMapping("/savefeedback")
// public List<?> savefeedback(
// @RequestParam(value = "loginId", required = true) String loginId,
// @RequestParam(value = "auditdate", required = true) String auditdate,
// @RequestParam(value = "shiftid", required = true) String shiftid,
// @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 = "final_food_count", required = true) String final_food_count,
// @RequestParam(value = "foodid", required = true) String foodid,
// @RequestParam(value = "food_others", required = false) String food_others,
// @RequestParam(value = "hub_id", required = true) String hub_id,
//
// @RequestParam(value = "q1", required = true) String q1,
// @RequestParam(value = "q2", required = true) String q2,
// @RequestParam(value = "q3", required = true) String q3,
// @RequestParam(value = "q4", required = true) String q4,
// @RequestParam(value = "q5", required = true) String q5,
// @RequestParam(value = "q6", required = true) String q6,
// @RequestParam(value = "q7", required = true) String q7,
// @RequestParam(value = "q8", required = true) String q8,
// @RequestParam(value = "q9", required = true) String q9,
// @RequestParam(value = "q10", required = true) String q10,
// @RequestParam(value = "q11", required = true) String q11,
// @RequestParam(value = "q12", required = true) String q12,
// @RequestParam(value = "q13", required = true) String q13,
// @RequestParam(value = "q14", required = true) String q14,
// @RequestParam(value = "q15", required = true) String q15,
// @RequestParam(value = "q16", required = true) String q16,
// @RequestParam(value = "q17", required = true) String q17,
// @RequestParam(value = "q18", required = true) String q18,
//
// @RequestParam(value = "image1", required = true) MultipartFile image1,
// @RequestParam(value = "image2", required = true) MultipartFile image2,
// @RequestParam(value = "image3", required = true) MultipartFile image3,
// @RequestParam(value = "image4", required = true) MultipartFile image4,
// @RequestParam(value = "image5", required = true) MultipartFile image5) {
//
// return pmcservice.saveFeedback(
// loginId, auditdate, shiftid, latitude, longitude, zone, ward, address,
// final_food_count, foodid, food_others, hub_id,
// Arrays.asList(q1, q2, q3, q4, q5, q6, q7, q8, q9, q10,
// q11, q12, q13, q14, q15, q16, q17, q18),
// image1, image2, image3, image4, image5);
// }
//pmc
@GetMapping("/getNotFilledCategories")
public List<Map<String, Object>> getNotFilledCategories(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getNotFilledCategories(shiftid, loginid, date);
}
@GetMapping("/getquestionsbycat")
public List<Map<String, Object>> getquestionsbycat(
@RequestParam int qcm_id,
@RequestParam int loginid,
@RequestParam int shiftid,
@RequestParam String latitude,
@RequestParam String longitude) {
return pmcservice.getquestionsbycat(qcm_id,loginid,shiftid,latitude,longitude);
}
@GetMapping("/getselectedmenu")
public List<Map<String, Object>> getselectedmenu(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getselectedmenu(shiftid, loginid, date);
}
@PostMapping("/savecatfeedback")
public List<?> savefeedback(
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "auditdate", required = true) String auditdate,
@RequestParam(value = "shiftid", required = true) String shiftid,
@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 = "final_food_count", required = false) String final_food_count,
@RequestParam(value = "foodid", required = true) String foodid,
@RequestParam(value = "food_others", required = false) String food_others,
@RequestParam(value = "hub_id", required = true) String hub_id,
@RequestParam(value = "qcm_id", required = true) String qcm_id,
@RequestParam(value = "questionAnswers", required = true) String questionAnswers,
@RequestParam(value = "images", required = false) MultipartFile[] images
)
{
return pmcservice.saveFeedbackbycat(
loginId, auditdate, shiftid, latitude, longitude, zone, ward, address,
final_food_count, foodid, food_others, hub_id, qcm_id,
questionAnswers, images
);
}
//foodswing
@GetMapping("/issuefoundhubs")
public List<Map<String, Object>> getfeedbackhubdetails(
@RequestParam (value = "loginid", required = false) Integer loginid,
@RequestParam String date
){
return pmcservice.getfeedbackhubdetails(loginid, date);
}
@GetMapping("/getfoodswingDataNoCategory")
public List<Map<String, Object>> getfoodswingDataNoCategory(
@RequestParam int shiftid,
@RequestParam int hub_id,
@RequestParam String date,
@RequestParam(value = "latitude", required = false) String latitude,
@RequestParam(value = "longitude", required = false) String longitude) {
return pmcservice.getfoodswingDataNoCategory(shiftid, hub_id, date,latitude,longitude);
}
@PostMapping("/savefoodswingdata")
public List<?> savefoodswingdata(
@RequestParam(value = "questionAnswers", required = true) String questionAnswers,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "latitude", required = false) String latitude,
@RequestParam(value = "longitude", required = false) String longitude,
@RequestParam(value = "images", required = false) MultipartFile[] images
){
return pmcservice.savefoodswingdata(questionAnswers,loginId,latitude,longitude,images);
}
//ce login data
@GetMapping("/celoginhubs")
public List<Map<String, Object>> getceloginhubs(
@RequestParam (value = "date", required = false) String date
){
return pmcservice.getceloginhubs();
}
@GetMapping("/gethubforcelogin")
public List<Map<String, Object>> gethubsforreport(
@RequestParam int hub_id) {
return pmcservice.getHubDateShiftDetails(hub_id);
}
@GetMapping("/getCEDataNoCategory")
public List<Map<String, Object>> getCEDataNoCategory(
@RequestParam int shiftid,
@RequestParam int hub_id,
@RequestParam String date) {
return pmcservice.getCEDataNoCategory(shiftid, hub_id, date);
}
@PostMapping("/savecelogindata")
public List<?> savecelogindata(
@RequestParam(value = "questionAnswers", required = true) String questionAnswers,
@RequestParam(value = "loginId", required = true) String loginId
){
return pmcservice.savecelogindata(questionAnswers,loginId);
}
//
//General Common Report
@GetMapping("/gethubsforreport")
public List<Map<String, Object>> gethubsforreport(
@RequestParam String date,
@RequestParam(required = false) Integer loginId) {
return pmcservice.gethubsforreport(date, loginId);
}
@GetMapping("/getcatsforhubreport")
public List<Map<String, Object>> getcatsforhubreport(
@RequestParam int shiftid,
@RequestParam int hub_id,
@RequestParam String date) {
return pmcservice.getcatsforhubreport(shiftid, hub_id, date);
}
@GetMapping("/getreportdata")
public List<Map<String, Object>> getreportdata(
@RequestParam int shiftid,
@RequestParam int hub_id,
@RequestParam String date,
@RequestParam int qcm_id) {
return pmcservice.getreportdata(shiftid, hub_id, date,qcm_id);
}
//penalty Report
@GetMapping("/penalty/hubs")
public List<Map<String, Object>> getPenaltyHubSummary(@RequestParam int loginid) {
return pmcservice.getPenaltyHubSummary(loginid);
}
@GetMapping("/penalty/hubdetails")
public List<Map<String, Object>> getHubDetails(
@RequestParam int hub_id,
@RequestParam String type) {
return pmcservice.getHubDateShiftDetails(hub_id, type);
}
@GetMapping("/penalty/category")
public List<Map<String, Object>> getCategoryReport(
@RequestParam int hub_id,
@RequestParam int shiftid,
@RequestParam String date,
@RequestParam String type) {
return pmcservice.getCategoryReport(hub_id, shiftid, date, type);
}
@GetMapping("/penalty/questions")
public List<Map<String, Object>> getQuestionReport(
@RequestParam int hub_id,
@RequestParam int shiftid,
@RequestParam String date,
@RequestParam String type,
@RequestParam int qcm_id) {
return pmcservice.getQuestionReport(hub_id, shiftid, date, type, qcm_id);
}
@GetMapping("/getfeedbackreport")
public List<Map<String, Object>> getfeedbackreport(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getfeedbackreport(shiftid, loginid, date);
}
@GetMapping("/getFinalFoodCount")
public List<Map<String, Object>> getFinalFoodCount(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getFinalFoodCountPerHubId(shiftid, loginid, date);
}
@GetMapping("/getfoodswingData")
public List<Map<String, Object>> getfoodswingData(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date){
return pmcservice.getfoodswingData(shiftid, loginid, date);
}
// dispatch
// @GetMapping("/getDispatchFoodCount")
// public List<Map<String, Object>> getZoneCountForDispatch(
// @RequestParam int shiftid,
// @RequestParam int loginid,
// @RequestParam String date) {
//
// return pmcservice.getFinalFoodCountForDispatch(shiftid, loginid, date);
// }
@GetMapping("/getDispatchFoodCount")
public List<Map<String, Object>> getZoneCountForDispatch(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getFoodCountForDispatch(shiftid, loginid, date);
}
// @PostMapping("/savedispatch")
// public List<?> savedispatch(
// @RequestParam(value = "pmc_audit_id", required = true) int pmc_audit_id,
// @RequestParam(value = "driver_name", required = true) String driver_name,
// @RequestParam(value = "driver_mob_num", required = true) String driver_mob_num,
// @RequestParam(value = "vehicle_number", required = true) String vehicle_number,
// @RequestParam(value = "packedfoodphoto", required = true) MultipartFile packedfoodphoto,
// @RequestParam(value = "vehiclephoto", required = true) MultipartFile vehiclephoto,
// @RequestParam(value = "loginId", required = true) String loginId,
// @RequestParam(value = "yet_dispatch_count", required = true) int yet_dispatch_count,
// @RequestParam(value = "dispatch_food_list") String dispatch_food_list) {
//
// return pmcservice.savedispatch(pmc_audit_id, driver_name, driver_mob_num, vehicle_number, packedfoodphoto,
// vehiclephoto, loginId, yet_dispatch_count, dispatch_food_list);
// }
@PostMapping("/savedispatch")
public List<?> savedispatch(
@RequestParam(value = "auditdate", required = true) String auditdate,
@RequestParam(value = "shiftid", required = true) String shiftid,
@RequestParam(value = "hub_id", required = true) String hub_id,
@RequestParam(value = "driver_name", required = true) String driver_name,
@RequestParam(value = "driver_mob_num", required = true) String driver_mob_num,
@RequestParam(value = "vehicle_number", required = true) String vehicle_number,
@RequestParam(value = "packedfoodphoto", required = true) MultipartFile packedfoodphoto,
@RequestParam(value = "vehiclephoto", required = true) MultipartFile vehiclephoto,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "yet_dispatch_count", required = true) int yet_dispatch_count,
@RequestParam(value = "dispatch_food_list") String dispatch_food_list) {
return pmcservice.savefordispatch(auditdate,shiftid,hub_id, driver_name, driver_mob_num, vehicle_number, packedfoodphoto,
vehiclephoto, loginId, yet_dispatch_count, dispatch_food_list);
}
@GetMapping("/getvehicleallocated")
public List<Map<String, Object>> getvehicleallocated(
@RequestParam int shiftid,
@RequestParam int loginid,
@RequestParam String date) {
return pmcservice.getvehicleallocated(shiftid, loginid, date);
}
}

1691
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/DistributionService.java
File diff suppressed because it is too large
View File

750
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/DriverService.java

@ -0,0 +1,750 @@
package in.gov.chennaicorporation.mobileservice.foodDistribution.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.PreparedStatement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class DriverService {
private JdbcTemplate jdbcFoodTemplate;
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("mysqlGccFoodDistributionSource") DataSource FoodDistributionSource) {
this.jdbcFoodTemplate = new JdbcTemplate(FoodDistributionSource);
}
@Autowired
public DriverService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, String id, MultipartFile file, String filetype) {
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("fooddistribution_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + "driver/" + filetype + "/" + 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();
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 + "driver/" + filetype + "/" + year + "/" + month + "/" + date
+ "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
if (filetype.equalsIgnoreCase("image")) {
// 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);
} else {
// Write the bytes to the file
Files.write(path, bytes);
}
// Get current date & time
LocalDateTime now = LocalDateTime.now();
// Format date-time (optional)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Date: " + now.format(formatter));
System.out.println("Activity: SluicePoint");
System.out.println("File Type: " + filetype);
System.out.println("File Upload Path: " + filePath);
System.out.println("File Path: " + filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save file " + file.getOriginalFilename());
return "error";
}
}
@Transactional
public List<Map<String, Object>> versionCheck() {
String sqlQuery = "SELECT * FROM `app_version` WHERE `isactive`=1 LIMIT 1";
List<Map<String, Object>> result = jdbcFoodTemplate.queryForList(sqlQuery);
return result;
}
public String getWardByLoginId(String loginid) {
String sqlQuery = "SELECT `ward` FROM `location_mapping` WHERE `siloginid` = ? AND `isactive`=1 AND `isdelete`=0 LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcFoodTemplate.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
}
@Transactional
public List<Map<String, Object>> getloginList(String username, String password, String usertype) {
String sqlQuery = "";
List<Map<String, Object>> result = null;
try {
switch (usertype) {
case "driver":
sqlQuery = "SELECT `loginid`, `name`, `username` FROM `driver_login` WHERE (`username`=? AND `password`=?) AND (`isactive`=1 AND `isdelete`=0) LIMIT 1";
result = jdbcFoodTemplate.queryForList(sqlQuery, username, password);
break;
case "vendor":
sqlQuery = "SELECT `loginid`, `name`, `username`, `hub_id` FROM `driver_login` WHERE (`username`=? AND `password`=?) AND (`isactive`=1 AND `isdelete`=0) LIMIT 1";
result = jdbcFoodTemplate.queryForList(sqlQuery, username, password);
break;
case "foodswing":
sqlQuery = "SELECT `loginid`, `name`, `username`,`hub_id` FROM `driver_login` WHERE (`username`=? AND `password`=?) AND (`isactive`=1 AND `isdelete`=0) LIMIT 1";
result = jdbcFoodTemplate.queryForList(sqlQuery, username, password);
break;
case "pmc":
sqlQuery = "SELECT `loginid`, `name`, `username`, `hub_id` FROM `driver_login` WHERE (`username`=? AND `password`=?) AND (`isactive`=1 AND `isdelete`=0) LIMIT 1";
result = jdbcFoodTemplate.queryForList(sqlQuery, username, password);
break;
// additional cases can be added here
default:
sqlQuery = "SELECT `loginid`, `name`, `username` FROM `driver_login` WHERE (`username`=? AND `password`=?) AND (`isactive`=1 AND `isdelete`=0) LIMIT 1";
result = jdbcFoodTemplate.queryForList(sqlQuery, username, password);
// result = Collections.emptyList();
break;
}
} catch (Exception e) {
// Log the error
e.printStackTrace();
// Return an error message as part of the result list
return Collections
.singletonList(Collections.singletonMap("error", "An error occurred while fetching data."));
}
// If no records found, return a status and message indicating no user found
if (result == null || result.isEmpty()) {
Map<String, Object> response = Map.of(
"status", 404,
"message", "User not found.");
return Collections.singletonList(response);
}
// Add a success status and message to the result
Map<String, Object> successResponse = Map.of(
"status", 200,
"message", "login successfuly.",
"data", result);
return Collections.singletonList(successResponse);
}
public List<Map<String, Object>> getDeliveryLocation(String loginid) {
// String searchDate = convertDateFormat(date,0);
String sql = "SELECT * FROM `location_mapping` WHERE `driverid`=? AND `isactive`=1 AND `isdelete`=0";
List<Map<String, Object>> DeliveryLocation = jdbcFoodTemplate.queryForList(sql, loginid);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Delivery Location Details.");
response.put("data", DeliveryLocation);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getDriverStatus(String siloginid) {
Map<String, Object> response = new HashMap<>();
// 1. Get driverid using siloginid
String sql1 = "SELECT driverid FROM location_mapping " +
"WHERE siloginid = ? AND isactive = 1 AND isdelete = 0";
List<Map<String, Object>> driverList = jdbcFoodTemplate.queryForList(sql1, siloginid);
if (driverList.isEmpty()) {
response.put("status", "Failed");
response.put("message", "No driver found");
response.put("data", Collections.emptyList());
return Collections.singletonList(response);
}
// Extract driverid
Object driverIdObj = driverList.get(0).get("driverid");
if (driverIdObj == null) {
response.put("status", "Failed");
response.put("message", "DriverID is null");
response.put("data", Collections.emptyList());
return Collections.singletonList(response);
}
String driverId = driverIdObj.toString();
// 2. Get latest start/stop entry
String sql = "SELECT dss.*, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', dss.image) AS photourl, " +
"lm.id AS mapping_id, lm.zone, lm.zone_name, lm.ward, lm.location, " +
"lm.latitude, lm.logitude, lm.si_name, lm.si_number " +
"FROM driver_start_stop dss " +
"JOIN location_mapping lm ON lm.driverid = dss.loginid " +
"WHERE dss.loginid = ? AND dss.isactive = 1 AND dss.isdelete = 0 " +
"ORDER BY dss.locationid DESC LIMIT 1";
List<Map<String, Object>> driverStatus = jdbcFoodTemplate.queryForList(sql, driverId);
response.put("status", "Success");
response.put("message", "Driver Status & Last Delivery Location Details");
response.put("data", driverStatus);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getLiveTrack(String siloginid, String date) {
Map<String, Object> response = new HashMap<>();
try {
// 1. Get driverid using siloginid
String sql1 = "SELECT driverid FROM location_mapping " +
"WHERE siloginid = ? AND isactive = 1 AND isdelete = 0";
List<Map<String, Object>> deliveryLocation = jdbcFoodTemplate.queryForList(sql1, siloginid);
if (deliveryLocation.isEmpty()) {
response.put("status", "Failed");
response.put("message", "No driver found");
response.put("data", Collections.emptyList());
return Collections.singletonList(response);
}
// Extract driverid
Object driverIdObj = deliveryLocation.get(0).get("driverid");
if (driverIdObj == null) {
response.put("status", "Failed");
response.put("message", "DriverID is null");
response.put("data", Collections.emptyList());
return Collections.singletonList(response);
}
String loginid = driverIdObj.toString();
// 2. Convert Date
String searchDate = convertDateFormat(date, 0);
// 3. Fetch Live Track
String sql2 = "SELECT * FROM driver_live_track " +
"WHERE loginid = ? AND DATE(datetime) = ? AND isactive = 1 AND isdelete = 0 " +
"ORDER BY datetime";
List<Map<String, Object>> liveTrack = jdbcFoodTemplate.queryForList(sql2, loginid, searchDate);
// 4. Prepare Response
response.put("status", "Success");
response.put("message", "Live Track Details.");
response.put("data", liveTrack);
} catch (Exception e) {
response.put("status", "Failed");
response.put("message", "Error: " + e.getMessage());
response.put("data", Collections.emptyList());
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getDriverLastStartStop(String loginid) {
String sql = "SELECT * FROM `driver_start_stop` WHERE `loginid`=? ORDER BY locationid DESC LIMIT 1";
List<Map<String, Object>> liveTrack = jdbcFoodTemplate.queryForList(sql, loginid);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Driver Status Details.");
response.put("data", liveTrack);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveStartStop(
String loginid,
String latitude,
String longitude,
String action,
String startid,
String driver_live_mobile,
MultipartFile image,
String address,
String driver_name) {
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
String filetype = "image";
// Q1 Image
final String[] image_path = { null };
if (image != null && !image.isEmpty()) {
image_path[0] = fileUpload(loginid, action, image, filetype);
if ("error".equalsIgnoreCase(image_path[0])) {
response.put("status", "error");
response.put("message", "Feedback image upload failed.");
result.add(response);
return result;
}
}
String insertSqltxt = "INSERT INTO `driver_start_stop`(`latitude`, `longitude`, `image`,`loginid`,`action`,`startid`,`driver_live_mobile`,`address`,`driver_name`) "
+ "VALUES (?,?,?,?,?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcFoodTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "requestid" });
int i = 1;
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, image_path[0]);
ps.setString(i++, loginid);
ps.setString(i++, action);
ps.setString(i++, startid);
ps.setString(i++, driver_live_mobile);
ps.setString(i++, address);
ps.setString(i++, driver_name);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Driver Point", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", action + " data inserted successfully.");
saveLiveLocation(loginid, latitude, longitude, address); // Save location In Live Track on start and stop
} else {
response.put("Driver Point", action + " insertId error!");
response.put("status", "error");
response.put("message", action + " data insert failed.");
}
result.add(response);
return result;
}
@Transactional
public List<Map<String, Object>> saveLiveLocation(
String loginid,
String latitude,
String longitude,
String address) {
String action = "Live Location";
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
String insertSqltxt = "INSERT INTO `driver_live_track`(`loginid`, `latitude`, `longitude`, `address`) "
+ "VALUES (?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcFoodTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "requestid" });
int i = 1;
ps.setString(i++, loginid);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, address);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Driver", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", action + " data inserted successfully.");
} else {
response.put("Driver", action + " insertId error!");
response.put("status", "error");
response.put("message", action + " data insert failed.");
}
result.add(response);
return result;
}
// Vendor
public List<Map<String, Object>> getPendingDetails(String loginid, String shiftid, String date, String hub_id) {
String searchDate = convertDateFormat(date, 0);
int hubIdInt = hub_id.isEmpty() ? 0 : Integer.parseInt(hub_id);
/*
*
* // 1. Get shortfall details
* String sql = "SELECT "
* + " dr.required_date, "
* + " dr.shiftid, "
* + " sm.Code, "
* + " sm.name, "
* + " sm.hint, "
* + " sm.time, "
* + " sm.enable_time, "
* + " sm.disable_time, "
* + " (dr.permanent + dr.nulm + dr.private + dr.others + dr.nmr) - "
* + " ("
* +
* " (dr.weeklyoff_permanent + dr.weeklyoff_nulm + dr.weeklyoff_private + dr.weeklyoff_others + dr.weeklyoff_nmr) + "
* +
* " (dr.absentees_permanent + dr.absentees_nulm + dr.absentees_private + dr.absentees_others + dr.absentees_nmr) "
* + " ) AS sum_total_food_requested "
* + "FROM daily_request dr "
* + "JOIN shift_master sm "
* + " ON sm.shiftid = dr.shiftid "
* + "WHERE dr.required_date = ? "
* + " AND dr.shiftid = ? "
* + " AND dr.isactive = 1 "
* + " AND dr.isdelete = 0"
* + " GROUP BY dr.required_date, dr.shiftid";
*/
// 1. Get shortfall details
String sql = "SELECT " +
" dr.required_date, " +
" dr.shiftid, " +
" sm.Code, " +
" sm.name, " +
" sm.hint, " +
" sm.time, " +
" sm.enable_time, " +
" sm.disable_time, " +
" SUM( " +
" (dr.permanent + dr.nulm + dr.private + dr.others + dr.nmr) - " +
" ( " +
" (dr.weeklyoff_permanent + dr.weeklyoff_nulm + dr.weeklyoff_private + dr.weeklyoff_others + dr.weeklyoff_nmr) + "
+
" (dr.absentees_permanent + dr.absentees_nulm + dr.absentees_private + dr.absentees_others + dr.absentees_nmr) "
+
" ) " +
" ) AS sum_total_food_requested " +
"FROM daily_request dr " +
"JOIN shift_master sm " +
" ON sm.shiftid = dr.shiftid " +
"WHERE dr.required_date = ? " +
" AND dr.shiftid = ? " +
" AND dr.hub_id = ? " +
" AND dr.isactive = 1 " +
" AND dr.isdelete = 0 " +
"GROUP BY dr.required_date, dr.shiftid";
List<Map<String, Object>> shortfallDetails = jdbcFoodTemplate.queryForList(sql, searchDate, shiftid, hubIdInt);
// 2. Get requested food details
sql = "SELECT "
+ " dr.requestid, "
+ " dr.request_by, "
+ " dr.request_date, "
+ " (dr.permanent + dr.nulm + dr.private + dr.others + dr.nmr) - "
+ " ( "
+ " (dr.weeklyoff_permanent + dr.weeklyoff_nulm + dr.weeklyoff_private + dr.weeklyoff_others + dr.weeklyoff_nmr) + "
+ " (dr.absentees_permanent + dr.absentees_nulm + dr.absentees_private + dr.absentees_others + dr.absentees_nmr) "
+ " ) AS total_food_requested, "
+ " lm.id AS mapping_id, "
+ " lm.zone, "
+ " lm.zone_name, "
+ " lm.ward, "
+ " lm.location, "
+ " lm.Latitude, "
+ " lm.logitude, "
+ " lm.si_name, "
+ " lm.si_number, "
+ " lm.driverid, "
+ " lm.siloginid "
+ "FROM daily_request dr "
+ "JOIN location_mapping lm "
+ " ON dr.request_by = lm.siloginid "
+ "WHERE "
+ " dr.required_date = ? "
+ " AND dr.shiftid = ? "
+ " AND dr.hub_id = ? "
+ " AND dr.isactive = 1 "
+ " AND dr.isdelete = 0 "
+ " AND lm.isactive = 1 "
+ " AND lm.isdelete = 0";
List<Map<String, Object>> requestedInfo = jdbcFoodTemplate.queryForList(sql, searchDate, shiftid, hubIdInt);
/*
* // 2. Get requested food details
* sql =
* "SELECT `foodid`, `type`, `name`, `isactive`, `isdelete` FROM `food_list_master` WHERE `isactive`=1 AND `isdelete`=0"
* ;
*
* List<Map<String, Object>> foodInfo = jdbcFoodTemplate.queryForList(sql);
*
* // 2. Combine both list results
* // Combine request info (shortfall + requested)
* //List<Map<String, Object>> requestInfo = new ArrayList<>();
* //requestInfo.addAll(shortfallDetails);
* //requestInfo.addAll(requestedInfo);
*/
// Final response structure
Map<String, Object> data = new HashMap<>();
data.put("request_info", requestedInfo);
data.put("summary_info", shortfallDetails);
// 3. Create final response
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Pending Details.");
response.put("data", data);
return Collections.singletonList(response);
}
// public List<Map<String, Object>> getMenuDetails(String loginid) {
// // Get requested food details
// String sql = "SELECT `foodid`, `type`, `name`, `isactive`, `isdelete` FROM
// `food_list_master` WHERE `isactive`=1 AND `isdelete`=0";
// List<Map<String, Object>> foodInfo = jdbcFoodTemplate.queryForList(sql);
// // 3. Create final response
// Map<String, Object> response = new HashMap<>();
// response.put("status", "Success");
// response.put("message", "Food Menu Details.");
// response.put("data", foodInfo);
// return Collections.singletonList(response);
// }
public List<Map<String, Object>> getMenuDetails(String loginid) {
// Get requested food details
String sql = "SELECT `foodid`, `type`, `name`, `isactive`, `isdelete`,`text_required` FROM `food_list_master` WHERE `isactive`=1 AND `isdelete`=0";
List<Map<String, Object>> foodInfo = jdbcFoodTemplate.queryForList(sql);
// 3. Create final response
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Food Menu Details.");
response.put("data", foodInfo);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getRequestUpdated(String loginid, String shiftid, String date) {
String searchDate = convertDateFormat(date, 0);
// Get requested food details
String sql = "SELECT `uid`, `shiftid`, `total_food_request_recived`, `total_food_transported`, `foodid`, `indate`, `inby`"
+ " FROM `vendor_food_update` WHERE `shiftid`=? AND DATE(`indate`)=? AND `isactive`=1 AND `isdelete`=0";
List<Map<String, Object>> requestUpadteInfo = jdbcFoodTemplate.queryForList(sql, shiftid, searchDate);
// 3. Create final response
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request Update Details.");
response.put("data", requestUpadteInfo);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveRequestUpadte(
String loginid,
String shiftid,
String total_food_request_recived,
String total_food_transported,
String foodid) {
String action = "Food Request Status update";
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
String insertSqltxt = "INSERT INTO `vendor_food_update`(`shiftid`, `total_food_request_recived`, `total_food_transported`, `foodid`,`inby`) "
+ "VALUES (?,?,?,?,?)";
String insertSql = insertSqltxt;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcFoodTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[] { "requestid" });
int i = 1;
ps.setString(i++, shiftid);
ps.setString(i++, total_food_request_recived);
ps.setString(i++, total_food_transported);
ps.setString(i++, foodid);
ps.setString(i++, loginid);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Driver", action + " insertId: " + lastInsertId);
response.put("status", "success");
response.put("message", action + " data inserted successfully.");
} else {
response.put("Driver", action + " insertId error!");
response.put("status", "error");
response.put("message", action + " data insert failed.");
}
result.add(response);
return result;
}
}

3804
src/main/java/in/gov/chennaicorporation/mobileservice/foodDistribution/service/PmcService.java
File diff suppressed because it is too large
View File

143
src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/controller/CattleApiController.java

@ -0,0 +1,143 @@
package in.gov.chennaicorporation.mobileservice.gccCattleSurvey.controller;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.gccCattleSurvey.service.CattleService;
@RequestMapping("/gccofficialapp/api/cattlesurveygcc")
@RestController("gccofficialappsgccCattleSurveyController")
public class CattleApiController {
@Autowired
private CattleService cattleService;
@GetMapping("/getbreeds")
public List<Map<String, Object>> getbreeds() {
return cattleService.getbreeds();
}
@GetMapping("/getcattle_type")
public List<Map<String, Object>> cattle_type() {
return cattleService.cattle_type();
}
@GetMapping("/getgcc_shed")
public List<Map<String, Object>> getgcc_shed() {
return cattleService.getgcc_shed();
}
@GetMapping("/getidproof")
public List<Map<String, Object>> getidproof() {
return cattleService.getidproof();
}
@GetMapping("/getspace_rearing")
public List<Map<String, Object>> getspace_rearing() {
return cattleService.getspace_rearing();
}
@GetMapping("/getvaccination_type")
public List<Map<String, Object>> getvaccination_type() {
return cattleService.getvaccination_type();
}
// @GetMapping("/getcattle_housed")
// public List<Map<String, Object>> getcattle_housed() {
//
// return cattleService.getcattle_housed();
// }
@PostMapping("/saveownerdetails")
public List<Map<String, Object>> saveownerdetails(
@RequestParam (required = false) String owner_name,
@RequestParam (required = false) String mobile_no,
@RequestParam (required = false) String address,
@RequestParam (required = false) int id_proof,
@RequestParam (required = false) String id_details,
@RequestParam (required = false) String house_type,
@RequestParam (required = false) int cattle_space,
@RequestParam (required = false) Double cattle_space_area,
@RequestParam (required = false) Integer cattle_space_gcc_shed,
@RequestParam (required = false) int no_of_cattles,
@RequestParam (required = false) String userid,
@RequestParam(value = "owner_photo", required = true) MultipartFile image,
@RequestParam (required = false) String latitude,
@RequestParam (required = false) String longitude,
@RequestParam (required = false) String zone,
@RequestParam (required = false) String ward,
@RequestParam (required = false) String location
){
return cattleService.saveownerdetails(owner_name,mobile_no,address,id_proof,id_details,house_type,
cattle_space,cattle_space_area,no_of_cattles,userid,image,latitude,
longitude,zone,ward,location,cattle_space_gcc_shed);
}
@GetMapping("/getownersbycby")
public List<Map<String, Object>> getownersbycby(@RequestParam String userid) {
return cattleService.getownersbycby(userid);
}
@GetMapping("/getownerdetails")
public List<Map<String, Object>> getownerdetails(@RequestParam String owner_ref_id) {
return cattleService.getownerdetails(owner_ref_id);
}
@PostMapping("/savecattledetails")
public List<Map<String, Object>> savecattledetails(
@RequestParam (required = false) String owner_ref_id,
@RequestParam (required = false) int cattle_type,
@RequestParam (required = false) int breed_type,
@RequestParam (required = false) String animal_name,
@RequestParam (required = false) Integer animal_age,
@RequestParam (required = false) String animal_gender,
@RequestParam (required = false) String cattle_maintained,
@RequestParam (required = false) Integer cattle_space_gcc_shed,
@RequestParam (required = false) String insurance_flag,
@RequestParam (required = false) String insurance_no,
@RequestParam (required = false) String microchip_flag,
@RequestParam (required = false) String microchip_no,
@RequestParam(value = "insurance_photo", required = false) MultipartFile ipimage,
@RequestParam (required = false) String license_flag,
@RequestParam (required = false) String licenese_no,
@RequestParam (required = false) String vaccination_flag,
@RequestParam (required = false) Integer vaccination_type,
@RequestParam (required = false) String vaccination_date,
@RequestParam (required = false) String userid,
@RequestParam(value = "cattle_photo", required = true) MultipartFile image,
@RequestParam (required = false) String latitude,
@RequestParam (required = false) String longitude,
@RequestParam (required = false) String zone,
@RequestParam (required = false) String ward,
@RequestParam (required = false) String location
){
return cattleService.savecattledetails(owner_ref_id,cattle_type,breed_type,animal_name,animal_age,animal_gender,
microchip_flag,microchip_no,license_flag,licenese_no,vaccination_flag,vaccination_type,vaccination_date,userid,image,latitude,
longitude,zone,ward,location,cattle_maintained,cattle_space_gcc_shed,insurance_flag,insurance_no,ipimage);
}
}

648
src/main/java/in/gov/chennaicorporation/mobileservice/gccCattleSurvey/service/CattleService.java

@ -0,0 +1,648 @@
package in.gov.chennaicorporation.mobileservice.gccCattleSurvey.service;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
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.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 in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class CattleService {
private JdbcTemplate jdbcTemplate;
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("mysqlCattleSurveyGccDataSource") DataSource CattleSurveyGccSource) {
this.jdbcTemplate = new JdbcTemplate(CattleSurveyGccSource);
}
@Autowired
public CattleService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, 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("gcc_cattlesurvey_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
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 + "_" + datetimetxt + "_" + file.getOriginalFilename();
fileName = fileName.replaceAll("\\s+", "");
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 List<Map<String, Object>> getbreeds() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM breed_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> breed_details=jdbcTemplate.queryForList(sql);
response.put("data",breed_details);
response.put("message", "Breed Types");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Breeds");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> cattle_type() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM cattle_type_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> cattle_details=jdbcTemplate.queryForList(sql);
response.put("data",cattle_details);
response.put("message", "Cattles Types");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Cattles");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getgcc_shed() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM gcc_shed_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> gcc_shed_details=jdbcTemplate.queryForList(sql);
response.put("data",gcc_shed_details);
response.put("message", "GCC Sheds");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting GCC Sheds");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getidproof() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM idproof_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> idproof_details=jdbcTemplate.queryForList(sql);
response.put("data",idproof_details);
response.put("message", "ID Proof Types");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting ID Proofs");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getspace_rearing() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM space_rearing_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> space_rearing_details=jdbcTemplate.queryForList(sql);
response.put("data",space_rearing_details);
response.put("message", "Space Rearing Types");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Space Rearing");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getvaccination_type() {
Map<String, Object> response = new HashMap<>();
try {
String sql="SELECT * FROM vaccination_type_master WHERE isactive=1 AND isdelete=0";
List<Map<String, Object>> vaccination_type_details=jdbcTemplate.queryForList(sql);
response.put("data",vaccination_type_details);
response.put("message", "Vaccination Types");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Vaccination Types");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
// public List<Map<String, Object>> getcattle_housed() {
//
// Map<String, Object> response = new HashMap<>();
//
// try {
//
// String sql="SELECT * FROM cattle_housed_master WHERE isactive=1 AND isdelete=0";
//
// List<Map<String, Object>> cattle_housed_details=jdbcTemplate.queryForList(sql);
//
// response.put("data",cattle_housed_details);
//
// response.put("message", "Cattle Housed Types");
// response.put("status", "Success");
//
// } catch (Exception e) {
// response.put("message", "Error in getting Cattle Housed Types");
// response.put("status", "Failed");
// e.printStackTrace();
// }
//
// return Collections.singletonList(response);
// }
public List<Map<String, Object>> saveownerdetails(String owner_name, String mobile_no, String address, int id_proof,
String id_details, String house_type, int cattle_space, Double cattle_space_area, int no_of_cattles,
String userid, MultipartFile image, String latitude, String longitude, String zone, String ward,
String location,Integer cattle_space_gcc_shed) {
Map<String, Object> response = new HashMap<>();
try {
String checkSql = "SELECT COUNT(*) FROM owner_details WHERE mobile_no = ? AND isactive=1 AND isdelete=0";
Integer count = jdbcTemplate.queryForObject(
checkSql,
Integer.class,
mobile_no
);
if (count != null && count > 0) {
response.put("status", "Failed");
response.put("message", "Mobile number already exists");
return Collections.singletonList(response);
}
String imagePath = "";
if (image == null || image.isEmpty()) {
response.put("status", "Failed");
response.put("message", "image is required");
return Collections.singletonList(response);
}
// image upload
if (image != null && !image.isEmpty()) {
imagePath = fileUpload("owner", image);
}
final String finalImagePath = imagePath;
String ownerSql="INSERT INTO owner_details (owner_name,mobile_no,address,id_proof,id_details,house_type,cattle_space,cattle_space_area,no_of_cattles,cby,latitude,longitude,zone,ward,location,owner_photo,cattle_space_gcc_shed)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(ownerSql, new String[] { "id" });
ps.setString(1,owner_name);
ps.setString(2,mobile_no);
ps.setString(3,address);
ps.setInt(4,id_proof);
ps.setString(5,id_details);
ps.setString(6,house_type);
ps.setInt(7,cattle_space);
if (cattle_space_area != null) ps.setDouble(8,cattle_space_area);
else ps.setNull(8, java.sql.Types.DOUBLE);
ps.setInt(9,no_of_cattles);
ps.setString(10,userid);
ps.setString(11, latitude);
ps.setString(12, longitude);
ps.setString(13, zone);
ps.setString(14, ward);
ps.setString(15, location);
ps.setString(16,finalImagePath);
if (cattle_space_gcc_shed != null) ps.setInt(17, cattle_space_gcc_shed);
else ps.setNull(17, java.sql.Types.INTEGER);
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 owner_details SET owner_ref_id = ? WHERE id = ? ";
jdbcTemplate.update(updateSql,refId, generatedId);
response.put("status", "Success");
response.put("message", "Owner Details Saved Successfully");
response.put("Ref_ID", refId);
}
} catch (Exception e) {
e.printStackTrace();
response.put("status", "Failed");
response.put("message", e.getMessage());
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getownersbycby(String userid) {
Map<String, Object> response = new HashMap<>();
try {
String sql =
"SELECT od.*, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files',od.owner_photo) AS img_full_path, " +
" COALESCE(cd.cattle_count,0) AS completed_count, " +
" GREATEST(0,(od.no_of_cattles - COALESCE(cd.cattle_count,0))) AS pending_count " +
" FROM owner_details od " +
" LEFT JOIN ( " +
" SELECT owner_ref_id, COUNT(*) AS cattle_count " +
" FROM cattle_details " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY owner_ref_id " +
" ) cd ON od.owner_ref_id = cd.owner_ref_id " +
" WHERE od.isactive=1 " +
" AND od.isdelete=0 " +
" AND od.is_completed=0 " +
" AND od.cby=?";
List<Map<String, Object>> owner_details=jdbcTemplate.queryForList(sql,userid);
response.put("data",owner_details);
response.put("message", "Cattle Owners Details");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Cattle Owners Details");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> getownerdetails(String owner_ref_id) {
Map<String, Object> response = new HashMap<>();
try {
String sql =
"SELECT od.*,CONCAT('" + fileBaseUrl + "/gccofficialapp/files',owner_photo) AS img_full_path, " +
"COALESCE(cd.cattle_count,0) AS completed_count, " +
"(od.no_of_cattles - COALESCE(cd.cattle_count,0)) AS pending_count " +
"FROM owner_details od " +
"LEFT JOIN ( " +
" SELECT owner_ref_id, COUNT(*) AS cattle_count " +
" FROM cattle_details " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY owner_ref_id " +
") cd ON od.owner_ref_id = cd.owner_ref_id " +
"WHERE od.isactive=1 AND od.isdelete=0 AND od.owner_ref_id=?";
List<Map<String, Object>> owner_details=jdbcTemplate.queryForList(sql,owner_ref_id);
response.put("data",owner_details);
response.put("message", "Owner Details");
response.put("status", "Success");
} catch (Exception e) {
response.put("message", "Error in getting Owner Details");
response.put("status", "Failed");
e.printStackTrace();
}
return Collections.singletonList(response);
}
public List<Map<String, Object>> savecattledetails(String owner_ref_id, int cattle_type, int breed_type,
String animal_name, Integer animal_age, String animal_gender, String microchip_flag, String microchip_no,
String license_flag, String licenese_no, String vaccination_flag, Integer vaccination_type,
String vaccination_date, String userid, MultipartFile image, String latitude, String longitude, String zone,
String ward, String location,String cattle_maintained,Integer cattle_space_gcc_shed,String insurance_flag,String insurance_no,MultipartFile ipimage) {
Map<String, Object> response = new HashMap<>();
try {
String imagePath = "";
String ipimagePath = "";
if (image == null || image.isEmpty()) {
response.put("status", "Failed");
response.put("message", "cattle image is required");
return Collections.singletonList(response);
}
// image upload
if (image != null && !image.isEmpty()) {
imagePath = fileUpload("cattle", image);
}
if (ipimage != null && !ipimage.isEmpty()) {
ipimagePath = fileUpload("cattle_insurance_photo", ipimage);
}
final String finalImagePath = imagePath;
final String finalipimagePath=ipimagePath;
final String vDate =
(vaccination_date != null && !vaccination_date.isEmpty())
? convertDateFormat(vaccination_date, 0)
: null;
String ownerSql="INSERT INTO cattle_details (owner_ref_id,cattle_type,breed_type,animal_name,animal_age,animal_gender,"
+ " microchip_flag,microchip_no,license_flag,licenese_no,vaccination_flag,vaccination_type,vaccination_date,cattle_photo,latitude,longitude,zone,"
+ " ward,location,cby,cattle_maintained,cattle_space_gcc_shed,insurance_flag,insurance_no,insurance_photo)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
int result = jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(ownerSql, new String[] { "id" });
ps.setString(1,owner_ref_id);
ps.setInt(2,cattle_type);
ps.setInt(3,breed_type);
ps.setString(4,animal_name);
if (animal_age != null) ps.setInt(5, animal_age);
else ps.setNull(5, java.sql.Types.INTEGER);
ps.setString(6,animal_gender);
ps.setString(7,microchip_flag);
ps.setString(8,microchip_no);
ps.setString(9,license_flag);
ps.setString(10,licenese_no);
ps.setString(11,vaccination_flag);
if (vaccination_type != null) ps.setInt(12, vaccination_type);
else ps.setNull(12, java.sql.Types.INTEGER);
if (vDate != null)
ps.setString(13, vDate);
else
ps.setNull(13, java.sql.Types.VARCHAR);
ps.setString(14,finalImagePath);
ps.setString(15, latitude);
ps.setString(16, longitude);
ps.setString(17, zone);
ps.setString(18, ward);
ps.setString(19, location);
ps.setString(20,userid);
ps.setString(21,cattle_maintained);
if (cattle_space_gcc_shed != null) ps.setInt(22, cattle_space_gcc_shed);
else ps.setNull(22, java.sql.Types.INTEGER);
ps.setString(23,insurance_flag);
ps.setString(24,insurance_no);
ps.setString(25,finalipimagePath);
return ps;
}, keyHolder);
if (result > 0) {
String updateSql =
"UPDATE owner_details od " +
"SET od.is_completed = 1 " +
"WHERE od.owner_ref_id = ? " +
"AND od.isactive = 1 " +
"AND od.isdelete = 0 " +
"AND od.no_of_cattles = ( " +
" SELECT COUNT(*) " +
" FROM cattle_details cd " +
" WHERE cd.owner_ref_id = od.owner_ref_id " +
" AND cd.isactive = 1 " +
" AND cd.isdelete = 0 " +
")";
jdbcTemplate.update(updateSql, owner_ref_id);
response.put("status", "Success");
response.put("message", "Cattle Details Saved for REF ID: "+owner_ref_id+" Owner Successfully");
}
} catch (Exception e) {
e.printStackTrace();
response.put("status", "Failed");
response.put("message", e.getMessage());
}
return Collections.singletonList(response);
}
}

98
src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/controller/ChildSurveyApiController.java

@ -0,0 +1,98 @@
package in.gov.chennaicorporation.mobileservice.gccChildrenSurvey.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.mobileservice.gccChildrenSurvey.service.ChildSurveyService;
@RequestMapping("/gccofficialapp/api/childsurvey")
@RestController("gccofficialappchildsurvey")
public class ChildSurveyApiController {
@Autowired
private ChildSurveyService childSurveyService;
@GetMapping("/questions")
public ResponseEntity<?> getQuestions() {
List<Map<String, Object>> data = childSurveyService.getSurveyQuestions();
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
@GetMapping("/questions_1")
public ResponseEntity<?> getQuestions1() {
List<Map<String, Object>> data = childSurveyService.getParticipateSurveyQuestions();
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
// @PostMapping("/save")
// public ResponseEntity<?> saveSurvey(@RequestBody Map<String, Object> request)
// {
// List<Map<String, Object>> responses = (List<Map<String, Object>>)
// request.get("responses");
// String result = childSurveyService.saveSurvey(responses);
// Map<String, Object> response = new HashMap<>();
// response.put("status", true);
// response.put("message", result);
// return ResponseEntity.ok(response);
// }
@PostMapping(value = "/save", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> saveSurvey(@RequestParam Map<String, String> params) {
String result = childSurveyService.saveSurveyFromParams(params);
return ResponseEntity.ok(Map.of(
"status", true,
"message", result));
}
@PostMapping(value = "/save_1", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> saveParticipateSurvey(@RequestParam Map<String, String> params) {
String result = childSurveyService.saveParticipateSurveyFromParams(params);
return ResponseEntity.ok(Map.of(
"status", true,
"message", result));
}
@GetMapping("/login")
public ResponseEntity<?> getLogin(@RequestParam String mobileNo, String password) {
Map<String, Object> response = childSurveyService.getLoginDetails(mobileNo, password);
return ResponseEntity.ok(response);
}
}

579
src/main/java/in/gov/chennaicorporation/mobileservice/gccChildrenSurvey/service/ChildSurveyService.java

@ -0,0 +1,579 @@
package in.gov.chennaicorporation.mobileservice.gccChildrenSurvey.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.Service;
@Service
public class ChildSurveyService {
@Autowired
JdbcTemplate jdbcChildSurveyTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlChildSurveyDataSource") DataSource childSurveyDataSource) {
this.jdbcChildSurveyTemplate = new JdbcTemplate(childSurveyDataSource);
}
public List<Map<String, Object>> getSurveyQuestions() {
// Step 1: Get all child_qids
String childSql = "SELECT DISTINCT child_qid FROM child_question_mapping " +
"WHERE isactive=1 AND isdelete=0";
List<Integer> childQids = jdbcChildSurveyTemplate.queryForList(childSql, Integer.class);
// Step 2: Get only parent questions
String questionSql = "SELECT * FROM child_survey_questions_master " +
"WHERE isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> questions = jdbcChildSurveyTemplate.queryForList(questionSql);
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> q : questions) {
Integer qid = (Integer) q.get("qid");
// Skip if this is a child question
if (childQids.contains(qid)) {
continue;
}
Map<String, Object> fullQuestion = buildQuestionWithOptions(q);
finalList.add(fullQuestion);
}
return finalList;
}
public List<Map<String, Object>> getParticipateSurveyQuestions() {
String questionSql = "SELECT * FROM child_survey_participate_master " +
"WHERE isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> questions = jdbcChildSurveyTemplate.queryForList(questionSql);
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> q : questions) {
Map<String, Object> fullQuestion = buildParticipateQuestionWithOptions(q);
finalList.add(fullQuestion);
}
return finalList;
}
private Map<String, Object> buildParticipateQuestionWithOptions(Map<String, Object> q) {
Integer qid = (Integer) q.get("qid");
String masterTable = (String) safe(q.get("master_table_name"));
// Maintain order
Map<String, Object> questionMap = new LinkedHashMap<>();
questionMap.put("qid", q.get("qid"));
questionMap.put("q_english", q.get("q_english"));
questionMap.put("q_tamil", safe(q.get("q_tamil")));
questionMap.put("field_name", q.get("field_name"));
questionMap.put("cdate", q.get("cdate"));
questionMap.put("question_type", q.get("question_type"));
questionMap.put("isactive", q.get("isactive"));
questionMap.put("isdelete", q.get("isdelete"));
questionMap.put("orderby", q.get("orderby"));
questionMap.put("is_mandatory", q.get("is_mandatory"));
questionMap.put("is_dropdown", q.get("is_dropdown"));
questionMap.put("flag", q.get("flag"));
questionMap.put("master_table_name", masterTable);
List<Map<String, Object>> options = new ArrayList<>();
if (masterTable != null && !masterTable.isEmpty()) {
options = getOptionsFromMaster(masterTable, qid);
}
questionMap.put("options", options);
return questionMap;
}
private Object safe(Object value) {
return value == null ? "" : value;
}
private Map<String, Object> buildQuestionWithOptions(Map<String, Object> q) {
Integer qid = (Integer) q.get("qid");
String masterTable = (String) safe(q.get("master_table_name"));
// Maintain order
Map<String, Object> questionMap = new LinkedHashMap<>();
questionMap.put("qid", q.get("qid"));
questionMap.put("q_english", q.get("q_english"));
questionMap.put("q_tamil", safe(q.get("q_tamil")));
questionMap.put("field_name", q.get("field_name"));
questionMap.put("cdate", q.get("cdate"));
questionMap.put("question_type", q.get("question_type"));
questionMap.put("isactive", q.get("isactive"));
questionMap.put("isdelete", q.get("isdelete"));
questionMap.put("orderby", q.get("orderby"));
questionMap.put("is_mandatory", q.get("is_mandatory"));
questionMap.put("is_dropdown", q.get("is_dropdown"));
questionMap.put("master_table_name", masterTable);
// String fieldName = (String) q.get("field_name");
// // default
// boolean isDropdown = false;
// // only for these 2 fields
// if ("duration".equalsIgnoreCase(fieldName) ||
// "dropout_year".equalsIgnoreCase(fieldName)) {
// isDropdown = true;
// }
// questionMap.put("is_dropdown", isDropdown);
List<Map<String, Object>> options = new ArrayList<>();
if (masterTable != null && !masterTable.isEmpty()) {
options = getOptionsFromMaster(masterTable, qid);
} else {
String optSql = "SELECT aid AS option_id, english_name, tamil_name, " +
"orderby, is_mandatory " +
"FROM child_survey_answer_master " +
"WHERE qid=? AND isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> dbOptions = jdbcChildSurveyTemplate.queryForList(optSql, qid);
for (Map<String, Object> opt : dbOptions) {
Map<String, Object> optionMap = new LinkedHashMap<>();
String englishName = (String) opt.get("english_name");
optionMap.put("option_id", opt.get("option_id"));
optionMap.put("english_name", opt.get("english_name"));
optionMap.put("tamil_name", safe(opt.get("tamil_name")));
optionMap.put("orderby", opt.get("orderby"));
// optionMap.put("imgfield", opt.get("img_required"));
// optionMap.put("textfield", opt.get("text_required"));
// optionMap.put("textname", opt.get("text_name"));
// optionMap.put("remarksfield", opt.get("remarks_required"));
optionMap.put("opt_mandatory", opt.get("is_mandatory"));
// NEW FIELD
boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others");
optionMap.put("is_others", isOthers);
// tell frontend to show textbox
optionMap.put("text", isOthers);
Integer aid = (Integer) opt.get("option_id");
// child questions
List<Map<String, Object>> childQuestions = getChildQuestionsRecursive(aid);
optionMap.put("child_questions", childQuestions);
options.add(optionMap);
}
}
questionMap.put("options", options);
return questionMap;
}
private List<Map<String, Object>> getChildQuestionsRecursive(Integer parentAid) {
String mappingSql = "SELECT child_qid FROM child_question_mapping " +
"WHERE parent_aid=? AND isactive=1 AND isdelete=0";
List<Integer> childQids = jdbcChildSurveyTemplate.queryForList(mappingSql, Integer.class, parentAid);
List<Map<String, Object>> childQuestions = new ArrayList<>();
for (Integer cqid : childQids) {
String qSql = "SELECT * FROM child_survey_questions_master " +
"WHERE qid=? AND isactive=1 AND isdelete=0";
Map<String, Object> childQ = jdbcChildSurveyTemplate.queryForMap(qSql, cqid);
// IMPORTANT: reuse same method (recursive)
Map<String, Object> fullChild = buildQuestionWithOptions(childQ);
childQuestions.add(fullChild);
}
return childQuestions;
}
// private List<Map<String, Object>> getOptionsFromMaster(String tableName) {
// String sql = "SELECT id AS option_id, " +
// "english_name, " +
// "IFNULL(tamil_name, '') AS tamil_name, " +
// "orderby, " +
// "is_mandatory " +
// "FROM " + tableName + " " +
// "WHERE isactive=1 AND isdelete=0 " +
// "ORDER BY orderby";
// return jdbcChildSurveyTemplate.queryForList(sql);
// }
private List<Map<String, Object>> getOptionsFromMaster(String tableName, Integer parentQid) {
String sql = "SELECT id AS option_id, " +
"english_name, " +
"IFNULL(tamil_name, '') AS tamil_name, " +
"orderby, " +
"is_mandatory " +
"FROM " + tableName + " " +
"WHERE isactive=1 AND isdelete=0 " +
"ORDER BY orderby";
List<Map<String, Object>> dbOptions = jdbcChildSurveyTemplate.queryForList(sql);
List<Map<String, Object>> options = new ArrayList<>();
for (Map<String, Object> opt : dbOptions) {
Map<String, Object> optionMap = new LinkedHashMap<>();
String englishName = (String) opt.get("english_name");
optionMap.put("option_id", opt.get("option_id"));
optionMap.put("english_name", englishName);
optionMap.put("tamil_name", opt.get("tamil_name"));
optionMap.put("orderby", opt.get("orderby"));
optionMap.put("is_mandatory", opt.get("is_mandatory"));
List<Map<String, Object>> childQuestions = new ArrayList<>();
boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others");
optionMap.put("is_others", isOthers);
optionMap.put("text", isOthers);
// 🔥 HANDLE "OTHERS"
if (isOthers) {
Map<String, Object> child = new LinkedHashMap<>();
child.put("qid", parentQid); // same parent qid
child.put("q_english", "Please specify");
child.put("q_tamil", "");
child.put("question_type", "text");
child.put("field_name", "q" + parentQid + "_other");
child.put("is_mandatory", false);
child.put("is_dropdown", false);
childQuestions.add(child);
}
optionMap.put("child_questions", childQuestions);
options.add(optionMap);
}
return options;
}
public String saveSurveyFromParams(Map<String, String> params) {
String cby = params.getOrDefault("cby", "1");
String timeStr = java.time.LocalDateTime.now()
.format(java.time.format.DateTimeFormatter.ofPattern("ddMMyyHHmmss"));
String surveyId = "GCC_CS_" + timeStr;
// Save surveyor location details first
String zone = params.get("zone");
String ward = params.get("ward");
String lat = params.get("latitude");
if (lat == null)
lat = params.get("lat");
String lng = params.get("longitude");
if (lng == null)
lng = params.get("long");
String address = params.get("address");
if (zone != null || lat != null || lng != null) {
try {
// 1. Insert without survey_id using KeyHolder
String logindetailsSql = "INSERT INTO surveyor_location_details " +
"(loginId, zone, ward, latitude, longitude, address, is_active, is_delete, cdate) " +
"VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())";
org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder();
final String finalLat = lat;
final String finalLng = lng;
jdbcChildSurveyTemplate.update(
connection -> {
java.sql.PreparedStatement ps = connection.prepareStatement(logindetailsSql,
java.sql.Statement.RETURN_GENERATED_KEYS);
ps.setString(1, cby);
ps.setString(2, zone);
ps.setString(3, ward);
ps.setString(4, finalLat);
ps.setString(5, finalLng);
ps.setString(6, address);
return ps;
},
keyHolder);
// 2. Fetch the generated location id
Number key = keyHolder.getKey();
if (key != null) {
Integer locationId = key.intValue();
// 3. Append to surveyId
surveyId = surveyId + locationId;
// 4. Update the location record with the final surveyId
String updateSql = "UPDATE surveyor_location_details SET survey_id = ? WHERE id = ?";
jdbcChildSurveyTemplate.update(updateSql, surveyId, locationId);
}
} catch (Exception e) {
// System.out.println("❌ Error saving surveyor location details: " +
// e.getMessage());
}
}
String insertSql = "INSERT INTO child_survey_response " +
"(survey_id, qid, answer, others_answer, cby, parent_answer_id, cdate, isactive, isdelete) " +
"VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0)";
for (Map.Entry<String, String> entry : params.entrySet()) {
String fieldName = entry.getKey().trim(); // q1, q2...
String answer = entry.getValue() == null ? "" : entry.getValue().trim();
// System.out.println("👉 Processing: " + fieldName);
// =====================================================
// 🔥 HANDLE DURATION (q3 assumed)
// =====================================================
if ("duration_value".equalsIgnoreCase(fieldName)) {
String value = answer;
String typeId = params.get("duration_type");
String typeName = "";
if (typeId != null) {
List<String> list = jdbcChildSurveyTemplate.queryForList(
"SELECT english_name FROM duration_master WHERE id=?",
String.class, typeId);
if (!list.isEmpty()) {
typeName = list.get(0);
}
}
String finalAnswer = value + " " + typeName;
// 👉 q3 = duration
jdbcChildSurveyTemplate.update(insertSql, surveyId, 3, finalAnswer, "", cby, null);
continue;
}
if ("duration_type".equalsIgnoreCase(fieldName)) {
continue;
}
// =====================================================
// 🔥 HANDLE DROPOUT YEAR (q30 assumed)
// =====================================================
if ("dropout_year_value".equalsIgnoreCase(fieldName)) {
String value = answer;
String typeId = params.get("dropout_year_type");
String typeName = "";
if (typeId != null) {
List<String> list = jdbcChildSurveyTemplate.queryForList(
"SELECT english_name FROM duration_master WHERE id=?",
String.class, typeId);
if (!list.isEmpty()) {
typeName = list.get(0);
}
}
String finalAnswer = value + " " + typeName;
// 👉 q30 = dropout_year
jdbcChildSurveyTemplate.update(insertSql, surveyId, 30, finalAnswer, "", cby, null);
continue;
}
if ("dropout_year_type".equalsIgnoreCase(fieldName)) {
continue;
}
// =====================================================
// 🔥 NORMAL Q1, Q2, Q3...
// =====================================================
if (fieldName.startsWith("q")) {
try {
Integer qid = Integer.parseInt(fieldName.substring(1));
String othersKey = fieldName + "_other";
String othersValue = params.getOrDefault(othersKey, "");
// System.out.println("✔ QID: " + qid);
jdbcChildSurveyTemplate.update(insertSql, surveyId, qid, answer, othersValue, cby, null);
} catch (Exception e) {
System.out.println("❌ Invalid field: " + fieldName);
}
}
}
return "Saved Successfully";
}
public String saveParticipateSurveyFromParams(Map<String, String> params) {
String cby = params.getOrDefault("cby", "1");
String timeStr = java.time.LocalDateTime.now()
.format(java.time.format.DateTimeFormatter.ofPattern("ddMMyyHHmmss"));
String surveyId = "GCC_CSP_" + timeStr;
// Save surveyor location details first
String zone = params.get("zone");
String ward = params.get("ward");
String lat = params.get("latitude");
if (lat == null)
lat = params.get("lat");
String lng = params.get("longitude");
if (lng == null)
lng = params.get("long");
String address = params.get("address");
if (zone != null || lat != null || lng != null) {
try {
// 1. Insert without survey_id using KeyHolder
String logindetailsSql = "INSERT INTO surveyor_location_details " +
"(loginId, zone, ward, latitude, longitude, address, is_active, is_delete, cdate) " +
"VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())";
org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder();
final String finalLat = lat;
final String finalLng = lng;
jdbcChildSurveyTemplate.update(
connection -> {
java.sql.PreparedStatement ps = connection.prepareStatement(logindetailsSql,
java.sql.Statement.RETURN_GENERATED_KEYS);
ps.setString(1, cby);
ps.setString(2, zone);
ps.setString(3, ward);
ps.setString(4, finalLat);
ps.setString(5, finalLng);
ps.setString(6, address);
return ps;
},
keyHolder);
// 2. Fetch the generated location id
Number key = keyHolder.getKey();
if (key != null) {
Integer locationId = key.intValue();
// 3. Append to surveyId
surveyId = surveyId + locationId;
// 4. Update the location record with the final surveyId
String updateSql = "UPDATE surveyor_location_details SET survey_id = ? WHERE id = ?";
jdbcChildSurveyTemplate.update(updateSql, surveyId, locationId);
}
} catch (Exception e) {
}
}
String insertSql = "INSERT INTO child_survey_participate_response " +
"(survey_id, qid, answer, others_answer, cby, parent_answer_id, cdate, isactive, isdelete) " +
"VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, 0)";
for (Map.Entry<String, String> entry : params.entrySet()) {
String fieldName = entry.getKey().trim(); // q1, q2...
String answer = entry.getValue() == null ? "" : entry.getValue().trim();
if (fieldName.startsWith("q")) {
try {
Integer qid = Integer.parseInt(fieldName.substring(1));
String othersKey = fieldName + "_other";
String othersValue = params.getOrDefault(othersKey, "");
jdbcChildSurveyTemplate.update(insertSql, surveyId, qid, answer, othersValue, cby, null);
} catch (Exception e) {
System.out.println("❌ Invalid field: " + fieldName);
}
}
}
return "Saved Successfully";
}
public Map<String, Object> getLoginDetails(String mobileNo, String password) {
try {
String sql = "SELECT uid as loginId,user_name, password, mobile_no, is_active, is_delete " +
"FROM login_details " +
"WHERE mobile_no = ? AND password = ? AND is_active = 1 AND is_delete = 0 Limit 1";
List<Map<String, Object>> data = jdbcChildSurveyTemplate.queryForList(sql, mobileNo, password);
Map<String, Object> response = new HashMap<>();
if (!data.isEmpty()) {
// Login success
response.put("is_login", true);
response.put("message", "Login Success");
response.put("data", data);
} else {
// Login failed
response.put("is_login", false);
response.put("message", "Invalid mobile number or password");
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error fetching batch details: " + e.getMessage());
}
}
}

BIN
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/.DS_Store

BIN
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Controller/.DS_Store

172
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Controller/DomesticWasteController.java

@ -0,0 +1,172 @@
package in.gov.chennaicorporation.mobileservice.gccDomesticWaste.Controller;
import in.gov.chennaicorporation.mobileservice.gccDomesticWaste.Service.DomesticWasteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/gccofficialapp/api/domesticwaste")
public class DomesticWasteController {
@Autowired
DomesticWasteService domesticWasteService;
@PostMapping("/save-request")
public ResponseEntity<?> saveRequest(
@RequestParam String user_name,
@RequestParam String mobile,
@RequestParam String address,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String zone,
@RequestParam String division,
@RequestParam String street_name,
@RequestParam(value="street_id", required = false) String street_id,
@RequestParam String remarks,
@RequestParam(value="sofa_type", required = false) String sofa_type,
@RequestParam("items") String itemsJson,
@RequestParam (name = "image") MultipartFile imageFile,
@RequestParam(value="is_app", required = false) String is_app) {
try {
Map<String, Object> result = domesticWasteService.saveMultipleWasteRequests(
user_name, mobile, address,
latitude, longitude, zone, division,
street_name, street_id, remarks,
imageFile, itemsJson, sofa_type, is_app
);
return ResponseEntity.ok(result);
} catch (Exception e) {
return ResponseEntity.status(500).body(Map.of("status", false, "message", e.getMessage()));
}
}
@GetMapping("/get-all-requests")
public ResponseEntity<List<Map<String, Object>>> getAllWasteRequests() {
List<Map<String, Object>> results = domesticWasteService.getAllWasteRequests();
return ResponseEntity.ok(results);
}
@GetMapping("/get-all-requests-by-login")
public ResponseEntity<List<Map<String, Object>>> getAllWasteRequests(@RequestParam String loginId) {
List<Map<String, Object>> results = domesticWasteService.getAllWasteRequestsbylogin(loginId);
return ResponseEntity.ok(results);
}
@GetMapping("/get-all-masters")
public ResponseEntity<List<Map<String, Object>>> getAllmasters() {
List<Map<String, Object>> results = domesticWasteService.getAllmasters();
return ResponseEntity.ok(results);
}
@GetMapping("/get-user-bymobile")
public ResponseEntity<List<Map<String, Object>>> getuserbymobile(@RequestParam String mobile) {
List<Map<String,Object>> results =domesticWasteService.getuserbymobile(mobile);
return ResponseEntity.ok(results);
}
@GetMapping("/get-user-AE2")
public ResponseEntity<List<Map<String, Object>>> getUserAE2(@RequestParam String loginId) {
List<Map<String, Object>> results = domesticWasteService.getuserAE2(loginId);
return ResponseEntity.ok(results);
}
// Zonal Requests based on loginId
@GetMapping("/get-user-zonal")
public ResponseEntity<List<Map<String, Object>>> getUserZonal(@RequestParam String loginId) {
List<Map<String, Object>> results = domesticWasteService.getuserZonal(loginId);
return ResponseEntity.ok(results);
}
@GetMapping("/userdetailsfilter")
public ResponseEntity<List<Map<String, Object>>> userdetailsfilter(@RequestParam int id) {
List<Map<String,Object>> results =domesticWasteService.userdetailsfilter(id);
return ResponseEntity.ok(results);
}
@PostMapping("/action-taken")
public ResponseEntity<?> saveActionTaken(
@RequestParam String reqid,
@RequestParam(value = "image") MultipartFile image,
@RequestParam("created_by") int createdBy,
@RequestParam String latitude,
@RequestParam String longitude
) {
Map<String, Object> result = domesticWasteService.actionTaken(reqid, image, createdBy,latitude,longitude);
if ((boolean) result.get("status")) {
return ResponseEntity.ok(result);
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
@PostMapping("/reject-user-req")
public ResponseEntity<?> rejectuserreq(@RequestParam String requestId) {
Map<String, Object> result = domesticWasteService.rejectuserreq(requestId);
return ResponseEntity.ok(result);
}
@GetMapping("/verify-latlong")
public ResponseEntity<Map<String, Object>> verifyLatLong(
@RequestParam String requestId,
@RequestParam String latitude,
@RequestParam String longitude) {
boolean result = domesticWasteService.verifylatlong(requestId, latitude, longitude);
Map<String, Object> response = Map.of(
"status", true,
"message", String.valueOf(result)
);
return ResponseEntity.ok(response);
}
@PostMapping("/reject-request-officer")
public ResponseEntity<Map<String, Object>> rejectUserRequestByOfficer(
@RequestParam String requestId,
@RequestParam String officer_remark,
@RequestParam String rejecttype,
@RequestParam int cancelled_by,
@RequestParam String latitude,
@RequestParam String longitude) {
Map<String, Object> result = domesticWasteService.rejectuserreqofficer(requestId, officer_remark, rejecttype, cancelled_by,latitude,longitude);
return ResponseEntity.ok(result);
}
@GetMapping(value="/getZoneReport")
public List<?> getZoneReport(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate
){
return domesticWasteService.getZoneReport(fromDate, toDate);
}
@GetMapping(value="/getWardReport")
public List<?> getWardReport(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate,
@RequestParam(value="zone", required = true) String zone
){
return domesticWasteService.getWardReport(fromDate, toDate, zone);
}
@GetMapping(value="/getWardStatusDetails")
public List<?> getWardStatusDetails(
@RequestParam(value="fromDate", required = true) String fromDate,
@RequestParam(value="toDate", required = true) String toDate,
@RequestParam(value="ward", required = true) String ward,
@RequestParam(value="status", required = true) String status
){
return domesticWasteService.getWardStatusDetails(fromDate, toDate, ward, status);
}
}

28
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Scheduler/DomesticWasteScheduler.java

@ -0,0 +1,28 @@
package in.gov.chennaicorporation.mobileservice.gccDomesticWaste.Scheduler;
import in.gov.chennaicorporation.mobileservice.gccDomesticWaste.Service.DomesticWasteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@EnableScheduling
public class DomesticWasteScheduler {
@Autowired
private DomesticWasteService domesticWasteService;
@Scheduled(cron = "0 0 1 * * WED", zone = "Asia/Kolkata")
//@Scheduled(fixedRate = 3000)
public void domesticWasteScheduler() {
System.out.println("DomesticWasteScheduler Started......");
Map<String,Object> result= domesticWasteService.updateOrderStatus("3");
System.out.println("Scheduler Result: " + result);
}
}

BIN
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Service/.DS_Store

797
src/main/java/in/gov/chennaicorporation/mobileservice/gccDomesticWaste/Service/DomesticWasteService.java

@ -0,0 +1,797 @@
package in.gov.chennaicorporation.mobileservice.gccDomesticWaste.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
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.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.sql.DataSource;
@Service
public class DomesticWasteService {
@Autowired
private JdbcTemplate jdbcDomesticWasteTemplate;
@Value("${file.upload.directory}")
private String baseUploadDir;
@Value("${domestic_waste_foldername}")
private String wasteFolder;
private String fileBaseUrl;
@Autowired
private Environment environment;
@Autowired
public void setDataSource(@Qualifier("mysqlGccDomesticWasteManagementDataSource") DataSource DomesticWasteManagementDataSource) {
this.jdbcDomesticWasteTemplate = new JdbcTemplate(DomesticWasteManagementDataSource);
}
public DomesticWasteService(Environment environment) {
this.environment = environment;
this.fileBaseUrl = environment.getProperty("fileBaseUrl");
}
public String fileUpload(MultipartFile file, String prefix) {
if (file == null || file.isEmpty()) {
return null;
}
try {
String year = String.valueOf(LocalDate.now().getYear());
String month = String.format("%02d", LocalDate.now().getMonthValue());
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyyyHHmmss"));
// Clean original file name
String originalFilename = file.getOriginalFilename().replaceAll("\\s+", "");
String fileName = prefix + "_" + timestamp + "_" + originalFilename;
// Create upload directory path
String uploadDirPath = baseUploadDir + wasteFolder + year + "/" + month;
File uploadDir = new File(uploadDirPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// Save file to server
File fullFilePath = new File(uploadDirPath + File.separator + fileName);
file.transferTo(fullFilePath);
// Return relative path to save in DB
return "/" + wasteFolder + year + "/" + month + "/" + fileName;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Map<String, Object> saveMultipleWasteRequests(String user_name, String mobile, String address,
String latitude, String longitude, String zone, String division,
String street_name, String street_id, String remarks,
MultipartFile imageFile, String itemsJson, String sofa_type, String is_app) {
final String is_app_value = (is_app == null || is_app.trim().isEmpty()) ? "1" : is_app;
String imagePath = fileUpload(imageFile, "domestic_waste_photo");
if (imagePath == null) {
return Map.of("status", false, "message", "Image upload failed");
}
try {
// Step 1: Insert main request (one time)
String insertMainSql = "INSERT INTO user_request_table " +
"(request_id, user_name, mobile, address, latitude, longitude, zone, division, street_name, street_id, remarks, image_url, sofa_type, is_app) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcDomesticWasteTemplate.update(con -> {
PreparedStatement ps = con.prepareStatement(insertMainSql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "TEMP"); // placeholder
ps.setString(2, user_name);
ps.setString(3, mobile);
ps.setString(4, address);
ps.setString(5, latitude);
ps.setString(6, longitude);
ps.setString(7, zone);
ps.setString(8, division);
ps.setString(9, street_name);
ps.setString(10, street_id);
ps.setString(11, remarks);
ps.setString(12, imagePath);
ps.setString(13, sofa_type);
ps.setString(14, is_app_value);
return ps;
}, keyHolder);
int generatedId = keyHolder.getKey().intValue();
String requestId = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + generatedId;
// Update request_id in user_request_table
jdbcDomesticWasteTemplate.update("UPDATE user_request_table SET request_id = ? WHERE id = ?", requestId, generatedId);
// Step 2: Insert items under the same request_id into the `items` table
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> items = objectMapper.readValue(itemsJson, new TypeReference<>() {});
String insertItemSql = "INSERT INTO items (iteam_id, quantity, req_table_id, requedt_id) VALUES (?, ?, ?, ?)";
for (Map<String, Object> item : items) {
Object itemIdObj = item.get("item_id");
Object quantityObj = item.get("quantity");
if (itemIdObj == null || quantityObj == null) {
continue;
}
int itemId = Integer.parseInt(itemIdObj.toString());
int quantity = Integer.parseInt(quantityObj.toString());
jdbcDomesticWasteTemplate.update(insertItemSql, itemId, quantity, generatedId, requestId);
}
return Map.of(
"status", true,
"message", "Request saved successfully",
"requestId", requestId
);
} catch (Exception e) {
e.printStackTrace();
return Map.of("status", false, "message", "Error: " + e.getMessage());
}
}
public List<Map<String, Object>> getAllWasteRequests() {
/*String sql = "SELECT " +
"u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.street_id, u.quantity, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"itm.quantity, i.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master i ON itm.iteam_id = i.id AND i.is_active = 1";
*/
String sql = "SELECT " +
"u.*, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_full_url, " +
"itm.quantity, i.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master i ON itm.iteam_id = i.id AND i.is_active = 1";
List<Map<String, Object>> rawData = jdbcDomesticWasteTemplate.queryForList(sql);
return groupRequestsWithItems(rawData);
}
public String getWardByLoginId(String loginid) {
String sqlQuery = "SELECT `ward` FROM gcc_penalty_hoardings.`hoading_user_list` WHERE `userid` = ? LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcDomesticWasteTemplate.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<Map<String, Object>> getAllWasteRequestsbylogin(String loginId) {
/*
String zoneSql = "SELECT zone, division FROM officer_master WHERE loginId = ? AND is_active = 1 AND is_delete = 0";
List<Map<String, Object>> zoneList = jdbcDomesticWasteTemplate.queryForList(zoneSql, loginId);
//if (zoneList.isEmpty()) return List.of();
if (zoneList.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", false);
response.put("message", "No data found");
return Collections.singletonList(response); // or just `response` depending on your return type
}
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
for (int i = 0; i < zoneList.size(); i++) {
Map<String, Object> row = zoneList.get(i);
zoneCondition.append("(u.zone = ? AND u.division = ?)");
if (i < zoneList.size() - 1) zoneCondition.append(" OR ");
params.add(row.get("zone"));
params.add(row.get("division"));
}
*/
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
zoneCondition.append("(u.division = ?)");
params.add(getWardByLoginId(loginId));
zoneCondition.append(") ORDER BY u.cdate DESC");
/*
String sql = "SELECT " +
"u.*, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_full_url, " +
"itm.quantity, i.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master i ON itm.iteam_id = i.id AND i.is_active = 1";
*/
String sql = "SELECT " +
"u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.quantity AS main_quantity, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " +
"u.is_active, u.is_delete, u.street_id, sm.status_master AS status, u.is_app, " +
"DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.status IN(1,3) " +
"AND u.is_active = 1 AND " + zoneCondition;
System.err.println(sql);
System.err.println(Arrays.toString(params.toArray()));
System.err.println(loginId);
List<Map<String, Object>> rawData = jdbcDomesticWasteTemplate.queryForList(sql, params.toArray());
return groupRequestsWithItems(rawData);
}
public List<Map<String, Object>> getAllmasters() {
String sql = "select id,item_name from item_master where is_active= 1";
return jdbcDomesticWasteTemplate.queryForList(sql);
}
public List<Map<String, Object>> getuserbymobile(String mobile) {
String sql = "SELECT " +
"u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.quantity AS main_quantity, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " +
"u.is_active, u.is_delete, u.street_id, sm.status_master AS status, u.is_app, " +
"DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.iteam_id, itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.mobile = ? AND u.is_active = 1";
List<Map<String, Object>> rawList = jdbcDomesticWasteTemplate.queryForList(sql, mobile);
Map<Integer, Map<String, Object>> groupedMap = new LinkedHashMap<>();
for (Map<String, Object> row : rawList) {
Integer id = (Integer) row.get("id");
Map<String, Object> item = null;
if (row.get("item_name") != null) {
item = new LinkedHashMap<>();
item.put("item_name", row.get("item_name"));
item.put("quantity", row.get("quantity"));
}
if (groupedMap.containsKey(id)) {
if (item != null) {
((List<Map<String, Object>>) groupedMap.get(id).get("items")).add(item);
}
} else {
Map<String, Object> newEntry = new LinkedHashMap<>();
newEntry.put("id", id);
newEntry.put("request_id", row.get("request_id"));
newEntry.put("user_name", row.get("user_name"));
newEntry.put("mobile", row.get("mobile"));
newEntry.put("address", row.get("address"));
newEntry.put("latitude", row.get("latitude"));
newEntry.put("longitude", row.get("longitude"));
newEntry.put("zone", row.get("zone"));
newEntry.put("division", row.get("division"));
newEntry.put("street_name", row.get("street_name"));
newEntry.put("main_quantity", row.get("main_quantity"));
newEntry.put("remarks", row.get("remarks"));
newEntry.put("image_url", row.get("image_url"));
newEntry.put("cdate", row.get("cdate"));
newEntry.put("is_active", row.get("is_active"));
newEntry.put("is_delete", row.get("is_delete"));
newEntry.put("street_id", row.get("street_id"));
newEntry.put("status", row.get("status")); // Now this is human-readable
newEntry.put("is_app", row.get("is_app"));
newEntry.put("close_date", row.get("close_date"));
newEntry.put("officer_upload_url", row.get("officer_upload_url"));
List<Map<String, Object>> items = new ArrayList<>();
if (item != null) {
items.add(item);
}
newEntry.put("items", items);
groupedMap.put(id, newEntry);
}
}
return new ArrayList<>(groupedMap.values());
}
public List<Map<String, Object>> getuserAE2(String loginId) {
/*
String zoneSql = "SELECT zone, division FROM officer_master WHERE loginId = ? AND is_active = 1 AND is_delete = 0";
List<Map<String, Object>> zoneList = jdbcDomesticWasteTemplate.queryForList(zoneSql, loginId);
//if (zoneList.isEmpty()) return List.of();
if (zoneList.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", false);
response.put("message", "No data found");
return Collections.singletonList(response); // or just `response` depending on your return type
}
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
for (int i = 0; i < zoneList.size(); i++) {
Map<String, Object> row = zoneList.get(i);
zoneCondition.append("(u.zone = ? AND u.division = ?)");
if (i < zoneList.size() - 1) zoneCondition.append(" OR ");
params.add(row.get("zone"));
params.add(row.get("division"));
}
zoneCondition.append(")");
*/
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
zoneCondition.append("(u.division = ?)");
params.add(getWardByLoginId(loginId));
zoneCondition.append(") ORDER BY u.cdate DESC");
String sql = "SELECT " +
"u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.quantity AS main_quantity, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " +
"u.is_active, u.is_delete, u.street_id, sm.status_master AS status, u.is_app, " +
"DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.status != '2' " +
"AND u.cdate <= ( CURDATE() - INTERVAL ((WEEKDAY(CURDATE()) + 5) % 7) DAY ) " +
"AND u.is_active = 1 AND " + zoneCondition;
List<Map<String, Object>> rawData = jdbcDomesticWasteTemplate.queryForList(sql, params.toArray());
return groupRequestsWithItems(rawData);
}
public List<Map<String, Object>> getuserZonal(String loginId) {
/*
String zoneSql = "SELECT zone, division FROM officer_master WHERE loginId = ? AND is_active = 1 AND is_delete = 0";
List<Map<String, Object>> zoneList = jdbcDomesticWasteTemplate.queryForList(zoneSql, loginId);
//if (zoneList.isEmpty()) return List.of();
if (zoneList.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", false);
response.put("message", "No data found");
return Collections.singletonList(response); // or just `response` depending on your return type
}
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
for (int i = 0; i < zoneList.size(); i++) {
Map<String, Object> row = zoneList.get(i);
zoneCondition.append("(u.zone = ? AND u.division = ?)");
if (i < zoneList.size() - 1) zoneCondition.append(" OR ");
params.add(row.get("zone"));
params.add(row.get("division"));
}
zoneCondition.append(")");
*/
List<Object> params = new ArrayList<>();
StringBuilder zoneCondition = new StringBuilder("(");
zoneCondition.append("(u.division = ?)");
params.add(getWardByLoginId(loginId));
zoneCondition.append(") ORDER BY u.cdate DESC");
String sql = "SELECT " +
"u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " +
"u.is_active, u.is_delete, u.street_id, sm.status_master AS status, u.is_app, " +
"DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.status != '2' " +
"AND u.cdate <= ( CURDATE() - INTERVAL ((WEEKDAY(CURDATE()) + 4) % 7) DAY ) " +
"AND u.is_active = 1 AND " + zoneCondition;
List<Map<String, Object>> rawData = jdbcDomesticWasteTemplate.queryForList(sql, params.toArray());
return groupRequestsWithItems(rawData);
}
public List<Map<String, Object>> userdetailsfilter(int id) {
String fileBaseUrl = environment.getProperty("fileBaseUrl");
// Step 1: Fetch zone, division, and street_id for the given request ID
String sql = "SELECT zone, division, street_id FROM user_request_table WHERE id = ?";
List<Map<String, Object>> result = jdbcDomesticWasteTemplate.queryForList(sql, id);
if (result.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", false);
response.put("message", "No data found");
return Collections.singletonList(response); // or just `response` depending on your return type
}
Map<String, Object> user = result.get(0);
String zone = (String) user.get("zone");
String division = (String) user.get("division");
Object streetIdObj = user.get("street_id");
// Step 2: Construct dynamic SQL query with/without street_id
String finalSql;
List<Object> params = new ArrayList<>();
params.add(zone);
params.add(division);
if (streetIdObj != null && !streetIdObj.toString().isBlank()) {
params.add(streetIdObj);
params.add(id);
finalSql = "SELECT u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, u.is_active, u.is_delete, u.street_id, " +
"sm.status_master AS status, u.is_app, DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.zone = ? AND u.division = ? AND u.street_id = ? AND u.id = ? AND u.is_active = 1";
} else {
params.add(id);
finalSql = "SELECT u.id, u.request_id, u.user_name, u.mobile, u.address, u.latitude, u.longitude, " +
"u.zone, u.division, u.street_name, u.remarks, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
"DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, u.is_active, u.is_delete, u.street_id, " +
"sm.status_master AS status, u.is_app, DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
"CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
"itm.quantity, im.item_name " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.zone = ? AND u.division = ? AND u.id = ? AND u.is_active = 1";
}
List<Map<String, Object>> rawData = jdbcDomesticWasteTemplate.queryForList(finalSql, params.toArray());
return groupRequestsWithItems(rawData);
}
public Map<String, Object> actionTaken(String requestId, MultipartFile imageFile, int createdBy,String latitude,String longitude ) {
try {
// Step 0: Fetch internal id using requestId
String fetchIdSql = "SELECT id FROM user_request_table WHERE request_id = ?";
List<Integer> idList = jdbcDomesticWasteTemplate.queryForList(fetchIdSql, new Object[]{requestId}, Integer.class);
if (idList.isEmpty()) {
return Map.of("status", false, "message", "No record found for the given requestId: " + requestId);
}
Integer id = idList.get(0);
// Step 1: Upload image
String imagePath = fileUpload(imageFile, "officer_action_photo");
// Step 2: Insert into officer_data
String insertSql = "INSERT INTO officer_data (request_id, image_url, cdate, is_active, created_by,latitude,longitude) " +
"VALUES (?, ?, NOW(), ?, ?, ?, ?)";
jdbcDomesticWasteTemplate.update(insertSql, requestId, imagePath, true, createdBy, latitude, longitude);
// Step 3: Update user_request_table - status, officer_upload_url, and close_date from officer_data
String updateSql = "UPDATE user_request_table u " +
"JOIN officer_data o ON o.request_id = u.request_id " +
"SET u.status = '2', " +
" u.officer_upload_url = ?, " +
" u.close_date = DATE(o.cdate) " +
"WHERE u.id = ?";
jdbcDomesticWasteTemplate.update(updateSql, imagePath, id);
return Map.of("status", true, "message", "Action taken recorded successfully");
} catch (Exception e) {
e.printStackTrace();
return Map.of("status", false, "message", "Error: " + e.getMessage());
}
}
//scheduler method
public Map<String, Object> updateOrderStatus(String status) {
try {
String sql = "UPDATE user_request_table " +
"SET status = ? " +
"WHERE status = '1' AND DATE(cdate) < CURDATE()";//
int updated = jdbcDomesticWasteTemplate.update(sql, status);
return Map.of("status", true, "message", "Order status updated", "rowsAffected", updated);
} catch (Exception e) {
e.printStackTrace();
return Map.of("status", false, "message", "Error: " + e.getMessage());
}
}
//to group items and quantity common method
private List<Map<String, Object>> groupRequestsWithItems(List<Map<String, Object>> flatList) {
Map<Integer, Map<String, Object>> groupedMap = new LinkedHashMap<>();
for (Map<String, Object> row : flatList) {
Integer id = (Integer) row.get("id");
if (!groupedMap.containsKey(id)) {
Map<String, Object> base = new LinkedHashMap<>(row);
base.remove("item_name");
base.remove("quantity");
base.remove("iteam_id");
base.put("items", new ArrayList<Map<String, Object>>());
groupedMap.put(id, base);
}
Map<String, Object> item = new LinkedHashMap<>();
item.put("item_name", row.get("item_name"));
item.put("quantity", row.get("quantity"));
((List<Map<String, Object>>) groupedMap.get(id).get("items")).add(item);
}
//return new ArrayList<>(groupedMap.values());
List<Object> result = new ArrayList<>(groupedMap.values());
if (result.isEmpty()) {
Map<String, Object> response = new HashMap<>();
response.put("status", false);
response.put("message", "No data found");
return Collections.singletonList(response); // or just `response` depending on your return type
} else {
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("message", "Data retrieved successfully");
response.put("data", result);
return Collections.singletonList(response); // or `response` directly
}
}
public boolean verifylatlong(String requestId, String latitude, String longitude) {
int radius = 50;
try {
String sql = "SELECT 1 FROM user_request_table u " +
"WHERE u.request_id = ? AND " +
"((6371008.8 * ACOS(" +
"COS(RADIANS(?)) * COS(RADIANS(u.latitude)) * COS(RADIANS(u.longitude) - RADIANS(?)) + " +
"SIN(RADIANS(?)) * SIN(RADIANS(u.latitude)))) < ?)";
List<Map<String, Object>> rows = jdbcDomesticWasteTemplate.queryForList(sql,
requestId, latitude, longitude, latitude, radius);
return !rows.isEmpty(); // true if one or more rows match the criteria
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Map<String, Object> rejectuserreq(String requestId) {
try {
// Step 0: Fetch internal id using requestId
String fetchIdSql = "SELECT id FROM user_request_table WHERE request_id = ?";
Integer id = jdbcDomesticWasteTemplate.queryForObject(fetchIdSql, new Object[]{requestId}, Integer.class);
if (id == null) {
return Map.of("status", false, "message", "No record found for the given requestId");
}
// Step 1: Update using id
String sql = "UPDATE user_request_table SET status = '4' WHERE id = ?";
jdbcDomesticWasteTemplate.update(sql, id);
return Map.of("status", true, "message", "Rejected user request successfully");
} catch (Exception e) {
e.printStackTrace();
return Map.of("status", false, "message", "Error: " + e.getMessage());
}
}
public Map<String, Object> rejectuserreqofficer(String requestId, String officer_remark,
String rejecttype, int cancelled_by,
String latitude, String longitude){
try {
// Step 0: Fetch internal id using requestId
String fetchIdSql = "SELECT id FROM user_request_table WHERE request_id = ?";
Integer id = jdbcDomesticWasteTemplate.queryForObject(fetchIdSql, new Object[]{requestId}, Integer.class);
if (id == null) {
return Map.of("status", false, "message", "No record found for the given requestId");
}
// Step 1: Proper SQL with commas
String sql = "UPDATE user_request_table SET `status` = '5', officer_remark = ?, "
+ "cancelled_by = ?, rejecttype = ?, reject_latitude = ?, reject_longitude = ? WHERE id = ?";
jdbcDomesticWasteTemplate.update(sql, officer_remark, cancelled_by, rejecttype, latitude, longitude, id);
return Map.of("status", true, "message", "Rejected user request successfully");
} catch (Exception e) {
e.printStackTrace();
return Map.of("status", false, "message", "Error: " + e.getMessage());
}
}
@Transactional
public List<Map<String, Object>> getZoneReport(String fromDate, String toDate) {
// 1. Fetch all active streets for the ward (with zone info)
String sqlStreet = "("
+ " SELECT "
+ " ur.zone,"
+ " COUNT(*) AS total_request,"
+ " SUM(CASE WHEN ur.status = 1 THEN 1 ELSE 0 END) AS open,"
+ " SUM(CASE WHEN ur.status = 2 THEN 1 ELSE 0 END) AS completed,"
+ " SUM(CASE WHEN ur.status = 3 THEN 1 ELSE 0 END) AS pending,"
+ " SUM(CASE WHEN ur.status = 4 THEN 1 ELSE 0 END) AS user_cancel,"
+ " SUM(CASE WHEN ur.status = 5 THEN 1 ELSE 0 END) AS officer_cancel"
+ " FROM user_request_table ur"
+ " WHERE ur.is_active = 1 AND ur.is_delete = 0"
+ " GROUP BY ur.zone"
+ ")"
+ "UNION ALL"
+ "("
+ " SELECT "
+ " 'TOTAL' AS zone,"
+ " COUNT(*) AS total_request,"
+ " SUM(CASE WHEN ur.status = 1 THEN 1 ELSE 0 END) AS open,"
+ " SUM(CASE WHEN ur.status = 2 THEN 1 ELSE 0 END) AS completed,"
+ " SUM(CASE WHEN ur.status = 3 THEN 1 ELSE 0 END) AS pending,"
+ " SUM(CASE WHEN ur.status = 4 THEN 1 ELSE 0 END) AS user_cancel,"
+ " SUM(CASE WHEN ur.status = 5 THEN 1 ELSE 0 END) AS officer_cancel"
+ " FROM user_request_table ur"
+ " WHERE ur.is_active = 1 AND ur.is_delete = 0"
+ ") "
+ "ORDER BY "
+ " CASE WHEN zone = 'TOTAL' THEN 999 ELSE zone END";
List<Map<String, Object>> reportList = jdbcDomesticWasteTemplate.queryForList(sqlStreet);
Map<String, Object> response = new LinkedHashMap<>();
response.put("status", "Success");
response.put("message", "Zone wise Report");
response.put("data", reportList);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getWardReport(String fromDate, String toDate, String zone) {
String sql =
"("
+ " SELECT "
+ " ur.division AS division, "
+ " COUNT(*) AS total_request, "
+ " SUM(CASE WHEN ur.status = 1 THEN 1 ELSE 0 END) AS open, "
+ " SUM(CASE WHEN ur.status = 2 THEN 1 ELSE 0 END) AS completed, "
+ " SUM(CASE WHEN ur.status = 3 THEN 1 ELSE 0 END) AS pending, "
+ " SUM(CASE WHEN ur.status = 4 THEN 1 ELSE 0 END) AS user_cancel, "
+ " SUM(CASE WHEN ur.status = 5 THEN 1 ELSE 0 END) AS officer_cancel "
+ " FROM user_request_table ur "
+ " WHERE ur.is_active = 1 AND ur.is_delete = 0 AND ur.zone = ? "
+ " GROUP BY ur.division "
+ ") "
+ "UNION ALL "
+ "("
+ " SELECT "
+ " 'TOTAL' AS division, "
+ " COUNT(*) AS total_request, "
+ " SUM(CASE WHEN ur.status = 1 THEN 1 ELSE 0 END) AS open, "
+ " SUM(CASE WHEN ur.status = 2 THEN 1 ELSE 0 END) AS completed, "
+ " SUM(CASE WHEN ur.status = 3 THEN 1 ELSE 0 END) AS pending, "
+ " SUM(CASE WHEN ur.status = 4 THEN 1 ELSE 0 END) AS user_cancel, "
+ " SUM(CASE WHEN ur.status = 5 THEN 1 ELSE 0 END) AS officer_cancel "
+ " FROM user_request_table ur "
+ " WHERE ur.is_active = 1 AND ur.is_delete = 0 AND ur.zone = ? "
+ ") "
+ "ORDER BY "
+ " CASE WHEN division = 'TOTAL' THEN 999 ELSE CAST(division AS UNSIGNED) END";
List<Map<String, Object>> reportList = jdbcDomesticWasteTemplate.queryForList(sql, zone, zone);
Map<String, Object> response = new LinkedHashMap<>();
response.put("status", "Success");
response.put("message", "Ward-wise Report");
response.put("data", reportList);
return Collections.singletonList(response);
}
@Transactional(readOnly = true)
public List<Map<String, Object>> getWardStatusDetails(
String fromDate, String toDate,
String ward, String status) {
// ✅ Base URL for images
String fileBaseUrl = "https://gccservices.in"; // or your configured value
// ✅ SQL query with ward + status filters
String sql =
"SELECT " +
" u.id, u.request_id, u.user_name, u.mobile, u.address, " +
" u.latitude, u.longitude, u.zone, u.division, u.street_name, " +
" u.quantity AS main_quantity, u.remarks, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.image_url) AS image_url, " +
" DATE_FORMAT(u.cdate, '%d-%m-%Y') AS cdate, " +
" sm.status_master AS status, " +
" DATE_FORMAT(u.close_date, '%d-%m-%Y') AS close_date, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', u.officer_upload_url) AS officer_upload_url, " +
" im.item_name, itm.quantity " +
"FROM user_request_table u " +
"LEFT JOIN items itm ON u.id = itm.req_table_id " +
"LEFT JOIN item_master im ON itm.iteam_id = im.id AND im.is_active = 1 " +
"LEFT JOIN status_master sm ON sm.id = u.status AND sm.is_active = 1 AND sm.is_delete = 0 " +
"WHERE u.is_active = 1 AND u.is_delete = 0 " +
" AND u.division = ? " +
" AND u.status = ? " +
"ORDER BY u.cdate DESC";
// ✅ Execute query
List<Map<String, Object>> reportList = jdbcDomesticWasteTemplate.queryForList(sql, ward, status);
return groupRequestsWithItems(reportList);
}
}

157
src/main/java/in/gov/chennaicorporation/mobileservice/gccHealthCamp/controller/HealthCampController.java

@ -0,0 +1,157 @@
package in.gov.chennaicorporation.mobileservice.gccHealthCamp.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.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.gccHealthCamp.service.HealthCampService;
@RequestMapping("/gccofficialapp/api/healthcamp")
@RestController("gccofficialapphealthcamp")
public class HealthCampController {
@Autowired
private HealthCampService healthCampService;
// get all camptypes
@GetMapping("/camptypes")
public List<Map<String, Object>> getAllHealthCamp() {
return healthCampService.getAllHealthCamp();
}
// get all disease category
@GetMapping("/diseasecategory")
public List<Map<String, Object>> getAllDisease() {
return healthCampService.getAlldisease();
}
// get all gender
@GetMapping("/gender")
public List<Map<String, Object>> getAllGender() {
return healthCampService.getAllgender();
}
@GetMapping("/getcampbydate")
public List<Map<String, Object>> getCampByDate(@RequestParam String userid) {
return healthCampService.getCampByDate(userid);
}
// save the camp details
@PostMapping("/savecampdetails")
public ResponseEntity<Map<String, Object>> saveHealthCampDetails(
@RequestParam("camptypeId") int camptypeId,
@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude,
@RequestParam("zone") String zone,
@RequestParam("ward") String ward,
@RequestParam("address") String address,
@RequestParam("campName") String campName,
//@RequestParam("noofpamphlets") int noofpamphlets,
@RequestParam("camp_photo") MultipartFile campPhoto,
@RequestParam("userid") String userid,
@RequestParam("streetName") String streetName,
@RequestParam("doc_name") String doc_name,
@RequestParam("mo_name") String mo_name,
@RequestParam("si_name") String si_name) {
// File upload paths
String campPhotoPath = (campPhoto != null) ? healthCampService.fileUpload(campPhoto, "camp_photo") : "";
// Save to DB
String saveStatus = healthCampService.saveHealthCampDetails(camptypeId, latitude, longitude, zone, ward,
address, campName, campPhotoPath, userid,streetName,doc_name,mo_name,si_name
);
if (saveStatus == null || saveStatus.isEmpty()) {
return ResponseEntity
.ok(Map.of("status", false, "message", "failed", "description", "Failed to save the details"));
}
return ResponseEntity
.ok(Map.of("status", true, "message", "success", "description", "Details saved successfully"));
}
// save the patient details
@PostMapping("/savepatientdetails")
public ResponseEntity<Map<String, Object>> savePatientDetails(
@RequestParam("campId") int campId,
@RequestParam("pat_name") String pat_name,
@RequestParam("pat_age") String pat_age,
@RequestParam("genderId") int genderId,
@RequestParam("mobileNo") String mobileNo,
@RequestParam("pat_address") String pat_address,
@RequestParam(required = false, name = "otherDisease") String otherDisease,
@RequestParam("remarks") String remarks,
@RequestParam("userid") String userid,
@RequestParam("diseaseIds") List<String> diseaseIds) {
// Save to DB
String saveStatus = healthCampService.savePatientDetails(
campId, pat_name, pat_age, genderId, mobileNo, pat_address, otherDisease, remarks, userid, diseaseIds
);
if (saveStatus == null || saveStatus.isEmpty()) {
return ResponseEntity
.ok(Map.of("status", false, "message", "failed", "description", "Failed to save the details"));
}
return ResponseEntity
.ok(Map.of("status", true, "message", "success", "description", "Details saved successfully"));
}
// Reports
@GetMapping("/campsummary")
public Map<String, Object> getCampSummary(@RequestParam("date") String date) {
return healthCampService.getCampSummary(date);
}
@GetMapping("/zonewisedetails")
public Map<String, Object> getWardwiseDetails(@RequestParam("date") String date,
@RequestParam("zoneId") String zoneId) {
return healthCampService.getWardwiseDetails(date, zoneId);
}
@GetMapping("/wardwisedetails")
public List<Map<String, Object>> getCampwiseDetails(@RequestParam("date") String date,
@RequestParam("ward") String ward) {
return healthCampService.getCampwiseDetails(date, ward);
}
@GetMapping("/campwisedetails")
public List<Map<String, Object>> getCampDetails(@RequestParam("campId") String campId) {
return healthCampService.getCampDetails(campId);
}
}

385
src/main/java/in/gov/chennaicorporation/mobileservice/gccHealthCamp/service/HealthCampService.java

@ -0,0 +1,385 @@
package in.gov.chennaicorporation.mobileservice.gccHealthCamp.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.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.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 in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class HealthCampService {
@Autowired
private JdbcTemplate jdbcHealthCampTemplate;
private final Environment environment;
private String fileBaseUrl;
@Autowired
public void setDataSource(@Qualifier("mysqlGccMedicalCampDataSource") DataSource healthCampDataSource) {
this.jdbcHealthCampTemplate = new JdbcTemplate(healthCampDataSource);
}
public HealthCampService(Environment environment) {
this.environment = environment;
this.fileBaseUrl = environment.getProperty("fileBaseUrl");
}
public List<Map<String, Object>> getAllHealthCamp() {
String sql = " select id,name from camp_type where is_active=1 AND is_delete=0 ";
return jdbcHealthCampTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAlldisease() {
String sql = " select id,disease_name from disease_master where is_active=1 AND is_delete=0 ";
return jdbcHealthCampTemplate.queryForList(sql);
}
public List<Map<String, Object>> getAllgender() {
String sql = " select id,gender from gender_master where is_active=1 AND is_delete=0 ";
return jdbcHealthCampTemplate.queryForList(sql);
}
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT ward FROM gcc_penalty_hoardings.hoading_user_list WHERE userid = ? AND type = ? LIMIT 1";
List<Map<String, Object>> results = jdbcHealthCampTemplate.queryForList(sqlQuery, loginid, type);
if (!results.isEmpty()) {
System.out.println("Ward....." + results);
// Extract the ward value from the first result
return (String) results.get(0).get("ward");
}
return "000";
}
public List<Map<String, Object>> getCampByDate(String userid) {
String ward = getWardByLoginId(userid, "si");
String sql = "select id,camp_name from camp_details WHERE ward = ? AND DATE(cdate) = CURDATE() AND is_active=1 AND is_delete=0 ";
return jdbcHealthCampTemplate.queryForList(sql,ward);
}
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("healthcamp_folder");
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();
}
}
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String saveHealthCampDetails(int camptypeId, String latitude, String longitude, String zone, String ward,
String address, String campName, String campPhotoPath, String userid,
String streetName,String doc_name,String mo_name,String si_name) {
String sql = "INSERT INTO camp_details ("
+ "camp_type_id, latitude, longitude, zone, ward, address, camp_name, camp_img, cby,"
+ "street_name, doc_name, mo_name, si_name "
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
int result = jdbcHealthCampTemplate.update(sql, camptypeId, latitude, longitude, zone, ward, address,
campName, campPhotoPath, userid, streetName, doc_name, mo_name, si_name);
return result > 0 ? "success" : "failed";
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
public String savePatientDetails(int campId, String pat_name, String pat_age, int genderId, String mobileNo,
String pat_address,
String otherDisease, String remarks, String userid, List<String> diseaseIds) {
String sql = "INSERT INTO patient_details ("
+ " camp_id, pt_name, pt_age, pt_gender_id, pt_mob_no, pt_address, pt_other_disease, remarks, cby"
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int result = jdbcHealthCampTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
ps.setInt(1, campId);
ps.setString(2, pat_name);
ps.setString(3, pat_age);
ps.setInt(4, genderId);
ps.setString(5, mobileNo);
ps.setString(6, pat_address);
// ps.setInt(7, diseaseId);
ps.setString(7, otherDisease);
ps.setString(8, remarks);
ps.setString(9, userid);
return ps;
}, keyHolder);
// return keyHolder.getKey().intValue();
if (result > 0) {
int generatedId = keyHolder.getKey().intValue();
String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String patientId = prefix + generatedId;
String updateSql = " UPDATE patient_details SET patient_id = ? WHERE id = ? ";
jdbcHealthCampTemplate.update(updateSql, patientId, generatedId);
// INSERT MULTIPLE DISEASES
String diseaseSql = "INSERT INTO diseases_details (patient_id, disease_id) VALUES (?, ?)";
for (String id : (diseaseIds)) {
int diseaseId = Integer.parseInt(id);
jdbcHealthCampTemplate.update(diseaseSql, patientId, diseaseId);
}
return patientId;
}
// return "error";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
// report related
public Map<String, Object> getCampSummary(String date) {
String datetxt = convertDateFormat(date,0);
try {
// Total Counts
String totalSql = "SELECT COUNT(DISTINCT cd.id) AS total_camp_count, " + "COUNT(pd.id) AS total_pat_count "
+ "FROM camp_details cd " + "LEFT JOIN patient_details pd ON cd.id = pd.camp_id "
+ "WHERE DATE(cd.cdate) = ?";
Map<String, Object> totalCounts = jdbcHealthCampTemplate.queryForMap(totalSql, datetxt);
// Zone-wise Counts
String zoneSql = "SELECT cd.zone, COUNT(DISTINCT cd.id) AS total_camp_count, "
+ "COUNT(pd.id) AS total_pat_count " + "FROM camp_details cd "
+ "LEFT JOIN patient_details pd ON cd.id = pd.camp_id " + "WHERE DATE(cd.cdate) = ? "
+ "GROUP BY cd.zone";
List<Map<String, Object>> zoneList = jdbcHealthCampTemplate.queryForList(zoneSql, datetxt);
totalCounts.put("zoneList", zoneList);
return totalCounts;
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> response = new HashMap<>();
response.put("status", "No data found");
return Collections.singletonMap("status", "No data found");
}
}
public Map<String, Object> getWardwiseDetails(String date, String zoneId) {
String datetxt = convertDateFormat(date,0);
try {
// Total Counts
String totalSql = "SELECT COUNT(DISTINCT cd.id) AS total_camp_count, " + "COUNT(pd.id) AS total_pat_count "
+ "FROM camp_details cd " + "LEFT JOIN patient_details pd ON cd.id = pd.camp_id "
+ "WHERE DATE(cd.cdate) = ? AND cd.zone=?";
Map<String, Object> totalCounts = jdbcHealthCampTemplate.queryForMap(totalSql, datetxt, zoneId);
// Zone-wise Counts
String zoneSql = "SELECT cd.ward, COUNT(DISTINCT cd.id) AS total_camp_count, "
+ "COUNT(pd.id) AS total_pat_count " + "FROM camp_details cd "
+ "LEFT JOIN patient_details pd ON cd.id = pd.camp_id " + "WHERE DATE(cd.cdate) = ? "
+ "AND cd.zone=? GROUP BY cd.ward";
List<Map<String, Object>> wardList = jdbcHealthCampTemplate.queryForList(zoneSql, datetxt, zoneId);
totalCounts.put("wardList", wardList);
return totalCounts;
} catch (Exception ex) {
ex.printStackTrace();
Map<String, Object> response = new HashMap<>();
response.put("status", "No data found");
return Collections.singletonMap("status", "No data found");
}
}
public List<Map<String, Object>> getCampwiseDetails(String date, String ward) {
String datetxt = convertDateFormat(date,0);
String sql = " Select cd.id, cd.zone, cd.ward, cd.camp_name,count(pd.id) as total_pat_count " + " FROM camp_details cd "
+ " LEFT JOIN patient_details pd " + " ON cd.id = pd.camp_id "
+ " WHERE DATE(cd.cdate) = ? and cd.ward = ? Group by cd.id ";
return jdbcHealthCampTemplate.queryForList(sql, datetxt, ward);
}
/*
public List<Map<String, Object>> getWardwiseDetails(String date, String zoneId) {
String datetxt = convertDateFormat(date,0);
String sql = "select cd.ward,count(pd.id) as pat_count "
+ "from camp_details cd "
+ "left join patient_details pd on pd.camp_id = cd.id "
+ "where cd.zone=? AND DATE(cd.cdate)=? AND cd.is_active=1 AND cd.is_delete=0 "
+ "group by cd.ward ";
return jdbcHealthCampTemplate.queryForList(sql,zoneId,datetxt );
}
*/
public List<Map<String, Object>> getCampDetails(String campId) {
String sql = " select pd.id, pd.patient_id, pd.pt_name, pd.pt_mob_no, "
+ " gm.gender, pd.pt_age, pd.pt_address, ct.name as camp_type, "
+ " cd.camp_name, cd.address,pd.remarks, " + " DATE_FORMAT(cd.cdate, '%d-%m-%Y') AS regDate, "
+ " DATE_FORMAT(cd.cdate, '%h:%i %p') AS Time, "
+ " GROUP_CONCAT(dm.disease_name SEPARATOR ', ') AS diseases " + " FROM patient_details pd "
+ " LEFT JOIN camp_details cd ON pd.camp_id = cd.id "
+ " LEFT JOIN gender_master gm on pd.pt_gender_id = gm.id "
+ " LEFT JOIN camp_type ct on cd.camp_type_id = ct.id "
+ " LEFT JOIN diseases_details dd ON pd.patient_id = dd.patient_id "
+ " LEFT JOIN disease_master dm ON dd.disease_id = dm.id " + " WHERE cd.id = ? " + " GROUP BY pd.id ";
return jdbcHealthCampTemplate.queryForList(sql, campId);
}
}

169
src/main/java/in/gov/chennaicorporation/mobileservice/gccHomeLessSurveyNew/Controller/HomeLessSurveyApiController.java

@ -0,0 +1,169 @@
package in.gov.chennaicorporation.mobileservice.gccHomeLessSurveyNew.Controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.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 org.springframework.web.multipart.MultipartHttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import in.gov.chennaicorporation.mobileservice.gccHomeLessSurveyNew.Service.HomeLessSurveyService;
@RequestMapping("/gccofficialapp/api/homelesssurvey")
@RestController("gccofficialapphomelesssurvey")
public class HomeLessSurveyApiController {
@Autowired
private HomeLessSurveyService homeLessSurveyService;
@GetMapping("/questions")
public ResponseEntity<?> getQuestions(@RequestParam Integer cid) {
List<Map<String, Object>> data = homeLessSurveyService.getSurveyQuestions(cid);
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
@GetMapping("/login")
public ResponseEntity<?> getLogin(@RequestParam String mobileNo, @RequestParam String password) {
Map<String, Object> response = homeLessSurveyService.getLoginDetails(mobileNo, password);
return ResponseEntity.ok(response);
}
@GetMapping("/states")
public ResponseEntity<?> getStates() {
List<Map<String, Object>> data = homeLessSurveyService.getStates();
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
@GetMapping("/districts")
public ResponseEntity<?> getDistricts(@RequestParam(required = false) String sid) {
List<Map<String, Object>> data = homeLessSurveyService.getDistricts(sid);
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
@GetMapping("/questions_category")
public ResponseEntity<?> getQuestionsCategory() {
List<Map<String, Object>> data = homeLessSurveyService.getQuestionsCategory();
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
// @PostMapping("/save")
// public ResponseEntity<?> saveResponses(
// @RequestParam Map<String, String> params,
// HttpServletRequest request) {
// MultipartHttpServletRequest multipartRequest = null;
// if (request instanceof MultipartHttpServletRequest) {
// multipartRequest = (MultipartHttpServletRequest) request;
// }
// Map<String, Object> result =
// homeLessSurveyService.saveSurveyResponses(params, multipartRequest);
// System.out.println("params ----------------------------------------->" +
// params);
// System.out.println("request-------------" + request);
// System.out.println("multipartRequest --------------------------------->" +
// multipartRequest);
// System.out.println("result ----------------------------------------->" +
// result);
// return ResponseEntity.ok(result);
// }
@PostMapping("/save")
public ResponseEntity<?> saveResponses(
@RequestParam Map<String, String> params,
HttpServletRequest request,
MultipartHttpServletRequest multipartRequest) {
Map<String, MultipartFile> files = multipartRequest.getFileMap();
// System.out.println("===== FORM PARAMETERS =====");
request.getParameterMap().forEach((key, values) -> {
for (String value : values) {
// System.out.println(key + " = " + value);
}
});
// System.out.println("\n===== FILES ====");
// multipartRequest.getFileMap().forEach((key, file) -> {
// System.out.println("Field Name : " + key);
// System.out.println("File Name : " + file.getOriginalFilename());
// System.out.println("Size : " + file.getSize());
// System.out.println("ContentType: " + file.getContentType());
// System.out.println("---------------------------");
// });
// System.out.println("\n===== FILES FINAL ====");
for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
String fieldName = entry.getKey();
MultipartFile file = entry.getValue();
// System.out.println("params :" + params);
// System.out.println("request :" + request);
// System.out.println("multipartRequest :" + multipartRequest);
// System.out.println("Field Name : " + fieldName);
// System.out.println("File Name : " + file.getOriginalFilename());
// System.out.println("Size : " + file.getSize());
}
// Existing service call
Map<String, Object> result = homeLessSurveyService.saveSurveyResponses(params, multipartRequest);
return ResponseEntity.ok(result);
}
@GetMapping("/category_status")
public ResponseEntity<?> getCategoryStatus(@RequestParam("survey_id") String surveyId) {
Map<String, Object> response = homeLessSurveyService.getCategoryStatus(surveyId);
return ResponseEntity.ok(response);
}
@GetMapping("/profile_list")
public ResponseEntity<?> getProfileList(@RequestParam(required = false) String cby) {
List<Map<String, Object>> data = homeLessSurveyService.getProfileCreatedList(cby);
Map<String, Object> response = new HashMap<>();
response.put("status", true);
response.put("data", data);
return ResponseEntity.ok(response);
}
}

974
src/main/java/in/gov/chennaicorporation/mobileservice/gccHomeLessSurveyNew/Service/HomeLessSurveyService.java

@ -0,0 +1,974 @@
package in.gov.chennaicorporation.mobileservice.gccHomeLessSurveyNew.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.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class HomeLessSurveyService {
@Autowired
JdbcTemplate jdbcHomeLessSurveyTemplate;
@Autowired
private Environment environment;
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final int STRING_LENGTH = 15;
private static final Random RANDOM = new SecureRandom();
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();
}
@Autowired
public void setDataSource(@Qualifier("mysqlHomeLessSurveyDataSource") DataSource homeLessSurveyDataSource) {
this.jdbcHomeLessSurveyTemplate = new JdbcTemplate(homeLessSurveyDataSource);
}
public List<Map<String, Object>> getSurveyQuestions(Integer cid) {
String childSql = "SELECT DISTINCT child_qid FROM homeless_question_mapping " +
"WHERE isactive=1 AND isdelete=0";
List<Integer> childQids = jdbcHomeLessSurveyTemplate.queryForList(childSql, Integer.class);
String questionSql = "SELECT * FROM homeless_survey_questions_master " +
"WHERE cid=? AND isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> questions = jdbcHomeLessSurveyTemplate.queryForList(questionSql, cid);
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> q : questions) {
Integer qid = (Integer) q.get("qid");
if (childQids.contains(qid)) {
continue;
}
Map<String, Object> fullQuestion = buildQuestionWithOptions(q);
finalList.add(fullQuestion);
}
return finalList;
}
private Map<String, Object> buildQuestionWithOptions(Map<String, Object> q) {
Integer qid = (Integer) q.get("qid");
String masterTable = (String) safe(q.get("master_table_name"));
// Maintain order
Map<String, Object> questionMap = new LinkedHashMap<>();
questionMap.put("qid", q.get("qid"));
questionMap.put("q_english", q.get("q_english"));
questionMap.put("q_tamil", safe(q.get("q_tamil")));
questionMap.put("field_name", q.get("field_name"));
questionMap.put("cdate", q.get("cdate"));
questionMap.put("question_type", q.get("question_type"));
questionMap.put("isactive", q.get("isactive"));
questionMap.put("isdelete", q.get("isdelete"));
questionMap.put("orderby", q.get("orderby"));
questionMap.put("is_mandatory", q.get("is_mandatory"));
questionMap.put("is_dropdown", q.get("is_dropdown"));
questionMap.put("flag", q.get("flag"));
questionMap.put("master_table_name", masterTable);
List<Map<String, Object>> options = new ArrayList<>();
if (masterTable != null && !masterTable.isEmpty()) {
if (masterTable.equalsIgnoreCase("state_master") || masterTable.equalsIgnoreCase("district_master")) {
options = new ArrayList<>();
} else {
options = getOptionsFromMaster(masterTable, qid);
}
} else {
String optSql = "SELECT id AS option_id, answer AS english_name, " +
"orderby, is_mandatory " +
"FROM homeless_survey_answer_master " +
"WHERE qid=? AND isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> dbOptions = jdbcHomeLessSurveyTemplate.queryForList(optSql, qid);
for (Map<String, Object> opt : dbOptions) {
Map<String, Object> optionMap = new LinkedHashMap<>();
String englishName = (String) opt.get("english_name");
optionMap.put("option_id", opt.get("option_id"));
optionMap.put("english_name", englishName);
optionMap.put("tamil_name", "");
optionMap.put("orderby", opt.get("orderby"));
optionMap.put("is_mandatory", opt.get("is_mandatory"));
boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others");
optionMap.put("is_others", isOthers);
optionMap.put("text", isOthers);
Integer aid = (Integer) opt.get("option_id");
List<Map<String, Object>> childQuestions = getChildQuestionsRecursive(aid);
optionMap.put("child_questions", childQuestions);
options.add(optionMap);
}
}
questionMap.put("options", options);
return questionMap;
}
private List<Map<String, Object>> getChildQuestionsRecursive(Integer parentAid) {
String mappingSql = "SELECT child_qid FROM homeless_question_mapping " +
"WHERE parent_aid=? AND isactive=1 AND isdelete=0";
List<Integer> childQids = jdbcHomeLessSurveyTemplate.queryForList(mappingSql, Integer.class, parentAid);
List<Map<String, Object>> childQuestions = new ArrayList<>();
for (Integer cqid : childQids) {
String qSql = "SELECT * FROM homeless_survey_questions_master " +
"WHERE qid=? AND isactive=1 AND isdelete=0";
List<Map<String, Object>> childQList = jdbcHomeLessSurveyTemplate.queryForList(qSql, cqid);
if (!childQList.isEmpty()) {
Map<String, Object> childQ = childQList.get(0);
Map<String, Object> fullChild = buildQuestionWithOptions(childQ);
childQuestions.add(fullChild);
}
}
return childQuestions;
}
private List<Map<String, Object>> getOptionsFromMaster(String tableName, Integer parentQid) {
String sql = "SELECT id AS option_id, " +
"english_name, " +
"IFNULL(tamil_name, '') AS tamil_name, " +
"orderby, " +
"is_mandatory " +
"FROM " + tableName + " " +
"WHERE isactive=1 AND isdelete=0 " +
"ORDER BY orderby";
List<Map<String, Object>> dbOptions = jdbcHomeLessSurveyTemplate.queryForList(sql);
List<Map<String, Object>> options = new ArrayList<>();
for (Map<String, Object> opt : dbOptions) {
Map<String, Object> optionMap = new LinkedHashMap<>();
String englishName = (String) opt.get("english_name");
optionMap.put("option_id", opt.get("option_id"));
optionMap.put("english_name", englishName);
optionMap.put("tamil_name", opt.get("tamil_name"));
optionMap.put("orderby", opt.get("orderby"));
optionMap.put("is_mandatory", opt.get("is_mandatory"));
List<Map<String, Object>> childQuestions = new ArrayList<>();
boolean isOthers = englishName != null && englishName.equalsIgnoreCase("Others");
optionMap.put("is_others", isOthers);
optionMap.put("text", isOthers);
if (isOthers) {
Map<String, Object> child = new LinkedHashMap<>();
child.put("qid", parentQid); // same parent qid
child.put("q_english", "Please specify");
child.put("q_tamil", "");
child.put("question_type", "text");
child.put("field_name", "q" + parentQid + "_other");
child.put("is_mandatory", false);
child.put("is_dropdown", false);
childQuestions.add(child);
}
optionMap.put("child_questions", childQuestions);
options.add(optionMap);
}
return options;
}
public List<Map<String, Object>> getStates() {
String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, orderby " +
"FROM state_master " +
"WHERE isactive=1 AND isdelete=0 " +
"ORDER BY orderby";
return jdbcHomeLessSurveyTemplate.queryForList(sql);
}
public List<Map<String, Object>> getQuestionsCategory() {
String sql = "SELECT * FROM question_category_master where isactive=1 and isdelete=0 order by orderby";
return jdbcHomeLessSurveyTemplate.queryForList(sql);
}
public List<Map<String, Object>> getDistricts(String sid) {
if (sid != null && !sid.trim().isEmpty()) {
String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " +
"FROM district_master " +
"WHERE sid=? AND isactive=1 AND isdelete=0 " +
"ORDER BY orderby";
return jdbcHomeLessSurveyTemplate.queryForList(sql, sid);
} else {
String sql = "SELECT id AS option_id, english_name, IFNULL(tamil_name, '') AS tamil_name, sid, orderby " +
"FROM district_master " +
"WHERE isactive=1 AND isdelete=0 " +
"ORDER BY orderby";
return jdbcHomeLessSurveyTemplate.queryForList(sql);
}
}
private Object safe(Object value) {
return value == null ? "" : value;
}
public Map<String, Object> getLoginDetails(String mobileNo, String password) {
try {
String sql = "SELECT uid as loginId,user_name, password, mobile_no, is_active, is_delete " +
"FROM login_details " +
"WHERE mobile_no = ? AND password = ? AND is_active = 1 AND is_delete = 0 Limit 1";
List<Map<String, Object>> data = jdbcHomeLessSurveyTemplate.queryForList(sql, mobileNo, password);
Map<String, Object> response = new HashMap<>();
if (!data.isEmpty()) {
// Login success
response.put("is_login", true);
response.put("message", "Login Success");
response.put("data", data);
} else {
// Login failed
response.put("is_login", false);
response.put("message", "Invalid mobile number or password");
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error fetching login details: " + e.getMessage());
}
}
@Transactional
public Map<String, Object> saveSurveyResponses(Map<String, String> params,
MultipartHttpServletRequest fileRequest) {
Map<String, Object> result = new HashMap<>();
try {
// URL-decode all parameter values to handle spaces, etc. (e.g. Adi%20Dravidar)
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() != null) {
String val = entry.getValue();
try {
if (val.contains("%")) {
entry.setValue(java.net.URLDecoder.decode(val, "UTF-8"));
}
} catch (Exception ex) {
// ignore
}
}
}
String surveyId = params.get("survey_id");
String cid = params.get("cid");
String cby = params.get("cby");
String zone = params.get("zone");
String ward = params.get("ward");
String latitude = params.get("latitude");
String longitude = params.get("longitude");
String address = params.get("address");
// System.out.println(" surveyId: " + surveyId);
// System.out.println(" cid: " + cid);
// System.out.println(" cby: " + cby);
// System.out.println(" zone: " + zone);
// System.out.println(" ward: " + ward);
// System.out.println(" latitude: " + latitude);
// System.out.println(" longitude: " + longitude);
// System.out.println(" address: " + address);
// If it is NOT the Profile category, verify that the profile is already created
if (cid == null || !cid.equals("1")) {
if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) {
result.put("status", false);
result.put("message",
"Survey ID is required for this category. Please save the Profile category first.");
return result;
}
// Check if the Profile category responses or surveyor location record exists
// for this surveyId
String checkProfileSql = "SELECT COUNT(*) FROM homeless_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0";
Integer profileCount = jdbcHomeLessSurveyTemplate.queryForObject(checkProfileSql, Integer.class,
surveyId);
String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0";
Integer locCount = jdbcHomeLessSurveyTemplate.queryForObject(checkLocSql, Integer.class, surveyId);
if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) {
result.put("status", false);
result.put("message",
"Profile not created for this survey ID. Please save the Profile category first.");
return result;
}
}
// 1. Generate surveyId if not provided
if (surveyId == null || surveyId.trim().isEmpty() || surveyId.equalsIgnoreCase("null")) {
String timeStr = java.time.LocalDateTime.now()
.format(java.time.format.DateTimeFormatter.ofPattern("ddMMyyHHmmss"));
surveyId = "GCC_HS_" + timeStr;
}
String resolvedLat = latitude;
if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) {
resolvedLat = params.get("lat");
}
if (resolvedLat == null || resolvedLat.trim().isEmpty() || resolvedLat.equalsIgnoreCase("null")) {
if (fileRequest != null) {
resolvedLat = fileRequest.getParameter("lat");
}
}
String resolvedLng = longitude;
if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) {
resolvedLng = params.get("long");
}
if (resolvedLng == null || resolvedLng.trim().isEmpty() || resolvedLng.equalsIgnoreCase("null")) {
if (fileRequest != null) {
resolvedLng = fileRequest.getParameter("long");
}
}
// If Profile category (cid = 1) is created, save surveyor location details
// first (like in child_survey)
if (cid != null && cid.equals("1") && (zone != null || resolvedLat != null || resolvedLng != null)) {
try {
String logindetailsSql = "INSERT INTO surveyor_location_details " +
"(loginId, zone, ward, latitude, longitude, address, is_active, is_delete, cdate) " +
"VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())";
org.springframework.jdbc.support.KeyHolder keyHolder = new org.springframework.jdbc.support.GeneratedKeyHolder();
final String finalLat = resolvedLat;
final String finalLng = resolvedLng;
final String finalZone = zone;
final String finalWard = ward;
final String finalAddress = address;
final String finalCby = cby;
jdbcHomeLessSurveyTemplate.update(
connection -> {
java.sql.PreparedStatement ps = connection.prepareStatement(logindetailsSql,
java.sql.Statement.RETURN_GENERATED_KEYS);
ps.setString(1, finalCby);
ps.setString(2, finalZone);
ps.setString(3, finalWard);
ps.setString(4, finalLat);
ps.setString(5, finalLng);
ps.setString(6, finalAddress);
return ps;
},
keyHolder);
Number key = keyHolder.getKey();
if (key != null) {
Integer locationId = key.intValue();
// Append the locationId to surveyId
surveyId = surveyId + locationId;
// Update the location record with the final surveyId
String updateSql = "UPDATE surveyor_location_details SET survey_id = ? WHERE id = ?";
jdbcHomeLessSurveyTemplate.update(updateSql, surveyId, locationId);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error saving surveyor location details: " + ex.getMessage());
}
}
// Deactivate existing active responses for this surveyId and cid
String deactivateSql = "UPDATE homeless_survey_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1";
jdbcHomeLessSurveyTemplate.update(deactivateSql, surveyId, cid);
String deactivateParticipateSql = "UPDATE homeless_survey_participate_response SET isactive = 0, isdelete = 1 WHERE survey_id = ? AND cid = ? AND isactive = 1";
jdbcHomeLessSurveyTemplate.update(deactivateParticipateSql, surveyId, cid);
String insertparticipateSql = "INSERT INTO homeless_survey_participate_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) "
+
"VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)";
String insertSql = "INSERT INTO homeless_survey_response (qid, answer, others_answer, survey_id, cid, cby, parent_answer_id, cdate, isactive, isdelete) "
+
"VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 1, 0)";
String qSql = "SELECT qid, question_type, field_name, q_english FROM homeless_survey_questions_master "
+ "WHERE cid = ? AND (isactive = 1 AND isdelete = 0 OR (cid = '1' AND field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))";
List<Map<String, Object>> questions = jdbcHomeLessSurveyTemplate.queryForList(qSql, cid);
boolean hasNotWillingResponse = false;
// First pass: check if qid = 1 is answered with "38" or "Not willing to respond
// (mark them)"
for (Map<String, Object> q : questions) {
Integer qid = (Integer) q.get("qid");
String fieldName = (String) q.get("field_name");
if (qid != null && qid == 1 && fieldName != null && params.containsKey(fieldName)) {
String answer = params.get(fieldName);
if (answer != null) {
String trimmed = answer.trim();
if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) {
hasNotWillingResponse = true;
}
}
}
}
for (Map<String, Object> q : questions) {
Integer qid = (Integer) q.get("qid");
String fieldName = (String) q.get("field_name");
String questionType = (String) q.get("question_type");
String qEnglish = (String) q.get("q_english");
// System.out.println("qid: " + qid);
// System.out.println("fieldName: " + fieldName);
// System.out.println("questionType: " + questionType);
// System.out.println("qEnglish: " + qEnglish);
if (fieldName == null || fieldName.trim().isEmpty()) {
continue;
}
// Check if the param exists or has a file upload
boolean hasParam = params.containsKey(fieldName);
boolean hasFile = false;
if (fileRequest != null) {
// System.out.println(
// "fieldName: " + fieldName + " - " +
// fileRequest.getFileMap().containsKey(fieldName));
// System.out.println("q_" + qid + " - " +
// fileRequest.getFileMap().containsKey("q_" + qid));
if (fileRequest.getFileMap().containsKey(fieldName) ||
fileRequest.getFileMap().containsKey("q_" + qid) ||
fileRequest.getFileMap().containsKey("file_" + qid) ||
fileRequest.getFileMap().containsKey("file" + qid) ||
fileRequest.getFileMap().containsKey("f_" + qid) ||
fileRequest.getFileMap().containsKey("f" + qid) ||
fileRequest.getFileMap().containsKey("q" + qid)) {
hasFile = true;
} else if (questionType != null
&& (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) {
boolean matchesOrGeneric = false;
if (fileRequest.getFileMap().size() == 1) {
String singleKey = fileRequest.getFileMap().keySet().iterator().next();
if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) ||
singleKey.contains("q_" + qid) ||
singleKey.contains("file_" + qid) ||
singleKey.contains("file" + qid) ||
singleKey.contains("f_" + qid) ||
singleKey.contains("f" + qid) ||
singleKey.contains("q" + qid) ||
singleKey.equalsIgnoreCase("files") ||
singleKey.equalsIgnoreCase("file") ||
singleKey.equalsIgnoreCase("image"))) {
matchesOrGeneric = true;
}
}
if (fileRequest.getFileMap().containsKey("files") ||
fileRequest.getFileMap().containsKey("file") ||
fileRequest.getFileMap().containsKey("image") ||
matchesOrGeneric) {
hasFile = true;
}
}
}
if (hasParam || hasFile) {
String answer = params.getOrDefault(fieldName, "");
if (answer == null) {
answer = "";
}
// Extract others_answer
String othersKey = fieldName + "_other";
String othersAnswer = params.getOrDefault(othersKey, "");
// Extract parent_answer_id
String parentKey = fieldName + "_parent_answer_id";
Integer parentAnswerId = 0;
if (params.get(parentKey) != null && !params.get(parentKey).isEmpty()) {
try {
parentAnswerId = Integer.parseInt(params.get(parentKey));
} catch (Exception ex) {
// ignore
}
}
// Handle image/file uploads
if (questionType != null
&& (questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) {
MultipartFile file = null;
if (fileRequest != null) {
file = fileRequest.getFile(fieldName);
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("q_" + qid);
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("file_" + qid);
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("file" + qid);
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("f_" + qid);
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("f" + qid);
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("q" + qid);
}
// Fallback generic scan
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("files");
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("file");
}
if (file == null || file.isEmpty()) {
file = fileRequest.getFile("image");
}
// Fallback scan
if (file == null || file.isEmpty()) {
for (String name : fileRequest.getFileMap().keySet()) {
if (name.equalsIgnoreCase(fieldName)
|| name.contains("q_" + qid)
|| name.contains("file_" + qid)
|| name.contains("file" + qid)
|| name.contains("f_" + qid)
|| name.contains("f" + qid)
|| name.contains("q" + qid)) {
file = fileRequest.getFile(name);
break;
}
}
}
// Ultimate fallback: if only 1 file exists in the request, use it
if ((file == null || file.isEmpty()) && fileRequest.getFileMap().size() == 1) {
String singleKey = fileRequest.getFileMap().keySet().iterator().next();
if (singleKey != null && (singleKey.equalsIgnoreCase(fieldName) ||
singleKey.contains("q_" + qid) ||
singleKey.contains("file_" + qid) ||
singleKey.contains("file" + qid) ||
singleKey.contains("f_" + qid) ||
singleKey.contains("f" + qid) ||
singleKey.contains("q" + qid) ||
singleKey.equalsIgnoreCase("files") ||
singleKey.equalsIgnoreCase("file") ||
singleKey.equalsIgnoreCase("image"))) {
file = fileRequest.getFileMap().values().iterator().next();
}
}
}
if (file != null && !file.isEmpty()) {
String uploadedPath = uploadSurveyFile(file, qEnglish, surveyId);
if (uploadedPath != null && !uploadedPath.startsWith("Failed")) {
answer = uploadedPath;
// System.out.println("--- Image Uploaded --- QID: " + qid + " | FieldName: " +
// fieldName + " | File: " + file.getOriginalFilename() + " | Path: " +
// uploadedPath);
}
}
}
boolean isNotWilling = false;
if (qid != null && qid == 1) {
String trimmed = answer.trim();
if ("38".equals(trimmed) || "Not willing to respond (mark them)".equalsIgnoreCase(trimmed)) {
isNotWilling = true;
}
}
if (isNotWilling) {
jdbcHomeLessSurveyTemplate.update(insertparticipateSql, qid, answer, othersAnswer, surveyId,
cid, cby,
parentAnswerId);
// System.out.println("--- DB SAVE (Participate) --- QID: " + qid + " |
// FieldName: " + fieldName + " | Answer: " + answer + " | OthersAnswer: " +
// othersAnswer);
} else {
if (!hasNotWillingResponse) {
jdbcHomeLessSurveyTemplate.update(insertSql, qid, answer, othersAnswer, surveyId, cid, cby,
parentAnswerId);
// System.out.println("--- DB SAVE (Response) --- QID: " + qid + " | FieldName:
// " + fieldName + " | Answer: " + answer + " | OthersAnswer: " + othersAnswer);
}
}
}
}
// Insert placeholder responses for all other active categories if they do not
// exist
if (!hasNotWillingResponse) {
try {
String catSql = "SELECT id FROM question_category_master WHERE isactive = 1 AND isdelete = 0";
List<Map<String, Object>> allCats = jdbcHomeLessSurveyTemplate.queryForList(catSql);
for (Map<String, Object> catMap : allCats) {
Object otherCidObj = catMap.get("id");
if (otherCidObj != null) {
String otherCid = otherCidObj.toString();
if (!otherCid.equals(cid)) {
String checkExistSql = "SELECT COUNT(*) FROM homeless_survey_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0";
Integer existCount = jdbcHomeLessSurveyTemplate.queryForObject(checkExistSql,
Integer.class,
surveyId, otherCid);
if (existCount == null || existCount == 0) {
String otherQSql = "SELECT qid FROM homeless_survey_questions_master WHERE cid = ? AND isactive = 1 AND isdelete = 0";
List<Integer> otherQids = jdbcHomeLessSurveyTemplate.queryForList(otherQSql,
Integer.class, otherCid);
for (Integer otherQid : otherQids) {
jdbcHomeLessSurveyTemplate.update(insertSql, otherQid, null, null, surveyId,
otherCid, cby, 0);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Error inserting placeholder survey responses: " + ex.getMessage());
}
}
result.put("status", true);
result.put("message", "Survey responses saved successfully");
result.put("survey_id", surveyId);
} catch (Exception e) {
e.printStackTrace();
result.put("status", false);
result.put("message", "Error saving survey responses: " + e.getMessage());
}
return result;
}
private String uploadSurveyFile(MultipartFile file, String qEnglish, String surveyId) {
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("homelesssurvey_document_foldername");
// if (serviceFolderName == null || serviceFolderName.trim().isEmpty()) {
// serviceFolderName = "homelesssurvey_image/";
// }
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
String finalUploadDir = uploadDirectory + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId;
try {
Path directoryPath = Paths.get(finalUploadDir);
if (!Files.exists(directoryPath)) {
Files.createDirectories(directoryPath);
}
String cleanName = qEnglish.replaceAll("[^a-zA-Z0-9]", "_").replaceAll("_+", "_");
String datetimetxt = DateTimeUtil.getCurrentDateTime() + "_" + generateRandomString();
String fileName = cleanName + "_" + datetimetxt + "_" + file.getOriginalFilename();
fileName = fileName.replaceAll("\\s+", "");
String filePath = finalUploadDir + "/" + fileName;
String relativePath = "/" + serviceFolderName + year + "/" + month + "/" + date + "/" + surveyId + "/"
+ fileName;
Path path = Paths.get(filePath);
byte[] bytes = file.getBytes();
try {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
if (image != null) {
byte[] compressedBytes = compressImage(image, 0.5f);
Files.write(path, compressedBytes);
} else {
Files.write(path, bytes);
}
} catch (Exception e) {
Files.write(path, bytes);
}
return relativePath;
} catch (IOException e) {
e.printStackTrace();
return "Failed to save file: " + e.getMessage();
}
}
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();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
public Map<String, Object> getCategoryStatus(String surveyId) {
Map<String, Object> result = new HashMap<>();
try {
// Check if the Profile category responses or surveyor location record exists
// for this surveyId
String checkProfileSql = "SELECT COUNT(*) FROM homeless_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0";
Integer profileCount = jdbcHomeLessSurveyTemplate.queryForObject(checkProfileSql, Integer.class, surveyId);
String checkLocSql = "SELECT COUNT(*) FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0";
Integer locCount = jdbcHomeLessSurveyTemplate.queryForObject(checkLocSql, Integer.class, surveyId);
if ((profileCount == null || profileCount == 0) && (locCount == null || locCount == 0)) {
result.put("status", false);
result.put("message",
"Profile not created for this survey ID. Please save the Profile category first.");
return result;
}
String catSql = "SELECT id, english_name, icon, orderby FROM question_category_master WHERE isactive=1 AND isdelete=0 ORDER BY orderby";
List<Map<String, Object>> categories = jdbcHomeLessSurveyTemplate.queryForList(catSql);
List<Map<String, Object>> dataList = new ArrayList<>();
for (Map<String, Object> cat : categories) {
Object cidObj = cat.get("id");
String cidStr = cidObj != null ? cidObj.toString() : "";
String responseSql = "SELECT COUNT(*) FROM (" +
" SELECT id FROM homeless_survey_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' "
+
" UNION ALL " +
" SELECT id FROM homeless_survey_participate_response WHERE survey_id = ? AND cid = ? AND isactive = 1 AND isdelete = 0 AND answer IS NOT NULL AND answer != '' "
+
") t";
Integer count = jdbcHomeLessSurveyTemplate.queryForObject(responseSql, Integer.class, surveyId, cidStr,
surveyId, cidStr);
Map<String, Object> statusMap = new HashMap<>();
statusMap.put("cid", cidObj);
statusMap.put("english_name", cat.get("english_name"));
statusMap.put("orderby", cat.get("orderby"));
statusMap.put("icon", cat.get("icon"));
statusMap.put("status", (count != null && count > 0) ? "Completed" : "Pending");
dataList.add(statusMap);
}
result.put("status", true);
result.put("data", dataList);
return result;
} catch (Exception e) {
e.printStackTrace();
result.put("status", false);
result.put("message", "Error fetching category status: " + e.getMessage());
return result;
}
}
public List<Map<String, Object>> getProfileCreatedList(String cby) {
List<Map<String, Object>> resultList = new ArrayList<>();
try {
String sql;
List<Object> args = new ArrayList<>();
if (cby != null && !cby.trim().isEmpty() && !cby.equalsIgnoreCase("null")) {
sql = "SELECT DISTINCT survey_id FROM homeless_survey_response WHERE cid = '1' AND cby = ? AND isactive = 1 AND isdelete = 0";
args.add(cby);
} else {
sql = "SELECT DISTINCT survey_id FROM homeless_survey_response WHERE cid = '1' AND isactive = 1 AND isdelete = 0";
}
List<String> surveyIds = jdbcHomeLessSurveyTemplate.queryForList(sql, args.toArray(), String.class);
for (String surveyId : surveyIds) {
Map<String, Object> profileMap = new LinkedHashMap<>();
profileMap.put("survey_id", surveyId);
// Fetch Location Details
String locSql = "SELECT zone, ward, latitude, longitude, address, loginId as cby, cdate FROM surveyor_location_details WHERE survey_id = ? AND is_active = 1 AND is_delete = 0 LIMIT 1";
List<Map<String, Object>> locData = jdbcHomeLessSurveyTemplate.queryForList(locSql, surveyId);
if (!locData.isEmpty()) {
Map<String, Object> loc = locData.get(0);
profileMap.put("cby", loc.get("cby"));
profileMap.put("cdate", loc.get("cdate"));
profileMap.put("zone", loc.get("zone"));
profileMap.put("ward", loc.get("ward"));
profileMap.put("latitude", loc.get("latitude"));
profileMap.put("longitude", loc.get("longitude"));
profileMap.put("address", loc.get("address"));
} else {
profileMap.put("zone", "");
profileMap.put("ward", "");
profileMap.put("latitude", "");
profileMap.put("longitude", "");
profileMap.put("address", "");
String fallbackSql = "SELECT cby, cdate FROM homeless_survey_response WHERE survey_id = ? AND cid = '1' AND isactive = 1 AND isdelete = 0 LIMIT 1";
List<Map<String, Object>> fallbackData = jdbcHomeLessSurveyTemplate.queryForList(fallbackSql,
surveyId);
if (!fallbackData.isEmpty()) {
profileMap.put("cby", fallbackData.get(0).get("cby"));
profileMap.put("cdate", fallbackData.get(0).get("cdate"));
} else {
profileMap.put("cby", "");
profileMap.put("cdate", "");
}
}
// Fetch Answers
String ansSql = "SELECT q.qid, q.field_name, q.question_type, q.q_english, q.master_table_name, r.answer, r.others_answer "
+
"FROM homeless_survey_response r " +
"JOIN homeless_survey_questions_master q ON r.qid = q.qid " +
"WHERE r.survey_id = ? AND r.cid = '1' AND r.isactive = 1 AND r.isdelete = 0 " +
"AND ((q.isactive = 1 AND q.isdelete = 0) OR (q.cid = '1' AND q.field_name IN ('q2', 'q78', 'q11', 'q8', 'q9', 'q10', 'q77')))";
List<Map<String, Object>> ansData = jdbcHomeLessSurveyTemplate.queryForList(ansSql, surveyId);
List<Map<String, Object>> answersList = new ArrayList<>();
String fileBaseUrlVal = environment.getProperty("fileBaseUrl");
if (fileBaseUrlVal == null) {
fileBaseUrlVal = "";
}
List<String> allowedFields = java.util.Arrays.asList("q2", "q78", "q11", "q8", "q9", "q10", "q77");
for (Map<String, Object> ans : ansData) {
String fieldName = (String) ans.get("field_name");
if (fieldName != null && allowedFields.contains(fieldName)) {
Integer qid = (Integer) ans.get("qid");
String qEnglish = (String) ans.get("q_english");
String masterTable = (String) ans.get("master_table_name");
String questionType = (String) ans.get("question_type");
String answerVal = (String) ans.get("answer");
String resolvedValue = answerVal != null ? answerVal : "";
if (answerVal != null && !answerVal.trim().isEmpty()) {
// Try to resolve the option ID to its english name
try {
int optionId = Integer.parseInt(answerVal.trim());
if (masterTable != null && !masterTable.trim().isEmpty()) {
String query = "SELECT english_name FROM " + masterTable + " WHERE id = ? LIMIT 1";
List<String> names = jdbcHomeLessSurveyTemplate.queryForList(query, String.class,
optionId);
if (!names.isEmpty()) {
resolvedValue = names.get(0);
}
} else {
String query = "SELECT answer FROM homeless_survey_answer_master WHERE qid = ? AND id = ? LIMIT 1";
List<String> names = jdbcHomeLessSurveyTemplate.queryForList(query, String.class,
qid, optionId);
if (!names.isEmpty()) {
resolvedValue = names.get(0);
}
}
} catch (NumberFormatException e) {
// Keep original value if not a valid number ID
}
}
if (resolvedValue != null && !resolvedValue.isEmpty() && questionType != null &&
(questionType.equalsIgnoreCase("image") || questionType.equalsIgnoreCase("file"))) {
resolvedValue = fileBaseUrlVal + "/gccofficialapp/files" + resolvedValue;
}
Map<String, Object> ansMap = new LinkedHashMap<>();
ansMap.put("question", qEnglish != null ? qEnglish : "");
ansMap.put("field_name", fieldName);
ansMap.put("field_value", resolvedValue != null ? resolvedValue : "");
answersList.add(ansMap);
String othersVal = (String) ans.get("others_answer");
if (othersVal != null && !othersVal.isEmpty()) {
Map<String, Object> othersMap = new LinkedHashMap<>();
othersMap.put("question", "Please specify");
othersMap.put("field_name", fieldName + "_other");
othersMap.put("field_value", othersVal);
answersList.add(othersMap);
}
}
}
profileMap.put("answers", answersList);
resultList.add(profileMap);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return resultList;
}
}

48
src/main/java/in/gov/chennaicorporation/mobileservice/gccMobileMenus/controller/MobileMenusApiController.java

@ -0,0 +1,48 @@
package in.gov.chennaicorporation.mobileservice.gccMobileMenus.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.mobileservice.gccMobileMenus.service.MobileMenusService;
@RequestMapping("/gccofficialapp/api/gccmobilemenu")
@RestController("gccofficialappgccmobilemenuConroller")
public class MobileMenusApiController {
@Autowired
private MobileMenusService mobileMenusService;
@GetMapping({ "/versionCheck" })
public List<?> versionCheck() {
return mobileMenusService.versionCheck();
}
@GetMapping("/getmenus")
public List<Map<String,Object>> getMenus(
@RequestParam Integer login_id){
return mobileMenusService.getMenus(login_id);
}
@GetMapping("/getsubmenus")
public List<Map<String,Object>> getSubMenus(
@RequestParam Integer login_id,
@RequestParam Integer menu_id){
return mobileMenusService.getSubMenus(login_id, menu_id);
}
}

88
src/main/java/in/gov/chennaicorporation/mobileservice/gccMobileMenus/service/MobileMenusService.java

@ -0,0 +1,88 @@
package in.gov.chennaicorporation.mobileservice.gccMobileMenus.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MobileMenusService {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlGccMobileMenuDataSource") DataSource gccMobiledenusDataSource) {
this.jdbcTemplate = new JdbcTemplate(gccMobiledenusDataSource);
}
@Transactional
public List<Map<String, Object>> versionCheck() {
String sqlQuery = " SELECT * FROM app_version WHERE isactive=1 LIMIT 1 ";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlQuery);
return result;
}
public List<Map<String,Object>> getMenus(Integer loginId){
String sql = " SELECT DISTINCT "
+ " mm.menu_id, "
+ " mm.menu_name, "
+ " mm.menu_icon, "
+ " mm.orderby "
+ " FROM menu_master mm "
+ " INNER JOIN usergroup_menu_mapping ugmm "
+ " ON mm.menu_id = ugmm.menu_id "
+ " INNER JOIN usergroup_login_mapping uglm "
+ " ON FIND_IN_SET(ugmm.usergroup_id, uglm.usergroup_id) "
+ " WHERE uglm.login_id = ? "
+ " AND uglm.isactive = 1 "
+ " AND uglm.isdelete = 0 "
+ " AND ugmm.isactive = 1 "
+ " AND ugmm.isdelete = 0 "
+ " AND mm.isactive = 1 "
+ " AND mm.isdelete = 0 "
+ " ORDER BY mm.orderby ";
return jdbcTemplate.queryForList(sql, loginId);
}
public List<Map<String,Object>> getSubMenus(
Integer loginId,
Integer menuId){
String sql = " SELECT DISTINCT "
+ " sm.submenu_id, "
+ " sm.submenu_name, "
+ " sm.submenu_icon, "
+ " sm.menu_id, "
+ " sm.orderby "
+ " FROM submenu_master sm "
+ " INNER JOIN usergroup_submenu_mapping ugsm "
+ " ON sm.submenu_id = ugsm.submenu_id "
+ " INNER JOIN usergroup_login_mapping uglm "
+ " ON FIND_IN_SET(ugsm.usergroup_id, uglm.usergroup_id) "
+ " WHERE uglm.login_id = ? "
+ " AND sm.menu_id = ? "
+ " AND uglm.isactive = 1 "
+ " AND uglm.isdelete = 0 "
+ " AND ugsm.isactive = 1 "
+ " AND ugsm.isdelete = 0 "
+ " AND sm.isactive = 1 "
+ " AND sm.isdelete = 0 "
+ " ORDER BY sm.orderby ";
return jdbcTemplate.queryForList(sql, loginId, menuId);
}
}

80
src/main/java/in/gov/chennaicorporation/mobileservice/gccSCP/controller/SCPController.java

@ -0,0 +1,80 @@
package in.gov.chennaicorporation.mobileservice.gccSCP.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.gccSCP.service.SCPService;
@RequestMapping("/gccofficialapp/api/scp/")
@RestController("gccofficialappsscp")
public class SCPController {
@Autowired
private SCPService scpService;
@GetMapping(value="/getSCPListForMap")
public List<?> getSCPListForMap(
@RequestParam(value="loginId", required = true) String cby,
@RequestParam(value="streetid", required = true) String streetid
){
return scpService.getSCPListForMap(cby,streetid);
}
@PostMapping("/saveActivity")
public List<?> saveActivity(
@RequestParam(value = "asset_id", required = true) String asset_id,
@RequestParam(value = "grating", required = true) String grating,
@RequestParam(value = "file", required = true) MultipartFile file,
@RequestParam(value = "zone", required = true) String zone,
@RequestParam(value = "ward", required = true) String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam(value = "latitude", required = true) String latitude,
@RequestParam(value = "longitude", required = true) String longitude,
@RequestParam(value = "loginId", required = true) String loginId,
@RequestParam(value = "road_type", required = true) String road_type
) {
return scpService.saveActivity(
asset_id,
grating,
file,
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
road_type
);
}
@GetMapping(value="/getZoneReport")
public List<?> getZoneReport(
@RequestParam(value="loginId", required = true) String cby
){
return scpService.getZoneReport(cby);
}
@GetMapping(value="/getWardReport")
public List<?> getWardReport(
@RequestParam(value="loginId", required = true) String cby,
@RequestParam(value="zone", required = true) String zone
){
return scpService.getWardReport(cby,zone);
}
@GetMapping(value="/getStreetReport")
public List<?> getStreetReport(
@RequestParam(value="loginId", required = true) String cby,
@RequestParam(value="ward", required = true) String ward
){
return scpService.getStreetReport(cby,ward);
}
}

461
src/main/java/in/gov/chennaicorporation/mobileservice/gccSCP/service/SCPService.java

@ -0,0 +1,461 @@
package in.gov.chennaicorporation.mobileservice.gccSCP.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.PreparedStatement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class SCPService {
private JdbcTemplate jdbcSCPTemplate;
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("mysqlActivityDataSource") DataSource SCPDataSource) {
this.jdbcSCPTemplate = new JdbcTemplate(SCPDataSource);
}
@Autowired
public SCPService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, String id, MultipartFile file, String filetype) {
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("scp_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + filetype + "/" + 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();
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 + filetype + "/" + year + "/" + month + "/" + date + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
if(filetype.equalsIgnoreCase("image"))
{
// 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);
}
else {
// Write the bytes to the file
Files.write(path, bytes);
}
// Get current date & time
LocalDateTime now = LocalDateTime.now();
// Format date-time (optional)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Date: "+ now.format(formatter));
System.out.println("Activity: Pump");
System.out.println("File Type: " + filetype);
System.out.println("File Upload Path: " + filePath);
System.out.println("File Path: " + filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save file " + file.getOriginalFilename());
return "error";
}
}
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT `ward` FROM gcc_penalty_hoardings.`hoading_user_list` WHERE `userid` = ? AND `type` = ? LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcSCPTemplate.queryForList(sqlQuery, loginid, type);
// 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<Map<String, Object>> getSCPListForMap(String loginid, String streetid) {
//String ward = getWardByLoginId(loginid,"ae");
/*
String sqlQuery ="SELECT "
+ " al.*, "
+ " CONCAT('" + fileBaseUrl + "/gccofficialapp/files/asset_images/2/', al.image) AS imageUrl, "
+ " EXISTS ("
+ " SELECT 1 FROM `scp_grating_activity` aa "
+ " WHERE aa.asset_id = al.id "
+ " ) AS `activity_completed` "
+ "FROM asset_list al "
+ "WHERE al.category_id = 2 AND al.streetid = ? AND al.isactive=1 AND isdelete=0 ";
*/
String sqlQuery =
"SELECT " +
" al.*, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files/asset_images/2/', al.image) AS imageUrl, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', aa.file) AS fileUrl, " +
" aa.activity_id, " +
" aa.grating, " +
" aa.inby AS activity_by, " +
" DATE_FORMAT(aa.indate, '%d-%m-%Y') AS activity_date, " +
" aa.road_type, " +
" CASE WHEN aa.activity_id IS NOT NULL THEN 1 ELSE 0 END AS activity_completed " +
"FROM asset_list al " +
"LEFT JOIN ( " +
" SELECT a1.* " +
" FROM scp_grating_activity a1 " +
" INNER JOIN ( " +
" SELECT asset_id, MAX(indate) AS latest_indate " +
" FROM scp_grating_activity " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY asset_id " +
" ) a2 ON a1.asset_id = a2.asset_id AND a1.indate = a2.latest_indate " +
" WHERE a1.isactive=1 AND a1.isdelete=0 " +
") aa ON aa.asset_id = al.id " +
"WHERE al.category_id = 2 " +
" AND al.streetid = ? " +
" AND al.isactive=1 " +
" AND al.isdelete=0";
List<Map<String, Object>> Pumps = jdbcSCPTemplate.queryForList(sqlQuery, streetid);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Pump & Sump Map List.");
response.put("data", Pumps);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveActivity(
String asset_id,
String grating,
MultipartFile file,
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
String road_type
) {
String filetxt =asset_id;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
String activityimg = fileUpload(grating, filetxt, file, filetype);
if ("error".equalsIgnoreCase(activityimg)) {
response.put("status", "error");
response.put("message", "SCP activity image insert failed.");
result.add(response);
return result;
}
String insertBeforeSql = "INSERT INTO `scp_grating_activity` (asset_id, grating, file, zone, ward, street_name, street_id, latitude, longitude, inby, road_type) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
String insertSql = insertBeforeSql;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcSCPTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"activity_id"});
int i = 1;
ps.setString(i++, asset_id);
ps.setString(i++, grating);
ps.setString(i++, activityimg);
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
ps.setString(i++, road_type);
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("SCP", " insertId: " +lastInsertId);
response.put("status", "success");
response.put("message", "SCP activity inserted successfully.");
} else {
response.put("SCP", " insertId error!");
response.put("status", "error");
response.put("message", "SCP activity insert failed.");
}
result.add(response);
return result;
}
public List<Map<String, Object>> getZoneReport(String loginid) {
String sqlQuery ="SELECT "
+ " al.zone,"
+ " COUNT(DISTINCT al.id) AS total_scp,"
+ " COUNT(DISTINCT CASE WHEN aa.activity_id IS NOT NULL THEN al.id END) AS Completed,"
+ " COUNT(DISTINCT CASE WHEN aa.activity_id IS NULL THEN al.id END) AS Pending,"
+ " COUNT(DISTINCT CASE WHEN aa.grating = 'yes' THEN al.id END) AS yes,"
+ " COUNT(DISTINCT CASE WHEN aa.grating = 'no' THEN al.id END) AS no"
+ " "
+ "FROM asset_list al"
+ " "
+ "LEFT JOIN ("
+ " SELECT a1.*"
+ " FROM scp_grating_activity a1"
+ " INNER JOIN ("
+ " SELECT asset_id, MAX(indate) AS latest_indate"
+ " FROM scp_grating_activity"
+ " WHERE isactive=1 AND isdelete=0"
+ " GROUP BY asset_id"
+ " ) a2 ON a1.asset_id = a2.asset_id AND a1.indate = a2.latest_indate"
+ " WHERE a1.isactive=1 AND a1.isdelete=0"
+ ") aa ON aa.asset_id = al.id"
+ " "
+ "WHERE al.category_id = 2 AND al.isactive=1 AND al.isdelete=0"
+ " "
+ "GROUP BY al.zone "
+ "ORDER BY al.zone";
List<Map<String, Object>> Pumps = jdbcSCPTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Zone SCP List.");
response.put("data", Pumps);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getWardReport(String loginid, String zone) {
String sqlQuery ="SELECT "
+ " al.zone,al.ward,"
+ " COUNT(DISTINCT al.id) AS total_scp,"
+ " COUNT(DISTINCT CASE WHEN aa.activity_id IS NOT NULL THEN al.id END) AS Completed,"
+ " COUNT(DISTINCT CASE WHEN aa.activity_id IS NULL THEN al.id END) AS Pending,"
+ " COUNT(DISTINCT CASE WHEN aa.grating = 'yes' THEN al.id END) AS yes,"
+ " COUNT(DISTINCT CASE WHEN aa.grating = 'no' THEN al.id END) AS no"
+ " "
+ "FROM asset_list al"
+ " "
+ "LEFT JOIN ("
+ " SELECT a1.*"
+ " FROM scp_grating_activity a1"
+ " INNER JOIN ("
+ " SELECT asset_id, MAX(indate) AS latest_indate"
+ " FROM scp_grating_activity"
+ " WHERE isactive=1 AND isdelete=0"
+ " GROUP BY asset_id"
+ " ) a2 ON a1.asset_id = a2.asset_id AND a1.indate = a2.latest_indate"
+ " WHERE a1.isactive=1 AND a1.isdelete=0"
+ ") aa ON aa.asset_id = al.id"
+ " "
+ "WHERE al.category_id = 2 AND al.isactive=1 AND al.isdelete=0 AND al.zone=?"
+ " "
+ "GROUP BY al.zone,al.ward "
+ "ORDER BY al.zone,al.ward";
List<Map<String, Object>> Pumps = jdbcSCPTemplate.queryForList(sqlQuery,zone);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Ward SCP List.");
response.put("data", Pumps);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getStreetReport(String loginid, String ward) {
String sqlQuery =
"SELECT " +
" al.streetid, " +
" al.streetname, " +
" COUNT(DISTINCT al.id) AS total_scp, " +
" COUNT(DISTINCT CASE WHEN aa.activity_id IS NOT NULL THEN al.id END) AS Completed, " +
" COUNT(DISTINCT CASE WHEN aa.activity_id IS NULL THEN al.id END) AS Pending, " +
" COUNT(DISTINCT CASE WHEN aa.grating = 'yes' THEN al.id END) AS yes, " +
" COUNT(DISTINCT CASE WHEN aa.grating = 'no' THEN al.id END) AS no " +
"FROM asset_list al " +
"LEFT JOIN ( " +
" SELECT a1.* " +
" FROM scp_grating_activity a1 " +
" INNER JOIN ( " +
" SELECT asset_id, MAX(indate) AS latest_indate " +
" FROM scp_grating_activity " +
" WHERE isactive=1 AND isdelete=0 " +
" GROUP BY asset_id " +
" ) a2 ON a1.asset_id = a2.asset_id AND a1.indate = a2.latest_indate " +
" WHERE a1.isactive=1 AND a1.isdelete=0 " +
") aa ON aa.asset_id = al.id " +
"WHERE al.category_id = 2 AND al.isactive=1 AND al.isdelete=0 AND al.ward=? " +
"GROUP BY al.streetid, al.streetname " +
"ORDER BY al.streetname";
List<Map<String, Object>> streetReport = jdbcSCPTemplate.queryForList(sqlQuery, ward);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Street-level SCP List.");
response.put("data", streetReport);
return Collections.singletonList(response);
}
}

72
src/main/java/in/gov/chennaicorporation/mobileservice/gccSpecialVehicle/controller/VehicleController.java

@ -0,0 +1,72 @@
package in.gov.chennaicorporation.mobileservice.gccSpecialVehicle.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.gccSpecialVehicle.service.VehicleService;
@RequestMapping("/gccofficialapp/api/specialvehicle/")
@RestController("gccofficialappsspecialvehicle")
public class VehicleController {
@Autowired
private VehicleService vehicleService;
@GetMapping("/getVehicleList")
public List<?> getVehicleList(@RequestParam("loginId") String loginId){
return vehicleService.getVehicleList(loginId);
}
@PostMapping("/saveActivity")
public List<?> saveActivity(
@RequestParam("vehicle_id") String vehicle_id,
@RequestParam("file") MultipartFile file,
@RequestParam("video")MultipartFile video,
@RequestParam("zone") String zone,
@RequestParam("ward") String ward,
@RequestParam(value = "street_name", required = false) String street_name,
@RequestParam(value = "street_id", required = false) String street_id,
@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude,
@RequestParam("loginId") String loginId,
@RequestParam("action") String action,
@RequestParam(value = "beforeActivityId", required = false) String beforeActivityId,
@RequestParam(value = "clean_weight", required = false) String clean_weight
) {
return vehicleService.saveActivity(
vehicle_id,
file,
video,
zone,
ward,
street_name,
street_id,
latitude,
longitude,
loginId,
action,
beforeActivityId,
clean_weight
);
}
@GetMapping("/getVehicleReport")
public List<?> getVehicleReport(@RequestParam("loginId") String loginId){
return vehicleService.getVehicleReport(loginId);
}
@GetMapping("/getVehicleSummaryReport")
public List<?> getVehicleSummaryReport(
@RequestParam("loginId") String loginId,
@RequestParam("vehicle_id") String vehicle_id
){
return vehicleService.getVehicleSummaryReport(loginId,vehicle_id);
}
}

494
src/main/java/in/gov/chennaicorporation/mobileservice/gccSpecialVehicle/service/VehicleService.java

@ -0,0 +1,494 @@
package in.gov.chennaicorporation.mobileservice.gccSpecialVehicle.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.PreparedStatement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class VehicleService {
private JdbcTemplate jdbcVehicleTemplate;
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("mysqlGccSpecialVehicleSource") DataSource VehicleDataSource) {
this.jdbcVehicleTemplate = new JdbcTemplate(VehicleDataSource);
}
@Autowired
public VehicleService(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 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();
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();
}
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// Check if the inputDate is not null or blank
if (inputDate != null && !inputDate.isBlank()) {
try {
// Define the input and output date formats
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Parse the input date string to LocalDate
LocalDate date = LocalDate.parse(inputDate, inputFormatter);
// Add the specified number of days to the date if 'add' is greater than 0
if (add > 0) {
date = date.plusDays(add);
}
// Format the date to the new format
return date.format(outputFormatter);
} catch (DateTimeParseException e) {
// Handle the case where the input date is invalid
System.out.println("Invalid date format: " + inputDate);
return "";
}
} else {
return "";
}
}
public String fileUpload(String name, String id, MultipartFile file, String filetype) {
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("Vehicle_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var date = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + filetype + "/" + 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();
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 + filetype + "/" + year + "/" + month + "/" + date + "/" + fileName;
// Create a new Path object
Path path = Paths.get(filePath);
// Get the bytes of the file
byte[] bytes = file.getBytes();
if(filetype.equalsIgnoreCase("image"))
{
// 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);
}
else {
// Write the bytes to the file
Files.write(path, bytes);
}
// Get current date & time
LocalDateTime now = LocalDateTime.now();
// Format date-time (optional)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("Date: "+ now.format(formatter));
System.out.println("Activity: Special Vehicle");
System.out.println("File Type: " + filetype);
System.out.println("File Upload Path: " + filePath);
System.out.println("File Path: " + filepath_txt);
return filepath_txt;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save file " + file.getOriginalFilename());
return "error";
}
}
public String getWardByLoginId(String loginid, String type) {
String sqlQuery = "SELECT `ward` FROM gcc_penalty_hoardings.`hoading_user_list` WHERE `userid` = ? AND `type` = ? LIMIT 1";
// Query the database using queryForList
List<Map<String, Object>> results = jdbcVehicleTemplate.queryForList(sqlQuery, loginid, type);
// 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<Map<String, Object>> getVehicleList(String loginid) {
String sqlVehicle = "SELECT * FROM vehicle_master WHERE isactive = 1 AND isdelete=0";
List<Map<String, Object>> vehicles = jdbcVehicleTemplate.queryForList(sqlVehicle);
List<Map<String, Object>> finalList = new ArrayList<>();
for (Map<String, Object> vehicle : vehicles) {
Map<String, Object> vehicleResponse = new HashMap<>(vehicle);
String vehicleId = vehicle.get("vehicle_id").toString();
String beforeActivityId = "0";
// === 1. BEFORE ACTIVITY ===
String sqlBefore = "SELECT *, "
+ "DATE_FORMAT(indate, '%d-%m-%Y') AS formatted_indate,"
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `img_file`) AS img_file_url, "
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `video_file`) AS video_file_url "
+ "FROM before_activity WHERE vehicle_id = ? AND isactive=1 AND isdelete=0 "
+ "ORDER BY activity_id DESC LIMIT 1";
List<Map<String, Object>> beforeActivities = jdbcVehicleTemplate.queryForList(sqlBefore, vehicleId);
Map<String, Object> beforeData = new HashMap<>();
if (!beforeActivities.isEmpty()) {
beforeActivityId = beforeActivities.get(0).get("activity_id").toString();
beforeData.put("status", "Completed");
beforeData.put("details", beforeActivities);
} else {
beforeData.put("status", "Pending");
beforeData.put("details", Collections.emptyList());
}
// === 2. AFTER ACTIVITY ===
String sqlAfter = "SELECT *, "
+ "DATE_FORMAT(indate, '%d-%m-%Y') AS formatted_indate, "
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `img_file`) AS img_file_url, "
+ "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', `video_file`) AS video_file_url "
+ "FROM after_activity WHERE vehicle_id = ? AND before_activity_id = ? AND isactive=1 AND isdelete=0 "
+ "ORDER BY activity_id DESC LIMIT 1";
List<Map<String, Object>> afterActivities = jdbcVehicleTemplate.queryForList(sqlAfter, vehicleId, beforeActivityId);
Map<String, Object> afterData = new HashMap<>();
if (!afterActivities.isEmpty()) {
afterData.put("status", "Completed");
afterData.put("details", afterActivities);
} else {
afterData.put("status", "Pending");
afterData.put("details", Collections.emptyList());
}
// === 3. OVERALL STATUS ===
String overallStatus = (!beforeActivities.isEmpty() && !afterActivities.isEmpty())
? "Completed"
: "Pending";
vehicleResponse.put("status", overallStatus);
vehicleResponse.put("before", beforeData);
vehicleResponse.put("after", afterData);
finalList.add(vehicleResponse);
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Vehicle List.");
response.put("data", finalList);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveActivity(
String vehicle_id,
MultipartFile file,
MultipartFile video,
String zone,
String ward,
String street_name,
String street_id,
String latitude,
String longitude,
String inby,
String action,
String beforeActivityId,
String clean_weight
) {
String filetxt =vehicle_id;
Map<String, Object> response = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<>();
// For Image
String filetype = "image";
String activityimg = fileUpload(action, filetxt, file, filetype);
if ("error".equalsIgnoreCase(activityimg)) {
response.put("status", "error");
response.put("message", "Special vehicle activity image insert failed.");
result.add(response);
return result;
}
// For Video
filetype = "video";
String activityvideo = fileUpload(action, filetxt, video, filetype);
if ("error".equalsIgnoreCase(activityvideo)) {
response.put("status", "error");
response.put("message", "Special vehicle activity video insert failed.");
result.add(response);
return result;
}
String insertBeforeSql = "INSERT INTO before_activity(vehicle_id, img_file, video_file, zone, ward, street_name, street_id, latitude, longitude, inby) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
String insertAfterSql = "INSERT INTO after_activity(vehicle_id, img_file, video_file, zone, ward, street_name, street_id, latitude, longitude, inby, before_activity_id, clean_weight) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
String insertSql = "before".equalsIgnoreCase(action) ? insertBeforeSql : insertAfterSql;
KeyHolder keyHolder = new GeneratedKeyHolder();
int affectedRows = jdbcVehicleTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"activity_id"});
int i = 1;
ps.setString(i++, vehicle_id);
ps.setString(i++, activityimg);
ps.setString(i++, activityvideo);
ps.setString(i++, zone);
ps.setString(i++, ward);
ps.setString(i++, street_name);
ps.setString(i++, street_id);
ps.setString(i++, latitude);
ps.setString(i++, longitude);
ps.setString(i++, inby);
if ("after".equalsIgnoreCase(action)) {
ps.setString(i++, beforeActivityId);
ps.setString(i++, clean_weight);
}
return ps;
}, keyHolder);
if (affectedRows > 0) {
int lastInsertId = keyHolder.getKey().intValue();
response.put("Special vehicle", action + " insertId: " +lastInsertId);
response.put("status", "success");
response.put("message", "Pump & Sump " + action + " activity inserted successfully.");
} else {
response.put("Special vehicle", action + " insertId error!");
response.put("status", "error");
response.put("message", "Special vehicle " + action + " activity insert failed.");
}
result.add(response);
return result;
}
public List<Map<String, Object>> getVehicleReport(String loginid) {
String sqlQuery =
"SELECT "
+ " vm.vehicle_id,"
+ " vm.vehicle_type,"
+ " vm.vehicle_no,"
+ " vm.vehicle_zone,"
+ " vm.vehicle_ward,"
+ " "
+ " COALESCE(COUNT(DISTINCT ba.activity_id), 0) AS Started_Count,"
+ " "
+ " COALESCE(COUNT(DISTINCT aa.activity_id), 0) AS End_Count,"
+ " "
+ " COALESCE(SUM(aa.clean_weight), 0) AS Total_Clean_Weight"
+ " "
+ "FROM vehicle_master vm "
+ "LEFT JOIN before_activity ba "
+ " ON ba.vehicle_id = vm.vehicle_id "
+ " AND ba.isactive = 1 "
+ " AND ba.isdelete = 0 "
+ "LEFT JOIN after_activity aa "
+ " ON aa.vehicle_id = vm.vehicle_id "
+ " AND aa.isactive = 1 "
+ " AND aa.isdelete = 0"
+ " "
+ "WHERE vm.isactive = 1"
+ " AND vm.isdelete = 0"
+ " "
+ "GROUP BY "
+ " vm.vehicle_id,"
+ " vm.vehicle_type,"
+ " vm.vehicle_no,"
+ " vm.vehicle_zone,"
+ " vm.vehicle_ward "
+ "ORDER BY "
+ " vm.vehicle_zone, vm.vehicle_ward, vm.vehicle_no";
List<Map<String, Object>> vechicleReport = jdbcVehicleTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Special Vehicle List.");
response.put("data", vechicleReport);
return Collections.singletonList(response);
}
public List<Map<String, Object>> getVehicleSummaryReport(String loginid, String vehicle_id) {
String sqlQuery =
"SELECT " +
" vm.vehicle_id, " +
" vm.vehicle_type, " +
" vm.vehicle_no, " +
" vm.vehicle_zone, " +
" vm.vehicle_ward, " +
" ba.activity_id AS start_activity_id, " +
" ba.indate AS start_date, " +
" ba.img_file AS start_img, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', ba.img_file) AS start_img_file_url, " +
" ba.video_file AS start_video, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', ba.video_file) AS start_video_file_url, " +
" aa.activity_id AS end_activity_id, " +
" aa.indate AS end_date, " +
" aa.img_file AS end_img, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', aa.img_file) AS end_img_file_url, " +
" aa.video_file AS end_video, " +
" CONCAT('" + fileBaseUrl + "/gccofficialapp/files', aa.video_file) AS end_video_file_url, " +
" COALESCE(aa.clean_weight, 0) AS clean_weight " +
"FROM vehicle_master vm " +
"LEFT JOIN before_activity ba " +
" ON ba.vehicle_id = vm.vehicle_id " +
" AND ba.isactive = 1 " +
" AND ba.isdelete = 0 " +
"LEFT JOIN after_activity aa " +
" ON aa.before_activity_id = ba.activity_id " +
" AND aa.vehicle_id = vm.vehicle_id " +
" AND aa.isactive = 1 " +
" AND aa.isdelete = 0 " +
"WHERE vm.isactive = 1 " +
" AND vm.isdelete = 0 " +
(vehicle_id != null && !vehicle_id.isBlank() ? " AND vm.vehicle_id = ? " : "") +
"ORDER BY vm.vehicle_zone, vm.vehicle_ward, vm.vehicle_no, ba.indate";
List<Map<String, Object>> vehicleReport;
if (vehicle_id != null && !vehicle_id.isBlank()) {
vehicleReport = jdbcVehicleTemplate.queryForList(sqlQuery, vehicle_id);
} else {
vehicleReport = jdbcVehicleTemplate.queryForList(sqlQuery);
}
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Vehicle Start-End Activity Report");
response.put("data", vehicleReport);
return Collections.singletonList(response);
}
}

313
src/main/java/in/gov/chennaicorporation/mobileservice/gccTenements/controller/TenementController.java

@ -0,0 +1,313 @@
package in.gov.chennaicorporation.mobileservice.gccTenements.controller;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.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.gccTenements.service.TenementService;
@RequestMapping("/gccofficialapp/api/tenement")
@RestController("gccofficialapptenement")
public class TenementController {
@Autowired
private TenementService tenementService;
@GetMapping("/getTenementsListByWard")
public Map<String, Object> getTenementsListByWard(@RequestParam(value = "loginid") String loginid,
@RequestParam(value = "type", required = false) String type) {
return tenementService.getTenementsListByWard(loginid, type);
}
@PostMapping("/saveAsset")
public ResponseEntity<Map<String, Object>> saveAsset(
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String address,
@RequestParam String am_id,
@RequestParam String name,
@RequestParam String cby,
@RequestParam(required = false) MultipartFile image) {
return ResponseEntity.ok(
tenementService.saveAsset(zone, ward, latitude, longitude,
address, am_id, name, cby, image));
}
/*
* @GetMapping("/getAssetListByRadius")
* public ResponseEntity<List<Map<String, Object>>> getAssetListByRadius(
*
* @RequestParam String latitude,
*
* @RequestParam String longitude) {
*
* return ResponseEntity.ok(
* tenementService.getAssetListByRadius(
* latitude,
* longitude));
* }
*/
@GetMapping("/getAssetListByRadius")
public Map<String, Object> getAssetListByRadius(
@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude) {
return tenementService.getAssetListByRadius(
latitude,
longitude);
}
@PostMapping("/saveIssue")
public ResponseEntity<Map<String, Object>> saveIssue(
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String assetlist_id,
@RequestParam MultipartFile before_image,
@RequestParam String radius,
@RequestParam String am_id,
@RequestParam String cby,
@RequestParam String remarks) {
return ResponseEntity.ok(
tenementService.saveIssue(
zone,
ward,
latitude,
longitude,
assetlist_id,
before_image,
radius,
am_id,
cby,
remarks));
}
@PostMapping("/saveIssueCompletion")
public Map<String, Object> saveIssueCompletion(
@RequestParam String issuelist1_id,
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String assetlist_id,
@RequestParam MultipartFile after_image,
@RequestParam String remarks,
@RequestParam String radius,
@RequestParam String am_id,
@RequestParam String cby) {
return tenementService.saveIssueCompletion(
issuelist1_id,
zone,
ward,
latitude,
longitude,
assetlist_id,
after_image,
remarks,
radius,
am_id,
cby);
}
@PostMapping("/saveIssueVerification")
public ResponseEntity<Map<String, Object>> saveIssueVerification(
@RequestParam String issuelist1_id,
@RequestParam String issuelist2_id,
@RequestParam String zone,
@RequestParam String ward,
@RequestParam String latitude,
@RequestParam String longitude,
@RequestParam String assetlist_id,
@RequestParam String remarks,
@RequestParam String radius,
@RequestParam String am_id,
@RequestParam(required = false) MultipartFile verify_image,
@RequestParam String cby,
@RequestParam(required = false) String status) {
return ResponseEntity.ok(
tenementService.saveIssueVerification(
issuelist1_id,
issuelist2_id,
zone,
ward,
latitude,
longitude,
assetlist_id,
remarks,
radius,
am_id,
verify_image,
cby,status));
}
@GetMapping("/getCreatedIssueList")
public Map<String, Object> getCreatedIssueList(
@RequestParam(required = false) String loginid, String ward) {
return tenementService.getCreatedIssueList(loginid, ward);
}
@GetMapping("/getIssueVerificationList")
public Map<String, Object> getIssueVerificationList(
@RequestParam(required = false) String loginid, @RequestParam(required = false) String ward) {
return tenementService.getIssueVerificationList(loginid, ward);
}
@GetMapping("/getZoneWiseReport")
public Map<String, Object> getZoneWiseReport(
@RequestParam String fromDate,
@RequestParam String toDate) {
// ✅ convert dd-MM-yyyy → yyyy-MM-dd
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedFromDate = LocalDate.parse(fromDate, inputFormatter)
.format(outputFormatter);
String formattedToDate = LocalDate.parse(toDate, inputFormatter)
.format(outputFormatter);
return tenementService.getZoneWiseReport(
formattedFromDate,
formattedToDate);
}
@GetMapping("/getWardWiseReport")
public Map<String, Object> getWardWiseReport(
@RequestParam String zone,
@RequestParam String fromDate,
@RequestParam String toDate) {
// ✅ convert dd-MM-yyyy to yyyy-MM-dd
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedFromDate = LocalDate.parse(fromDate, inputFormatter)
.format(outputFormatter);
String formattedToDate = LocalDate.parse(toDate, inputFormatter)
.format(outputFormatter);
return tenementService.getWardWiseReport(
zone,
formattedFromDate,
formattedToDate);
}
@GetMapping("/getSchemeWiseReport")
public Map<String, Object> getSchemeWiseReport(
@RequestParam String ward,
@RequestParam String fromDate,
@RequestParam String toDate) {
// ✅ dd-MM-yyyy → yyyy-MM-dd
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedFromDate = LocalDate.parse(fromDate, inputFormatter)
.format(outputFormatter);
String formattedToDate = LocalDate.parse(toDate, inputFormatter)
.format(outputFormatter);
return tenementService.getSchemeWiseReport(
ward,
formattedFromDate,
formattedToDate);
}
/*
* @GetMapping("/getComplaintDetails")
* public Map<String, Object> getComplaintDetails(
*
* @RequestParam String ward,
*
* @RequestParam String status,
*
* @RequestParam String fromDate,
*
* @RequestParam String toDate) {
*
* // ✅ convert dd-MM-yyyy → yyyy-MM-dd
* DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
*
* DateTimeFormatter outputFormatter =
* DateTimeFormatter.ofPattern("yyyy-MM-dd");
*
* String formattedFromDate = LocalDate.parse(fromDate, inputFormatter)
* .format(outputFormatter);
*
* String formattedToDate = LocalDate.parse(toDate, inputFormatter)
* .format(outputFormatter);
*
* return tenementService.getComplaintDetails(
* ward,
* status,
* formattedFromDate,
* formattedToDate);
* }
*/
@GetMapping("/getComplaintDetails")
public Map<String, Object> getComplaintDetails(
@RequestParam String ward,
@RequestParam String schemeid,
@RequestParam String status,
@RequestParam String fromDate,
@RequestParam String toDate) {
// ✅ convert dd-MM-yyyy → yyyy-MM-dd
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedFromDate = LocalDate.parse(fromDate, inputFormatter)
.format(outputFormatter);
String formattedToDate = LocalDate.parse(toDate, inputFormatter)
.format(outputFormatter);
return tenementService.getComplaintDetails(
ward,
schemeid,
status,
formattedFromDate,
formattedToDate);
}
}

2785
src/main/java/in/gov/chennaicorporation/mobileservice/gccTenements/service/TenementService.java
File diff suppressed because it is too large
View File

181
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIActivityController.java

@ -0,0 +1,181 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.gccactivity.service.Activity;
@RequestMapping("/gccofficialapp/api/")
@RestController("gccofficialappActivityRest")
public class APIActivityController {
@Autowired
private Activity activity;
@GetMapping(value="/asset/getActivityCategory")
public List<?> getActivityCategory(@RequestParam(value = "departmentId", required = false) String departmentId){
return activity.getActivityCategory(departmentId);
}
@GetMapping(value="/asset/checkAssetExistsCount")
public Map<String, Object> checkAssetExistsCount(
@RequestParam(value = "categoryId", required = false) String categoryId,
@RequestParam(value = "streetId", required = false) String streetId,
@RequestParam(value = "latitude", required = false) String latitude,
@RequestParam(value = "longitude", required = false) String longitude
){
int count = activity.checkAssetExistsCount(categoryId, streetId, latitude, longitude);
Map<String, Object> response = new HashMap<>();
response.put("count", count);
return response;
}
@PostMapping(value="/asset/save")
public List<?> saveAsset(@RequestParam MultiValueMap<String, String> formData,
@RequestParam("assetTypeId") String assetTypeId,
@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude,
@RequestParam("zone") String zone,
@RequestParam("ward") String ward,
@RequestParam("streeId") String streeId,
@RequestParam("streetName") String streetName,
@RequestParam("loginId") String loginId,
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "file", required = false) MultipartFile file
) {
return activity.saveAsset(formData, assetTypeId, latitude, longitude, zone, ward, streeId, streetName, loginId, name, file);
}
@GetMapping(value="/asset/loadAssetlistbyStreetId")
public List<?> loadAssetlistbyStreetId(@RequestParam("assetTypeId") String assetTypeId,@RequestParam("streetId") String streetId){
return activity.loadAssetlistbyStreetId(assetTypeId,streetId);
}
@GetMapping(value="/asset/loadAssetQuestionlistbyAssetTypeId")
public List<?> loadAssetQuestionlistbyAssetTypeId(@RequestParam("assetTypeId") String assetTypeId){
return activity.loadAssetQuestionlistbyAssetTypeId(assetTypeId);
}
@PostMapping(value="/asset/saveAssetAction")
public List<?> saveAssetAction(@RequestParam MultiValueMap<String, String> formData,
@RequestParam("catId") String catId,
@RequestParam("assetId") String assetId,
@RequestParam("remarks") String remarks,
@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude,
@RequestParam(value = "loginId", required = false) String loginId,
@RequestParam("feedbackId") String feedbackId,
@RequestParam(value = "before_file", required = false) MultipartFile beforeFile,
@RequestParam(value = "after_file", required = false) MultipartFile afterFile
) {
return activity.saveAssetAction(formData, catId, assetId, remarks, latitude, longitude, loginId, feedbackId, beforeFile, afterFile);
}
@GetMapping(value="/asset/loadAssetLastFeedbackHistoryByUser")
public List<?> loadAssetLastFeedbackHistoryByUser(@RequestParam("catId") String catId, @RequestParam("assetId") String assetId,@RequestParam("loginId") String loginId){
return activity.loadAssetLastFeedbackHistoryByUser(catId,assetId,loginId);
}
@GetMapping(value="/asset/loadAssetLastFeedbackByUser")
public List<?> loadAssetLastFeedbackByUser(@RequestParam("catId") String catId, @RequestParam("assetId") String assetId,@RequestParam("loginId") String loginId){
return activity.loadAssetLastFeedbackByUser(catId,assetId,loginId);
}
@GetMapping(value = "/asset/filterReports")
public Map<String, Object> filterReports(
@RequestParam(value = "assetTypeId", required = false) String assetTypeId,
@RequestParam(value = "fromDate", required = false) String fromDate,
@RequestParam(value = "toDate", required = false) String toDate,
@RequestParam(value = "zone", required = false) String zone,
@RequestParam(value = "ward", required = false) String ward,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value = "loginId", required = false) String loginId
){
return activity.filterReports(assetTypeId, fromDate, toDate, zone, ward, streetid,loginId);
}
@GetMapping(value = "/asset/scpfilterReports")
public Map<String, Object> scpfilterReports(
@RequestParam(value = "assetTypeId", required = false) String assetTypeId,
@RequestParam(value = "fromDate", required = false) String fromDate,
@RequestParam(value = "toDate", required = false) String toDate,
@RequestParam(value = "zone", required = false) String zone,
@RequestParam(value = "ward", required = false) String ward,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value = "loginId", required = false) String loginId
){
return activity.scpfilterReports(assetTypeId, fromDate, toDate, zone, ward, streetid,loginId);
}
@GetMapping(value = "/asset/scpReportAssetList")
public Map<String, Object> scpReportAssetList(
@RequestParam(value = "assetTypeId", required = false) String assetTypeId,
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "fromDate", required = false) String fromDate,
@RequestParam(value = "toDate", required = false) String toDate,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value = "loginId", required = false) String loginId
){
return activity.scpReportAssetList(assetTypeId, status, fromDate, toDate, streetid,loginId);
}
@GetMapping(value = "/asset/scpDeactivate")
public String scpDeactivate(
@RequestParam(value = "assetid", required = true) String id,
@RequestParam(value = "loginId", required = true) String loginId
){
return activity.scpDeactivate(id,loginId);
}
@GetMapping(value = "/asset/filterReportsByDate")
public List<Map<String, Object>> filterReportsByDate(
@RequestParam(value = "assetTypeId", required = false) String assetTypeId,
@RequestParam(value = "fromDate", required = false) String fromDate,
@RequestParam(value = "toDate", required = false) String toDate,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value = "loginId", required = false) String loginId
){
return activity.filterReportsByDate(assetTypeId, fromDate, toDate, fromDate, toDate, streetid, loginId);
}
@GetMapping(value = "/asset/dashboardFiletReport")
public List<Map<String, Object>> dashboardFiletReport(
@RequestParam(value = "assetTypeId", required = false) String assetTypeId,
@RequestParam(value = "fromDate", required = false) String fromDate,
@RequestParam(value = "toDate", required = false) String toDate,
@RequestParam(value = "zone", required = false) String zone,
@RequestParam(value = "ward", required = false) String ward,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value = "loginId", required = false) String loginId
){
return activity.dashboardFiletReport(assetTypeId, fromDate, toDate, zone, ward, streetid, loginId);
}
@GetMapping("/sendwhatsapp")
public String fetchApi() {
String url="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=7845014181&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome to GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+36837+.";
System.out.println(activity.getApiResponse());
return "test";
}
@GetMapping(value="/asset/encroachment_vendor_type")
public List<?> encroachment_vendor_type(){
return activity.encroachment_vendor_type();
}
@GetMapping(value="/asset/encroachment_vendor_items")
public List<?> encroachment_vendor_items(){
return activity.encroachment_vendor_items();
}
}

153
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIMassActivityController.java

@ -0,0 +1,153 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.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.gccactivity.service.MassClearn;
@RequestMapping("/gccofficialapp/api/massClearn/")
@RestController("massActivityRest")
public class APIMassActivityController {
@Autowired
private MassClearn massClearn;
@GetMapping(value="/getBrrRoadType")
public List<?> getBrrRoadType(@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getBrrRoadType(loginId);
}
@GetMapping(value="/getAllTaskList")
public List<?> getAllTaskList(@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getAllTaskList(loginId);
}
@GetMapping(value="/getTaskListByZone")
public List<?> getAllTaskListByZone(
@RequestParam("zone") String zone,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getTaskListByZone(zone,loginId);
}
@GetMapping(value="/getTaskListByWard")
public List<?> getTaskListByWard(
@RequestParam("ward") String ward,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getTaskListByWard(ward,loginId);
}
@GetMapping(value="/getTaskListByStreetId")
public List<?> getAllTaskListByStreetId(
@RequestParam("streeId") String streeId,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getAllTaskListByStreetId(streeId,loginId);
}
@GetMapping(value="/getTaskDatesInMonth")
public List<?> getTaskDatesInMonth(
@RequestParam("month") String month,
@RequestParam("year") String year,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getTaskDatesInMonth(month,year,loginId);
}
@GetMapping(value="/getAllTaskListByMonth")
public List<?> getAllTaskListByMonth(
@RequestParam("month") String month,
@RequestParam("year") String year,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getAllTaskListByMonth(month,year,loginId);
}
@GetMapping(value="/getAllTaskListByDate")
public List<?> getAllTaskListByDate(
@RequestParam("workdate") String workdate,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getAllTaskListByDate(workdate,loginId);
}
@GetMapping(value="/getTaskInfoBytaskId")
public List<?> getTaskInfoBytaskId(
@RequestParam("taskId") String taskId,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getTaskInfoBytaskId(taskId,loginId);
}
@GetMapping(value="/getTaskHistoryBytaskId")
public List<?> getTaskHistoryBytaskId(
@RequestParam("taskId") String taskId,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.getTaskHistoryBytaskId(taskId,loginId);
}
@PostMapping(value="/saveTask")
public List<?> saveTask(
@RequestParam("taskname") String taskname,
@RequestParam("roadtype") String roadtype,
@RequestParam("fromdate") String fromdate,
@RequestParam("todate") String todate,
@RequestParam("activitytype") String activitytype,
@RequestParam("zone") String zone,
@RequestParam("ward") String ward,
@RequestParam("streeId") String streeId,
@RequestParam("streetName") String streetName,
@RequestParam("taskremarks") String taskremarks,
@RequestParam("loginId") String loginId,
@RequestParam("streetlength") String streetlength
) {
return massClearn.saveTask(taskname, roadtype, fromdate, todate, activitytype, zone, ward, streeId, streetName, taskremarks, loginId, streetlength);
}
@GetMapping(value="/DeleteTask")
public List<?> DeleteTask(
@RequestParam("taskId") String taskId,
@RequestParam("loginId") String loginId){
return massClearn.DeleteTask(taskId,loginId);
}
@PostMapping(value="/saveTaskActivity")
public List<?> saveTaskActivity(
@RequestParam("taskid") String taskid,
@RequestParam("before_after") String before_after,
@RequestParam(value="activitystatus", required = false) String activitystatus,
@RequestParam("activity_id") String activity_id,
@RequestParam("remarks") String remarks,
@RequestParam("loginId") String loginId,
@RequestParam(value = "file", required = false) MultipartFile file) {
return massClearn.saveTaskActivity(taskid, before_after, activitystatus, activity_id, remarks, loginId, file);
}
@GetMapping(value="/reportByDate")
public List<?> reportByDate(
@RequestParam("fromdate") String fromdate,
@RequestParam("todate") String todate,
@RequestParam("roadtype") String roadtype,
@RequestParam(value = "zone", required = false) String zone,
@RequestParam(value = "ward", required = false) String ward,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status){
return massClearn.reportByDate(fromdate, todate, roadtype, zone, ward, streetid,loginId,status);
}
@GetMapping(value="/reportByStatus")
public List<?> reportByStatus(
@RequestParam("fromdate") String fromdate,
@RequestParam("todate") String todate,
@RequestParam("status") String status,
@RequestParam("roadtype") String roadtype,
@RequestParam(value = "zone", required = false) String zone,
@RequestParam(value = "ward", required = false) String ward,
@RequestParam(value = "streetid", required = false) String streetid,
@RequestParam(value="loginId", required = false) String loginId){
return massClearn.reportByStatus(fromdate, todate, status, roadtype, zone, ward, streetid,loginId);
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.controller;

1
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gccactivity;

1896
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java
File diff suppressed because it is too large
View File

34
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/DateTimeUtil.java

@ -0,0 +1,34 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.service;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Service
public class DateTimeUtil {
public static String getCurrentDateTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentYear() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentMonth() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentDay() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
public static String getCurrentDateTimeMysql() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return now.format(formatter);
}
}

712
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/MassClearn.java

@ -0,0 +1,712 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Service
public class MassClearn {
private JdbcTemplate jdbcActivityTemplate;
private final Environment environment;
private String fileBaseUrl;
@Autowired
public void setDataSource(@Qualifier("mysqlActivityDataSource") DataSource activityDataSource) {
this.jdbcActivityTemplate = new JdbcTemplate(activityDataSource);
}
@Autowired
public MassClearn(Environment environment) {
this.environment = environment;
this.fileBaseUrl=environment.getProperty("fileBaseUrl");
}
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();
}
@Transactional
public List<Map<String, Object>> getBrrRoadType(String loginId){
String sqlQuery = "SELECT * FROM `brr_road_type`";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getAllTaskList(String loginId){
String sqlQuery = "SELECT * FROM `brr_task` WHERE (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getTaskListByZone(
String zone,
String loginId){
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name FROM "
+ "`brr_task` WHERE `zone`=? AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, zone);
return result;
}
@Transactional
public List<Map<String, Object>> getTaskListByWard(
String ward,
String loginId){
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name "
+ "FROM `brr_task` WHERE `ward`=? AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, ward);
return result;
}
@Transactional
public List<Map<String, Object>> getAllTaskListByStreetId(
String streetId,
String loginId){
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name "
+ "FROM `brr_task` WHERE `streeId`=? AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, streetId);
return result;
}
@Transactional
public List<Map<String, Object>> getTaskDatesInMonth(
String month,
String year,
String loginId) {
String sqlQuery = "WITH RECURSIVE date_sequence AS ("
+ " SELECT DATE(CONCAT(?, '-', ?, '-01')) AS taskdate "
+ " UNION ALL "
+ " SELECT DATE_ADD(taskdate, INTERVAL 1 DAY) "
+ " FROM date_sequence "
+ " WHERE taskdate < LAST_DAY(CONCAT(?, '-', ?, '-01')) "
+ ") "
+ "SELECT "
+ " ds.taskdate, "
+ " bt.id AS taskid "
+ "FROM "
+ " date_sequence ds "
+ "JOIN "
+ " brr_task bt "
+ "ON ds.taskdate BETWEEN bt.fromdate AND bt.todate "
+ "AND bt.isactive = 1 AND bt.isdelete = 0 "
+ "ORDER BY ds.taskdate ASC, bt.id ASC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, year, month, year, month);
return result;
}
@Transactional
public List<Map<String, Object>> getAllTaskListByMonth(
String month,
String year,
String loginId) {
String sqlQuery = "SELECT *, CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown' "
+ " END AS status_name "
+ "FROM `brr_task` "
+ "WHERE (MONTH(`fromdate`) = ? AND YEAR(`fromdate`) = ?) "
+ "OR (MONTH(`todate`) = ? AND YEAR(`todate`) = ?) "
+ "AND `isactive` = 1 AND `isdelete` = 0 "
+ "ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, month, year, month, year);
return result;
}
@Transactional
public List<Map<String, Object>> getAllTaskListByDate(
String workdate,
String loginId) {
String sqlQuery = "SELECT *, CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown' "
+ " END AS status_name "
+ "FROM `brr_task` "
+ "WHERE (STR_TO_DATE(?, '%d-%m-%Y') BETWEEN `fromdate` AND `todate`) "
+ "AND `isactive` = 1 AND `isdelete` = 0 "
+ "ORDER BY `id` DESC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, workdate);
return result;
}
@Transactional
public List<Map<String, Object>> getTaskInfoBytaskId(
String taskId,
String loginId){
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name "
+ "FROM `brr_task` WHERE `id`=? AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, taskId);
return result;
}
@Transactional
public List<Map<String, Object>> getTaskHistoryBytaskId(
String taskId,
String loginId){
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name "
+ "FROM `brr_task` WHERE `id`=? AND (`isactive`=1 AND `isdelete`=0) ORDER BY `id` DESC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, taskId);
if (result.isEmpty()) {
return result;
}else {
String sqlQuery3 = "SELECT *,CONCAT('"+fileBaseUrl+"/gccofficialapp/files', filepath) AS imageUrl "
+ "FROM `brr_task_activity_log` WHERE taskid=? ORDER BY `id` DESC";
List<Map<String, Object>> result2 = jdbcActivityTemplate.queryForList(sqlQuery3, taskId);
// Add the result2 and result3 to the main result map
result.get(0).put("task_activity_data", result2);
}
return result;
}
@Transactional
public List<Map<String, Object>> saveTask(
String taskname,
String roadtype,
String fromdate,
String todate,
String activitytype,
String zone,
String ward,
String streeId,
String streetName,
String taskremarks,
String loginId,
String streetlength) {
List<Map<String, Object>> result=null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
String sqlQuery = "INSERT INTO `brr_task`(`taskname`, `roadtype`, `fromdate`, `todate`, `activitytype`, `zone`, `ward`, `streetid`, `streetname`, `taskremarks`, `cby`,`streetlength`) "
+ "VALUES (?,?,STR_TO_DATE(?, '%d-%m-%Y'),STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcActivityTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, taskname);
ps.setString(2, roadtype);
ps.setString(3, fromdate);
ps.setString(4, todate);
ps.setString(5, activitytype);
ps.setString(6, zone);
ps.setString(7, ward);
ps.setString(8, streeId);
ps.setString(9, streetName);
ps.setString(10, taskremarks);
ps.setString(11, loginId);
ps.setString(12, streetlength);
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 task was inserted successfully!");
System.out.println("A new task was inserted successfully! Insert ID: " + generatedId);
} else {
response.put("status", "error");
response.put("message", "Failed to insert a new task.");
}
} 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<Map<String, Object>> DeleteTask(String taskId, String loginId){
String sqlQuery = "SELECT * FROM brr_task WHERE `cby`='"+loginId+"' and `id`='"+taskId+"'";
System.out.println(sqlQuery);
List<Map<String, Object>> results = jdbcActivityTemplate.queryForList(sqlQuery);
if (!results.isEmpty()) {
sqlQuery = "UPDATE `brr_task` SET isdelete=1 WHERE `id`=?";
jdbcActivityTemplate.update(sqlQuery,taskId);
sqlQuery = "INSERT INTO `brr_task_log`(`type`, `taskid`, `cby`) "
+ "VALUES ('Delete',?,?)";
jdbcActivityTemplate.update(sqlQuery,taskId,loginId);
Map<String, Object> response = new HashMap<>();
response.put("Activity", "Delete");
response.put("status", "success");
response.put("message", "Task Delete successfully!");
System.out.println("Task was delete successfully! Task ID: " + taskId + "Delete Request By: "+loginId);
return Collections.singletonList(response);
} else {
// Handle the case when there are no results
Map<String, Object> response = new HashMap<>();
response.put("Activity", "Delete");
response.put("status", "Failed");
response.put("message", "You don’t have access to delete this task!");
System.out.println("Task was delete failed! Task ID: " + taskId + "Delete Request By: "+loginId);
return Collections.singletonList(response);
}
}
@Transactional
public List<Map<String, Object>> saveTaskActivity(
String taskid,
String before_after,
String activitystatus,
String activity_id,
String remarks,
String loginId,
MultipartFile file) {
List<Map<String, Object>> result=null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
// Set the file path where you want to save it
String uploadDirectory = environment.getProperty("file.upload.directory");
String serviceFolderName = environment.getProperty("brr_activity_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 OrgfileName = before_after +"_"+ datetimetxt + "_" + file.getOriginalFilename();
String fileName = OrgfileName.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);
//File Size
Long fileSize = file.getSize();
// File Type
String fileType = file.getContentType();
String sqlQuery = "INSERT INTO `brr_task_activity_log`(`taskid`, `activity_photo`, `activitystatus`, `remarks`, `before_after`, `cby`, `filetype`, `filesize`, `filepath`, `activity_id`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcActivityTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, taskid);
ps.setString(2, fileName);
ps.setString(3, activitystatus);
ps.setString(4, remarks);
ps.setString(5, before_after);
ps.setString(6, loginId);
ps.setString(7, fileType);
ps.setLong(8, fileSize);
ps.setString(9, filepath_txt);
ps.setString(10, activity_id);
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 task was inserted successfully!");
System.out.println("A new task was inserted successfully! Insert ID: " + generatedId);
if(!activitystatus.isBlank() && !activitystatus.isEmpty() && activitystatus.equalsIgnoreCase("yes") && before_after.equalsIgnoreCase("after")) {
// Pending
String sqlQuery_u = "UPDATE `brr_task` SET `status`=4 WHERE `id`='"+taskid+"'";
jdbcActivityTemplate.update(sqlQuery_u);
}
if(!activitystatus.isBlank() && !activitystatus.isEmpty() && activitystatus.equalsIgnoreCase("no") && before_after.equalsIgnoreCase("after")) {
// Closed
String sqlQuery_u = "UPDATE `brr_task` SET `status`=3 WHERE `id`='"+taskid+"'";
jdbcActivityTemplate.update(sqlQuery_u);
}
if(!activitystatus.isBlank() && !activitystatus.isEmpty() && before_after.equalsIgnoreCase("before")) {
// In-Progress
String sqlQuery_u = "UPDATE `brr_task` SET `status`=2 WHERE `id`='"+taskid+"'";
jdbcActivityTemplate.update(sqlQuery_u);
}
} else {
response.put("status", "error");
response.put("message", "Failed to insert a new task.");
}
} 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());
}
}
} catch (IOException e) {
e.printStackTrace();
response.put("status", "error");
response.put("message", "Image Upload failed!");
}
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> reportByDate(
String fromdate,
String todate,
String roadtype,
String zone,
String ward,
String streetid,
String loginId,
String Status) {
String selectVariable ="zone";
String statusidQuery ="";
// Use equals() for string comparison
if ("Open".equals(Status)) {
statusidQuery = " AND `status` = 1 "; // Open
} else if ("In-Progress".equals(Status)) {
statusidQuery = " AND `status` = 2 "; // Pending
} else if ("Pending".equals(Status)) {
statusidQuery = " AND `status` = 3 "; // Closed
} else if ("Completed".equals(Status)) {
statusidQuery = " AND `status` = 4 "; // Closed
}
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
selectVariable = selectVariable + ",ward";
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
selectVariable = selectVariable + ",streetid,streetName";
}
String sqlQuery = "SELECT "
+ selectVariable +","
+ "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `Open`, "
+ "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS `In-Progress`, "
+ "SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) AS `Pending`, "
+ "SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS `Completed` "
+ "FROM `brr_task` "
+ "WHERE "
+ "(`fromdate` >= STR_TO_DATE(?, '%d-%m-%Y') AND `todate` <= STR_TO_DATE(?, '%d-%m-%Y')) And "
+ "(`fromdate` <= STR_TO_DATE(?, '%d-%m-%Y') AND `todate` >= STR_TO_DATE(?, '%d-%m-%Y')) ";
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
sqlQuery = sqlQuery + " AND zone = '"+zone+"' ";
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
sqlQuery = sqlQuery + " AND ward = '"+ward+"' ";
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
sqlQuery = sqlQuery + " AND streetid = '"+streetid+"'";
}
if (roadtype != null && !roadtype.isEmpty() && !roadtype.isBlank()) {
sqlQuery = sqlQuery + " AND roadtype = '"+roadtype+"' ";
}
sqlQuery = sqlQuery+ statusidQuery +" AND (`isactive` = 1 AND `isdelete` = 0) "
+ "GROUP BY "+selectVariable+" ORDER BY zone ASC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, fromdate, todate, todate, fromdate);
return result;
}
@Transactional
public List<Map<String, Object>> reportByDate2(
String fromdate,
String todate,
String roadtype,
String zone,
String ward,
String streetid,
String loginId,
String Status) {
String sqlQuery = "SELECT "
+ " streetname, streetid, zone, ward, "
+ " SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `Open`, "
+ " SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS `In-Progress`, "
+ " SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) AS `Pending`, "
+ " SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS `Completed` "
+ "FROM `brr_task` "
+ "WHERE "
+ "("
+ "(STR_TO_DATE(?, '%d-%m-%Y') <= `fromdate` AND STR_TO_DATE(?, '%d-%m-%Y') >= `fromdate`) OR "
+ "(STR_TO_DATE(?, '%d-%m-%Y') <= `todate` AND STR_TO_DATE(?, '%d-%m-%Y') >= `todate`) "
+ ") ";
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
sqlQuery = sqlQuery + " AND zone = '"+zone+"' ";
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
sqlQuery = sqlQuery + " AND ward = '"+ward+"' ";
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
sqlQuery = sqlQuery + " AND streetid = '"+streetid+"'";
}
if (roadtype != null && !roadtype.isEmpty() && !roadtype.isBlank()) {
sqlQuery = sqlQuery + " AND roadtype = '"+roadtype+"' ";
}
sqlQuery = sqlQuery+ " AND (`isactive` = 1 AND `isdelete` = 0) "
+ "GROUP BY streetname,streetid, zone, ward "
+ "ORDER BY streetname ASC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, fromdate, todate,fromdate, todate);
return result;
}
@Transactional
public List<Map<String, Object>> reportByStatus(
String fromdate,
String todate,
String Status,
String roadtype,
String zone,
String ward,
String streetid,
String loginId) {
int statusid = 0;
// Use equals() for string comparison
if ("Open".equals(Status)) {
statusid = 1; // Open
} else if ("In-Progress".equals(Status)) {
statusid = 2; // Pending
} else if ("Pending".equals(Status)) {
statusid = 3; // Closed
} else if ("Completed".equals(Status)) {
statusid = 4; // Closed
}
System.out.println(statusid);
// Main SQL query to retrieve tasks based on status and date range
String sqlQuery = "SELECT *,CASE "
+ " WHEN status = 1 THEN 'Open'"
+ " WHEN status = 2 THEN 'In-Progress'"
+ " WHEN status = 3 THEN 'Pending'"
+ " WHEN status = 4 THEN 'Completed'"
+ " ELSE 'unknown'"
+ " END AS status_name "
+ "FROM `brr_task` "
+ "WHERE "
+ "("
// + "(STR_TO_DATE(?, '%d-%m-%Y') <= `fromdate` AND STR_TO_DATE(?, '%d-%m-%Y') >= `fromdate`) OR "
// + "(STR_TO_DATE(?, '%d-%m-%Y') <= `todate` AND STR_TO_DATE(?, '%d-%m-%Y') >= `todate`) "
+ "(`fromdate` >= STR_TO_DATE(?, '%d-%m-%Y') AND `todate` <= STR_TO_DATE(?, '%d-%m-%Y')) And "
+ "(`fromdate` <= STR_TO_DATE(?, '%d-%m-%Y') AND `todate` >= STR_TO_DATE(?, '%d-%m-%Y')) "
+ ") AND `status` = ? ";
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
sqlQuery = sqlQuery + " AND zone = '"+zone+"' ";
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
sqlQuery = sqlQuery + " AND ward = '"+ward+"' ";
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
sqlQuery = sqlQuery + " AND streetid = '"+streetid+"'";
}
if (roadtype != null && !roadtype.isEmpty() && !roadtype.isBlank()) {
sqlQuery = sqlQuery + " AND roadtype = '"+roadtype+"' ";
}
sqlQuery = sqlQuery + "AND `isactive` = 1 AND `isdelete` = 0 "
+ "GROUP BY streetname, id "
+ "ORDER BY streetname ASC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, fromdate, todate, todate,fromdate, statusid);
if (result.isEmpty()) {
return result;
} else {
for (Map<String, Object> task : result) {
String taskId = task.get("id").toString();
// SQL query to retrieve task activity logs
String sqlQuery2 = "("
+ " SELECT "
+ " *,"
+ " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', filepath) AS imageUrl,"
+ " 0 AS activity_id "
+ " FROM "
+ " `brr_task_activity_log` "
+ " WHERE "
+ " taskid = ? AND before_after = 'before' "
+ " ORDER BY "
+ " `id` DESC "
+ " LIMIT 1 "
+ ") "
+ "UNION ALL "
+ "( "
+ " SELECT "
+ " *,"
+ " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', filepath) AS imageUrl, "
+ " (SELECT id FROM brr_task_activity_log bl WHERE bl.taskid = brr_task_activity_log.taskid AND bl.before_after = 'before' ORDER BY id DESC LIMIT 1) AS activity_id "
+ " FROM "
+ " `brr_task_activity_log` "
+ " WHERE "
+ " taskid = ? AND before_after = 'after'"
+ " ORDER BY "
+ " `id` DESC "
+ " LIMIT 1"
+ ") "
+ "ORDER BY `id` DESC";
List<Map<String, Object>> result2 = jdbcActivityTemplate.queryForList(sqlQuery2, taskId, taskId);
// Add the task activity data to the corresponding task
task.put("task_activity_data", result2);
}
}
return result;
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.service;

149
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<String, String> formData,
@RequestParam(value = "loginId", required = false) String loginId){
return educationActivity.getUnmapSchoolList(formData,loginId);
}
@GetMapping(value="/getSchoolList")
public List<?> getSchoolList(@RequestParam MultiValueMap<String, String> 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<String, String> formData,
@RequestParam(value = "loginId", required = false) String loginId){
return educationActivity.getMenu(formData, loginId);
}
@GetMapping(value="/getBuildings")
public List<?> getBuildings(@RequestParam MultiValueMap<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> formData,
@RequestParam Map<String, MultipartFile> 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);
}
}
}

1
src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/controller/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gcceducation.controller;

1
src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gcceducation;

1127
src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/EducationActivity.java
File diff suppressed because it is too large
View File

1
src/main/java/in/gov/chennaicorporation/mobileservice/gcceducation/service/package-info.java

@ -0,0 +1 @@
package in.gov.chennaicorporation.mobileservice.gcceducation.service;

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save