Browse Source

GCC Mobile App Source

main
Balaji 2 years ago
commit
6b438d9efd
  1. BIN
      .DS_Store
  2. BIN
      mobileservice/.DS_Store
  3. 33
      mobileservice/.gitignore
  4. 19
      mobileservice/.mvn/wrapper/maven-wrapper.properties
  5. BIN
      mobileservice/gcc_mobile_service_uploads/.DS_Store
  6. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/.DS_Store
  7. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/.DS_Store
  8. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/1.png
  9. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/1_1.png
  10. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/1_2.png
  11. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/2.png
  12. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_3.png
  13. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_4.png
  14. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_5.png
  15. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/3.png
  16. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_1.png
  17. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_2.png
  18. BIN
      mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_3.png
  19. BIN
      mobileservice/gcc_mobile_service_uploads/asset_activity/.DS_Store
  20. BIN
      mobileservice/gcc_mobile_service_uploads/asset_images/.DS_Store
  21. BIN
      mobileservice/gcc_mobile_service_uploads/brr_activity_images/.DS_Store
  22. BIN
      mobileservice/gcc_mobile_service_uploads/sos_rescue_activity_images/.DS_Store
  23. 259
      mobileservice/mvnw
  24. 149
      mobileservice/mvnw.cmd
  25. 122
      mobileservice/pom.xml
  26. BIN
      mobileservice/src/.DS_Store
  27. BIN
      mobileservice/src/main/.DS_Store
  28. 13
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/MobileServiceApplication.java
  29. 28
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/UpdateResponse.java
  30. 22
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/AppConfig.java
  31. 134
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java
  32. 20
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/JacksonConfiguration.java
  33. 187
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIOfficialController.java
  34. 22
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/controller/APIPetController.java
  35. 76
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/controller/FileController.java
  36. 42
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/controller/MainController.java
  37. 108
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIActivityController.java
  38. 153
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/APIMassActivityController.java
  39. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/package-info.java
  40. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/package-info.java
  41. 955
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java
  42. 29
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/DateTimeUtil.java
  43. 710
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/MassClearn.java
  44. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/package-info.java
  45. 121
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/controller/APIOfficerController.java
  46. 60
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/controller/APIUserController.java
  47. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/controller/package-info.java
  48. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/package-info.java
  49. 650
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/service/OfficerActivity.java
  50. 224
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/service/UserActivity.java
  51. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/service/package-info.java
  52. 24
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java
  53. 24
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyController.java
  54. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/package-info.java
  55. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/package-info.java
  56. 29
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java
  57. 29
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyService.java
  58. 1
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/package-info.java
  59. 922
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/DataSyncService.java
  60. 23
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OTPGenerator.java
  61. 355
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java
  62. 33
      mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/PetAPIService.java
  63. BIN
      mobileservice/src/main/resources/.DS_Store
  64. 1
      mobileservice/src/main/resources/application-local.properties
  65. 1
      mobileservice/src/main/resources/application-production.properties
  66. 34
      mobileservice/src/main/resources/application.properties
  67. 65
      mobileservice/src/main/resources/static/assets/_js/main/app.js
  68. 1110
      mobileservice/src/main/resources/static/assets/_js/main/modules/helpers.js
  69. 802
      mobileservice/src/main/resources/static/assets/_js/main/modules/template.js
  70. 179
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_calendar.js
  71. 143
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_charts.js
  72. 156
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_chat.js
  73. 106
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_dialogs.js
  74. 88
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_image_cropper.js
  75. 154
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_maps_vector.js
  76. 47
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_nestable.js
  77. 41
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_onboarding.js
  78. 50
      mobileservice/src/main/resources/static/assets/_js/pages/be_comp_rating.js
  79. 124
      mobileservice/src/main/resources/static/assets/_js/pages/be_forms_validation.js
  80. 89
      mobileservice/src/main/resources/static/assets/_js/pages/be_pages_dashboard.js
  81. 225
      mobileservice/src/main/resources/static/assets/_js/pages/be_pages_dashboard_v1.js
  82. 104
      mobileservice/src/main/resources/static/assets/_js/pages/be_pages_ecom_dashboard.js
  83. 271
      mobileservice/src/main/resources/static/assets/_js/pages/be_pages_projects_tasks.js
  84. 45
      mobileservice/src/main/resources/static/assets/_js/pages/be_ui_animations.js
  85. 2184
      mobileservice/src/main/resources/static/assets/_js/pages/be_ui_icons.js
  86. 41
      mobileservice/src/main/resources/static/assets/_js/pages/be_ui_progress.js
  87. 73
      mobileservice/src/main/resources/static/assets/_js/pages/db_analytics.js
  88. 144
      mobileservice/src/main/resources/static/assets/_js/pages/db_corporate_slim.js
  89. 93
      mobileservice/src/main/resources/static/assets/_js/pages/db_crypto.js
  90. 42
      mobileservice/src/main/resources/static/assets/_js/pages/op_auth_lock.js
  91. 42
      mobileservice/src/main/resources/static/assets/_js/pages/op_auth_reminder.js
  92. 51
      mobileservice/src/main/resources/static/assets/_js/pages/op_auth_signin.js
  93. 69
      mobileservice/src/main/resources/static/assets/_js/pages/op_auth_signup.js
  94. 34
      mobileservice/src/main/resources/static/assets/_js/pages/op_coming_soon.js
  95. 78
      mobileservice/src/main/resources/static/assets/_js/pages/op_installation.js
  96. 149
      mobileservice/src/main/resources/static/assets/_scss/bootstrap/_accordion.scss
  97. 71
      mobileservice/src/main/resources/static/assets/_scss/bootstrap/_alert.scss
  98. 38
      mobileservice/src/main/resources/static/assets/_scss/bootstrap/_badge.scss
  99. 40
      mobileservice/src/main/resources/static/assets/_scss/bootstrap/_breadcrumb.scss
  100. 142
      mobileservice/src/main/resources/static/assets/_scss/bootstrap/_button-group.scss

BIN
.DS_Store

BIN
mobileservice/.DS_Store

33
mobileservice/.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/

19
mobileservice/.mvn/wrapper/maven-wrapper.properties

@ -0,0 +1,19 @@
# 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.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip

BIN
mobileservice/gcc_mobile_service_uploads/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/1.png

After

Width: 43  |  Height: 43  |  Size: 1.9 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/1_1.png

After

Width: 41  |  Height: 40  |  Size: 1.3 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/1_2.png

After

Width: 40  |  Height: 40  |  Size: 1.2 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/2.png

After

Width: 40  |  Height: 40  |  Size: 3.1 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_3.png

After

Width: 40  |  Height: 40  |  Size: 981 B

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_4.png

After

Width: 40  |  Height: 40  |  Size: 2.3 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/2_5.png

After

Width: 40  |  Height: 40  |  Size: 1.6 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/3.png

After

Width: 40  |  Height: 40  |  Size: 2.9 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_1.png

After

Width: 40  |  Height: 40  |  Size: 2.5 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_2.png

After

Width: 40  |  Height: 40  |  Size: 2.3 KiB

BIN
mobileservice/gcc_mobile_service_uploads/app_icon/menu/3_3.png

After

Width: 40  |  Height: 40  |  Size: 1.6 KiB

BIN
mobileservice/gcc_mobile_service_uploads/asset_activity/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/asset_images/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/brr_activity_images/.DS_Store

BIN
mobileservice/gcc_mobile_service_uploads/sos_rescue_activity_images/.DS_Store

259
mobileservice/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
mobileservice/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"

122
mobileservice/pom.xml

@ -0,0 +1,122 @@
<?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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

BIN
mobileservice/src/.DS_Store

BIN
mobileservice/src/main/.DS_Store

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

@ -0,0 +1,13 @@
package in.gov.chennaicorporation.mobileservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MobileServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MobileServiceApplication.class, args);
}
}

28
mobileservice/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;
}
}

22
mobileservice/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://localhost:8063";
public String mtm = "http://localhost:8060";
public String petRegistration = "http://localhost:8061";
public String garbageCollection = "http://localhost:8067"; //117.232.67.158
public String gccappsMysqlPassword = "";
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

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

@ -0,0 +1,134 @@
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 dbpassword = "gccroot";
private static String dbpassword = "";
//////////////////////////////(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://localhost:3306/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://localhost:3306/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://localhost:3306/gcc_penalty");
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://localhost:3306/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://localhost:3306/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://localhost:3306/gcc_sos");
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
mobileservice/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;
}
}

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

@ -0,0 +1,187 @@
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";
}
// API FOR TOTHER APP
@GetMapping(value="/sendOTP")
public List sendOTP(HttpServletRequest request,
@RequestParam("mobileNo") String mobileNo,
@RequestParam("otpLength") Integer OTP_LENGTH) {
String generatedToken = OTPGenerator.generateOTP(OTP_LENGTH);
return officialAPIService.sendOTP(request, mobileNo, generatedToken);
}
@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="/getMenu")
public List getMenu(@RequestParam String loginId){
return officialAPIService.getMenu(loginId);
}
@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
mobileservice/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);
}
}

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

@ -0,0 +1,76 @@
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();
}
}
}

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

@ -0,0 +1,42 @@
package in.gov.chennaicorporation.mobileservice.controller;
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;
@RequestMapping("/gccofficialapp")
@Controller("mainController")
public class MainController {
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";
}
}

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

@ -0,0 +1,108 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.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.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(){
return activity.getActivityCategory();
}
@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 = "file", required = false) MultipartFile file
) {
return activity.saveAsset(formData, assetTypeId, latitude, longitude, zone, ward, streeId, streetName, loginId, 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/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("/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";
}
}

153
mobileservice/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
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/controller/package-info.java

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

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

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

955
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java

@ -0,0 +1,955 @@
package in.gov.chennaicorporation.mobileservice.gccactivity.service;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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.sql.Statement;
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.stream.Collectors;
import java.io.*;
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.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
@Service
public class Activity {
private JdbcTemplate jdbcActivityTemplate;
private DateTimeUtil dateTimeUtil;
private final Environment environment;
@Autowired
public void setDataSource(@Qualifier("mysqlActivityDataSource") DataSource activityDataSource) {
this.jdbcActivityTemplate = new JdbcTemplate(activityDataSource);
}
@Autowired
public Activity(Environment environment) {
this.environment = environment;
}
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>> getActivityCategory(){
String sqlQuery = "SELECT * FROM `activity_category` WHERE (`isactive`=1 AND `isdelete`=0) ORDER BY `display_order` ASC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> saveAsset(
MultiValueMap<String, String> formData,
String assetType,
String latitude,
String longitude,
String zone,
String ward,
String streeId,
String streetName,
String loginId,
MultipartFile file) {
List<Map<String, Object>> result=null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
String image = assetFileUpload(assetType,file);
String sqlQuery = "INSERT INTO `asset_list`(`category_id`, `image`, `latitude`, `longitude`, `zone`, `ward`, `streetid`, `streetname`, `cby`) "
+ "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, assetType);
ps.setString(2, image);
ps.setString(3, latitude);
ps.setString(4, longitude);
ps.setString(5, zone);
ps.setString(6, ward);
ps.setString(7, streeId);
ps.setString(8, streetName);
ps.setString(9, loginId);
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 asset was inserted successfully!");
System.out.println("A new asset was inserted successfully! Insert ID: " + generatedId);
} else {
response.put("status", "error");
response.put("message", "Failed to insert a new asset.");
}
} catch (DataAccessException e) {
System.out.println("Data Access Exception:");
Throwable rootCause = e.getMostSpecificCause();
if (rootCause instanceof SQLException) {
SQLException sqlException = (SQLException) rootCause;
System.out.println("SQL State: " + sqlException.getSQLState());
System.out.println("Error Code: " + sqlException.getErrorCode());
System.out.println("Message: " + sqlException.getMessage());
response.put("status", "error");
response.put("message", sqlException.getMessage());
response.put("sqlState", sqlException.getSQLState());
response.put("errorCode", sqlException.getErrorCode());
} else {
System.out.println("Message: " + rootCause.getMessage());
response.put("status", "error");
response.put("message", rootCause.getMessage());
}
}
return Collections.singletonList(response);
}
public String assetFileUpload(String catId, 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("activity_new_asset_foldername");
uploadDirectory = uploadDirectory + serviceFolderName + catId;
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 = catId + "_" + datetimetxt + "_" + file.getOriginalFilename();
fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + 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(fileName);
return fileName;
} catch (IOException e) {
e.printStackTrace();
return "Failed to save file " + file.getOriginalFilename();
}
}
@Transactional
public List<Map<String, Object>> loadAssetlistbyStreetId(String assetTypeId, String streetId){
String serviceFolderName = environment.getProperty("activity_new_asset_foldername");
String filePath=serviceFolderName + assetTypeId+"/";
//String sqlQuery = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/"+filePath+"', image) AS imageUrl FROM `asset_list` WHERE `category_id`=? AND `streetid`=?";
String sqlQuery="SELECT al.*, CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/', al.image) AS imageUrl, "
+ "af.feedback_date AS lastfeedbackdate FROM asset_list al "
+ "LEFT JOIN ( SELECT af1.*, af2.latest_feedback_date FROM activity_feedback af1 "
+ "INNER JOIN ( SELECT asset_id, MAX(feedback_date) AS latest_feedback_date FROM activity_feedback GROUP BY asset_id ) af2 "
+ "ON af1.asset_id = af2.asset_id AND af1.feedback_date = af2.latest_feedback_date ) af "
+ "ON al.id = af.asset_id WHERE al.category_id = ? AND al.streetid = ?";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery,assetTypeId,streetId);
return result;
}
@Transactional
public List<Map<String, Object>> loadAssetQuestionlistbyAssetTypeId(String assetTypeId){
String sqlQuery = "SELECT * FROM `activity_questions` WHERE (`isactive`=1 AND `isdelete`=0) AND `category_id`=? ORDER BY `display_order` ASC";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery,assetTypeId);
return result;
}
@Transactional
public List<Map<String, Object>> saveAssetAction(
MultiValueMap<String, String> formData,
String catId,
String assetId,
String remarks,
String latitude,
String longitude,
String loginId,
String feedbackId,
MultipartFile beforeFile,
MultipartFile afterFile){
String beforeFileName="";
String afterFileName="";
List<Map<String, Object>> result=null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
//if(feedbackId.equals("0")) {
String sqlQuery = "INSERT INTO `activity_feedback`(`asset_id`, `remarks`, `feedback_by`,`latitude`, `longitude`, `feedback_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, assetId);
ps.setString(2, remarks);
ps.setString(3, loginId);
ps.setString(4, latitude);
ps.setString(5, longitude);
ps.setString(6, feedbackId);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
System.out.println("Activity inserted successfully! Insert ID: " + generatedId);
// Save User Feedback Data
saveFeedbackData(formData,lastInsertId);
// File Upload call
if (beforeFile == null || beforeFile.isEmpty()) {
System.out.println("Before File is empty ");
}
else {
beforeFileName = fileUpload(catId, "before",lastInsertId, beforeFile);
}
if (afterFile == null || afterFile.isEmpty()) {
System.out.println("After File is empty ");
}
else {
afterFileName = fileUpload(catId, "after", lastInsertId, afterFile);
}
response.put("status", "Success");
response.put("message", "Your activity was recorded successfully.");
return Collections.singletonList(response);
} else {
response.put("status", "error");
response.put("message", "Failed to insert the activity data.");
return Collections.singletonList(response);
}
} 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);
}
//}
//return Collections.singletonList(response);
}
public String saveFeedbackData(MultiValueMap<String, String> formData, int feedbackId) {
// Process the form data here
for (String key : formData.keySet()) {
if (!key.equals("catId")
&& !key.equals("assetId")
&& !key.equals("remarks")
&& !key.equals("latitude")
&& !key.equals("longitude")
&& !key.equals("loginId")
&& !key.equals("feedbackId")
&& !key.equals("beforeFile")
&& !key.equals("afterFile")) {
List<String> values = formData.get(key);
// Remove empty values
List<String> filteredValues = values.stream()
.filter(value -> !value.isEmpty())
.map(String::trim)
.collect(Collectors.toList());
// Do something with the field values
if (!filteredValues.isEmpty()) {
//String feedback = filteredValues.toString().trim();
String feedback = String.join(" ", filteredValues).trim();
String[] parts = key.split("_");
int lastInsertId = 0;
if (parts.length == 2) {
String questionType = parts[0];
String questionId = parts[1];
if (questionId != null && !questionId.isEmpty() && !questionId.isBlank()) {
// Insert Data
String sqlQuery = "INSERT INTO `activity_feedback_data`(`feedback_id`, `qid`, `feedback`) "
+ "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.setInt(1, feedbackId);
ps.setString(2, questionId);
ps.setString(3, feedback);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
System.out.println("Activity Feedback inserted successfully! Insert Feedback Data ID: " + lastInsertId);
}
} catch (DataAccessException e) {
System.out.println("File insert Feedback Data.");
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());
} else {
System.out.println("Message: " + rootCause.getMessage());
}
}
}
}
}
}
}
return "success";
}
public String fileUpload(String catId, String fileAction, int lastInsertfeedbackId, 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("activity_foldername");
int feedbackId=lastInsertfeedbackId;
uploadDirectory = uploadDirectory + serviceFolderName + catId;
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 = catId + "_" + fileAction + "_" + lastInsertfeedbackId + "_" + datetimetxt + "_" + file.getOriginalFilename();
String fileName = OrgfileName.replaceAll("\\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + 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 `activity_feedback_file`(`feedback_id`, `fileaction`, `filepath`, `filename`, `filetype`, `filesize`) "
+ "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.setInt(1, lastInsertfeedbackId);
ps.setString(2, fileAction);
ps.setString(3, filePath);
ps.setString(4, fileName);
ps.setString(5, fileType);
ps.setLong(6, fileSize);
return ps;
}
}, keyHolder);
if (affectedRows > 0) {
Number generatedId = keyHolder.getKey();
lastInsertId = (generatedId != null) ? generatedId.intValue() : 0;
System.out.println("Activity File inserted successfully! Insert File ID: " + generatedId);
}
} catch (DataAccessException e) {
System.out.println("File insert failed.");
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());
} else {
System.out.println("Message: " + rootCause.getMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
return "Failed to save file " + file.getOriginalFilename();
}
return "File Saved succussfully!";
}
@Transactional
public List<Map<String, Object>> loadAssetLastFeedbackHistoryByUser(String catId, String assetId, String loginId) {
// Query to get the last feedback by user for the given asset
String sqlQuery = "SELECT * FROM `activity_feedback` WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`asset_id`=? AND `feedback_by`=?) ORDER BY `feedback_date` DESC LIMIT 1";
// Execute the query and get the result
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, assetId, loginId);
String feedback_id = "0";
if (result.isEmpty()) {
return result;
}else {
// Get the feedback_id from the first result
feedback_id = result.get(0).get("id").toString();
String feedback_id_before = result.get(0).get("feedback_id").toString();
// Query to get feedback data for the feedback_id
String sqlQuery2 = "SELECT *,`activity_questions`.english,`activity_questions`.tamil FROM `activity_feedback_data`, `activity_questions` WHERE feedback_id=? "
+ "AND `activity_questions`.qid = `activity_feedback_data`.`qid`";
List<Map<String, Object>> result2 = jdbcActivityTemplate.queryForList(sqlQuery2, feedback_id);
// Query to get feedback files for the feedback_id
//uploadDirectory = uploadDirectory + serviceFolderName + catId;
String serviceFolderName = environment.getProperty("activity_foldername");
String filePath=serviceFolderName + catId+"/";
String sqlQuery3 = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/"+filePath+"', filename) AS imageUrl "
+ "FROM `activity_feedback_file` WHERE feedback_id=? or feedback_id=?";
List<Map<String, Object>> result3 = jdbcActivityTemplate.queryForList(sqlQuery3, feedback_id, feedback_id_before);
// Add the result2 and result3 to the main result map
result.get(0).put("feedback_value", result2);
result.get(0).put("feedback_file", result3);
return result;
}
}
@Transactional
public List<Map<String, Object>> loadAssetLastFeedbackByUser(String catId, String assetId, String loginId) {
// Query to get the last feedback by user for the given asset
String sqlQuery = "SELECT * FROM `activity_feedback` WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`asset_id`=? AND `feedback_by`=?) ORDER BY `feedback_date` DESC LIMIT 1";
// Execute the query and get the result
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, assetId, loginId);
String feedback_id = "0";
if (result.isEmpty()) {
return result;
}else {
// Get the feedback_id from the first result
feedback_id = result.get(0).get("id").toString();
}
// Query to get feedback data for the feedback_id
String sqlQuery2 = "SELECT * FROM `activity_feedback_data` WHERE feedback_id=?";
List<Map<String, Object>> result2 = jdbcActivityTemplate.queryForList(sqlQuery2, feedback_id);
// Query to get feedback files for the feedback_id
//uploadDirectory = uploadDirectory + serviceFolderName + catId;
String serviceFolderName = environment.getProperty("activity_foldername");
String filePath=serviceFolderName + catId+"/";
String sqlQuery3 = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/"+filePath+"', filename) AS imageUrl FROM `activity_feedback_file` WHERE feedback_id=?";
List<Map<String, Object>> result3 = jdbcActivityTemplate.queryForList(sqlQuery3, feedback_id);
// Add the result2 and result3 to the main result map
result.get(0).put("feedback_value", result2);
result.get(0).put("feedback_file", result3);
return result;
}
@Transactional
public List<Map<String, Object>> loadAssetFeedback(String catId, String assetId, String loginId) {
// Query to get the last feedback by user for the given asset
String sqlQuery = "SELECT * FROM `activity_feedback` WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`asset_id`=? AND `feedback_by`=?) ORDER BY `feedback_date` DESC LIMIT 1";
// Execute the query and get the result
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery, assetId, loginId);
String feedback_id = "0";
if (result.isEmpty()) {
return result;
}else {
// Get the feedback_id from the first result
feedback_id = result.get(0).get("id").toString();
}
// Query to get feedback data for the feedback_id
String sqlQuery2 = "SELECT * FROM `activity_feedback_data` WHERE feedback_id=?";
List<Map<String, Object>> result2 = jdbcActivityTemplate.queryForList(sqlQuery2, feedback_id);
// Query to get feedback files for the feedback_id
//uploadDirectory = uploadDirectory + serviceFolderName + catId;
String serviceFolderName = environment.getProperty("activity_foldername");
String filePath=serviceFolderName + catId+"/";
String sqlQuery3 = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/"+filePath+"', filename) AS imageUrl FROM `activity_feedback_file` WHERE feedback_id=?";
List<Map<String, Object>> result3 = jdbcActivityTemplate.queryForList(sqlQuery3, feedback_id);
// Add the result2 and result3 to the main result map
result.get(0).put("feedback_value", result2);
result.get(0).put("feedback_file", result3);
return result;
}
// For report and Dashboard
@Transactional
public Map<String, Object> filterReports(
String assetType,
String fromDate,
String toDate,
String zone,
String ward,
String streetid,
String loginId) {
String groupQuery="al.zone";
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
groupQuery+=",al.ward";
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
groupQuery+=",al.streetid,al.streetname";
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
//sqlQuery.append(" AND al.streetid = ?");
}
// Start constructing the SQL query
StringBuilder sqlQuery = new StringBuilder("SELECT "
+ groupQuery
+ " ,COUNT(DISTINCT al.id) AS total_assets, "
+ " COALESCE(SUM(CASE WHEN aff.fileaction = 'before' THEN 1 ELSE 0 END), 0) AS total_started, "
+ " COALESCE(SUM(CASE WHEN aff.fileaction = 'after' THEN 1 ELSE 0 END), 0) AS total_completed, "
+ " COALESCE(COUNT(DISTINCT al.id) - "
+ " SUM(CASE WHEN aff.fileaction = 'before' THEN 1 ELSE 0 END) - "
+ " SUM(CASE WHEN aff.fileaction = 'after' THEN 1 ELSE 0 END), 0) AS total_pending "
+ "FROM "
+ " asset_list al "
+ "LEFT JOIN "
+ " (SELECT "
+ " af.id, "
+ " af.asset_id "
+ " FROM "
+ " activity_feedback af "
+ " INNER JOIN "
+ " (SELECT asset_id, MAX(feedback_date) AS latest_feedback_date "
+ " FROM activity_feedback "
+ " WHERE 1=1 ");
// Add date range filter if both fromDate and toDate are provided
if (fromDate != null && toDate != null) {
sqlQuery.append(" AND feedback_date BETWEEN ? AND ?");
}
sqlQuery.append(" GROUP BY asset_id) latest_feedback_dates "
+ " ON "
+ " af.asset_id = latest_feedback_dates.asset_id "
+ " AND af.feedback_date = latest_feedback_dates.latest_feedback_date "
+ " ) latest_feedback ON al.id = latest_feedback.asset_id "
+ "LEFT JOIN "
+ " activity_feedback_file aff ON latest_feedback.id = aff.feedback_id "
+ "WHERE 1=1 ");
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
sqlQuery.append(" AND al.zone = ?");
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
sqlQuery.append(" AND al.ward = ?");
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
sqlQuery.append(" AND al.streetid = ?");
}
if (assetType != null && !assetType.isEmpty() && !assetType.isBlank()) {
sqlQuery.append(" AND al.category_id = ?");
}
// Group by zone
sqlQuery.append(" GROUP BY "+groupQuery);
// Prepare parameters
List<Object> params = new ArrayList<>();
if (fromDate != null && toDate != null) {
fromDate = convertDateFormat(fromDate,0);
toDate = convertDateFormat(toDate,1);
params.add(fromDate);
params.add(toDate);
}
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
params.add(zone);
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
params.add(ward);
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
params.add(streetid);
}
if (assetType != null && !assetType.isEmpty() && !assetType.isBlank()) {
params.add(assetType);
}
// Execute query
System.out.println(sqlQuery.toString()); // For debugging
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(sqlQuery.toString(), params.toArray());
// Overall totals query
StringBuilder sqlQueryOverall = new StringBuilder("SELECT "
+ " COUNT(DISTINCT al.id) AS total_assets, "
+ " COALESCE(SUM(CASE WHEN aff.fileaction = 'before' THEN 1 ELSE 0 END), 0) AS total_started, "
+ " COALESCE(SUM(CASE WHEN aff.fileaction = 'after' THEN 1 ELSE 0 END), 0) AS total_completed, "
+ " COALESCE(COUNT(DISTINCT al.id) - "
+ " SUM(CASE WHEN aff.fileaction = 'before' THEN 1 ELSE 0 END) - "
+ " SUM(CASE WHEN aff.fileaction = 'after' THEN 1 ELSE 0 END), 0) AS total_pending "
+ "FROM "
+ " asset_list al "
+ "LEFT JOIN "
+ " (SELECT "
+ " af.id, "
+ " af.asset_id "
+ " FROM "
+ " activity_feedback af "
+ " INNER JOIN "
+ " (SELECT asset_id, MAX(feedback_date) AS latest_feedback_date "
+ " FROM activity_feedback "
+ " WHERE 1=1 ");
// Add date range filter if both fromDate and toDate are provided
if (fromDate != null && toDate != null) {
sqlQueryOverall.append(" AND feedback_date BETWEEN ? AND ?");
}
sqlQueryOverall.append(" GROUP BY asset_id) latest_feedback_dates "
+ " ON "
+ " af.asset_id = latest_feedback_dates.asset_id "
+ " AND af.feedback_date = latest_feedback_dates.latest_feedback_date "
+ " ) latest_feedback ON al.id = latest_feedback.asset_id AND (al.isactive=1 AND al.isdelete=0) "
+ "LEFT JOIN "
+ " activity_feedback_file aff ON latest_feedback.id = aff.feedback_id "
+ "WHERE 1=1 ");
// Add additional filters if provided
if (zone != null && !zone.isEmpty() && !zone.isBlank()) {
sqlQueryOverall.append(" AND al.zone = ?");
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
sqlQueryOverall.append(" AND al.ward = ?");
}
if (streetid != null && !streetid.isEmpty() && !streetid.isBlank()) {
sqlQueryOverall.append(" AND al.streetid = ?");
}
if (assetType != null && !assetType.isEmpty() && !assetType.isBlank()) {
sqlQueryOverall.append(" AND al.category_id = ?");
}
// Execute overall query
List<Map<String, Object>> overallResult = jdbcActivityTemplate.queryForList(sqlQueryOverall.toString(), params.toArray());
// Combine results
Map<String, Object> result2 = new HashMap<>();
result2.put("zoneWise", result);
result2.put("overallTotals", overallResult.isEmpty() ? Collections.singletonMap("total_started", 0) : overallResult.get(0));
return result2;
}
@Transactional
public List<Map<String, Object>> filterReportsByDate(
String assetType,
String fromDate,
String toDate,
String zone,
String ward,
String streetid,
String loginId) {
// Step 1: Generate all dates within the specified month and year
String sqlQueryForTasks = "SELECT "
+ " `asset_list`.`id`,"
+ " `asset_list`.`category_id`, "
+ " `asset_list`.`image`, "
+ " `asset_list`.`latitude`, "
+ " `asset_list`.`longitude`, "
+ " `asset_list`.`zone`, "
+ " `asset_list`.`ward`, "
+ " `asset_list`.`streetid`, "
+ " `asset_list`.`streetname`, "
+ " `asset_list`.`cdate`, "
+ " `asset_list`.`cby`, "
+ " `asset_list`.`isactive`, "
+ " `asset_list`.`isdelete`, "
+ " `asset_list`.`gis_id`, "
+ " GROUP_CONCAT(`activity_feedback`.`id`) AS feedback_ids "
+ "FROM "
+ " `activity_feedback` "
+ "JOIN "
+ " `asset_list` ON `asset_list`.`id` = `activity_feedback`.`asset_id` "
+ "WHERE "
+ " DATE_FORMAT(`activity_feedback`.`feedback_date`, '%d-%m-%Y') BETWEEN ? AND ? "
+ "AND "
+ " `asset_list`.`category_id` = ? "
+ "AND "
+ " `asset_list`.`streetid` = ? "
+ "AND (`asset_list`.`isactive`=1 AND `asset_list`.`isdelete`=0) "
+ "GROUP BY "
+ " `asset_list`.`id`";
System.out.println(sqlQueryForTasks);
// Execute the query to get the tasks
List<Map<String, Object>> taskResult = jdbcActivityTemplate.queryForList(sqlQueryForTasks, fromDate, toDate, assetType, streetid);
// Step 2: For each task, load the detailed feedback similar to loadAssetFeedback method
for (Map<String, Object> task : taskResult) {
String assetId = task.get("id").toString();
String catId = task.get("category_id").toString();
String feedbackIds = task.get("feedback_ids").toString();
// Query to get the last feedback by user for the given asset
String sqlQueryForFeedback = "SELECT * FROM `activity_feedback` WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`asset_id`="+assetId+" AND id IN ("+feedbackIds+")) ORDER BY `feedback_date` DESC LIMIT 1";
// Execute the query and get the feedback result
List<Map<String, Object>> feedbackResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedback);
if (!feedbackResult.isEmpty()) {
String feedback_id = feedbackResult.get(0).get("id").toString();
// Query to get feedback data for the feedback_id
String sqlQueryForFeedbackData = "SELECT *,`activity_questions`.english,`activity_questions`.tamil FROM `activity_feedback_data`, `activity_questions` WHERE feedback_id=? "
+ "AND `activity_questions`.qid = `activity_feedback_data`.`qid`";
List<Map<String, Object>> feedbackDataResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedbackData, feedback_id);
// Query to get feedback files for the feedback_id
String serviceFolderName = environment.getProperty("activity_foldername");
String filePath = serviceFolderName + catId + "/";
String sqlQueryForFeedbackFiles = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/" + filePath + "', filename) "
+ "AS imageUrl FROM `activity_feedback_file` WHERE feedback_id IN (" + feedbackIds + ")";
List<Map<String, Object>> feedbackFileResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedbackFiles);
System.out.println(sqlQueryForFeedbackFiles + feedbackIds);
// Add feedback data and files to the task result
task.put("feedback_value", feedbackDataResult);
task.put("feedback_file", feedbackFileResult);
}
}
return taskResult;
}
/*
@Transactional
public List<Map<String, Object>> filterReportsByDate(
String assetType,
String fromDate,
String toDate,
String zone,
String ward,
String streetid,
String loginId) {
// Step 1: Generate all dates within the specified month and year
String sqlQueryForTasks = "SELECT `asset_list`.*, `activity_feedback`.`id` feedbackid "
+ "FROM `activity_feedback`, `asset_list` "
+ "WHERE DATE_FORMAT(`activity_feedback`.`feedback_date`, '%d-%m-%Y') "
+ " BETWEEN ? AND ? "
+ "AND `asset_list`.`id` = `activity_feedback`.`asset_id` "
+ "AND `asset_list`.`category_id`=? "
+ "AND `asset_list`.`streetid` = ? ";
System.out.println(sqlQueryForTasks);
// Execute the query to get the tasks
List<Map<String, Object>> taskResult = jdbcActivityTemplate.queryForList(sqlQueryForTasks, fromDate, toDate, assetType, streetid);
// Step 2: For each task, load the detailed feedback similar to loadAssetFeedback method
for (Map<String, Object> task : taskResult) {
String assetId = task.get("id").toString();
String feedbackId = task.get("feedbackid").toString();
// Query to get the last feedback by user for the given asset
String sqlQueryForFeedback = "SELECT * FROM `activity_feedback` WHERE (`isactive`=1 AND `isdelete`=0) "
+ "AND (`asset_id`=? AND id=?) ORDER BY `feedback_date` DESC LIMIT 1";
// Execute the query and get the feedback result
List<Map<String, Object>> feedbackResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedback, assetId, feedbackId);
if (!feedbackResult.isEmpty()) {
String feedback_id = feedbackResult.get(0).get("id").toString();
// Query to get feedback data for the feedback_id
String sqlQueryForFeedbackData = "SELECT *,`activity_questions`.english,`activity_questions`.tamil FROM `activity_feedback_data`, `activity_questions` WHERE feedback_id=? "
+ "AND `activity_questions`.qid = `activity_feedback_data`.`qid`";
List<Map<String, Object>> feedbackDataResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedbackData, feedback_id);
// Query to get feedback files for the feedback_id
String serviceFolderName = environment.getProperty("activity_foldername");
String filePath = serviceFolderName + assetId + "/";
String sqlQueryForFeedbackFiles = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/" + filePath + "', filename) AS imageUrl FROM `activity_feedback_file` WHERE feedback_id=?";
List<Map<String, Object>> feedbackFileResult = jdbcActivityTemplate.queryForList(sqlQueryForFeedbackFiles, feedback_id);
// Add feedback data and files to the task result
task.put("feedback_value", feedbackDataResult);
task.put("feedback_file", feedbackFileResult);
}
}
return taskResult;
}
*/
// Function to convert date string from dd-MM-yyyy to yyyy-MM-dd
public static String convertDateFormat(String inputDate, int add) {
// 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);
if(add>0) {
// Add one day to the date
date = date.plusDays(1);
}
// Format the date to the new format
return date.format(outputFormatter);
}
public String getApiResponse() {
//String url="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=9176617754&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+36837+.";
String url="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password={{PASSWORD}}&send_to=9176617754&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%2C+%0A%0AYour+User+Registration+request+for+booking+Community+Centre+submitted+successfully.";
RestTemplate restTemplate = new RestTemplate();
//String response = restTemplate.getForObject(url, String.class);
//String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=9176617754&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is 00000&entityid=1401572690000011081&templateid=1407172346444550398";
//String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=9176617754&from=GCCCRP&body=Welcome to GCC, Your User Registration for booking Community Centre is successful.&entityid=1401572690000011081&templateid=1407172346621223019";
HttpURLConnection connection = null;
URL url2;
try {
url2 = new URL(url);
connection = (HttpURLConnection) url2.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(urlString);
//String Response = restTemplate.exchange(url2, String.class);
return "";
}
}

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

@ -0,0 +1,29 @@
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);
}
}

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

@ -0,0 +1,710 @@
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;
@Autowired
public void setDataSource(@Qualifier("mysqlActivityDataSource") DataSource activityDataSource) {
this.jdbcActivityTemplate = new JdbcTemplate(activityDataSource);
}
@Autowired
public MassClearn(Environment environment) {
this.environment = environment;
}
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('https://gccservices.chennaicorporation.gov.in/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('https://gccservices.chennaicorporation.gov.in/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('https://gccservices.chennaicorporation.gov.in/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
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/package-info.java

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

121
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/controller/APIOfficerController.java

@ -0,0 +1,121 @@
package in.gov.chennaicorporation.mobileservice.gccsos.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.gccsos.service.OfficerActivity;
@RequestMapping("/gccofficialapp/api/gccsos/officer/")
@RestController("gccofficialappOffcierSOSRest")
public class APIOfficerController {
@Autowired
private OfficerActivity officerActivity;
@GetMapping(value="/getAllRequest")
public List<?> getAllRequest(
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward,
@RequestParam(value="streetid", required = false) String streetid,
@RequestParam(value="fromdate", required = false) String fromdate,
@RequestParam(value="todate", required = false) String todate,
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status
){
return officerActivity.getAllRequest(request_type, zone, ward, streetid, fromdate, todate, loginId,status);
}
@GetMapping(value="/dashboard")
public List<?> dashboard(
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId
){
return officerActivity.dashboard(loginId, request_type);
}
@GetMapping(value="/dashboardByType")
public List<?> dashboardByType(
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status
){
return officerActivity.dashboardByType(loginId, request_type, status);
}
@GetMapping(value="/dashboardByZone")
public List<?> dashboardByZone(
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status,
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward
){
return officerActivity.dashboardByZone(loginId, request_type, status, zone ,ward);
}
@GetMapping(value="/dashboardByWard")
public List<?> dashboardByWard(
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status,
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward
){
return officerActivity.dashboardByWard(loginId, request_type, status, zone ,ward);
}
@GetMapping(value="/dashboardByList")
public List<?> dashboardByList(
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value="status", required = false) String status,
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward
){
return officerActivity.dashboardByList(loginId, request_type, status, zone ,ward);
}
@GetMapping(value="/reportByDate")
public List<?> reportByDate(
@RequestParam(value = "fromdate", required = false) String fromdate,
@RequestParam(value = "todate", required = false) String todate,
@RequestParam("request_type") String request_type,
@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 officerActivity.reportByDate(fromdate, todate, request_type, zone, ward, streetid,loginId,status);
}
@PostMapping(value="/saveRequestUpdate")
public List<?> saveRequestUpdate(
@RequestParam(value="rescue_id", required = true) String rescue_id,
@RequestParam(value="latitude", required = false) String latitude,
@RequestParam(value="longitude", required = false) String longitude,
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward,
@RequestParam(value="streetid", required = false) String streetid,
@RequestParam(value="streetname", required = false) String streetname,
@RequestParam(value="remarks", required = false) String remarks,
@RequestParam(value="loginId", required = false) String loginId,
@RequestParam(value = "file", required = false) MultipartFile file
){
return officerActivity.saveRequestUpdate(rescue_id, latitude, longitude, zone, ward, streetid, streetname, remarks, loginId, file);
}
@GetMapping(value="/getRequestDataById")
public List<?> getRequestDataById(
@RequestParam(value="rescue_id", required = true) String rescue_id
){
return officerActivity.getRequestDataById(rescue_id);
}
}

60
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/controller/APIUserController.java

@ -0,0 +1,60 @@
package in.gov.chennaicorporation.mobileservice.gccsos.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.gccsos.service.UserActivity;
@RequestMapping("/gccofficialapp/api/gccsos/user/")
@RestController("gccofficialappUserSOSRest")
public class APIUserController {
@Autowired
private UserActivity userActivity;
@PostMapping(value="/saveRequest")
public List<?> saveRequest(
@RequestParam(value="contact_name", required = false) String contact_name,
@RequestParam(value="contact_number", required = false) String contact_number,
@RequestParam(value="latitude", required = false) String latitude,
@RequestParam(value="longitude", required = false) String longitude,
@RequestParam(value="zone", required = false) String zone,
@RequestParam(value="ward", required = false) String ward,
@RequestParam(value="streetid", required = false) String streetid,
@RequestParam(value="streetname", required = false) String streetname,
@RequestParam(value="location_details", required = false) String location_details,
@RequestParam(value="request_type", required = false) String request_type,
@RequestParam(value="no_of_count", required = false) String no_of_count,
@RequestParam(value="if_any", required = false) String if_any,
@RequestParam(value="land_mark", required = false) String land_mark,
@RequestParam(value="remarks", required = false) String remarks,
@RequestParam(value="loginId", required = false) String loginId
){
return userActivity.saveRequest(contact_name, contact_number,
latitude, longitude, zone, ward, streetid, streetname,
location_details, request_type, no_of_count, if_any,
land_mark, remarks, loginId);
}
@GetMapping(value="/getMyRequest")
public List<?> getMyRequest(
@RequestParam(value="loginId", required = true) String loginId,
@RequestParam(value="status", required = true) String status
){
return userActivity.getMyRequest(loginId,status);
}
@GetMapping(value="/getRequestDataById")
public List<?> getRequestDataById(
@RequestParam(value="rescue_id", required = true) String rescue_id
){
return userActivity.getRequestDataById(rescue_id);
}
}

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

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

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

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

650
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/service/OfficerActivity.java

@ -0,0 +1,650 @@
package in.gov.chennaicorporation.mobileservice.gccsos.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.web.multipart.MultipartFile;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class OfficerActivity {
private JdbcTemplate jdbcSOSTemplate;
private final Environment environment;
@Autowired
public void setDataSource(@Qualifier("mysqlGccSOSDataSource") DataSource sosDataSource) {
this.jdbcSOSTemplate = new JdbcTemplate(sosDataSource);
}
@Autowired
public OfficerActivity(Environment environment) {
this.environment = environment;
}
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 List<Map<String, Object>> dashboard(
String loginId,
String request_type
){
String requestQueryValue="";
if ("Assistance".equals(request_type)) {
requestQueryValue = "'Medical','Food'"; // Assistance
} else if ("Rescue Operation".equals(request_type)) {
requestQueryValue = "'Rescue'"; // Rescue Operation
}
else if ("Emergency".equals(request_type)) {
requestQueryValue = "'CurrentInWater','FloodWater'"; // Rescue Operation
}
String sqlQuery = "SELECT "
+ "SUM(1) AS `Requested`, "
+ "SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS `Pending`, "
+ "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `Closed` "
+ "FROM `rescue` "
+ "WHERE `isactive`=1 ";
if (request_type != null && !request_type.isEmpty() && !request_type.isBlank()) {
sqlQuery = sqlQuery + " AND request_type IN ("+requestQueryValue+")";
}
sqlQuery = sqlQuery + "";
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> dashboardByType(
String loginId,
String request_type,
String status
){
String requestQueryValue="";
String statusQueryValue="";
if ("Assistance".equals(request_type)) {
requestQueryValue = "'Medical','Food'"; // Assistance
} else if ("Rescue Operation".equals(request_type)) {
requestQueryValue = "'Rescue'"; // Rescue Operation
}
else if ("Emergency".equals(request_type)) {
requestQueryValue = "'CurrentInWater','FloodWater'"; // Rescue Operation
}
if ("Request".equals(status)) {
statusQueryValue = "0,1"; // Assistance
} else if ("Pending".equals(status)) {
statusQueryValue = "0"; // Open
} else if ("Closed".equals(status)) {
statusQueryValue = "1"; // Closed
}
String sqlQuery = "SELECT ";
if ("Assistance".equals(request_type)) {
sqlQuery = sqlQuery + "SUM(CASE WHEN `request_type` = 'Medical' THEN 1 ELSE 0 END) AS `Medical`, "
+ "SUM(CASE WHEN `request_type` = 'Food' THEN 1 ELSE 0 END) AS `Food` ";
}
else if ("Rescue Operation".equals(request_type)) {
sqlQuery = sqlQuery + "SUM(CASE WHEN `request_type` = 'Rescue' THEN 1 ELSE 0 END) AS `Rescue` ";
}
else if ("Emergency".equals(request_type)) {
sqlQuery = sqlQuery + "SUM(CASE WHEN `request_type` = 'CurrentInWater' THEN 1 ELSE 0 END) AS `CurrentInWater`, "
+ "SUM(CASE WHEN `request_type` = 'FloodWater' THEN 1 ELSE 0 END) AS `FloodWater` ";
}
sqlQuery = sqlQuery + "FROM `rescue` WHERE `isactive`=1 ";
if (requestQueryValue != null && !requestQueryValue.isEmpty() && !requestQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND request_type IN ("+requestQueryValue+")";
}
if (statusQueryValue != null && !statusQueryValue.isEmpty() && !statusQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND status IN ("+statusQueryValue+")";
}
sqlQuery = sqlQuery + "";
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("data", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> dashboardByZone(
String loginId,
String request_type,
String status,
String zone,
String ward
){
String selectVariable ="zone";
String requestQueryValue="";
String statusQueryValue="";
if ("Medical".equals(request_type)) {
requestQueryValue = "'Medical'"; // Medical
} else if ("Food".equals(request_type)) {
requestQueryValue = "'Food'"; // Food
} else if ("Rescue".equals(request_type)) {
requestQueryValue = "'Rescue'"; // Rescue
}else if ("CurrentInWater".equals(request_type)) {
requestQueryValue = "'CurrentInWater'"; // Current In Water
}else if ("FloodWater".equals(request_type)) {
requestQueryValue = "'FloodWater'"; // Flood Water
}
if ("Request".equals(status)) {
statusQueryValue = "0,1"; // Assistance
} else if ("Pending".equals(status)) {
statusQueryValue = "0"; // Open
} else if ("Closed".equals(status)) {
statusQueryValue = "1"; // 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 ";
sqlQuery = sqlQuery + selectVariable + ""
+ " ,SUM(1) AS `Total` ";
sqlQuery = sqlQuery + "FROM `rescue` WHERE `isactive`=1 ";
if (requestQueryValue != null && !requestQueryValue.isEmpty() && !requestQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND request_type IN ("+requestQueryValue+")";
}
if (statusQueryValue != null && !statusQueryValue.isEmpty() && !statusQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND status IN ("+statusQueryValue+")";
}
sqlQuery = sqlQuery + "GROUP BY "+selectVariable+" ORDER BY zone ASC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put(request_type, result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> dashboardByWard(
String loginId,
String request_type,
String status,
String zone,
String ward
){
String selectVariable ="ward";
String requestQueryValue="";
String statusQueryValue="";
if ("Medical".equals(request_type)) {
requestQueryValue = "'Medical'"; // Medical
} else if ("Food".equals(request_type)) {
requestQueryValue = "'Food'"; // Food
} else if ("Rescue".equals(request_type)) {
requestQueryValue = "'Rescue'"; // Rescue
}else if ("CurrentInWater".equals(request_type)) {
requestQueryValue = "'CurrentInWater'"; // Current In Water
}else if ("FloodWater".equals(request_type)) {
requestQueryValue = "'FloodWater'"; // Flood Water
}
if ("Request".equals(status)) {
statusQueryValue = "0,1"; // Assistance
} else if ("Pending".equals(status)) {
statusQueryValue = "0"; // Open
} else if ("Closed".equals(status)) {
statusQueryValue = "1"; // Closed
}
if (ward != null && !ward.isEmpty() && !ward.isBlank()) {
selectVariable = selectVariable + ",streetid,streetName";
}
String sqlQuery = "SELECT ";
sqlQuery = sqlQuery + selectVariable + ""
+ " ,SUM(1) AS `Total` ";
sqlQuery = sqlQuery + "FROM `rescue` WHERE `isactive`=1 ";
if (requestQueryValue != null && !requestQueryValue.isEmpty() && !requestQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND request_type IN ("+requestQueryValue+")";
}
if (statusQueryValue != null && !statusQueryValue.isEmpty() && !statusQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND status IN ("+statusQueryValue+")";
}
sqlQuery = sqlQuery + "GROUP BY "+selectVariable+" ORDER BY `ward` ASC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("zone", result);
return Collections.singletonList(response);
}
public List<Map<String, Object>> dashboardByList(
String loginId,
String request_type,
String status,
String zone,
String ward
){
String selectVariable ="ward";
String requestQueryValue="";
String statusQueryValue="";
if ("Medical".equals(request_type)) {
requestQueryValue = "'Medical'"; // Medical
} else if ("Food".equals(request_type)) {
requestQueryValue = "'Food'"; // Food
} else if ("Rescue".equals(request_type)) {
requestQueryValue = "'Rescue'"; // Rescue
}else if ("CurrentInWater".equals(request_type)) {
requestQueryValue = "'CurrentInWater'"; // Current In Water
}else if ("FloodWater".equals(request_type)) {
requestQueryValue = "'FloodWater'"; // Flood Water
}
if ("Request".equals(status)) {
statusQueryValue = "0,1"; // Assistance
} else if ("Pending".equals(status)) {
statusQueryValue = "0"; // Open
} else if ("Closed".equals(status)) {
statusQueryValue = "1"; // Closed
}
String sqlQuery = "SELECT * FROM `rescue` WHERE `isactive`=1 ";
if (requestQueryValue != null && !requestQueryValue.isEmpty() && !requestQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND request_type IN ("+requestQueryValue+")";
}
if (statusQueryValue != null && !statusQueryValue.isEmpty() && !statusQueryValue.isBlank()) {
sqlQuery = sqlQuery + " AND status IN ("+statusQueryValue+") ";
}
sqlQuery = sqlQuery + "ORDER BY cdate ASC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("ward", result);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> getAllRequest(
String request_type,
String zone,
String ward,
String streetid,
String fromdate,
String todate,
String loginId,
String status){
String statusidQuery ="";
System.out.println("Status: "+status);
// Use equals() for string comparison
if ("Pending".equals(status)) {
statusidQuery = " AND `status` = 0 "; // Open
} else if ("Closed".equals(status)) {
statusidQuery = " AND `status` = 1 "; // Closed
}
String sqlQuery = "SELECT *,CASE"
+ " WHEN status = 0 THEN 'Pending' "
+ " WHEN status = 1 THEN 'Closed' "
+ " ELSE 'unknown'"
+ " END AS status_name "
+ " FROM `rescue` WHERE `isactive`=1 ";
// 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 (request_type != null && !request_type.isEmpty() && !request_type.isBlank()) {
sqlQuery = sqlQuery + " AND request_type = '"+request_type+"' ";
}
if (todate == null || todate.isEmpty() || todate.isBlank()) {
todate = fromdate;
}
if (fromdate != null && !fromdate.isEmpty() && !fromdate.isBlank()) {
sqlQuery = sqlQuery + " "
+ "AND `cdate` BETWEEN STR_TO_DATE('"+fromdate+" 00:00:00', '%d-%m-%Y %H:%i:%s') "
+ "AND STR_TO_DATE('"+todate+" 23:59:59', '%d-%m-%Y %H:%i:%s')";
}
sqlQuery = sqlQuery + statusidQuery + "ORDER BY `id` DESC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("data", result);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> reportByDate(
String fromdate,
String todate,
String request_type,
String zone,
String ward,
String streetid,
String loginId,
String status) {
String selectVariable ="zone";
String statusidQuery ="";
/*
System.out.println("Status: "+status);
// Use equals() for string comparison
if ("Open".equals(status)) {
statusidQuery = " AND `status` = 0 "; // Open
} else if ("Closed".equals(status)) {
statusidQuery = " AND `status` = 1 "; // 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(1) AS `Requested`, "
+ "SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS `Pending`, "
+ "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `Closed` "
+ "FROM `rescue` "
+ "WHERE `isactive`=1 ";
// 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 (request_type != null && !request_type.isEmpty() && !request_type.isBlank()) {
sqlQuery = sqlQuery + " AND request_type = '"+request_type+"' ";
}
if (todate == null || todate.isEmpty() || todate.isBlank()) {
todate = fromdate;
}
if (fromdate != null && !fromdate.isEmpty() && !fromdate.isBlank()) {
sqlQuery = sqlQuery + statusidQuery +" "
+ "AND `cdate` BETWEEN STR_TO_DATE('"+fromdate+" 00:00:00', '%d-%m-%Y %H:%i:%s') "
+ "AND STR_TO_DATE('"+todate+" 23:59:59', '%d-%m-%Y %H:%i:%s') ";
}
sqlQuery = sqlQuery + "GROUP BY "+selectVariable+" ORDER BY zone ASC";
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "Success");
response.put("message", "Request List");
response.put("data", result);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> saveRequestUpdate(
String rescue_id,
String latitude,
String longitude,
String zone,
String ward,
String streetid,
String streetname,
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("sos_activity_foldername");
var year = DateTimeUtil.getCurrentYear();
var month = DateTimeUtil.getCurrentMonth();
var day = DateTimeUtil.getCurrentDay();
uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+day+"/";
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 = rescue_id +"_"+ datetimetxt + "_" + file.getOriginalFilename();
String fileName = OrgfileName.replaceAll("\\s+", ""); // Remove space on filename
String filePath = uploadDirectory + "/" + fileName;
String filepath_txt = "/"+serviceFolderName + year +"/"+month+"/"+day+"/"+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 `rescue_officer_update`(`rescue_id`, "
+ "`activity_photo`, `filepath`, `filetype`, `filesize`, `remarks`, "
+ "`latitude`, `longitude`, `zone`, `ward`, `streetid`, `streetname`, `officer_id`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcSOSTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, rescue_id);
ps.setString(2, fileName);
ps.setString(3, filepath_txt);
ps.setString(4, fileType);
ps.setLong(5, fileSize);
ps.setString(6, remarks);
ps.setString(7, latitude);
ps.setString(8, longitude);
ps.setString(9, zone);
ps.setString(10, ward);
ps.setString(11, streetid);
ps.setString(12, streetname);
ps.setString(13, loginId);
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 rescue officer update was inserted successfully!");
System.out.println("A rescue officer update was inserted successfully! rescue Update ID: " + generatedId);
if(!rescue_id.isBlank() && !rescue_id.isEmpty()) {
// Pending
String sqlQuery_u = "UPDATE `rescue` SET `status`=1 WHERE `id`='"+rescue_id+"'";
jdbcSOSTemplate.update(sqlQuery_u);
}
} else {
response.put("status", "error");
response.put("message", "Failed to insert rescue officer update.");
}
} 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 (officer update)!");
}
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> getRequestDataById(
String rescue_id){
String sqlQuery = "SELECT *,CASE"
+ " WHEN status = 0 THEN 'Pending' "
+ " WHEN status = 1 THEN 'Closed' "
+ " ELSE 'unknown'"
+ " END AS status_name "
+ " FROM `rescue` WHERE `id`='"+rescue_id+"'";
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
if (result.isEmpty()) {
return result;
}else {
String sqlQuery2 = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files', filepath) AS imageUrl "
+ "FROM `rescue_officer_update` WHERE rescue_id='"+rescue_id+"'";
List<Map<String, Object>> result2 = jdbcSOSTemplate.queryForList(sqlQuery2);
System.out.println(sqlQuery2);
// Add the result2 and result3 to the main result map
result.get(0).put("officer_activity_data", result2);
}
response.put("status", "success");
response.put("message", "Request Information");
response.put("Data", result);
return Collections.singletonList(response);
}
}

224
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccsos/service/UserActivity.java

@ -0,0 +1,224 @@
package in.gov.chennaicorporation.mobileservice.gccsos.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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil;
@Service
public class UserActivity {
private JdbcTemplate jdbcSOSTemplate;
private final Environment environment;
@Autowired
public void setDataSource(@Qualifier("mysqlGccSOSDataSource") DataSource sosDataSource) {
this.jdbcSOSTemplate = new JdbcTemplate(sosDataSource);
}
@Autowired
public UserActivity(Environment environment) {
this.environment = environment;
}
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>> saveRequest(
String contact_name,
String contact_number,
String latitude,
String longitude,
String zone,
String ward,
String streetid,
String streetname,
String location_details,
String request_type,
String no_of_count,
String if_any,
String land_mark,
String remarks,
String loginId
) {
List<Map<String, Object>> result=null;
Map<String, Object> response = new HashMap<>();
int lastInsertId = 0;
String sqlQuery = "INSERT INTO `rescue`(`contact_name`, `contact_number`, `latitude`, `longitude`, `zone`, `ward`, "
+ "`streetid`, `streetname`, `location_details`, `request_type`, `no_of_count`, `if_any`, `land_mark`, "
+ "`remarks`, `user_id`) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
int affectedRows = jdbcSOSTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"});
ps.setString(1, contact_name);
ps.setString(2, contact_number);
ps.setString(3, latitude);
ps.setString(4, longitude);
ps.setString(5, zone);
ps.setString(6, ward);
ps.setString(7, streetid);
ps.setString(8, streetname);
ps.setString(9, location_details);
ps.setString(10, request_type);
ps.setString(11, no_of_count);
ps.setString(12, if_any);
ps.setString(13, land_mark);
ps.setString(14, remarks);
ps.setString(15, loginId);
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 SOS request was inserted successfully!");
System.out.println("A new SOS request was inserted successfully! Insert ID: " + generatedId);
} else {
response.put("status", "error");
response.put("message", "Failed to insert a new SOS request.");
}
} 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>> getMyRequest(
String loginId,
String status){
String statusidQuery ="";
// Use equals() for string comparison
if ("Pending".equals(status)) {
statusidQuery = " AND `status` = 0 "; // Open
} else if ("Closed".equals(status)) {
statusidQuery = " AND `status` = 1 "; // Closed
}
String sqlQuery = "SELECT *,CASE"
+ " WHEN status = 0 THEN 'Pending' "
+ " WHEN status = 1 THEN 'Closed' "
+ " ELSE 'unknown'"
+ " END AS status_name "
+ " FROM `rescue` WHERE `user_id`='"+loginId+"' ";
sqlQuery = sqlQuery + statusidQuery;
System.out.println(sqlQuery);
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("message", "Request Information");
response.put("Data", result);
return Collections.singletonList(response);
}
@Transactional
public List<Map<String, Object>> getRequestDataById(
String rescue_id){
String sqlQuery = "SELECT *,CASE"
+ " WHEN status = 0 THEN 'Pending' "
+ " WHEN status = 1 THEN 'Closed' "
+ " ELSE 'unknown'"
+ " END AS status_name "
+ " FROM `rescue` WHERE `id`='"+rescue_id+"'";
List<Map<String, Object>> result = jdbcSOSTemplate.queryForList(sqlQuery);
Map<String, Object> response = new HashMap<>();
if (result.isEmpty()) {
return result;
}else {
String sqlQuery2 = "SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files', filepath) AS imageUrl "
+ "FROM `rescue_officer_update` WHERE rescue_id='"+rescue_id+"'";
List<Map<String, Object>> result2 = jdbcSOSTemplate.queryForList(sqlQuery2);
System.out.println(sqlQuery2);
// Add the result2 and result3 to the main result map
result.get(0).put("officer_activity_data", result2);
}
response.put("status", "success");
response.put("message", "Request Information");
response.put("Data", result);
return Collections.singletonList(response);
}
}

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

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

24
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java

@ -0,0 +1,24 @@
package in.gov.chennaicorporation.mobileservice.penalty.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.mobileservice.penalty.service.CattleCatchService;
@RequestMapping("/gccofficialapp/cattlecatch/api")
@RestController("apiCattleCatchRest")
public class APICattleCatchController {
@Autowired
private CattleCatchService cattleCatchService;
@GetMapping(value="/getpenaltytypes")
public List<Map<String, Object>> getPenaltyTypes() {
return cattleCatchService.getPenaltyTypeList();
}
}

24
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyController.java

@ -0,0 +1,24 @@
package in.gov.chennaicorporation.mobileservice.penalty.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import in.gov.chennaicorporation.mobileservice.penalty.service.PenaltyService;
@RequestMapping("/gccofficialapp/penalty/api")
@RestController("apiPenaltyRest")
public class APIPenaltyController {
@Autowired
private PenaltyService penaltyService;
@GetMapping(value="/getpenaltytypes")
public List<Map<String, Object>> getPenaltyTypes() {
return penaltyService.getPenaltyTypeList();
}
}

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

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

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

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

29
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java

@ -0,0 +1,29 @@
package in.gov.chennaicorporation.mobileservice.penalty.service;
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 CattleCatchService {
private JdbcTemplate jdbcPenaltyTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlPenaltyDataSource") DataSource penaltyDataSource) {
this.jdbcPenaltyTemplate = new JdbcTemplate(penaltyDataSource);
}
@Transactional
public List<Map<String, Object>> getPenaltyTypeList() {
String SqlQuery = "SELECT `id`, `name`, `display_name` FROM `penalty_types` WHERE `isdelete`=0 AND `isactive`=1";
List<Map<String, Object>> result = jdbcPenaltyTemplate.queryForList(SqlQuery);
return result;
}
}

29
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyService.java

@ -0,0 +1,29 @@
package in.gov.chennaicorporation.mobileservice.penalty.service;
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 PenaltyService {
private JdbcTemplate jdbcPenaltyTemplate;
@Autowired
public void setDataSource(@Qualifier("mysqlPenaltyDataSource") DataSource penaltyDataSource) {
this.jdbcPenaltyTemplate = new JdbcTemplate(penaltyDataSource);
}
@Transactional
public List<Map<String, Object>> getPenaltyTypeList() {
String SqlQuery = "SELECT `id`, `name`, `display_name` FROM `penalty_types` WHERE `isdelete`=0 AND `isactive`=1";
List<Map<String, Object>> result = jdbcPenaltyTemplate.queryForList(SqlQuery);
return result;
}
}

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

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

922
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/DataSyncService.java

@ -0,0 +1,922 @@
package in.gov.chennaicorporation.mobileservice.service;
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 javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
public class DataSyncService {
private JdbcTemplate oracleERPJdbcTemplate;
private JdbcTemplate mysqlJdbcTemplate;
@Autowired
@Qualifier("oracleERPDataSource")
private DataSource oracleERPDataSource;
@Autowired
public void setDataSource(@Qualifier("oracleERPDataSource") DataSource oracleERPDataSource,
@Qualifier("mysqlPGRMasterDataSource") DataSource mysqlDataSource) {
this.oracleERPJdbcTemplate = new JdbcTemplate(oracleERPDataSource);
this.mysqlJdbcTemplate = new JdbcTemplate(mysqlDataSource);
}
private int getTotalRecordCount(String tablename) {
String countQuery = "SELECT COUNT(*) FROM "+tablename;
if(tablename.equals("EG_USER@erp")) {
countQuery = "SELECT COUNT(*) FROM "+tablename+" WHERE ISPORTALUSER!=1";
}
if(tablename.equals("EGGR_COMPLAINTDETAILS@erp")) {
countQuery = "SELECT COUNT(*) FROM "+tablename+" WHERE YEAR(COMPLAINTDATE) = '2023'";
}
if(tablename.equals("EGGR_REDRESSALDETAILS@erp")) {
countQuery = "SELECT COUNT(*) FROM "+tablename+" WHERE YEAR(RESPONSEDATE) = '2023'";
}
return oracleERPJdbcTemplate.queryForObject(countQuery, Integer.class);
}
private List<Map<String, Object>> fetchBatch(int startRow, int endRow, String tablename) {
String fetchQuery = "";
fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+") a " +
"WHERE ROWNUM <= ?) WHERE rnum > ?";
if(tablename.equals("EG_USER@erp")) {
fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+" WHERE ISPORTALUSER!=1) a " +
"WHERE ROWNUM <= ?) WHERE rnum > ?";
}
if(tablename.equals("EGGR_COMPLAINTDETAILS@erp")) {
fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+" WHERE YEAR(COMPLAINTDATE) = '2023') a " +
"WHERE ROWNUM <= ?) WHERE rnum > ?";
}
if(tablename.equals("EGGR_REDRESSALDETAILS@erp")) {
fetchQuery = "SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM "+tablename+" WHERE AND YEAR(RESPONSEDATE) = '2023') a " +
"WHERE ROWNUM <= ?) WHERE rnum > ?";
}
return oracleERPJdbcTemplate.queryForList(fetchQuery, endRow, startRow);
}
private List<Map<String, Object>> fetchExistingData(List<Object> ids, String tablename, String primaryKeyColumn) {
String idList = ids.stream().map(Objects::toString).collect(Collectors.joining(", "));
String fetchQuery = "SELECT * FROM "+tablename+" WHERE "+primaryKeyColumn+" IN (" + idList + ")";
System.out.println(fetchQuery);
return mysqlJdbcTemplate.queryForList(fetchQuery);
}
private boolean compareAndPrint(Object existingPrimaryKeyValue, Object primaryKeyValue) {
Integer existingKey = (existingPrimaryKeyValue instanceof Integer) ? (Integer) existingPrimaryKeyValue : null;
Integer keyToCompare = (primaryKeyValue instanceof BigDecimal) ? ((BigDecimal) primaryKeyValue).intValue() : null;
//System.out.println("Comparing existingPrimaryKeyValue: " + existingKey + " (" + (existingKey != null ? existingKey.getClass().getName() : "null") + ") with primaryKeyValue: " + keyToCompare + " (" + (keyToCompare != null ? keyToCompare.getClass().getName() : "null") + ")");
return Objects.equals(existingKey, keyToCompare);
}
public void syncEgUserData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EG_USER@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "id_user"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EG_USER@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EG_USER",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_USER (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEgDepartmentData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EG_DEPARTMENT@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "ID_DEPT"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EG_DEPARTMENT@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EG_DEPARTMENT",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_DEPARTMENT (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEgBoundaryData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EG_BOUNDARY@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "ID_BNDRY"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EG_BOUNDARY@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EG_BOUNDARY",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EG_BOUNDARY (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEggrComplaintStatusData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EGGR_COMPLAINTSTATUS@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "COMPLAINTSTATUSID"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTSTATUS@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTSTATUS",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTSTATUS (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEggrComplaintTypesData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EGGR_COMPLAINTTYPES@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "COMPLAINTTYPEID"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTTYPES@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTTYPES",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTTYPES (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEggrComplaintGroupData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EGGR_COMPLAINTGROUP@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "ID_COMPLAINTGROUP"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTGROUP@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTGROUP",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTGROUP (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEggrComplaintDetailsData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EGGR_COMPLAINTDETAILS@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "COMPLAINTID"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EGGR_COMPLAINTDETAILS@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EGGR_COMPLAINTDETAILS",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_COMPLAINTDETAILS (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
public void syncEggrRedressalDetailsData() {
int batchSize = 10000;
int totalRecords = getTotalRecordCount("EGGR_REDRESSALDETAILS@erp");
int totalBatches = (totalRecords + batchSize - 1) / batchSize; // Round up
System.out.println("totalRecords : " + totalRecords + "\n"
+ "totalBatches : " + totalBatches);
String autoIncrementColumn = "id"; // Replace 'id' with the actual auto-increment column name if different
String primaryKeyColumn = "REDRESSALID"; // Replace 'id_user' with the actual primary key column name if different
for (int batch = 0; batch < totalBatches; batch++) {
int startRow = batch * batchSize;
int endRow = startRow + batchSize;
long startTime = System.currentTimeMillis();
List<Map<String, Object>> rows = fetchBatch(startRow, endRow,"EGGR_REDRESSALDETAILS@erp");
long endTime = System.currentTimeMillis();
long queryTime = endTime - startTime;
System.out.println("Fetch Batch Time Taken: " + queryTime + " ms");
if (!rows.isEmpty()) {
// Extract primary keys from the fetched rows
List<Object> ids = rows.stream()
.map(row -> row.get(primaryKeyColumn))
.collect(Collectors.toList());
// Fetch existing data from MySQL
startTime = System.currentTimeMillis();
List<Map<String, Object>> existingRows = fetchExistingData(ids,"EGGR_REDRESSALDETAILS",primaryKeyColumn);
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Fetch Existing Data Time Taken: " + queryTime + " ms");
StringBuilder insertQuery = new StringBuilder("INSERT INTO EGGR_REDRESSALDETAILS (");
StringBuilder updateQuery = new StringBuilder(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
updateQuery.append(", ");
}
first = false;
insertQuery.append(key);
updateQuery.append(key).append("=VALUES(").append(key).append(")");
}
insertQuery.append(") VALUES (");
first = true;
for (String key : rows.get(0).keySet()) {
if (key.equalsIgnoreCase(autoIncrementColumn) || key.equalsIgnoreCase("RNUM")) {
continue; // Skip the auto-increment column and RNUM
}
if (!first) {
insertQuery.append(", ");
}
first = false;
insertQuery.append("?");
}
insertQuery.append(")").append(updateQuery.toString());
startTime = System.currentTimeMillis();
for (Map<String, Object> row : rows) {
Object primaryKeyValue = row.get(primaryKeyColumn);
// Filter to find if there is any existing row with the same primary key value
Map<String, Object> existingRow = existingRows.stream()
.filter(eRow -> compareAndPrint(eRow.get(primaryKeyColumn), primaryKeyValue))
.findFirst()
.orElse(null);
if (existingRow != null) {
System.out.println("Match found: primaryKeyValue: " + primaryKeyValue + " == existingPrimaryKeyValue: " + existingRow.get(primaryKeyColumn));
boolean hasChanges = !row.equals(existingRow);
if (hasChanges) {
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Updated: " + primaryKeyValue);
}
} else {
System.out.println("No match found: primaryKeyValue: " + primaryKeyValue);
Object[] values = row.entrySet().stream()
.filter(entry -> !entry.getKey().equalsIgnoreCase(autoIncrementColumn) && !entry.getKey().equalsIgnoreCase("RNUM"))
.map(Map.Entry::getValue)
.toArray();
mysqlJdbcTemplate.update(insertQuery.toString(), values);
System.out.println("Inserted: " + primaryKeyValue);
}
}
endTime = System.currentTimeMillis();
queryTime = endTime - startTime;
System.out.println("Insert/Update Time Taken: " + queryTime + " ms");
System.out.println("Batch " + (batch+1) + " Completed\n");
}
}
}
}

23
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OTPGenerator.java

@ -0,0 +1,23 @@
package in.gov.chennaicorporation.mobileservice.service;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
public class OTPGenerator {
private static final String NUMERIC_CHARACTERS = "0123456789";
private static final int OTP_LENGTH = 6;
public static String generateOTP(int OTP_LENGTH) {
SecureRandom random = new SecureRandom();
StringBuilder otp = new StringBuilder(OTP_LENGTH);
for (int i = 0; i < OTP_LENGTH; i++) {
int index = random.nextInt(NUMERIC_CHARACTERS.length());
otp.append(NUMERIC_CHARACTERS.charAt(index));
}
return otp.toString();
}
}

355
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java

@ -0,0 +1,355 @@
package in.gov.chennaicorporation.mobileservice.service;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.hibernate.internal.build.AllowSysOut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import in.gov.chennaicorporation.mobileservice.UpdateResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.client.RestTemplate;
@Service
public class OfficialAPIService {
private JdbcTemplate jdbcErpTemplate;
private JdbcTemplate jdbcUserTemplate;
private JdbcTemplate jdbcOfficalTemplate;
private JdbcTemplate jdbcActivityTemplate;
@Autowired
public void setDataSource(
@Qualifier("oracleERPDataSource") DataSource erpDataSource,
@Qualifier("mysqlGCCUserDataSource") DataSource gccUserDataSource,
@Qualifier("mysqlPGRMasterDataSource") DataSource officialDataSource,
@Qualifier("mysqlActivityDataSource") DataSource activityDataSource) {
this.jdbcErpTemplate = new JdbcTemplate(erpDataSource);
this.jdbcUserTemplate = new JdbcTemplate(gccUserDataSource);
this.jdbcOfficalTemplate = new JdbcTemplate(officialDataSource);
this.jdbcActivityTemplate = new JdbcTemplate(activityDataSource);
}
public List<Map<String, Object>> sendOTP(HttpServletRequest request,
@RequestParam("MobileNo") String MobileNo,
@RequestParam("generatedToken") String OTP) {
Boolean sendSMS = true;
Map<String, Object> successResponse =null;
if(getUserListByMobileNumber(MobileNo).size()<=0)
{
sendSMS = false;
successResponse = Map.of(
"status", 404,
"message", "Given mobile number “"+MobileNo+"” is not registered."
);
}
if(sendSMS) {
//Integer OTP = OTP;
String generatedToken = "Your OTP is " + OTP + ".OTP is valid for the next 5 minutes.\nBy\nGreater Chennai Corporation.";
//String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+MobileNo+"&from=GCCCRP&body="+generatedToken+"&entityid=1401572690000011081&templateid=1407165856492044436";
String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + MobileNo + "&from=GCCCRP&body=" + generatedToken + "&entityid=1401572690000011081&templateid=1407165856492044436";
System.out.println(urlString);
RestTemplate restTemplate = new RestTemplate();
System.out.println(getUserListByMobileNumber(MobileNo).size());
String Response = restTemplate.getForObject(urlString, String.class);
//System.out.println(Response);
// Add a success status and message to the result
successResponse = Map.of(
"status", 200,
"message", "SMS Send successfully to Mobile No "+MobileNo+".",
//"data", Response,
"OTP", OTP
);
}
return Collections.singletonList(successResponse);
}
@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 "erp":
//sqlQuery = "SELECT * FROM `EG_USER` WHERE `ISPORTALUSER` <> 1 AND `ISACTIVE` = 1 AND `EXTRAFIELD2` = ? AND `PIN` = ? LIMIT 1";
sqlQuery = "SELECT * FROM `EG_USER` WHERE `EXTRAFIELD2` = ? AND `PIN` = ? LIMIT 1";
result = jdbcOfficalTemplate.queryForList(sqlQuery, username, password);
break;
case "nonerp":
sqlQuery = "SELECT * FROM `EG_USER` WHERE `EXTRAFIELD2` = ? AND `PIN` = ? LIMIT 1";
result = jdbcOfficalTemplate.queryForList(sqlQuery, username, password);
break;
// additional cases can be added here
default:
sqlQuery = "SELECT * FROM `EG_USER` WHERE `EXTRAFIELD2` = ? AND `PIN` = ? LIMIT 1";
result = jdbcOfficalTemplate.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);
}
@Transactional
public List<UpdateResponse> updatePassword(String username, String password) {
// Initialize the list to hold the result message
List<UpdateResponse> responseList = new ArrayList<>();
try {
// SQL query for updating the password
String sqlQuery = "UPDATE `EG_USER` SET `PIN` = ? WHERE `EXTRAFIELD2` = ?";
// Execute the update query using jdbcTemplate and prepared statements to prevent SQL injection
int rowsAffected = jdbcOfficalTemplate.update(sqlQuery, password, username);
// Check if any rows were updated
if (rowsAffected > 0) {
responseList.add(new UpdateResponse(200, "Password or Pin updated successfully."));
} else {
responseList.add(new UpdateResponse(404, "Password or Pin not updated."));
}
} catch (Exception e) {
// Handle any exceptions that occur during the update process
responseList.add(new UpdateResponse(500, "Error updating Password or Pin: " + e.getMessage()));
}
// Return the list containing the update message
return responseList;
}
@Transactional
public List<Map<String, Object>> getUserListByMobileNumber(String mobileNo) {
String sqlQuery = "";
List<Map<String, Object>> result=null;
sqlQuery = "SELECT * FROM `EG_USER` WHERE `EXTRAFIELD2` = ? AND `ISACTIVE`=1";
result = jdbcOfficalTemplate.queryForList(sqlQuery, mobileNo);
return result;
}
@Transactional
public List<Map<String, Object>> getUserList() {
String SqlQuery = "";
SqlQuery="SELECT * FROM `EG_USER` WHERE `ISACTIVE`=1";
List<Map<String, Object>> result = jdbcOfficalTemplate.queryForList(SqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getUserinfo(String USER_NAME) {
String SqlQuery = "";
SqlQuery="SELECT * FROM `EG_USER` WHERE `USER_NAME`=? AND `ISACTIVE`=1";
List<Map<String, Object>> result = jdbcOfficalTemplate.queryForList(SqlQuery,USER_NAME);
return result;
}
@Transactional
public List<Map<String, Object>> getUserGroups(String loginId) {
String SqlQuery = "";
SqlQuery="SELECT `groups` FROM `user_mapping_details` WHERE `userid`=?";
System.out.println(SqlQuery);
System.out.println("loginId : "+loginId);
List<Map<String, Object>> result = jdbcUserTemplate.queryForList(SqlQuery,loginId);
return result;
}
@Transactional
public List<Map<String, Object>> getUserModules(String loginId) {
String SqlQuery = "";
String groups ="0";
List<Map<String, Object>> groupids=getUserGroups(loginId);
// Check if the list is not empty
if (groupids != null && !groupids.isEmpty()) {
// Retrieve the first map in the list
Map<String, Object> firstEntry = groupids.get(0);
// Check if the map contains the "groups" key
if (firstEntry.containsKey("groups")) {
// Get the "groups" value
groups = (String) firstEntry.get("groups");
// Do something with the groups value
System.out.println("Groups: " + groups);
} else {
System.out.println("The 'groups' key is not present.");
}
} else {
System.out.println("No data found in groupids.");
}
//SqlQuery="SELECT GROUP_CONCAT(`module_id`) AS module_ids FROM `user_group_module_access` WHERE `group_id` IN ("+groups+") GROUP by `group_id`";
SqlQuery="SELECT GROUP_CONCAT(DISTINCT `module_id` ORDER BY `module_id` ASC) AS module_ids "
+ "FROM `user_group_module_access` "
+ "WHERE `group_id` IN ("+groups+")";
List<Map<String, Object>> result = jdbcUserTemplate.queryForList(SqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getUserMenuItem(String loginId) {
String SqlQuery = "";
String menus ="0";
List<Map<String, Object>> moduleids=getUserModules(loginId);
// Check if the list is not empty
if (moduleids != null && !moduleids.isEmpty()) {
// Retrieve the first map in the list
Map<String, Object> firstEntry = moduleids.get(0);
// Check if the map contains the "groups" key
if (firstEntry.containsKey("module_ids")) {
// Get the "groups" value
menus = (String) firstEntry.get("module_ids");
// Do something with the groups value
System.out.println("Menus: " + menus);
} else {
System.out.println("The 'module_ids' key is not present.");
}
} else {
System.out.println("No data found in moduleids.");
}
//SqlQuery="SELECT GROUP_CONCAT(`menuitem_id`) AS menuitem_ids FROM `user_group_menu_access` WHERE `module_id` IN ("+menus+") GROUP by `module_id`";
SqlQuery="SELECT GROUP_CONCAT(DISTINCT `menuitem_id` ORDER BY `menuitem_id` ASC) AS menuitem_ids FROM "
+ "`user_group_menu_access` WHERE `module_id` IN ("+menus+")";
List<Map<String, Object>> result = jdbcUserTemplate.queryForList(SqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getMenu(String loginId) {
System.out.println("getMenu LoginID: " + loginId);
String SqlQuery = "";
String menus ="0";
if(loginId.isBlank() || loginId.isEmpty() || loginId==null || loginId.equals(null) || loginId.equals("null")) {
loginId="11342";
}
List<Map<String, Object>> moduleids=getUserModules(loginId);
// Check if the list is not empty
if (moduleids != null && !moduleids.isEmpty()) {
// Retrieve the first map in the list
Map<String, Object> firstEntry = moduleids.get(0);
// Check if the map contains the "groups" key
if (firstEntry.containsKey("module_ids")) {
// Get the "groups" value
menus = (String) firstEntry.get("module_ids");
// Do something with the groups value
System.out.println("Menus: " + menus);
} else {
System.out.println("The 'module_ids' key is not present.");
}
} else {
System.out.println("No data found in moduleids.");
}
SqlQuery="SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/app_icon/menu/', icon_url) "
+ "AS iconUrl FROM `modules` WHERE `ISACTIVE`=1 AND `id` IN ("+menus+")";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(SqlQuery);
return result;
}
@Transactional
public List<Map<String, Object>> getSubMenu(String loginId, String menuId) {
String SqlQuery = "";
String menuitem ="0";
if(loginId.isBlank() || loginId.isEmpty() || loginId==null || loginId.equals(null) || loginId.equals("null")) {
loginId="11342";
}
List<Map<String, Object>> moduleids=getUserMenuItem(loginId);
// Check if the list is not empty
if (moduleids != null && !moduleids.isEmpty()) {
// Retrieve the first map in the list
Map<String, Object> firstEntry = moduleids.get(0);
// Check if the map contains the "groups" key
if (firstEntry.containsKey("menuitem_ids")) {
// Get the "groups" value
menuitem = (String) firstEntry.get("menuitem_ids");
// Do something with the groups value
System.out.println("MenuItems: " + menuitem);
} else {
System.out.println("The 'menuitem_ids' key is not present.");
}
} else {
System.out.println("No data found in menuitem_ids.");
}
SqlQuery="SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/app_icon/menu/', icon_url) "
+ "AS iconUrl FROM `menuitem` WHERE `ISACTIVE`=1 AND `module_id`=? AND `id` IN ("+menuitem+")";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(SqlQuery,menuId);
return result;
}
@Transactional
public List<Map<String, Object>> getSubSubMenu(String loginId, String menuId, String submenuId ) {
String SqlQuery = "";
SqlQuery="SELECT *,CONCAT('https://gccservices.chennaicorporation.gov.in/gccofficialapp/files/app_icon/menu/', icon_url) AS iconUrl FROM `submenuitem` WHERE `ISACTIVE`=1 AND `module_id`=? AND `menuitem_id`=?";
List<Map<String, Object>> result = jdbcActivityTemplate.queryForList(SqlQuery,menuId,submenuId);
return result;
}
}

33
mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/PetAPIService.java

@ -0,0 +1,33 @@
package in.gov.chennaicorporation.mobileservice.service;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import in.gov.chennaicorporation.mobileservice.configuration.AppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Service
public class PetAPIService {
private final RestTemplate restTemplate;
private final AppConfig appConfig;
@Autowired
public PetAPIService(
RestTemplate restTemplate,
AppConfig appConfig) {
this.restTemplate = restTemplate;
this.appConfig = appConfig;
}
public List<Map<String, Object>> fetchApiData(String fromDate, String toDate) {
String url = appConfig.petRegistration+"/api/admin/paymentInfo?"; // Replace with the actual URL
url = url + "fromDate="+fromDate+"&toDate="+toDate;
ResponseEntity<List> response = restTemplate.getForEntity(url, List.class);
return response.getBody();
}
}

BIN
mobileservice/src/main/resources/.DS_Store

1
mobileservice/src/main/resources/application-local.properties

@ -0,0 +1 @@
assets.base-url=/assets/

1
mobileservice/src/main/resources/application-production.properties

@ -0,0 +1 @@
assets.base-url=/gccofficialapp/assets/

34
mobileservice/src/main/resources/application.properties

@ -0,0 +1,34 @@
#spring.profiles.active=local
spring.profiles.active=production
spring.application.name=Mobile Service
# Enable live reload (default is true)
spring.devtools.livereload.enabled=true
# Enable restart (default is true)
spring.devtools.restart.enabled=true
# HTTP Server
server.port = 8067
server.error.include-stacktrace= on_param
# Hibernate logging
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
# Maximum file size
spring.servlet.multipart.max-file-size=20MB
# Maximum request size (including all files)
spring.servlet.multipart.max-request-size=20MB
file.upload.directory=${user.dir}/gcc_mobile_service_uploads/
activity_foldername = asset_activity/
activity_new_asset_foldername = asset_images/
brr_activity_foldername= brr_activity_images/
sos_activity_foldername= sos_rescue_activity_images/

65
mobileservice/src/main/resources/static/assets/_js/main/app.js

@ -0,0 +1,65 @@
/*
* Document : app.js
* Author : pixelcave
* Description: Main entry point
*
*/
// Import required modules
import Template from './modules/template';
// App extends Template
export default class App extends Template {
/*
* Auto called when creating a new instance
*
*/
constructor() {
super();
}
/*
* Here you can override or extend any function you want from Template class
* if you would like to change/extend/remove the default functionality.
*
* This way it will be easier for you to update the module files if a new update
* is released since all your changes will be in here overriding the original ones.
*
* Let's have a look at the _uiInit() function, the one that runs the first time
* we create an instance of Template class or App class which extends it. This function
* inits all vital functionality but you can change it to fit your own needs.
*
*/
/*
* EXAMPLE #1 - Removing default functionality by making it empty
*
*/
// _uiInit() {}
/*
* EXAMPLE #2 - Extending default functionality with additional code
*
*/
// _uiInit() {
// // Call original function
// super._uiInit();
//
// // Your extra JS code afterwards
// }
/*
* EXAMPLE #3 - Replacing default functionality by writing your own code
*
*/
// _uiInit() {
// // Your own JS code without ever calling the original function's code
// }
}
// Create a new instance of App
window.Dashmix = new App();

1110
mobileservice/src/main/resources/static/assets/_js/main/modules/helpers.js
File diff suppressed because it is too large
View File

802
mobileservice/src/main/resources/static/assets/_js/main/modules/template.js

@ -0,0 +1,802 @@
/*
* Document : template.js
* Author : pixelcave
* Description: UI Framework custom functionality
*
*/
// Imports
import * as bootstrap from 'bootstrap';
import SimpleBar from 'simplebar';
import Helpers from './helpers';
// Assignments
window.bootstrap = bootstrap;
window.SimpleBar = SimpleBar;
// Template
export default class Template {
/*
* Auto called when creating a new instance
*
*/
constructor() {
this.onLoad(() => this._uiInit());
}
/*
* Init all vital functionality
*
*/
_uiInit() {
// Layout variables
this._lHtml = document.documentElement;
this._lBody = document.body;
this._lpageLoader = document.getElementById('page-loader');
this._lPage = document.getElementById('page-container');
this._lSidebar = document.getElementById('sidebar');
this._lSidebarScrollCon = this._lSidebar && this._lSidebar.querySelector('.js-sidebar-scroll');
this._lSideOverlay = document.getElementById('side-overlay');
this._lResize = false;
this._lHeader = document.getElementById('page-header');
this._lHeaderSearch = document.getElementById('page-header-search');
this._lHeaderSearchInput = document.getElementById('page-header-search-input');
this._lHeaderLoader = document.getElementById('page-header-loader');
this._lMain = document.getElementById('main-container');
this._lFooter = document.getElementById('page-footer');
// Helper variables
this._lSidebarScroll = false;
this._lSideOverlayScroll = false;
// Base UI Init
this._uiHandleTheme();
this._uiHandleDarkMode();
this._uiHandleSidebars();
this._uiHandleHeader();
this._uiHandleNav();
// API Init
this._uiApiLayout();
this._uiApiBlocks();
// Init the following helpers by default
this.helpers([
'bs-tooltip',
'bs-popover',
'dm-toggle-class',
'dm-year-copy',
'dm-ripple',
]);
// Page Loader (hide it)
this._uiHandlePageLoader();
}
/*
* Handles sidebar and side overlay scrolling functionality/styles
*
*/
_uiHandleSidebars(mode = 'init') {
let self = this;
if (self._lSidebar || self._lSideOverlay) {
if (mode === 'init') {
// Add 'side-trans-enabled' class to #page-container (enables sidebar and side overlay transition on open/close)
// Fixes IE10, IE11 and Edge bug in which animation was executed on each page load
self._lPage.classList.add('side-trans-enabled');
// Remove side transitions on window resizing
window.addEventListener('resize', () => {
clearTimeout(self._lResize);
self._lPage.classList.remove('side-trans-enabled');
self._lResize = setTimeout(() => { self._lPage.classList.add('side-trans-enabled'); }, 500);
});
// Init custom scrolling
this._uiHandleSidebars('custom-scroll');
} else if (mode = 'custom-scroll') {
// If .side-scroll is added to #page-container, enable custom scrolling
if (self._lPage.classList.contains('side-scroll')) {
// Init custom scrolling on Sidebar
if ((self._lSidebar) && !self._lSidebarScroll) {
self._lSidebarScroll = new SimpleBar(self._lSidebarScrollCon);
}
// Init custom scrolling on Side Overlay
if ((self._lSideOverlay) && !self._lSideOverlayScroll) {
self._lSideOverlayScroll = new SimpleBar(self._lSideOverlay);
}
}
}
}
}
/*
* Handles header related classes
*
*/
_uiHandleHeader() {
let self = this;
// If the header is fixed and has the glass style, add the related class on scrolling to add a background color to the header
if (self._lPage.classList.contains('page-header-glass') && self._lPage.classList.contains('page-header-fixed')) {
window.addEventListener('scroll', e => {
if (window.scrollY > 60) {
self._lPage.classList.add('page-header-scroll');
} else {
self._lPage.classList.remove('page-header-scroll');
}
});
window.dispatchEvent(new CustomEvent('scroll'));
}
}
/*
* Toggle Submenu functionality
*
*/
_uiHandleNav() {
let links = document.querySelectorAll('[data-toggle="submenu"]');
// When a submenu link is clicked
if (links) {
links.forEach(link => {
link.addEventListener('click', e => {
e.preventDefault();
// Get main navigation
let mainNav = link.closest('.nav-main');
// Check if we are in horizontal navigation, large screen and hover is enabled
if (
!(
(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) > 991
&& mainNav.classList.contains('nav-main-horizontal')
&& mainNav.classList.contains('nav-main-hover')
)
) {
// Get link's parent
let parentLi = link.closest('li');
if (parentLi.classList.contains('open')) {
// If submenu is open, close it..
parentLi.classList.remove('open');
link.setAttribute('aria-expanded', 'false');
} else {
// .. else if submenu is closed, close all other (same level) submenus first before open it
Array.from(link.closest('ul').children).forEach(el => {
el.classList.remove('open');
});
parentLi.classList.add('open');
link.setAttribute('aria-expanded', 'true');
}
}
return false;
});
});
}
}
/*
* Page loading screen functionality
*
*/
_uiHandlePageLoader(mode = 'hide', colorClass) {
if (mode === 'show') {
if (this._lpageLoader) {
if (colorClass) {
this._lpageLoader.className = '';
this._lpageLoader.classList.add(colorClass);
}
this._lpageLoader.classList.add('show');
} else {
let pageLoader = document.createElement('div');
pageLoader.id = 'page-loader';
if (colorClass) {
pageLoader.classList.add(colorClass);
}
pageLoader.classList.add('show');
this._lPage.insertBefore(pageLoader, this._lPage.firstChild);
this._lpageLoader = document.getElementById('page-loader');
}
} else if (mode === 'hide') {
if (this._lpageLoader) {
this._lpageLoader.classList.remove('show');
}
}
}
/*
* Saves/Retrieves Dark Mode preference to local storage
*
*/
_uiHandleDarkMode(mode = 'init') {
let self = this;
// If dark mode is not enabled by default remember default sidebar
// and header style to return to after any possible dark mode disabling
if (mode === 'init' && !self._lPage.classList.contains('dark-mode')) {
if (self._lPage.classList.contains('sidebar-dark')) {
localStorage.setItem('dashmixDefaultsSidebarDark', true);
} else {
localStorage.removeItem('dashmixDefaultsSidebarDark');
}
if (self._lPage.classList.contains('page-header-dark')) {
localStorage.setItem('dashmixDefaultsPageHeaderDark', true);
} else {
localStorage.removeItem('dashmixDefaultsPageHeaderDark');
}
}
// If remember-theme class is added in #page-container
if (self._lPage.classList.contains('remember-theme')) {
let darkMode = localStorage.getItem('dashmixDarkMode') || false;
if (mode === 'init') {
if (darkMode) {
self._lPage.classList.add('sidebar-dark');
self._lPage.classList.add('page-header-dark');
self._lPage.classList.add('dark-mode');
} else if (mode === 'init') {
self._lPage.classList.remove('dark-mode');
}
} else if (mode === 'on') {
localStorage.setItem('dashmixDarkMode', true);
} else if (mode === 'off') {
localStorage.removeItem('dashmixDarkMode');
}
} else if (mode === 'init') {
localStorage.removeItem('dashmixDarkMode');
}
}
/*
* Set active color theme functionality
*
*/
_uiHandleTheme() {
let self = this;
let themeEl = document.getElementById('css-theme');
let rememberTheme = this._lPage.classList.contains('remember-theme') ? true : false;
// If remember theme is enabled
if (rememberTheme) {
let themeName = localStorage.getItem('dashmixThemeName') || false;
// Update color theme
if (themeName) {
self._uiUpdateTheme(themeEl, themeName);
}
// Update theme element
themeEl = document.getElementById('css-theme');
} else {
localStorage.removeItem('dashmixThemeName');
}
// Set the active color theme link as active
document.querySelectorAll('[data-toggle="theme"][data-theme="' + (themeEl ? themeEl.getAttribute('href') : 'default') + '"]').forEach(link => {
link.classList.add('active');
});
// When a color theme link is clicked
document.querySelectorAll('[data-toggle="theme"]').forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
// Get element's data
let themeName = el.dataset.theme;
// Set this color theme link as active
document.querySelectorAll('[data-toggle="theme"]').forEach(link => {
link.classList.remove('active');
});
document.querySelector('[data-toggle="theme"][data-theme="' + themeName + '"]').classList.add('active');
// Update color theme
self._uiUpdateTheme(themeEl, themeName);
// Update theme element
themeEl = document.getElementById('css-theme');
// If remember theme is enabled, save the new active color theme
if (rememberTheme) {
localStorage.setItem('dashmixThemeName', themeName);
}
});
});
}
/*
* Updates the color theme
*
*/
_uiUpdateTheme(themeEl, themeName) {
if (themeName === 'default') {
if (themeEl) {
themeEl.parentNode.removeChild(themeEl);
}
} else {
if (themeEl) {
themeEl.setAttribute('href', themeName);
} else {
let themeLink = document.createElement('link');
themeLink.id = 'css-theme';
themeLink.setAttribute('rel', 'stylesheet');
themeLink.setAttribute('href', themeName);
document.getElementById('css-main').insertAdjacentElement('afterend', themeLink);
}
}
}
/*
* Layout API
*
*/
_uiApiLayout(mode = 'init') {
let self = this;
// API with object literals
let layoutAPI = {
init: () => {
let buttons = document.querySelectorAll('[data-toggle="layout"]');
// Call layout API on button click
if (buttons) {
buttons.forEach(btn => {
btn.addEventListener('click', e => {
self._uiApiLayout(btn.dataset.action);
});
})
}
// Prepend Page Overlay div if enabled (used when Side Overlay opens)
if (self._lPage.classList.contains('enable-page-overlay')) {
let pageOverlay = document.createElement('div');
pageOverlay.id = 'page-overlay';
self._lPage.insertBefore(pageOverlay, self._lPage.firstChild);
document.getElementById('page-overlay').addEventListener('click', e => {
self._uiApiLayout('side_overlay_close');
});
}
},
sidebar_pos_toggle: () => {
self._lPage.classList.toggle('sidebar-r');
},
sidebar_pos_left: () => {
self._lPage.classList.remove('sidebar-r');
},
sidebar_pos_right: () => {
self._lPage.classList.add('sidebar-r');
},
sidebar_toggle: () => {
if (window.innerWidth > 991) {
self._lPage.classList.toggle('sidebar-o');
} else {
self._lPage.classList.toggle('sidebar-o-xs');
}
},
sidebar_open: () => {
if (window.innerWidth > 991) {
self._lPage.classList.add('sidebar-o');
} else {
self._lPage.classList.add('sidebar-o-xs');
}
},
sidebar_close: () => {
if (window.innerWidth > 991) {
self._lPage.classList.remove('sidebar-o');
} else {
self._lPage.classList.remove('sidebar-o-xs');
}
},
sidebar_mini_toggle: () => {
if (window.innerWidth > 991) {
self._lPage.classList.toggle('sidebar-mini');
}
},
sidebar_mini_on: () => {
if (window.innerWidth > 991) {
self._lPage.classList.add('sidebar-mini');
}
},
sidebar_mini_off: () => {
if (window.innerWidth > 991) {
self._lPage.classList.remove('sidebar-mini');
}
},
sidebar_style_toggle: () => {
if (self._lPage.classList.contains('sidebar-dark')) {
self._uiApiLayout('sidebar_style_light');
} else {
self._uiApiLayout('sidebar_style_dark');
}
},
sidebar_style_dark: () => {
self._lPage.classList.add('sidebar-dark');
localStorage.setItem('dashmixDefaultsSidebarDark', true);
},
sidebar_style_light: () => {
self._lPage.classList.remove('sidebar-dark');
self._lPage.classList.remove('dark-mode');
localStorage.removeItem('dashmixDefaultsSidebarDark');
},
side_overlay_toggle: () => {
if (self._lPage.classList.contains('side-overlay-o')) {
self._uiApiLayout('side_overlay_close');
} else {
self._uiApiLayout('side_overlay_open');
}
},
side_overlay_open: () => {
// When ESCAPE key is hit close the side overlay
document.addEventListener('keydown', e => {
if (e.key === 'Esc' || e.key === 'Escape') {
self._uiApiLayout('side_overlay_close');
}
});
self._lPage.classList.add('side-overlay-o');
},
side_overlay_close: () => {
self._lPage.classList.remove('side-overlay-o');
},
side_overlay_mode_hover_toggle: () => {
self._lPage.classList.toggle('side-overlay-hover');
},
side_overlay_mode_hover_on: () => {
self._lPage.classList.add('side-overlay-hover');
},
side_overlay_mode_hover_off: () => {
self._lPage.classList.remove('side-overlay-hover');
},
header_glass_toggle: () => {
self._lPage.classList.toggle('page-header-glass');
self._uiHandleHeader();
},
header_glass_on: () => {
self._lPage.classList.add('page-header-glass');
self._uiHandleHeader();
},
header_glass_off: () => {
self._lPage.classList.remove('page-header-glass');
self._uiHandleHeader();
},
header_mode_toggle: () => {
self._lPage.classList.toggle('page-header-fixed');
},
header_mode_static: () => {
self._lPage.classList.remove('page-header-fixed');
},
header_mode_fixed: () => {
self._lPage.classList.add('page-header-fixed');
},
header_style_toggle: () => {
if (self._lPage.classList.contains('page-header-dark')) {
self._uiApiLayout('header_style_light');
} else {
self._uiApiLayout('header_style_dark');
}
},
header_style_dark: () => {
self._lPage.classList.add('page-header-dark');
localStorage.setItem('dashmixDefaultsPageHeaderDark', true);
},
header_style_light: () => {
self._lPage.classList.remove('page-header-dark');
self._lPage.classList.remove('dark-mode');
localStorage.removeItem('dashmixDefaultsPageHeaderDark');
},
header_search_on: () => {
self._lHeaderSearch.classList.add('show');
self._lHeaderSearchInput.focus();
// When ESCAPE key is hit close the search section
document.addEventListener('keydown', e => {
if (e.key === 'Esc' || e.key === 'Escape') {
self._uiApiLayout('header_search_off');
}
});
},
header_search_off: () => {
self._lHeaderSearch.classList.remove('show');
self._lHeaderSearchInput.blur();
},
header_loader_on: () => {
self._lHeaderLoader.classList.add('show');
},
header_loader_off: () => {
self._lHeaderLoader.classList.remove('show');
},
dark_mode_toggle: () => {
if (self._lPage.classList.contains('dark-mode')) {
self._uiApiLayout('dark_mode_off');
} else {
self._uiApiLayout('dark_mode_on');
}
},
dark_mode_on: () => {
self._lPage.classList.add('sidebar-dark');
self._lPage.classList.add('page-header-dark');
self._lPage.classList.add('dark-mode');
this._uiHandleDarkMode('on');
},
dark_mode_off: () => {
if (!localStorage.getItem('dashmixDefaultsSidebarDark')) {
self._lPage.classList.remove('sidebar-dark');
}
if (!localStorage.getItem('dashmixDefaultsPageHeaderDark')) {
self._lPage.classList.remove('page-header-dark');
}
self._lPage.classList.remove('dark-mode');
this._uiHandleDarkMode('off');
},
content_layout_toggle: () => {
if (self._lPage.classList.contains('main-content-boxed')) {
self._uiApiLayout('content_layout_narrow');
} else if (self._lPage.classList.contains('main-content-narrow')) {
self._uiApiLayout('content_layout_full_width');
} else {
self._uiApiLayout('content_layout_boxed');
}
},
content_layout_boxed: () => {
self._lPage.classList.remove('main-content-narrow');
self._lPage.classList.add('main-content-boxed');
},
content_layout_narrow: () => {
self._lPage.classList.remove('main-content-boxed');
self._lPage.classList.add('main-content-narrow');
},
content_layout_full_width: () => {
self._lPage.classList.remove('main-content-boxed');
self._lPage.classList.remove('main-content-narrow');
}
};
// Call layout API
if (layoutAPI[mode]) {
layoutAPI[mode]();
}
}
/*
* Blocks API
*
*/
_uiApiBlocks(mode = 'init', block = false) {
let self = this;
// Helper variables
let elBlock, btnFullscreen, btnContentToggle;
// Set default icons for fullscreen and content toggle buttons
let iconBase = 'si';
let iconFullscreen = 'si-size-fullscreen';
let iconFullscreenActive = 'si-size-actual';
let iconContent = 'si-arrow-up';
let iconContentActive = 'si-arrow-down';
// API with object literals
let blockAPI = {
init: () => {
// Auto add the default toggle icons to fullscreen and content toggle buttons
document.querySelectorAll('[data-toggle="block-option"][data-action="fullscreen_toggle"]').forEach(btn => {
btn.innerHTML = '<i class="' + iconBase + ' ' + (btn.closest('.block').classList.contains('block-mode-fullscreen') ? iconFullscreenActive : iconFullscreen) + '"></i>';
});
document.querySelectorAll('[data-toggle="block-option"][data-action="content_toggle"]').forEach(btn => {
btn.innerHTML = '<i class="' + iconBase + ' ' + (btn.closest('.block').classList.contains('block-mode-hidden') ? iconContentActive : iconContent) + '"></i>';
});
// Call blocks API on option button click
document.querySelectorAll('[data-toggle="block-option"]').forEach(btn => {
btn.addEventListener('click', e => {
this._uiApiBlocks(btn.dataset.action, btn.closest('.block'));
});
});
},
fullscreen_toggle: () => {
elBlock.classList.remove('block-mode-pinned');
elBlock.classList.toggle('block-mode-fullscreen');
// Update block option icon
if (btnFullscreen) {
if (elBlock.classList.contains('block-mode-fullscreen')) {
btnFullscreen && btnFullscreen.querySelector('i').classList.replace(iconFullscreen, iconFullscreenActive);
} else {
btnFullscreen && btnFullscreen.querySelector('i').classList.replace(iconFullscreenActive, iconFullscreen);
}
}
},
fullscreen_on: () => {
elBlock.classList.remove('block-mode-pinned')
elBlock.classList.add('block-mode-fullscreen');
// Update block option icon
btnFullscreen && btnFullscreen.querySelector('i').classList.replace(iconFullscreen, iconFullscreenActive);
},
fullscreen_off: () => {
elBlock.classList.remove('block-mode-fullscreen');
// Update block option icon
btnFullscreen && btnFullscreen.querySelector('i').classList.replace(iconFullscreenActive, iconFullscreen);
},
content_toggle: () => {
elBlock.classList.toggle('block-mode-hidden');
// Update block option icon
if (btnContentToggle) {
if (elBlock.classList.contains('block-mode-hidden')) {
btnContentToggle.querySelector('i').classList.replace(iconContent, iconContentActive);
} else {
btnContentToggle.querySelector('i').classList.replace(iconContentActive, iconContent);
}
}
},
content_hide: () => {
elBlock.classList.add('block-mode-hidden');
// Update block option icon
btnContentToggle && btnContentToggle.querySelector('i').classList.replace(iconContent, iconContentActive);
},
content_show: () => {
elBlock.classList.remove('block-mode-hidden');
// Update block option icon
btnContentToggle && btnContentToggle.querySelector('i').classList.replace(iconContentActive, iconContent);
},
state_toggle: () => {
elBlock.classList.toggle('block-mode-loading');
// Return block to normal state if the demostration mode is on in the refresh option button - data-action-mode="demo"
if (elBlock.querySelector('[data-toggle="block-option"][data-action="state_toggle"][data-action-mode="demo"]')) {
setTimeout(() => {
elBlock.classList.remove('block-mode-loading');
}, 2000);
}
},
state_loading: () => {
elBlock.classList.add('block-mode-loading');
},
state_normal: () => {
elBlock.classList.remove('block-mode-loading');
},
pinned_toggle: () => {
elBlock.classList.remove('block-mode-fullscreen');
elBlock.classList.toggle('block-mode-pinned');
},
pinned_on: () => {
elBlock.classList.remove('block-mode-fullscreen');
elBlock.classList.add('block-mode-pinned');
},
pinned_off: () => {
elBlock.classList.remove('block-mode-pinned');
},
close: () => {
elBlock.classList.add('d-none');
},
open: () => {
elBlock.classList.remove('d-none');
}
};
if (mode === 'init') {
// Call Block API
blockAPI[mode]();
} else {
// Get block element
elBlock = (block instanceof Element) ? block : document.querySelector(`${block}`);
// If element exists, procceed with block functionality
if (elBlock) {
// Get block option buttons if exist (need them to update their icons)
btnFullscreen = elBlock.querySelector('[data-toggle="block-option"][data-action="fullscreen_toggle"]');
btnContentToggle = elBlock.querySelector('[data-toggle="block-option"][data-action="content_toggle"]');
// Call Block API
if (blockAPI[mode]) {
blockAPI[mode]();
}
}
}
}
/*
********************************************************************************************
*
* Helpers
*
*********************************************************************************************
*/
/*
* On DOM content loaded
*
*/
onLoad(fn) {
if (document.readyState != 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
/*
********************************************************************************************
*
* Create aliases for easier/quicker access to vital methods
*
*********************************************************************************************
*/
/*
* Init base functionality
*
*/
init() {
this._uiInit();
}
/*
* Layout API
*
*/
layout(mode) {
this._uiApiLayout(mode);
}
/*
* Blocks API
*
*/
block(mode, block) {
this._uiApiBlocks(mode, block);
}
/*
* Handle Page Loader
*
*/
loader(mode, colorClass) {
this._uiHandlePageLoader(mode, colorClass);
}
/*
* Run Helpers
*
*/
helpers(helpers, options = {}) {
Helpers.run(helpers, options);
}
/*
* Run Helpers on DOM content loaded
*
*/
helpersOnLoad(helpers, options = {}) {
this.onLoad(() => Helpers.run(helpers, options));
}
}

179
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_calendar.js

@ -0,0 +1,179 @@
/*
* Document : be_comp_calendar.js
* Author : pixelcave
* Description: Custom JS code used in Calendar Page
*/
// Full Calendar, for more examples you can check out http://fullcalendar.io/
class pageCompCalendar {
/*
* Add event to the events list
*
*/
static addEvent() {
let eventInput = document.querySelector('.js-add-event');
let eventInputVal = '';
// When the add event form is submitted
document.querySelector('.js-form-add-event').addEventListener('submit', e => {
e.preventDefault();
// Get input value
eventInputVal = eventInput.value;
// Check if the user entered something
if (eventInputVal) {
let eventList = document.getElementById('js-events');
let newEvent = document.createElement('li');
let newEventDiv = document.createElement('div');
// Prepare new event div
newEventDiv.classList.add('js-event');
newEventDiv.classList.add('p-2');
newEventDiv.classList.add('fs-sm');
newEventDiv.classList.add('fw-medium');
newEventDiv.classList.add('rounded');
newEventDiv.classList.add('bg-info-light');
newEventDiv.classList.add('text-info');
newEventDiv.textContent = eventInputVal;
// Prepare new event li
newEvent.appendChild(newEventDiv);
// Add it to the events list
eventList.insertBefore(newEvent, eventList.firstChild);
// Clear input field
eventInput.value = '';
}
});
}
/*
* Init drag and drop event functionality
*
*/
static initEvents() {
new FullCalendar.Draggable(document.getElementById('js-events'), {
itemSelector: '.js-event',
eventData: function (eventEl) {
return {
title: eventEl.textContent,
backgroundColor: getComputedStyle(eventEl).color,
borderColor: getComputedStyle(eventEl).color
};
}
});
}
/*
* Init calendar demo functionality
*
*/
static initCalendar() {
let date = new Date();
let d = date.getDate();
let m = date.getMonth();
let y = date.getFullYear();
let calendar = new FullCalendar.Calendar(document.getElementById('js-calendar'), {
themeSystem: 'standard',
firstDay: 1,
editable: true,
droppable: true,
headerToolbar: {
left: 'title',
right: 'prev,next today dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
drop: function (info) {
info.draggedEl.parentNode.remove();
},
events: [
{
title: 'Gaming Day',
start: new Date(y, m, 1),
allDay: true
},
{
title: 'Skype Meeting',
start: new Date(y, m, 3)
},
{
title: 'Project X',
start: new Date(y, m, 9),
end: new Date(y, m, 12),
allDay: true,
color: '#e04f1a'
},
{
title: 'Work',
start: new Date(y, m, 17),
end: new Date(y, m, 19),
allDay: true,
color: '#82b54b'
},
{
id: 999,
title: 'Hiking (repeated)',
start: new Date(y, m, d - 1, 15, 0)
},
{
id: 999,
title: 'Hiking (repeated)',
start: new Date(y, m, d + 3, 15, 0)
},
{
title: 'Landing Template',
start: new Date(y, m, d - 3),
end: new Date(y, m, d - 3),
allDay: true,
color: '#ffb119'
},
{
title: 'Lunch',
start: new Date(y, m, d + 7, 15, 0),
color: '#82b54b'
},
{
title: 'Coding',
start: new Date(y, m, d, 8, 0),
end: new Date(y, m, d, 14, 0),
},
{
title: 'Trip',
start: new Date(y, m, 25),
end: new Date(y, m, 27),
allDay: true,
color: '#ffb119'
},
{
title: 'Reading',
start: new Date(y, m, d + 8, 20, 0),
end: new Date(y, m, d + 8, 22, 0)
},
{
title: 'Follow us on Twitter',
start: new Date(y, m, 22),
allDay: true,
url: 'http://twitter.com/pixelcave',
color: '#3c90df'
}
]
});
calendar.render();
}
/*
* Init functionality
*
*/
static init() {
this.addEvent();
this.initEvents();
this.initCalendar();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompCalendar.init());

143
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_charts.js

@ -0,0 +1,143 @@
/*
* Document : be_comp_charts.js
* Author : pixelcave
* Description: Custom JS code used in Charts Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageCompCharts {
/*
* Init Charts
*
*/
static initChartsChartJS() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = "rgba(0,0,0,.04)";
Chart.defaults.scale.grid.zeroLineColor = "rgba(0,0,0,.1)";
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.line.borderWidth = 2;
Chart.defaults.elements.point.radius = 5;
Chart.defaults.elements.point.hoverRadius = 7;
Chart.defaults.plugins.tooltip.radius = 3;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
// Get Chart Containers
let chartLinesCon = document.getElementById('js-chartjs-lines');
let chartBarsCon = document.getElementById('js-chartjs-bars');
let chartRadarCon = document.getElementById('js-chartjs-radar');
let chartPolarCon = document.getElementById('js-chartjs-polar');
let chartPieCon = document.getElementById('js-chartjs-pie');
let chartDonutCon = document.getElementById('js-chartjs-donut');
// Set Chart and Chart Data variables
let chartLines, chartBars, chartRadar, chartPolar, chartPie, chartDonut;
let chartLinesBarsRadarData, chartPolarPieDonutData;
// Lines/Bar/Radar Chart Data
chartLinesBarsRadarData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .75)',
borderColor: 'rgba(6, 101, 208, 1)',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [34, 42, 62, 78, 39, 83, 98]
},
{
label: 'Last Week',
fill: true,
backgroundColor: 'rgba(108, 117, 125, .25)',
borderColor: 'rgba(108, 117, 125, .75)',
pointBackgroundColor: 'rgba(108, 117, 125, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(108, 117, 125, 1)',
data: [130, 95, 125, 160, 187, 110, 143]
}
]
};
// Polar/Pie/Donut Data
chartPolarPieDonutData = {
labels: [
'Earnings',
'Sales',
'Tickets'
],
datasets: [{
data: [
65,
15,
20
],
backgroundColor: [
'rgba(141, 196, 81, 1)',
'rgba(255, 177, 25, 1)',
'rgba(224, 79, 26, 1)'
],
hoverBackgroundColor: [
'rgba(141, 196, 81, .5)',
'rgba(255, 177, 25, .5)',
'rgba(224, 79, 26, .5)'
]
}]
};
// Init Charts
if (chartLinesCon !== null) {
chartLines = new Chart(chartLinesCon, {type: 'line', data: chartLinesBarsRadarData, options: { responsive: true, maintainAspectRatio: false, tension: .4 }});
}
if (chartBarsCon !== null) {
chartBars = new Chart(chartBarsCon, {type: 'bar', data: chartLinesBarsRadarData, options: { responsive: true, maintainAspectRatio: false }});
}
if (chartRadarCon !== null) {
chartRadar = new Chart(chartRadarCon, {type: 'radar', data: chartLinesBarsRadarData, options: { responsive: true, maintainAspectRatio: false }});
}
if (chartPolarCon !== null) {
chartPolar = new Chart(chartPolarCon, {type: 'polarArea', data: chartPolarPieDonutData, options: { responsive: true, maintainAspectRatio: false }});
}
if (chartPieCon !== null) {
chartPie = new Chart(chartPieCon, {type: 'pie', data: chartPolarPieDonutData, options: { responsive: true, maintainAspectRatio: false }});
}
if (chartDonutCon !== null) {
chartDonut = new Chart(chartDonutCon, {type: 'doughnut', data: chartPolarPieDonutData, options: { responsive: true, maintainAspectRatio: false }});
}
}
/*
* Randomize Easy Pie Chart values
*
*/
static initRandomEasyPieChart() {
document.querySelectorAll('.js-pie-randomize').forEach(btn => {
btn.addEventListener('click', e => {
btn.closest('.block').querySelectorAll('.pie-chart').forEach(chart => {
jQuery(chart).data('easyPieChart').update(Math.floor((Math.random() * 100) + 1));
});
});
});
}
/*
* Init functionality
*
*/
static init() {
this.initChartsChartJS();
this.initRandomEasyPieChart();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompCharts.init());

156
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_chat.js

@ -0,0 +1,156 @@
/*
* Document : be_comp_chat.js
* Author : pixelcave
* Description: Custom JS code used in Chat Page
*/
// Message Classes
let classesMsgBase = ['fs-sm', 'd-inline-block', 'fw-medium', 'animated', 'fadeIn', 'bg-body-light', 'border-3', 'px-3', 'py-2', 'mb-2', 'shadow-sm', 'mw-100'],
classesMsgSelf = ['border-end', 'border-primary', 'rounded-start', 'text-start'],
classesMsgOther = ['border-start', 'border-dark', 'rounded-end'],
classesMsgHeader = ['fs-sm', 'text-muted', 'animated', 'fadeIn', 'my-2'];
class pageCompChat {
/*
* Init chat
*
*/
static initChat() {
let self = this;
// Set variables
let chatForms = document.querySelectorAll('.js-chat-form form');
// Init form submission
chatForms.forEach(form => {
form.addEventListener('submit', e => {
// Stop form submission
e.preventDefault();
// Get chat input
let chatInput = e.currentTarget.querySelector('.js-chat-input');
// Add message
self.chatAddMessage(parseInt(chatInput.dataset.targetChatId), chatInput.value, 'self', chatInput);
});
});
}
/*
* Add a header message to a chat window
*
*/
static chatAddHeader(chatId, chatMsg, chatMsgLevel) {
// Get chat messages window
let chatWindow = document.querySelector('.js-chat-messages[data-chat-id="' + chatId + '"]');
// If header and chat window exists
if (chatMsg && chatWindow !== null) {
// Create new message elements and add the correct classes
let newChatMsgCon = document.createElement('div');
let newChatMsg = document.createElement('div');
classesMsgHeader.forEach(cls => {
newChatMsg.classList.add(cls);
});
if (chatMsgLevel === 'self') {
newChatMsg.classList.add('text-end');
newChatMsgCon.classList.add('ms-4');
} else {
newChatMsgCon.classList.add('me-4');
}
// Set text message
newChatMsg.innerText = chatMsg;
// Append message to chat window
newChatMsgCon.appendChild(newChatMsg);
chatWindow.appendChild(newChatMsgCon);
// Scroll the message list to the bottom
chatWindow.scrollTop = chatWindow.scrollHeight;
}
}
/*
* Add a message to a chat window
*
*/
static chatAddMessage(chatId, chatMsg, chatMsgLevel, chatInput) {
// Get chat messages window
let chatWindow = document.querySelector('.js-chat-messages[data-chat-id="' + chatId + '"]');
// If message and chat window exists
if (chatMsg && chatWindow !== null) {
// Create new message elements and add the correct classes
let newChatMsgCon = document.createElement('div');
let newChatMsg = document.createElement('div');
classesMsgBase.forEach(cls => {
newChatMsg.classList.add(cls);
});
if (chatMsgLevel === 'self') {
newChatMsgCon.classList.add('text-end');
newChatMsgCon.classList.add('ms-4');
classesMsgSelf.forEach(cls => {
newChatMsg.classList.add(cls);
});
} else {
newChatMsgCon.classList.add('me-4');
classesMsgOther.forEach(cls => {
newChatMsg.classList.add(cls);
});
}
// Set text message
newChatMsg.innerText = chatMsg;
// Append message to chat window
newChatMsgCon.appendChild(newChatMsg);
chatWindow.appendChild(newChatMsgCon);
// Scroll the message list to the bottom
chatWindow.scrollTop = chatWindow.scrollHeight;
// If input is set, reset it
if (chatInput !== null) {
chatInput.value = '';
}
}
}
/*
* Init functionality
*
*/
static init() {
this.initChat();
}
/*
* Add header
*
*/
static addHeader(chatId, chatMsg, chatMsgLevel = '') {
this.chatAddHeader(chatId, chatMsg, chatMsgLevel);
}
/*
* Add message
*
*/
static addMessage(chatId, chatMsg, chatMsgLevel = '') {
this.chatAddMessage(chatId, chatMsg, chatMsgLevel, null);
}
}
// Initialize when page loads
Dashmix.onLoad(() => {
pageCompChat.init();
window.Chat = pageCompChat;
});

106
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_dialogs.js

@ -0,0 +1,106 @@
/*
* Document : be_comp_dialogs.js
* Author : pixelcave
* Description: Custom JS code used in Dialogs Page
*/
// SweetAlert2, for more examples you can check out https://github.com/sweetalert2/sweetalert2
class pageDialogs {
/*
* SweetAlert2 demo functionality
*
*/
static sweetAlert2() {
// Set default properties
let toast = Swal.mixin({
buttonsStyling: false,
target: '#page-container',
customClass: {
confirmButton: 'btn btn-success m-1',
cancelButton: 'btn btn-danger m-1',
input: 'form-control'
}
});
// Init a simple dialog on button click
document.querySelector('.js-swal-simple').addEventListener('click', e => {
toast.fire('Hi, this is just a simple message!');
});
// Init an success dialog on button click
document.querySelector('.js-swal-success').addEventListener('click', e => {
toast.fire('Success', 'Everything was updated perfectly!', 'success');
});
// Init an info dialog on button click
document.querySelector('.js-swal-info').addEventListener('click', e => {
toast.fire('Info', 'Just an informational message!', 'info');
});
// Init an warning dialog on button click
document.querySelector('.js-swal-warning').addEventListener('click', e => {
toast.fire('Warning', 'Something needs your attention!', 'warning');
});
// Init an error dialog on button click
document.querySelector('.js-swal-error').addEventListener('click', e => {
toast.fire('Oops...', 'Something went wrong!', 'error');
});
// Init an question dialog on button click
document.querySelector('.js-swal-question').addEventListener('click', e => {
toast.fire('Question', 'Are you sure about that?', 'question');
});
// Init an example confirm dialog on button click
document.querySelector('.js-swal-confirm').addEventListener('click', e => {
toast.fire({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
icon: 'warning',
showCancelButton: true,
customClass: {
confirmButton: 'btn btn-danger m-1',
cancelButton: 'btn btn-secondary m-1'
},
confirmButtonText: 'Yes, delete it!',
html: false,
preConfirm: e => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, 50);
});
}
}).then(result => {
if (result.value) {
toast.fire('Deleted!', 'Your imaginary file has been deleted.', 'success');
// result.dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
} else if (result.dismiss === 'cancel') {
toast.fire('Cancelled', 'Your imaginary file is safe :)', 'error');
}
});
});
// Init an example confirm alert on button click
document.querySelector('.js-swal-custom-position').addEventListener('click', e => {
toast.fire({
position: 'top-end',
title: 'Perfect!',
text: 'Nice Position!',
icon: 'success'
});
});
}
/*
* Init functionality
*
*/
static init() {
this.sweetAlert2();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageDialogs.init());

88
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_image_cropper.js

@ -0,0 +1,88 @@
/*
* Document : be_comp_image_cropper.js
* Author : pixelcave
* Description: Custom JS code used in Image Cropper Page
*/
// Image Cropper, for more examples you can check out https://fengyuanchen.github.io/cropperjs/
class pageCompImageCropper {
/*
* Init image cropper demo functionality
*
*/
static initImageCropper() {
// Get Image Container
let image = document.getElementById('js-img-cropper');
// Set Options
Cropper.setDefaults({
aspectRatio: 4 / 3,
preview: '.js-img-cropper-preview'
});
// Init Image Cropper
let cropper = new Cropper(image, {
crop: function (e) {
// e.detail contains all data required to crop the image server side
// You will have to send it to your custom server side script and crop the image there
// Since this event is fired each time you set the crop section, you could also use getData()
// method on demand. Please check out https://fengyuanchen.github.io/cropperjs/ for more info
// console.log(e.detail);
}
});
// Mini Cropper API
document.querySelectorAll('[data-toggle="cropper"]').forEach(btn => {
btn.addEventListener('click', e => {
let method = btn.dataset.method || false;
let option = btn.dataset.option || false;
// Method selection with object literals
let cropperAPI = {
zoom: () => {
cropper.zoom(option);
},
setDragMode: () => {
cropper.setDragMode(option);
},
rotate: () => {
cropper.rotate(option);
},
scaleX: () => {
cropper.scaleX(option);
btn.dataset.option = -(option);
},
scaleY: () => {
cropper.scaleY(option);
btn.dataset.option = -(option);
},
setAspectRatio: () => {
cropper.setAspectRatio(option);
},
crop: () => {
cropper.crop();
},
clear: () => {
cropper.clear();
}
};
// If method exists, execute it
if (cropperAPI[method]) {
cropperAPI[method]();
}
});
});
}
/*
* Init functionality
*
*/
static init() {
this.initImageCropper();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompImageCropper.init());

154
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_maps_vector.js

@ -0,0 +1,154 @@
/*
* Document : be_comp_maps_vector.js
* Author : pixelcave
* Description: Custom JS code used in Vector Maps Page
*/
// Set default options for all maps
let mapOptions = {
map: '',
backgroundColor: '#ffffff',
regionStyle: {
initial: {
fill: '#1F75D5',
'fill-opacity': 1,
stroke: 'none',
'stroke-width': 0,
'stroke-opacity': 1
},
hover: {
'fill-opacity': .8,
cursor: 'pointer'
}
}
};
// jVectorMap, for more examples you can check out http://jvectormap.com/documentation/
class pageCompMapsVector {
/*
* Init World Map
*
*/
static initMapWorld() {
// Set Active Map
mapOptions['map'] = 'world_mill_en';
// Init Map
jQuery('.js-vector-map-world').vectorMap(mapOptions);
}
/*
* Init Europe Map
*
*/
static initMapEurope() {
// Set Active Map
mapOptions['map'] = 'europe_mill_en';
// Init Map
jQuery('.js-vector-map-europe').vectorMap(mapOptions);
}
/*
* Init USA Map
*
*/
static initMapUsa() {
// Set Active Map
mapOptions['map'] = 'us_aea_en';
// Init Map
jQuery('.js-vector-map-usa').vectorMap(mapOptions);
}
/*
* Init India Map
*
*/
static initMapIndia() {
// Set Active Map
mapOptions['map'] = 'in_mill_en';
// Init Map
jQuery('.js-vector-map-india').vectorMap(mapOptions);
}
/*
* Init China Map
*
*/
static initMapChina() {
// Set Active Map
mapOptions['map'] = 'cn_mill_en';
// Init Map
jQuery('.js-vector-map-china').vectorMap(mapOptions);
}
/*
* Init Australia Map
*
*/
static initMapAustralia() {
// Set Active Map
mapOptions['map'] = 'au_mill_en';
// Init Map
jQuery('.js-vector-map-australia').vectorMap(mapOptions);
}
/*
* Init South Africa Map
*
*/
static initMapSouthAfrica() {
// Set Active Map
mapOptions['map'] = 'za_mill_en';
// Init Map
jQuery('.js-vector-map-south-africa').vectorMap(mapOptions);
}
/*
* Init France Map
*
*/
static initMapFrance() {
// Set Active Map
mapOptions['map'] = 'fr_mill_en';
// Init Map
jQuery('.js-vector-map-france').vectorMap(mapOptions);
}
/*
* Init Germany Map
*
*/
static initMapGermany() {
// Set Active Map
mapOptions['map'] = 'de_mill_en';
// Init Map
jQuery('.js-vector-map-germany').vectorMap(mapOptions);
}
/*
* Init functionality
*
*/
static init() {
this.initMapWorld();
this.initMapEurope();
this.initMapUsa();
this.initMapIndia();
this.initMapChina();
this.initMapAustralia();
this.initMapSouthAfrica();
this.initMapFrance();
this.initMapGermany();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompMapsVector.init());

47
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_nestable.js

@ -0,0 +1,47 @@
/*
* Document : be_comp_nestable.js
* Author : pixelcave
* Description: Custom JS code used in Nestable Page
*/
// Nestable2, for more examples you can check out https://github.com/RamonSmit/Nestable2
class pageCompNestable {
/*
* Nestable2 demo functionality
*
*/
static nestable2() {
// Init Connected Lists
jQuery('.js-nestable-connected-simple').
add('.js-nestable-connected-icons').
add('.js-nestable-connected-treeview').nestable({
group: 0
});
// Init Simple List
jQuery('.js-nestable-simple').nestable({
group: 1
});
// Init Icons List
jQuery('.js-nestable-icons').nestable({
group: 2
});
// Init Tree View List
jQuery('.js-nestable-treeview').nestable({
group: 3
});
}
/*
* Init functionality
*
*/
static init() {
this.nestable2();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompNestable.init());

41
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_onboarding.js

@ -0,0 +1,41 @@
/*
* Document : be_comp_onboarding.js
* Author : pixelcave
* Description: Custom JS code used in Onboarding Page
*/
// Onboarding Modal using Bootstrap Modal and Slick slider
class pageCompOnboarding {
/*
* Init example onboarding modal functionality
*
*/
static initOnboardingModal() {
// Get onboarding modal
let modalEl = document.getElementById('modal-onboarding');
let modal = new bootstrap.Modal(modalEl);
// Show Onboarding Modal by default
modal.show();
// Re-init Slick Slider every time the modal is shown
modalEl.addEventListener('shown.bs.modal', e => {
// Remove enabled class added by the helper to prevent re-init
document.querySelector('#modal-onboarding .js-slider').classList.remove('js-slider-enabled');
// Re-init Slick Slider
Dashmix.helpers('jq-slick');
});
}
/*
* Init functionality
*
*/
static init() {
this.initOnboardingModal();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompOnboarding.init());

50
mobileservice/src/main/resources/static/assets/_js/pages/be_comp_rating.js

@ -0,0 +1,50 @@
/*
* Document : be_comp_rating.js
* Author : pixelcave
* Description: Custom JS code used in Rating Page
*/
// jQuery Raty, for more examples you can check out https://github.com/wbotelhos/raty
class pageCompRating {
/*
* Init demo rating functionality
*
*/
static initRating() {
// Init Raty on .js-rating class
jQuery('.js-rating').each((index, element) => {
let el = jQuery(element);
el.raty({
score: el.data('score') || 0,
number: el.data('number') || 5,
cancel: el.data('cancel') || false,
target: el.data('target') || false,
targetScore: el.data('target-score') || false,
precision: el.data('precision') || false,
cancelOff: el.data('cancel-off') || 'fa fa-fw fa-times-circle text-danger',
cancelOn: el.data('cancel-on') || 'fa fa-fw fa-times-circle',
starHalf: el.data('star-half') || 'fa fa-fw fa-star-half text-warning',
starOff: el.data('star-off') || 'fa fa-fw fa-star text-muted',
starOn: el.data('star-on') || 'fa fa-fw fa-star text-warning',
starType: 'i',
hints: ['Just Bad!', 'Almost There!', 'It’s ok!', 'That’s nice!', 'Incredible!'],
click: function (score, evt) {
// Here you could add your logic on rating click
// console.log('ID: ' + this.id + "\nscore: " + score + "\nevent: " + evt);
}
});
});
}
/*
* Init functionality
*
*/
static init() {
this.initRating();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageCompRating.init());

124
mobileservice/src/main/resources/static/assets/_js/pages/be_forms_validation.js

@ -0,0 +1,124 @@
/*
* Document : be_forms_validation.js
* Author : pixelcave
* Description: Custom JS code used in Forms Validation Page
*/
// Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
class pageFormsValidation {
/*
* Init Validation functionality
*
*/
static initValidation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation').validate({
ignore: [],
rules: {
'val-username': {
required: true,
minlength: 3
},
'val-email': {
required: true,
emailWithDot: true
},
'val-password': {
required: true,
minlength: 5
},
'val-confirm-password': {
required: true,
equalTo: '#val-password'
},
'val-suggestions': {
required: true,
minlength: 5
},
'val-skill': {
required: true
},
'val-currency': {
required: true,
currency: ['$', true]
},
'val-website': {
required: true,
url: true
},
'val-phoneus': {
required: true,
phoneUS: true
},
'val-digits': {
required: true,
digits: true
},
'val-number': {
required: true,
number: true
},
'val-range': {
required: true,
range: [1, 5]
},
'val-terms': {
required: true
},
'val-select2': {
required: true
},
'val-select2-multiple': {
required: true,
minlength: 2
}
},
messages: {
'val-username': {
required: 'Please enter a username',
minlength: 'Your username must consist of at least 3 characters'
},
'val-email': 'Please enter a valid email address',
'val-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
},
'val-confirm-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long',
equalTo: 'Please enter the same password as above'
},
'val-select2': 'Please select a value!',
'val-select2-multiple': 'Please select at least 2 values!',
'val-suggestions': 'What can we do to become better?',
'val-skill': 'Please select a skill!',
'val-currency': 'Please enter a price!',
'val-website': 'Please enter your website!',
'val-phoneus': 'Please enter a US phone!',
'val-digits': 'Please enter only digits!',
'val-number': 'Please enter a number!',
'val-range': 'Please enter a number between 1 and 5!',
'val-terms': 'You must agree to the service terms!'
}
});
// Init Validation on Select2 change
jQuery('.js-select2').on('change', e => {
jQuery(e.currentTarget).valid();
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageFormsValidation.init());

89
mobileservice/src/main/resources/static/assets/_js/pages/be_pages_dashboard.js

@ -0,0 +1,89 @@
/*
* Document : be_pages_dashboard.js
* Author : pixelcave
* Description: Custom JS code used in Default Dashboard Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageDashboard {
/*
* Init Charts
*
*/
static initChartsBars() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = 'transparent';
Chart.defaults.scale.grid.zeroLineColor = 'transparent';
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.line.borderWidth = 1;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
// Get Chart Containers
let chartBarsCon = document.getElementById('js-chartjs-analytics-bars');
// Set Chart and Chart Data variables
let chartBars, chartLinesBarsData;
// Bars Chart Data
chartLinesBarsData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .6)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [73, 68, 69, 53, 60, 72, 82]
},
{
label: 'Last Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [62, 32, 59, 55, 52, 56, 73]
}
]
};
// Init Chart
if (chartBarsCon !== null) {
chartBars = new Chart(chartBarsCon, {
type: 'bar',
data: chartLinesBarsData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return context.dataset.label + ': ' + context.parsed.y + ' Customers';
}
}
}
}
}
});
}
}
/*
* Init functionality
*
*/
static init() {
this.initChartsBars();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageDashboard.init());

225
mobileservice/src/main/resources/static/assets/_js/pages/be_pages_dashboard_v1.js

@ -0,0 +1,225 @@
/*
* Document : be_pages_dashboard.js
* Author : pixelcave
* Description: Custom JS code used in default Dashboard v1 Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageDashboardv1 {
/*
* Init Charts
*
*/
static initChartsMain() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = 'transparent';
Chart.defaults.scale.grid.zeroLineColor = 'transparent';
Chart.defaults.scale.display = false;
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.point.radius = 0;
Chart.defaults.elements.point.hoverRadius = 0;
Chart.defaults.plugins.tooltip.radius = 3;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
// Get Chart Containers
let chartMainCon = document.getElementById('js-chartjs-dashboard-earnings');
// Set Main Chart variables
let chartMain, chartMainOptions, chartMainData, chartMainDataYear, chartMainDataMonth, chartMainDataWeek;
// Main Chart Options
chartMainOptions = {
responsive: true,
maintainAspectRatio: false,
tension: .4,
scales: {
y: {
suggestedMin: 0,
suggestedMax: 260
}
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return ' ' + context.parsed.y + ' Sales';
}
}
}
}
};
// Main Chart Default Data
chartMainData = {
labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
datasets: [
{
label: 'This Year',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .5)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [50, 210, 110, 90, 230, 130, 190, 75, 155, 120, 140, 230]
},
{
label: 'Last Year',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [210, 150, 90, 220, 150, 216, 143, 150, 240, 230, 136, 150]
}
]
};
// Main Chart for Year
chartMainDataYear = {
labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
datasets: [
{
label: 'This Year',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .5)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [50, 210, 110, 90, 230, 130, 190, 75, 155, 120, 140, 230]
},
{
label: 'Last Year',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [210, 150, 90, 220, 150, 216, 143, 150, 240, 230, 136, 150]
}
]
};
// Set up month labels
let chartMainDataMonthLabels = [];
for (let i = 0; i < 30; i++) {
chartMainDataMonthLabels[i] = (i === 29) ? '1 day ago' : (30 - i) + ' days ago';
}
// Main Chart Data for Month
chartMainDataMonth = {
labels: chartMainDataMonthLabels,
datasets: [
{
label: 'This Month',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .5)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [50, 210, 110, 90, 230, 130, 190, 75, 155, 120, 140, 230, 50, 210, 110, 90, 230, 130, 155, 120, 140, 230, 50, 210, 110, 90, 230, 130, 190, 75]
},
{
label: 'Last Month',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [210, 150, 90, 220, 150, 216, 143, 150, 136, 150, 210, 150, 90, 220, 150, 216, 240, 230, 136, 150, 210, 150, 90, 220, 150, 216, 143, 150, 240, 230]
}
]
};
// Main Chart Data for Week
chartMainDataWeek = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .5)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [34, 42, 62, 78, 39, 83, 98]
},
{
label: 'Last Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [130, 95, 125, 160, 187, 110, 143]
}
]
};
// Init Main Chart
if (chartMainCon !== null) {
chartMain = new Chart(chartMainCon, {
type: 'line',
data: chartMainData,
options: chartMainOptions
});
}
// Toggle to Week data
document.querySelector('[data-toggle="dashboard-chart-set-week"]').addEventListener('click', () => {
chartMain.data.labels = chartMainDataWeek.labels;
chartMain.data.datasets[0] = chartMainDataWeek.datasets[0];
chartMain.data.datasets[1] = chartMainDataWeek.datasets[1];
chartMain.update();
});
// Toggle to Month data
document.querySelector('[data-toggle="dashboard-chart-set-month"]').addEventListener('click', () => {
chartMain.data.labels = chartMainDataMonth.labels;
chartMain.data.datasets[0] = chartMainDataMonth.datasets[0];
chartMain.data.datasets[1] = chartMainDataMonth.datasets[1];
chartMain.update();
});
// Toggle to Year data
document.querySelector('[data-toggle="dashboard-chart-set-year"]').addEventListener('click', () => {
chartMain.data.labels = chartMainDataYear.labels;
chartMain.data.datasets[0] = chartMainDataYear.datasets[0];
chartMain.data.datasets[1] = chartMainDataYear.datasets[1];
chartMain.update();
});
}
/*
* Init functionality
*
*/
static init() {
this.initChartsMain();
}
}
// Initialize when page loads
jQuery(() => {
pageDashboardv1.init();
});

104
mobileservice/src/main/resources/static/assets/_js/pages/be_pages_ecom_dashboard.js

@ -0,0 +1,104 @@
/*
* Document : be_pages_ecom_dashboard.js
* Author : pixelcave
* Description: Custom JS code used in eCommerce Dashboard Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageEcomDashboard {
/*
* Init Charts
*
*/
static initOverviewChart() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = 'transparent';
Chart.defaults.scale.grid.zeroLineColor = 'transparent';
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.point.radius = 0;
Chart.defaults.elements.point.hoverRadius = 0;
Chart.defaults.plugins.tooltip.radius = 3;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
// Get Chart Container
let chartOverviewCon = document.getElementById('js-chartjs-overview');
// Set Chart Variables
let chartOverview, chartOverviewOptions, chartOverviewData;
// Overview Chart Options
chartOverviewOptions = {
responsive: true,
maintainAspectRatio: false,
tension: .4,
scales: {
y: {
suggestedMin: 0,
suggestedMax: 600
}
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return '$ ' + context.parsed.y;
}
}
}
}
};
// Overview Chart Data
chartOverviewData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .5)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, 1)',
data: [369, 255, 420, 330, 460, 160, 350]
},
{
label: 'Last Week',
fill: true,
backgroundColor: 'rgba(6, 101, 208, .2)',
borderColor: 'transparent',
pointBackgroundColor: 'rgba(6, 101, 208, .2)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(6, 101, 208, .2)',
data: [270, 460, 290, 231, 419, 450, 280]
}
]
};
// Init Overview Chart
if (chartOverviewCon !== null) {
chartOverview = new Chart(chartOverviewCon, {
type: 'line',
data: chartOverviewData,
options: chartOverviewOptions
});
}
}
/*
* Init functionality
*
*/
static init() {
this.initOverviewChart();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageEcomDashboard.init());

271
mobileservice/src/main/resources/static/assets/_js/pages/be_pages_projects_tasks.js

@ -0,0 +1,271 @@
/*
* Document : be_pages_projects_tasks.js
* Author : pixelcave
* Description: Custom JS code used in Project Tasks and Tasks Dashboard Page
*/
// Helper variables
let taskIdNext, tasks, taskForm, taskInput, taskInputVal,
taskList, taskListStarred, taskListCompleted,
taskBadge, taskBadgeStarred, taskBadgeCompleted;
class pageTasks {
/*
* Init Tasks
*
*/
static initTasks() {
let self = this;
// Set variables
tasks = jQuery('.js-tasks');
taskForm = jQuery('#js-task-form');
taskInput = jQuery('#js-task-input');
taskList = jQuery('.js-task-list');
taskListStarred = jQuery('.js-task-list-starred');
taskListCompleted = jQuery('.js-task-list-completed');
taskBadge = jQuery('.js-task-badge');
taskBadgeStarred = jQuery('.js-task-badge-starred');
taskBadgeCompleted = jQuery('.js-task-badge-completed');
// Set your own next new task id based on your database setup
taskIdNext = 10;
// Update badges
this.badgesUpdate();
// New task form submission
taskForm.on('submit', e => {
e.preventDefault();
// Get input value
taskInputVal = taskInput.prop('value');
// Check if the user entered something
if (taskInputVal) {
// Add Task
self.taskAdd(taskInputVal);
// Clear and focus input field
taskInput.prop('value', '').focus();
}
});
// Task status update on checkbox click
let stask, staskId;
tasks.on('click', '.js-task-status', e => {
stask = jQuery(e.currentTarget).closest('.js-task');
staskId = stask.data('task-id');
// Check task status and toggle it
if (stask.data('task-completed')) {
self.taskSetActive(staskId);
} else {
self.taskSetCompleted(staskId);
}
});
// Task starred status update on star click
let ftask, ftaskId;
tasks.on('click', '.js-task-star', e => {
ftask = jQuery(e.currentTarget).closest('.js-task');
ftaskId = ftask.data('task-id');
// Check task starred status and toggle it
if (ftask.data('task-starred')) {
self.taskStarRemove(ftaskId);
} else {
self.taskStarAdd(ftaskId);
}
});
// Remove task on remove button click
tasks.on('click', '.js-task-remove', e => {
ftask = jQuery(e.currentTarget).closest('.js-task');
ftaskId = ftask.data('task-id');
// Remove task
self.taskRemove(ftaskId);
});
}
/*
* Update Badges
*
*/
static badgesUpdate() {
taskBadge.text(taskList.children().length || '');
taskBadgeStarred.text(taskListStarred.children().length || '');
taskBadgeCompleted.text(taskListCompleted.children().length || '');
}
/*
* Add a new task
*
*/
static taskAdd(taskContent) {
// Add it to the task list
taskList.prepend(`
<div class="js-task block block-rounded mb-2 animated fadeIn" data-task-id="${taskIdNext}" data-task-completed="false" data-task-starred="false">
<table class="table table-borderless table-vcenter mb-0">
<tr>
<td class="text-center pe-0" style="width: 38px;">
<div class="js-task-status form-check">
<input type="checkbox" class="form-check-input" id="tasks-cb-id${taskIdNext}" name="tasks-cb-id${taskIdNext}">
<label class="form-check-label" for="tasks-cb-id${taskIdNext}"></label>
</div>
</td>
<td class="js-task-content fw-semibold ps-0">
${jQuery('<span />').text(taskContent).html()}
</td>
<td class="text-end" style="width: 100px;">
<button type="button" class="js-task-star btn btn-sm btn-link text-warning">
<i class="far fa-star fa-fw"></i>
</button>
<button type="button" class="js-task-remove btn btn-sm btn-link text-danger">
<i class="fa fa-times fa-fw"></i>
</button>
</td>
</tr>
</table>
</div>
`);
// Update badges
this.badgesUpdate();
// Save the task based on your database setup
// ..
// Update task next id
taskIdNext++;
}
/*
* Remove a task
*
*/
static taskRemove(taskId) {
jQuery('.js-task[data-task-id="' + taskId + '"]').remove();
// Update badges
this.badgesUpdate();
// Remove the task based on your database setup
// ..
}
/*
* Star a task
*
*/
static taskStarAdd(taskId) {
let task = jQuery('.js-task[data-task-id="' + taskId + '"]');
// Check if exists and update accordignly the markup
if (task.length > 0) {
task.data('task-starred', true);
task.find('.js-task-star > i').toggleClass('fa far');
if (!task.data('task-completed')) {
task.prependTo(taskListStarred);
}
// Update badges
this.badgesUpdate();
// Star the task based on your database setup
// ..
}
}
/*
* Unstar a task
*
*/
static taskStarRemove(taskId) {
let task = jQuery('.js-task[data-task-id="' + taskId + '"]');
// Check if exists and update accordignly the markup
if (task.length > 0) {
task.data('task-starred', false);
task.find('.js-task-star > i').toggleClass('fa far');
if (!task.data('task-completed')) {
task.prependTo(taskList);
}
// Update badges
this.badgesUpdate();
// Unstar the task based on your database setup
// ..
}
}
/*
* Set a task to active
*
*/
static taskSetActive(taskId) {
let task = jQuery('.js-task[data-task-id="' + taskId + '"]');
// Check if exists and update accordignly
if (task.length > 0) {
task.data('task-completed', false);
task.find('.table').toggleClass('bg-body');
task.find('.js-task-status > input').prop('checked', false);
task.find('.js-task-content > del').contents().unwrap();
if (task.data('task-starred')) {
task.prependTo(taskListStarred);
} else {
task.prependTo(taskList);
}
// Update badges
this.badgesUpdate();
// Update task status based on your database setup
// ..
}
}
/*
* Set a task to completed
*
*/
static taskSetCompleted(taskId) {
let task = jQuery('.js-task[data-task-id="' + taskId + '"]');
// Check if exists and update accordignly
if (task.length > 0) {
task.data('task-completed', true);
task.find('.table').toggleClass('bg-body');
task.find('.js-task-status > input').prop('checked', true);
task.find('.js-task-content').wrapInner('<del></del>');
task.prependTo(taskListCompleted);
// Update badges
this.badgesUpdate();
// Update task status based on your database setup
// ..
}
}
/*
* Init functionality
*
*/
static init() {
this.initTasks();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageTasks.init());

45
mobileservice/src/main/resources/static/assets/_js/pages/be_ui_animations.js

@ -0,0 +1,45 @@
/*
* Document : be_ui_animations.js
* Author : pixelcave
* Description: Custom JS code used in Animations Page
*/
class pageAnimations {
/*
* Animation toggle functionality
*
*/
static animationsToggle() {
let animationClass, animationButton, currentSection;
// On button click
document.querySelectorAll('.js-animation-section button').forEach(btn => {
btn.addEventListener('click', e => {
animationClass = btn.dataset.animationClass;
currentSection = btn.closest('.js-animation-section');
// Update class preview
currentSection.querySelector('.js-animation-preview').textContent = animationClass;
// Update animation object classes
let animationObject = currentSection.querySelector('.js-animation-object')
animationObject.classList = '';
animationObject.classList.add('js-animation-object');
animationObject.classList.add('animated');
animationObject.classList.add(animationClass);
});
});
}
/*
* Init functionality
*
*/
static init() {
this.animationsToggle();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageAnimations.init());

2184
mobileservice/src/main/resources/static/assets/_js/pages/be_ui_icons.js
File diff suppressed because it is too large
View File

41
mobileservice/src/main/resources/static/assets/_js/pages/be_ui_progress.js

@ -0,0 +1,41 @@
/*
* Document : be_ui_progress.js
* Author : pixelcave
* Description: Custom JS code used in Progress Page
*/
class pageProgress {
/*
* Bars randomize functionality
*
*/
static barsRandomize() {
document.querySelectorAll('.js-bar-randomize').forEach(item => {
item.addEventListener('click', e => {
item.closest('.block').querySelectorAll('.progress-bar').forEach(bar => {
let random = Math.floor((Math.random() * 91) + 10);
let content = bar.querySelector('span');
// Update progress width
bar.style.width = random + '%';
// Update progress label
if (content) {
content.textContent = random + '%';
}
});
});
});
}
/*
* Init functionality
*
*/
static init() {
this.barsRandomize();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageProgress.init());

73
mobileservice/src/main/resources/static/assets/_js/pages/db_analytics.js

@ -0,0 +1,73 @@
/*
* Document : db_analytics.js
* Author : pixelcave
* Description: Custom JS code used in Analytics Dashboard Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageDashboardAnalytics {
/*
* Init Charts
*
*/
static initChartsBars() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = 'transparent';
Chart.defaults.scale.grid.zeroLineColor = 'transparent';
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.line.borderWidth = 1;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
// Get Chart Containers
let chartBarsCon = document.getElementById('js-chartjs-analytics-bars');
// Set Chart and Chart Data variables
let chartBars, chartLinesBarsData;
// Bars Chart Data
chartLinesBarsData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(103, 114, 229, .75)',
borderColor: 'rgba(103, 114, 229, 1)',
pointBackgroundColor: 'rgba(103, 114, 229, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(103, 114, 229, 1)',
data: [500, 750, 650, 570, 582, 480, 680]
},
{
label: 'Last Week',
fill: true,
backgroundColor: 'rgba(108, 117, 125, .15)',
borderColor: 'rgba(108, 117, 125, .75)',
pointBackgroundColor: 'rgba(108, 117, 125, 1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(108, 117, 125, 1)',
data: [352, 530, 541, 521, 410, 395, 460]
}
]
};
// Init Chart
if (chartBarsCon !== null) {
chartBars = new Chart(chartBarsCon, {type: 'bar', data: chartLinesBarsData, options: { responsive: true, maintainAspectRatio: false }});
}
}
/*
* Init functionality
*
*/
static init() {
this.initChartsBars();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageDashboardAnalytics.init());

144
mobileservice/src/main/resources/static/assets/_js/pages/db_corporate_slim.js

@ -0,0 +1,144 @@
/*
* Document : db_corporate_slim.js
* Author : pixelcave
* Description: Custom JS code used in Corporate Slim Dashboard Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class DbCorporateSlim {
/*
* Init Charts
*
*/
static initCorporateChartJS() {
// Set Global Chart.js configuration
Chart.defaults.color = '#7c7c7c';
Chart.defaults.scale.grid.color = "transparent";
Chart.defaults.scale.grid.zeroLineColor = "transparent";
Chart.defaults.scale.display = false;
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.line.borderWidth = 2;
Chart.defaults.elements.point.radius = 6;
Chart.defaults.elements.point.hoverRadius = 10;
Chart.defaults.plugins.tooltip.radius = 3;
Chart.defaults.plugins.legend.display = false;
// Chart Containers
let chartCorporateSlimProjectsCon = document.getElementById('js-chartjs-corporate-slim-projects');
let chartCorporateSlimTicketsCon = document.getElementById('js-chartjs-corporate-slim-tickets');
// Chart Variables
let chartCorporateSlimProjects, chartCorporateSlimTickets;
// Lines Charts Data
let chartCorporateSlimProjectsData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(73, 80, 87, .1)',
borderColor: 'rgba(73, 80, 87, .35)',
pointBackgroundColor: 'rgba(73, 80, 87, .5)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(73, 80, 87, .5)',
data: [14, 16, 6, 14, 10, 19, 12]
}
]
};
let chartCorporateSlimProjectsOptions = {
responsive: true,
maintainAspectRatio: false,
tension: .4,
scales: {
y: {
suggestedMin: 0,
suggestedMax: 22
}
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return ' ' + context.parsed.y + ' Sales';
}
}
}
}
};
let chartCorporateSlimTicketsData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fill: true,
backgroundColor: 'rgba(130, 181, 75, .1)',
borderColor: 'rgba(130, 181, 75, .35)',
pointBackgroundColor: 'rgba(130, 181, 75, .5)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(130, 181, 75, .5)',
data: [35, 20, 29, 20, 40, 34, 45]
}
]
};
let chartCorporateSlimTicketsOptions = {
responsive: true,
maintainAspectRatio: false,
tension: .4,
scales: {
y: {
suggestedMin: 0,
suggestedMax: 50
}
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return ' ' + context.parsed.y + ' Tickets';
}
}
}
}
};
// Init Charts
if (chartCorporateSlimProjectsCon !== null) {
chartCorporateSlimProjects = new Chart(chartCorporateSlimProjectsCon, {
type: 'line',
data: chartCorporateSlimProjectsData,
options: chartCorporateSlimProjectsOptions
});
}
if (chartCorporateSlimTicketsCon !== null) {
chartCorporateSlimTickets = new Chart(chartCorporateSlimTicketsCon, {
type: 'line',
data: chartCorporateSlimTicketsData,
options: chartCorporateSlimTicketsOptions
});
}
}
/*
* Init functionality
*
*/
static init() {
this.initCorporateChartJS();
}
}
// Initialize when page loads
Dashmix.onLoad(() => DbCorporateSlim.init());

93
mobileservice/src/main/resources/static/assets/_js/pages/db_crypto.js

@ -0,0 +1,93 @@
/*
* Document : db_crypto.js
* Author : pixelcave
* Description: Custom JS code used in Crypto Dashboard Page
*/
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
class pageDashboardCrypto {
/*
* Init Charts
*
*/
static initChartsBitcoin() {
// Set Global Chart.js configuration
Chart.defaults.color = '#818d96';
Chart.defaults.scale.grid.color = 'transparent';
Chart.defaults.scale.grid.zeroLineColor = 'transparent';
Chart.defaults.scale.beginAtZero = true;
Chart.defaults.elements.point.radius = 0;
Chart.defaults.elements.point.hoverRadius = 0;
Chart.defaults.plugins.tooltip.radius = 3;
Chart.defaults.plugins.legend.display = false;
// Get Chart Container
let chartBitcoinCon = document.getElementById('js-chartjs-bitcoin');
// Set up labels
let chartBitcoinlabels = [];
for (let i = 0; i < 30; i++) {
chartBitcoinlabels[i] = (i === 29) ? '1 day ago' : (30 - i) + ' days ago';
}
// Crypto Data
let chartBitcoinData = [10500, 10400, 9500, 8268, 10218, 8250, 8707, 9284, 9718, 9950, 9879, 10147, 10883, 11071, 11332, 11584, 11878, 13540, 16501, 16007, 15142, 14869, 16762, 17276, 16808, 16678, 16771, 12900, 13100, 14000];
// Init Chart
if (chartBitcoinCon !== null) {
let chartBitcoin = new Chart(chartBitcoinCon, {
type: 'line',
data: {
labels: chartBitcoinlabels,
datasets: [
{
label: 'Bitcoin Price',
fill: true,
backgroundColor: 'rgba(255,193,7,.25)',
borderColor: 'rgba(255,193,7,1)',
pointBackgroundColor: 'rgba(255,193,7,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(255,193,7,1)',
data: chartBitcoinData
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
tension: .4,
scales: {
y: {
suggestedMin: 6000,
suggestedMax: 20000
}
},
interaction: {
intersect: false,
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
return ' $' + context.parsed.y;
}
}
}
}
}
});
}
}
/*
* Init functionality
*
*/
static init() {
this.initChartsBitcoin();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageDashboardCrypto.init());

42
mobileservice/src/main/resources/static/assets/_js/pages/op_auth_lock.js

@ -0,0 +1,42 @@
/*
* Document : op_auth_lock.js
* Author : pixelcave
* Description: Custom JS code used in Lock Page
*/
class pageAuthLock {
/*
* Init Lock Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
*
*/
static initValidation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation-lock').validate({
rules: {
'lock-password': {
required: true,
minlength: 3
}
},
messages: {
'lock-password': {
required: 'Please enter your valid password'
}
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageAuthLock.init());

42
mobileservice/src/main/resources/static/assets/_js/pages/op_auth_reminder.js

@ -0,0 +1,42 @@
/*
* Document : op_auth_reminder.js
* Author : pixelcave
* Description: Custom JS code used in Password Reminder Page
*/
class pageAuthReminder {
/*
* Init Password Reminder Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
*
*/
static initValidation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation-reminder').validate({
rules: {
'reminder-credential': {
required: true,
minlength: 3
}
},
messages: {
'reminder-credential': {
required: 'Please enter a valid credential'
}
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageAuthReminder.init());

51
mobileservice/src/main/resources/static/assets/_js/pages/op_auth_signin.js

@ -0,0 +1,51 @@
/*
* Document : op_auth_signin.js
* Author : pixelcave
* Description: Custom JS code used in Sign In Page
*/
class pageAuthSignIn {
/*
* Init Sign In Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
*
*/
static initValidation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation-signin').validate({
rules: {
'login-username': {
required: true,
minlength: 3
},
'login-password': {
required: true,
minlength: 5
}
},
messages: {
'login-username': {
required: 'Please enter a username',
minlength: 'Your username must consist of at least 3 characters'
},
'login-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
}
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageAuthSignIn.init());

69
mobileservice/src/main/resources/static/assets/_js/pages/op_auth_signup.js

@ -0,0 +1,69 @@
/*
* Document : op_auth_signup.js
* Author : pixelcave
* Description: Custom JS code used in Sign Up Page
*/
class pageAuthSignUp {
/*
* Init Sign Up Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
*
*/
static initValidation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation-signup').validate({
rules: {
'signup-username': {
required: true,
minlength: 3
},
'signup-email': {
required: true,
emailWithDot: true
},
'signup-password': {
required: true,
minlength: 5
},
'signup-password-confirm': {
required: true,
equalTo: '#signup-password'
},
'signup-terms': {
required: true
}
},
messages: {
'signup-username': {
required: 'Please enter a username',
minlength: 'Your username must consist of at least 3 characters'
},
'signup-email': 'Please enter a valid email address',
'signup-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
},
'signup-password-confirm': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long',
equalTo: 'Please enter the same password as above'
},
'signup-terms': 'You must agree to the service terms!'
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageAuthSignUp.init());

34
mobileservice/src/main/resources/static/assets/_js/pages/op_coming_soon.js

@ -0,0 +1,34 @@
/*
* Document : op_coming_soon.js
* Author : pixelcave
* Description: Custom JS code used in Coming Soon Page
*/
class pageComingSoon {
/*
* Init Countdown.js, for more examples you can check out https://github.com/hilios/jQuery.countdown
*
*/
static countdown() {
jQuery('.js-countdown').countdown((new Date().getFullYear() + 2) + '/02/01', e => {
jQuery(e.currentTarget).html(e.strftime('<div class="row items-push push text-center">'
+ '<div class="col-6 col-md-3"><div class="fs-1 fw-bold text-white">%-D</div><div class="fs-sm fw-bold text-muted">DAYS</div></div>'
+ '<div class="col-6 col-md-3"><div class="fs-1 fw-bold text-white">%H</div><div class="fs-sm fw-bold text-muted">HOURS</div></div>'
+ '<div class="col-6 col-md-3"><div class="fs-1 fw-bold text-white">%M</div><div class="fs-sm fw-bold text-muted">MINUTES</div></div>'
+ '<div class="col-6 col-md-3"><div class="fs-1 fw-bold text-white">%S</div><div class="fs-sm fw-bold text-muted">SECONDS</div></div>'
+ '</div>'
));
});
}
/*
* Init functionality
*
*/
static init() {
this.countdown();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageComingSoon.init());

78
mobileservice/src/main/resources/static/assets/_js/pages/op_installation.js

@ -0,0 +1,78 @@
/*
* Document : op_installation.js
* Author : pixelcave
* Description: Custom JS code used in Installation Page
*/
// Form Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
class pageInstallation {
/*
* Init Installation Form Validation
*
*/
static initValidationInstallation() {
// Load default options for jQuery Validation plugin
Dashmix.helpers('jq-validation');
// Init Form Validation
jQuery('.js-validation-installation').validate({
rules: {
'install-db-name': {
required: true
},
'install-db-username': {
required: true
},
'install-db-password': {
required: true
},
'install-admin-email': {
required: true,
emailWithDot: true
},
'install-admin-password': {
required: true,
minlength: 5
},
'install-admin-password-confirm': {
required: true,
equalTo: '#install-admin-password'
}
},
messages: {
'install-db-name': {
required: 'Please provide the name of your database'
},
'install-db-username': {
required: 'Please provide the username with access to your database'
},
'install-db-password': {
required: 'Please provide the password of your database user'
},
'install-admin-email': {
required: 'Please enter your email'
},
'install-admin-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
},
'install-admin-password-confirm': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
/*
* Init functionality
*
*/
static init() {
this.initValidationInstallation();
}
}
// Initialize when page loads
Dashmix.onLoad(() => pageInstallation.init());

149
mobileservice/src/main/resources/static/assets/_scss/bootstrap/_accordion.scss

@ -0,0 +1,149 @@
//
// Base styles
//
.accordion {
// scss-docs-start accordion-css-vars
--#{$prefix}accordion-color: #{$accordion-color};
--#{$prefix}accordion-bg: #{$accordion-bg};
--#{$prefix}accordion-transition: #{$accordion-transition};
--#{$prefix}accordion-border-color: #{$accordion-border-color};
--#{$prefix}accordion-border-width: #{$accordion-border-width};
--#{$prefix}accordion-border-radius: #{$accordion-border-radius};
--#{$prefix}accordion-inner-border-radius: #{$accordion-inner-border-radius};
--#{$prefix}accordion-btn-padding-x: #{$accordion-button-padding-x};
--#{$prefix}accordion-btn-padding-y: #{$accordion-button-padding-y};
--#{$prefix}accordion-btn-color: #{$accordion-button-color};
--#{$prefix}accordion-btn-bg: #{$accordion-button-bg};
--#{$prefix}accordion-btn-icon: #{escape-svg($accordion-button-icon)};
--#{$prefix}accordion-btn-icon-width: #{$accordion-icon-width};
--#{$prefix}accordion-btn-icon-transform: #{$accordion-icon-transform};
--#{$prefix}accordion-btn-icon-transition: #{$accordion-icon-transition};
--#{$prefix}accordion-btn-active-icon: #{escape-svg($accordion-button-active-icon)};
--#{$prefix}accordion-btn-focus-border-color: #{$accordion-button-focus-border-color};
--#{$prefix}accordion-btn-focus-box-shadow: #{$accordion-button-focus-box-shadow};
--#{$prefix}accordion-body-padding-x: #{$accordion-body-padding-x};
--#{$prefix}accordion-body-padding-y: #{$accordion-body-padding-y};
--#{$prefix}accordion-active-color: #{$accordion-button-active-color};
--#{$prefix}accordion-active-bg: #{$accordion-button-active-bg};
// scss-docs-end accordion-css-vars
}
.accordion-button {
position: relative;
display: flex;
align-items: center;
width: 100%;
padding: var(--#{$prefix}accordion-btn-padding-y) var(--#{$prefix}accordion-btn-padding-x);
@include font-size($font-size-base);
color: var(--#{$prefix}accordion-btn-color);
text-align: left; // Reset button style
background-color: var(--#{$prefix}accordion-btn-bg);
border: 0;
@include border-radius(0);
overflow-anchor: none;
@include transition(var(--#{$prefix}accordion-transition));
&:not(.collapsed) {
color: var(--#{$prefix}accordion-active-color);
background-color: var(--#{$prefix}accordion-active-bg);
box-shadow: inset 0 calc(-1 * var(--#{$prefix}accordion-border-width)) 0 var(--#{$prefix}accordion-border-color); // stylelint-disable-line function-disallowed-list
&::after {
background-image: var(--#{$prefix}accordion-btn-active-icon);
transform: var(--#{$prefix}accordion-btn-icon-transform);
}
}
// Accordion icon
&::after {
flex-shrink: 0;
width: var(--#{$prefix}accordion-btn-icon-width);
height: var(--#{$prefix}accordion-btn-icon-width);
margin-left: auto;
content: "";
background-image: var(--#{$prefix}accordion-btn-icon);
background-repeat: no-repeat;
background-size: var(--#{$prefix}accordion-btn-icon-width);
@include transition(var(--#{$prefix}accordion-btn-icon-transition));
}
&:hover {
z-index: 2;
}
&:focus {
z-index: 3;
border-color: var(--#{$prefix}accordion-btn-focus-border-color);
outline: 0;
box-shadow: var(--#{$prefix}accordion-btn-focus-box-shadow);
}
}
.accordion-header {
margin-bottom: 0;
}
.accordion-item {
color: var(--#{$prefix}accordion-color);
background-color: var(--#{$prefix}accordion-bg);
border: var(--#{$prefix}accordion-border-width) solid var(--#{$prefix}accordion-border-color);
&:first-of-type {
@include border-top-radius(var(--#{$prefix}accordion-border-radius));
.accordion-button {
@include border-top-radius(var(--#{$prefix}accordion-inner-border-radius));
}
}
&:not(:first-of-type) {
border-top: 0;
}
// Only set a border-radius on the last item if the accordion is collapsed
&:last-of-type {
@include border-bottom-radius(var(--#{$prefix}accordion-border-radius));
.accordion-button {
&.collapsed {
@include border-bottom-radius(var(--#{$prefix}accordion-inner-border-radius));
}
}
.accordion-collapse {
@include border-bottom-radius(var(--#{$prefix}accordion-border-radius));
}
}
}
.accordion-body {
padding: var(--#{$prefix}accordion-body-padding-y) var(--#{$prefix}accordion-body-padding-x);
}
// Flush accordion items
//
// Remove borders and border-radius to keep accordion items edge-to-edge.
.accordion-flush {
.accordion-collapse {
border-width: 0;
}
.accordion-item {
border-right: 0;
border-left: 0;
@include border-radius(0);
&:first-child { border-top: 0; }
&:last-child { border-bottom: 0; }
.accordion-button {
&,
&.collapsed {
@include border-radius(0);
}
}
}
}

71
mobileservice/src/main/resources/static/assets/_scss/bootstrap/_alert.scss

@ -0,0 +1,71 @@
//
// Base styles
//
.alert {
// scss-docs-start alert-css-vars
--#{$prefix}alert-bg: transparent;
--#{$prefix}alert-padding-x: #{$alert-padding-x};
--#{$prefix}alert-padding-y: #{$alert-padding-y};
--#{$prefix}alert-margin-bottom: #{$alert-margin-bottom};
--#{$prefix}alert-color: inherit;
--#{$prefix}alert-border-color: transparent;
--#{$prefix}alert-border: #{$alert-border-width} solid var(--#{$prefix}alert-border-color);
--#{$prefix}alert-border-radius: #{$alert-border-radius};
// scss-docs-end alert-css-vars
position: relative;
padding: var(--#{$prefix}alert-padding-y) var(--#{$prefix}alert-padding-x);
margin-bottom: var(--#{$prefix}alert-margin-bottom);
color: var(--#{$prefix}alert-color);
background-color: var(--#{$prefix}alert-bg);
border: var(--#{$prefix}alert-border);
@include border-radius(var(--#{$prefix}alert-border-radius));
}
// Headings for larger alerts
.alert-heading {
// Specified to prevent conflicts of changing $headings-color
color: inherit;
}
// Provide class for links that match alerts
.alert-link {
font-weight: $alert-link-font-weight;
}
// Dismissible alerts
//
// Expand the right padding and account for the close button's positioning.
.alert-dismissible {
padding-right: $alert-dismissible-padding-r;
// Adjust close link position
.btn-close {
position: absolute;
top: 0;
right: 0;
z-index: $stretched-link-z-index + 1;
padding: $alert-padding-y * 1.25 $alert-padding-x;
}
}
// scss-docs-start alert-modifiers
// Generate contextual modifier classes for colorizing the alert.
@each $state, $value in $theme-colors {
$alert-background: shift-color($value, $alert-bg-scale);
$alert-border: shift-color($value, $alert-border-scale);
$alert-color: shift-color($value, $alert-color-scale);
@if (contrast-ratio($alert-background, $alert-color) < $min-contrast-ratio) {
$alert-color: mix($value, color-contrast($alert-background), abs($alert-color-scale));
}
.alert-#{$state} {
@include alert-variant($alert-background, $alert-border, $alert-color);
}
}
// scss-docs-end alert-modifiers

38
mobileservice/src/main/resources/static/assets/_scss/bootstrap/_badge.scss

@ -0,0 +1,38 @@
// Base class
//
// Requires one of the contextual, color modifier classes for `color` and
// `background-color`.
.badge {
// scss-docs-start badge-css-vars
--#{$prefix}badge-padding-x: #{$badge-padding-x};
--#{$prefix}badge-padding-y: #{$badge-padding-y};
@include rfs($badge-font-size, --#{$prefix}badge-font-size);
--#{$prefix}badge-font-weight: #{$badge-font-weight};
--#{$prefix}badge-color: #{$badge-color};
--#{$prefix}badge-border-radius: #{$badge-border-radius};
// scss-docs-end badge-css-vars
display: inline-block;
padding: var(--#{$prefix}badge-padding-y) var(--#{$prefix}badge-padding-x);
@include font-size(var(--#{$prefix}badge-font-size));
font-weight: var(--#{$prefix}badge-font-weight);
line-height: 1;
color: var(--#{$prefix}badge-color);
text-align: center;
white-space: nowrap;
vertical-align: baseline;
@include border-radius(var(--#{$prefix}badge-border-radius));
@include gradient-bg();
// Empty badges collapse automatically
&:empty {
display: none;
}
}
// Quick fix for badges in buttons
.btn .badge {
position: relative;
top: -1px;
}

40
mobileservice/src/main/resources/static/assets/_scss/bootstrap/_breadcrumb.scss

@ -0,0 +1,40 @@
.breadcrumb {
// scss-docs-start breadcrumb-css-vars
--#{$prefix}breadcrumb-padding-x: #{$breadcrumb-padding-x};
--#{$prefix}breadcrumb-padding-y: #{$breadcrumb-padding-y};
--#{$prefix}breadcrumb-margin-bottom: #{$breadcrumb-margin-bottom};
@include rfs($breadcrumb-font-size, --#{$prefix}breadcrumb-font-size);
--#{$prefix}breadcrumb-bg: #{$breadcrumb-bg};
--#{$prefix}breadcrumb-border-radius: #{$breadcrumb-border-radius};
--#{$prefix}breadcrumb-divider-color: #{$breadcrumb-divider-color};
--#{$prefix}breadcrumb-item-padding-x: #{$breadcrumb-item-padding-x};
--#{$prefix}breadcrumb-item-active-color: #{$breadcrumb-active-color};
// scss-docs-end breadcrumb-css-vars
display: flex;
flex-wrap: wrap;
padding: var(--#{$prefix}breadcrumb-padding-y) var(--#{$prefix}breadcrumb-padding-x);
margin-bottom: var(--#{$prefix}breadcrumb-margin-bottom);
@include font-size(var(--#{$prefix}breadcrumb-font-size));
list-style: none;
background-color: var(--#{$prefix}breadcrumb-bg);
@include border-radius(var(--#{$prefix}breadcrumb-border-radius));
}
.breadcrumb-item {
// The separator between breadcrumbs (by default, a forward-slash: "/")
+ .breadcrumb-item {
padding-left: var(--#{$prefix}breadcrumb-item-padding-x);
&::before {
float: left; // Suppress inline spacings and underlining of the separator
padding-right: var(--#{$prefix}breadcrumb-item-padding-x);
color: var(--#{$prefix}breadcrumb-divider-color);
content: var(--#{$prefix}breadcrumb-divider, escape-svg($breadcrumb-divider)) #{"/* rtl:"} var(--#{$prefix}breadcrumb-divider, escape-svg($breadcrumb-divider-flipped)) #{"*/"};
}
}
&.active {
color: var(--#{$prefix}breadcrumb-item-active-color);
}
}

142
mobileservice/src/main/resources/static/assets/_scss/bootstrap/_button-group.scss

@ -0,0 +1,142 @@
// Make the div behave like a button
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-flex;
vertical-align: middle; // match .btn alignment given font-size hack above
> .btn {
position: relative;
flex: 1 1 auto;
}
// Bring the hover, focused, and "active" buttons to the front to overlay
// the borders properly
> .btn-check:checked + .btn,
> .btn-check:focus + .btn,
> .btn:hover,
> .btn:focus,
> .btn:active,
> .btn.active {
z-index: 1;
}
}
// Optional: Group multiple button groups together for a toolbar
.btn-toolbar {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
.input-group {
width: auto;
}
}
.btn-group {
@include border-radius($btn-border-radius);
// Prevent double borders when buttons are next to each other
> :not(.btn-check:first-child) + .btn,
> .btn-group:not(:first-child) {
margin-left: -$btn-border-width;
}
// Reset rounded corners
> .btn:not(:last-child):not(.dropdown-toggle),
> .btn.dropdown-toggle-split:first-child,
> .btn-group:not(:last-child) > .btn {
@include border-end-radius(0);
}
// The left radius should be 0 if the button is:
// - the "third or more" child
// - the second child and the previous element isn't `.btn-check` (making it the first child visually)
// - part of a btn-group which isn't the first child
> .btn:nth-child(n + 3),
> :not(.btn-check) + .btn,
> .btn-group:not(:first-child) > .btn {
@include border-start-radius(0);
}
}
// Sizing
//
// Remix the default button sizing classes into new ones for easier manipulation.
.btn-group-sm > .btn { @extend .btn-sm; }
.btn-group-lg > .btn { @extend .btn-lg; }
//
// Split button dropdowns
//
.dropdown-toggle-split {
padding-right: $btn-padding-x * .75;
padding-left: $btn-padding-x * .75;
&::after,
.dropup &::after,
.dropend &::after {
margin-left: 0;
}
.dropstart &::before {
margin-right: 0;
}
}
.btn-sm + .dropdown-toggle-split {
padding-right: $btn-padding-x-sm * .75;
padding-left: $btn-padding-x-sm * .75;
}
.btn-lg + .dropdown-toggle-split {
padding-right: $btn-padding-x-lg * .75;
padding-left: $btn-padding-x-lg * .75;
}
// The clickable button for toggling the menu
// Set the same inset shadow as the :active state
.btn-group.show .dropdown-toggle {
@include box-shadow($btn-active-box-shadow);
// Show no shadow for `.btn-link` since it has no other button styles.
&.btn-link {
@include box-shadow(none);
}
}
//
// Vertical button groups
//
.btn-group-vertical {
flex-direction: column;
align-items: flex-start;
justify-content: center;
> .btn,
> .btn-group {
width: 100%;
}
> .btn:not(:first-child),
> .btn-group:not(:first-child) {
margin-top: -$btn-border-width;
}
// Reset rounded corners
> .btn:not(:last-child):not(.dropdown-toggle),
> .btn-group:not(:last-child) > .btn {
@include border-bottom-radius(0);
}
> .btn ~ .btn,
> .btn-group:not(:first-child) > .btn {
@include border-top-radius(0);
}
}

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

Loading…
Cancel
Save