Jelajahi Sumber

process data

herlanS_ 1 hari lalu
induk
melakukan
79ccfd51f5

+ 19 - 0
.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
+#
+#   http://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.9/apache-maven-3.9.9-bin.zip

+ 16 - 0
config/cpx-processor-setting_example.yml

@@ -0,0 +1,16 @@
+server.port: 4300
+spring:
+  datasource:
+    hikari:
+      minimumIdle: 2
+      maximumPoolSize: 10
+      idleTimeout: 30000
+      connectionTimeout: 30000
+      leakDetectionThreshold: 30000
+  jpa:
+    show-sql: true
+    properties:
+      hibernate:
+        format_sql: false
+#    hibernate:
+#      ddl-auto: update

+ 62 - 0
config/general-setting-example.yml

@@ -0,0 +1,62 @@
+web:
+  port: 8080
+sch:
+  port: 4200
+rep:
+  port: 4300
+prc:
+  port: 4400
+database:
+  type: sqlserver
+  host: 103.226.138.208
+  port: 1433
+  name: cpxdb
+  username: sa
+  password: D4tacom!
+  properties: encrypt=true;trustServerCertificate=true;
+cpx:
+  info:
+    companyName: Bank Ini Itu
+    lang: en
+  https: true
+  pin:
+    personalAccess: 2
+    min: 2
+    max: 4
+    patternStart: '01'
+    patternEnd: '7777'
+  email:
+    host: "smtp.postmarkapp.com"
+    from: "septiyan@datacomsolusindo.co.id"
+    port: 587
+    username: "PM-T-outbound-A1HZcKx3kEduzlNoyGvKMR"
+    password: "EbLCFpy7CrwajY016zbkGlvBFgcPChqY1zcq"
+    mailProtocol: "smtp"
+    mailAuth: true
+    mailStarttls: true
+    mailSsl: true
+    mailDebug: false
+  pdfPassword:
+    column: name
+    length: 4
+    start: 1
+  emailContent:
+    pin:
+      subject: "belum ada tuh"
+      content: "Hope you enjoyed using CallMaster.<br><br>
+      Your new PIN is attached in this encrypted PDF file<br>
+      The password for this file is {pin_description}<br><br>
+      Example, {column} is <strong>{ex_data}</strong>, then password is <strong>{ex_password}</strong><br><br>
+      Regards,<br>
+      {company} {year}"
+
+#    host: "mail.datacomsolusindo.co.id"
+#    from: "septiyan@datacomsolusindo.co.id"
+#    port: 587
+#    username: "septiyan"
+#    password: "sep582%*@"
+#    mailProtocol: "smtp"
+#    mailAuth: true
+#    mailStarttls: true
+#    mailSsl: false
+#    mailDebug: false

File diff ditekan karena terlalu besar
+ 2006 - 0
log/cpx-scheduler/processor.log


+ 259 - 0
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
+#
+#    http://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 - 0
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    http://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"

+ 130 - 0
pom.xml

@@ -0,0 +1,130 @@
+<?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.4</version>
+		<relativePath/> <!-- lookup parent from repository -->
+	</parent>
+	<groupId>com.datacomsolusindo</groupId>
+	<artifactId>cpx-processor</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+	<name>cpx-processor</name>
+	<description>Cpx Data Processor</description>
+	<url/>
+	<licenses>
+		<license/>
+	</licenses>
+	<developers>
+		<developer/>
+	</developers>
+	<scm>
+		<connection/>
+		<developerConnection/>
+		<tag/>
+		<url/>
+	</scm>
+	<properties>
+		<java.version>21</java.version>
+		<kotlin.version>1.9.25</kotlin.version>
+	</properties>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-actuator</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-data-jpa</artifactId>
+		</dependency>
+<!--		<dependency>-->
+<!--			<groupId>org.springframework.boot</groupId>-->
+<!--			<artifactId>spring-boot-starter-web</artifactId>-->
+<!--		</dependency>-->
+		<dependency>
+			<groupId>com.fasterxml.jackson.module</groupId>
+			<artifactId>jackson-module-kotlin</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jetbrains.kotlin</groupId>
+			<artifactId>kotlin-reflect</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.jetbrains.kotlin</groupId>
+			<artifactId>kotlin-stdlib</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>com.datacomsolusindo</groupId>
+			<artifactId>cpx-shared-code</artifactId>
+			<version>0.0.1-SNAPSHOT</version>
+		</dependency>
+
+
+		<dependency>
+			<groupId>com.microsoft.sqlserver</groupId>
+			<artifactId>mssql-jdbc</artifactId>
+			<scope>runtime</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.mina</groupId>
+			<artifactId>mina-core</artifactId>
+			<version>2.2.3</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-test</artifactId>
+			<scope>test</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.jetbrains.kotlin</groupId>
+			<artifactId>kotlin-test-junit5</artifactId>
+			<scope>test</scope>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
+		<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.boot</groupId>
+				<artifactId>spring-boot-maven-plugin</artifactId>
+			</plugin>
+			<plugin>
+				<groupId>org.jetbrains.kotlin</groupId>
+				<artifactId>kotlin-maven-plugin</artifactId>
+				<configuration>
+					<args>
+						<arg>-Xjsr305=strict</arg>
+					</args>
+					<compilerPlugins>
+						<plugin>spring</plugin>
+						<plugin>jpa</plugin>
+					</compilerPlugins>
+					<pluginOptions>
+						<option>all-open:annotation=jakarta.persistence.Entity</option>
+						<option>all-open:annotation=jakarta.persistence.MappedSuperclass</option>
+						<option>all-open:annotation=jakarta.persistence.Embeddable</option>
+					</pluginOptions>
+				</configuration>
+				<dependencies>
+					<dependency>
+						<groupId>org.jetbrains.kotlin</groupId>
+						<artifactId>kotlin-maven-allopen</artifactId>
+						<version>${kotlin.version}</version>
+					</dependency>
+					<dependency>
+						<groupId>org.jetbrains.kotlin</groupId>
+						<artifactId>kotlin-maven-noarg</artifactId>
+						<version>${kotlin.version}</version>
+					</dependency>
+				</dependencies>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

+ 141 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/AppEvent.kt

@@ -0,0 +1,141 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.entity.PhoneUserPbx
+import com.datacomsolusindo.cpx_shared_code.service.ApiService
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import io.github.semutkecil.simplecriteria.FilterData
+import org.apache.mina.core.service.IoAcceptor
+import org.apache.mina.core.session.IdleStatus
+import org.apache.mina.filter.codec.ProtocolCodecFilter
+import org.apache.mina.filter.codec.textline.TextLineCodecFactory
+import org.apache.mina.transport.socket.nio.NioSocketAcceptor
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.beans.factory.annotation.Value
+import org.springframework.boot.context.event.ApplicationReadyEvent
+import org.springframework.context.event.ContextClosedEvent
+import org.springframework.context.event.EventListener
+import org.springframework.scheduling.annotation.Scheduled
+import org.springframework.stereotype.Component
+import java.io.PrintWriter
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.time.LocalDateTime
+import java.time.format.DateTimeFormatter
+
+
+@Component
+class AppEvent {
+    val logger = SimpleLogger.getLogger(this.javaClass)
+
+    @Value("\${tcp.server.port:5000}")
+    lateinit var tcpPort: String
+
+    @Autowired
+    lateinit var apiService: ApiService
+
+    @Autowired
+    lateinit var processorMessageHandler: ProcessorMessageHandler
+
+    val simulationExtList: MutableList<Map<String, Any?>> = mutableListOf()
+
+    var ioAcceptor: IoAcceptor? = null
+
+    var simulationSocket: Socket? = null
+    var simulationSocketWriter: PrintWriter? = null
+
+    @EventListener(ApplicationReadyEvent::class)
+    fun doSomethingAfterStartup() {
+        logger.info("app start")
+        ioAcceptor = upTcpServer(tcpPort.toInt())
+
+        //simulation
+        val simulationSocket = Socket("127.0.0.1", tcpPort.toInt())
+        simulationSocketWriter = PrintWriter(simulationSocket.getOutputStream(), true)
+//        LDAPPBX
+        //TRNKI
+
+        simulationExtList.addAll(
+            apiService.findListAll(
+                PhoneUserPbx::class.java, listOf(PhoneUserPbx::extension.name, PhoneUserPbx::pin.name),
+                FilterData.filter("pbx.code", FilterData.FILTEROP.EQ, "LDAPPBX")
+            )
+        )
+
+
+        // Setup input stream to receive data from the server
+//        val `in` = BufferedReader(InputStreamReader(socket.getInputStream()))
+
+
+        // Send message to the server
+//        out.println("Hello from client!")
+//        out.println("Hello from client!")
+//        out.println("Hello from client!")
+
+
+        // Receive response from the server
+//        val response = `in`.readLine()
+//        println("Server says: $response")
+
+
+        // Close the socket
+//        socket.close()
+    }
+
+    val dateFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
+    fun generateSimCdr(): String {
+        val soc = LocalDateTime.now()
+        val duration = (5..500).random().toLong()
+        val waiting = (1..20).random().toLong()
+        val extSim = simulationExtList[(0..<simulationExtList.size).random()]
+        val pin = (extSim["pin"] as String?) ?: ""
+        val ext = (extSim["extension"] as String?) ?: ""
+        //        * CDR,HO,G,2024-02-16 11:01:16,2024-02-16 11:01:20,2024-02-16 11:04:30,4,190,9,,11,,08121008912,,1201,Rina,101,,,D,S,V,,,,,,,
+
+        //021
+        //0274
+        //0341
+        //031
+        //024
+        //0632
+        //0361
+
+        val num = listOf("021","0274","0341","031","024","0632","0361","0812","085").random() + (100000..999999).random()
+//        val num = "021" + (100000..999999).random()
+
+        return "CDR,LDAPPBX,G,${
+            soc.minusSeconds(waiting).format(dateFormater)
+        },${soc.format(dateFormater)},${
+            soc.plusSeconds(duration).format(dateFormater)
+        },$waiting,$duration,${(1..9).random()},,TRNKI,,$num,,$pin,tanpanama,$ext,,,D,S,V,,,,,,,"
+
+    }
+
+    @EventListener(ContextClosedEvent::class)
+    fun onContextClosedEvent(contextClosedEvent: ContextClosedEvent) {
+        simulationSocket?.close()
+    }
+
+    @Scheduled(cron = "0/5 * * * * ?")
+    fun simulation() {
+//        * CDR,HO,G,2024-02-16 11:01:16,2024-02-16 11:01:20,2024-02-16 11:04:30,4,190,9,,11,,08121008912,,1201,Rina,101,,,D,S,V,,,,,,,
+//        * CDR,HO,G,2024-02-16 12:02:22,2024-02-16 12:02:30,2024-02-16 12:12:40,8,620,,,12,,5824747,,1202,Joko,102,,,D,S,V,,,,,,,
+//        * CDR,HO,G,2024-02-16 13:03:08,2024-02-16 13:03:20,2024-02-16 13:03:50,12,30,9,,14,,085623780984,,1203,Yudha,103,,108,TT,S,V,,,,,,,
+        if (simulationExtList.isNotEmpty()) {
+            simulationSocketWriter?.println(generateSimCdr())
+        }
+    }
+
+    fun upTcpServer(port: Int): IoAcceptor {
+        val acceptor: IoAcceptor = NioSocketAcceptor()
+        acceptor.filterChain.addLast("codec", ProtocolCodecFilter(TextLineCodecFactory()))
+        acceptor.handler = processorMessageHandler
+        acceptor.sessionConfig.readBufferSize = 2048
+        acceptor.sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 10)
+        acceptor.bind(InetSocketAddress(port))
+        logger.info(
+            "Gateway server standby at port $port"
+        )
+        return acceptor
+    }
+}
+

+ 452 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/CalculateCost2Service.kt

@@ -0,0 +1,452 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.entity.Area
+import com.datacomsolusindo.cpx_shared_code.entity.Hlr
+import com.datacomsolusindo.cpx_shared_code.entity.Holiday
+import com.datacomsolusindo.cpx_shared_code.entity.Rate
+import com.datacomsolusindo.cpx_shared_code.service.ApiService
+import com.datacomsolusindo.cpx_shared_code.utility.EnumData
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import com.datacomsolusindo.cpx_shared_code.utility.Util
+import com.fasterxml.jackson.module.kotlin.readValue
+import io.github.semutkecil.simplecriteria.FilterData
+import jakarta.transaction.Transactional
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.stereotype.Service
+import java.time.DayOfWeek
+import java.time.LocalDateTime
+import java.time.LocalTime
+import java.time.format.DateTimeFormatter
+import java.time.temporal.ChronoUnit
+import kotlin.math.*
+import kotlin.time.measureTimedValue
+
+@Service
+class CalculateCost2Service {
+    @Autowired
+    lateinit var apiService: ApiService
+
+
+    private val logger = SimpleLogger.getLogger(this::class.java)
+
+    fun calculateCost(
+        callTo: CallTo,
+        callFrom: CallFrom,
+        zone: String,
+        startOfCall: LocalDateTime,
+        duration: Long,
+        logger: SimpleLogger
+    ): Double {
+        logger.info("----------------Calculate Cost-----------------")
+        logger.info("From: ${Util.mapper.writeValueAsString(callFrom)}")
+        logger.info("To:   ${Util.mapper.writeValueAsString(callTo)}")
+        val distance = calculateDistance(callFrom.latitude, callFrom.longitude, callTo.latitude, callTo.longitude)
+        logger.info("Start: ${startOfCall.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))}")
+        logger.info(
+            "End:   ${
+                startOfCall.plusSeconds(duration).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+            }"
+        )
+        logger.info("Duration: $duration Seconds")
+        logger.info("Distance: $distance km")
+        logger.info("Zone: $zone")
+
+        val spl = splitRate(startOfCall, duration).map {
+            val endTime = it.startCall.plusSeconds(it.duration).toLocalTime()
+            val startTime = it.startCall.toLocalTime()
+            val (dayCode, measureHoliday) = measureTimedValue { getDayCode(it.startCall, callTo.holidayPage) }
+            logger.info("Populate Holiday data ${measureHoliday.inWholeMilliseconds}ms")
+            logger.info("Day Code: $dayCode")
+            val rateTime = getRate(
+                dayCode,
+                callFrom.providerCode,
+                callTo.providerCode,
+                zone,
+                callFrom.ratePageName,
+                logger
+            )?.let { t ->
+                logger.info("Rate Id: ${t["rateId"]}")
+                Util.mapper.readValue<Map<Long, Map<LocalTime, List<Map<String, Any>>>>>(t["tarif"] as String)
+            }?.entries
+                ?.sortedBy { t -> t.key }
+                ?.lastOrNull { t -> t.key <= distance }
+                ?.value
+                ?.entries
+                ?.sortedBy { t -> t.key }
+                ?.associate { t -> t.key to t.value }
+                ?.filter { t ->
+                    if (endTime.hour + endTime.minute + endTime.second == 0) {
+                        true
+                    } else {
+                        t.key.isBefore(endTime)
+                    }
+                }
+
+            val start = rateTime?.entries?.lastOrNull { t ->
+                !t.key.isAfter(startTime)
+            }?.key
+
+            val rateTimeUsed = if (start != null) {
+                rateTime.filter { t ->
+                    !t.key.isBefore(start)
+                }
+            } else {
+                rateTime
+            }
+
+            val rateTimeToList = rateTimeUsed?.entries?.toList()
+            val rateEachTimeBand = rateTimeToList?.mapIndexed { i, t ->
+                logger.info("\tTimeBand: ${t.key}")
+                val mapValue: MutableMap<String, Any> = when (i) {
+                    0 -> {
+                        val dUnit = if (rateTimeToList.size == 1) {
+                            it.duration
+                        } else {
+                            startTime.until(rateTimeToList[1].key, ChronoUnit.SECONDS)
+                        }
+
+                        mutableMapOf(
+                            "time" to t.key,
+                            "start" to startTime,
+                            "duration" to dUnit,
+                            "end" to startTime.plusSeconds(dUnit),
+                        )
+                    }
+
+                    rateTimeToList.size - 1 -> {
+                        val dt = abs(endTime.until(t.key, ChronoUnit.SECONDS))
+                        mutableMapOf(
+                            "time" to t.key,
+                            "start" to t.key,
+                            "duration" to dt,
+                            "end" to t.key.plusSeconds(dt),
+                        )
+                    }
+
+                    else -> {
+                        val dt = abs(t.key.until(rateTimeToList[i + 1].key, ChronoUnit.SECONDS))
+                        mutableMapOf(
+                            "time" to t.key,
+                            "start" to t.key,
+                            "duration" to dt,
+                            "end" to t.key.plusSeconds(dt),
+                        )
+                    }
+                }
+                val valueCost = countRepetitionCost(mapValue["duration"] as Long, t.value, logger)
+
+                mapValue["value"] = valueCost
+                mapValue
+            }
+
+            rateEachTimeBand
+        }
+
+
+        val totalCost = spl.mapNotNull {
+            it?.sumOf { tb ->
+                val rep = tb["value"] as List<Map<String, Any>>
+                rep.sumOf { re -> re["cost"] as Double }
+            }
+        }.sum()
+        logger.info("Total Cost: $totalCost")
+        logger.info("--------------End Calculate Cost---------------")
+        return totalCost
+    }
+
+    private fun countRepetitionCost(
+        duration: Long,
+        repetitionList: List<Map<String, Any>>,
+        logger: SimpleLogger
+    ): List<MutableMap<String, Any>> {
+
+        var durCount = duration
+
+        return repetitionList.sortedBy { it["rep_number"] as Int }.mapIndexedNotNull {i,it->
+//            logger.info("repetition count ${repetitionList.size} data $it")
+            if (durCount > 0) {
+                val valueMap = it.toMutableMap()
+                val pulse = (it["pulse"] as Int).toLong()
+                val maxPulse = ((it["rep_time"] as Int) * (it["pulse"] as Int)).toLong()
+
+                val pulseCount = if ((it["rep_time"] as Int) == 0) {
+//                    logger.info("repetition time is 0")
+                    val usedPulse = durCount / pulse + (if (durCount % pulse == 0L) 0 else 1)
+                    durCount = 0
+                    usedPulse
+                } else {
+                    val pulseData = durCount / pulse + (if (durCount % pulse == 0L) 0 else 1)
+//                    logger.info("pulse data $pulseData - pulse max $maxPulse")
+                    if (pulseData <= (it["rep_time"] as Int).toLong()) {
+                        durCount = 0
+                        pulseData
+                    } else {
+                        durCount -= maxPulse
+                        (it["rep_time"] as Int).toLong()
+                    }
+                }
+
+                valueMap["pulse_used"] = pulseCount
+                valueMap["duration_used"] = pulseCount * (it["pulse"] as Int).toLong()
+                valueMap["cost"] = pulseCount.toDouble() * it["rate_value"].toString().toDouble()
+                logger.info("\t\tRepetition_$i: $valueMap")
+                valueMap
+            } else {
+                null
+            }
+
+        }
+    }
+
+    private fun splitRate(startOfCall: LocalDateTime, duration: Long): MutableList<TimeRate> {
+        val endOfCall = startOfCall.plusSeconds(duration)
+        var startDate = startOfCall
+        var dur = 0L
+
+        val listTimeRate = mutableListOf<TimeRate>()
+        while (startDate != endOfCall) {
+            var nextEnd = LocalDateTime.of(startDate.plusDays(1).toLocalDate(), LocalTime.of(0, 0, 0))
+
+            if (nextEnd.isAfter(endOfCall)) {
+                nextEnd = endOfCall
+            }
+
+            val todayDuration = ChronoUnit.SECONDS.between(startDate, nextEnd)
+            dur += todayDuration
+            listTimeRate.add(TimeRate(startDate, todayDuration))
+            startDate = nextEnd
+        }
+
+        if (listTimeRate.size > 1 && listTimeRate.sumOf { it.duration } != duration) {
+            listTimeRate[listTimeRate.size - 1].duration += 1
+        }
+
+        return listTimeRate
+    }
+
+    fun getCallTo(number: String, logger: SimpleLogger): CallTo? {
+        val (hlr, measureHlr) = measureTimedValue {
+            apiService.findListPage(
+                Hlr::class.java,
+                listOf("id", "prefix", "provider.code", "area", "domain", "zone.code", "holiday"),
+                FilterData.filter("prefix", FilterData.FILTEROP.LIKEREVSTART, number),
+                size = null
+            ).maxByOrNull { it["prefix"].toString().length }
+        }
+
+        logger.info("populate hlr data ${measureHlr.inWholeMilliseconds}ms")
+
+        if (!hlr.isNullOrEmpty() && hlr["provider.code"] != null) {
+
+            val (areaTo, measureArea) = measureTimedValue {
+                apiService.findListPage(
+                    Area::class.java,
+                    listOf("longitude", "latitude", "uid"),
+                    FilterData.filter("code", FilterData.FILTEROP.EQ, hlr["area"] as String),
+                    size = 1
+                ).firstOrNull()
+            }
+
+            if (areaTo != null) {
+                return CallTo(
+                    areaCode = hlr["area"] as String,
+                    areaUid = areaTo["uid"] as String,
+                    latitude = areaTo["latitude"] as Double,
+                    longitude = areaTo["longitude"] as Double,
+                    domain = hlr["domain"] as String,
+                    providerCode = hlr["provider.code"] as String,
+                    holidayPage = hlr["holiday"] as Int?,
+                    zone = hlr["zone.code"] as String?,
+                    number = number
+                )
+            } else {
+                logger.info("unidentified area from $hlr")
+                return null
+            }
+        } else {
+            logger.info("unidentified call to $hlr")
+            return null
+        }
+    }
+
+    fun getCallFrom(
+        phoneUser: Map<String, Any?>?,
+        ext: String?,
+        pin: String?,
+        isCallerToZoneExist: Boolean,
+        trunk: Map<String, Any?>?,
+        pbx: Map<String, Any?>?,
+        logger: SimpleLogger
+    ): CallFrom? {
+        val dataMap = if (trunk != null && trunk["provider.code"] != null && trunk["area.code"] != null) {
+            trunk
+        } else {
+            pbx
+        }
+
+        if (dataMap != null && dataMap["area.code"] != null && dataMap["provider.code"] != null) {
+
+            var phoneType = EnumData.PhoneType.UNDEFINED
+
+            val domain = if (isCallerToZoneExist) {
+                "-"
+            } else {
+                val (hlrDomain, measureDomainFrom) = measureTimedValue {
+                    apiService.findListPage(
+                        Hlr::class.java,
+                        listOf("domain", "provider.code", "phoneType"),
+                        FilterData.filter("area", FilterData.FILTEROP.EQ, dataMap["area.code"] as String),
+                        size = null
+                    )
+                }//
+                logger.info("populate domain from data ${measureDomainFrom.inWholeMilliseconds}ms")
+
+                val hlr = if (hlrDomain.isEmpty()) {
+                    null
+                } else
+                    if (hlrDomain.any { it["provider.code"] == dataMap["provider.code"] as String }) {
+                        hlrDomain.first { it["provider.code"] == dataMap["provider.code"] as String }
+                    } else {
+                        hlrDomain.first()
+                    }
+
+
+                if (hlr == null) {
+                    logger.info("domain not found from area ${dataMap["area.code"]} and ${dataMap["provider.code"]}")
+                    return null;
+                }
+                phoneType = hlr["phoneType"] as EnumData.PhoneType
+                hlr["domain"].toString()
+            }
+
+            val ratePage: String? = if (phoneUser != null) {                //search phone user for rate page
+                phoneUser["phoneUser.ratePage.name"] as String?
+            } else {
+                null
+            }
+
+
+            return CallFrom(
+                areaCode = dataMap["area.code"] as String,
+                latitude = dataMap["area.latitude"] as Double,
+                longitude = dataMap["area.longitude"] as Double,
+                providerCode = dataMap["provider.code"] as String,
+                domain = domain,
+                ratePageName = ratePage,
+                ext = ext,
+                pin = pin,
+                phoneUserUid = phoneUser?.get("phoneUser.uid") as String?,
+                phoneType = phoneType
+            )
+
+        } else {
+            logger.info("unidentified call from $dataMap")
+            return null
+        }
+    }
+
+    private fun getDayCode(startOfCall: LocalDateTime, holidayPage: Int?): Int {
+        val isHoliday = apiService.findListAll(
+            Holiday::class.java,
+            listOf("holiday", "page"),
+            FilterData.and(
+                FilterData.filter("holiday", FilterData.FILTEROP.GED, "${LocalDateTime.now().year}-01-01"),
+                FilterData.filter("holiday", FilterData.FILTEROP.LED, "${LocalDateTime.now().year}-12-31")
+            )
+        ).firstOrNull {
+            if (holidayPage != null) {
+                (it["holiday"] as LocalDateTime).toLocalDate() == startOfCall.toLocalDate() && (it["page"] as Int?) == holidayPage
+            } else {
+                (it["holiday"] as LocalDateTime).toLocalDate() == startOfCall.toLocalDate()
+            }
+        } != null
+
+        return if (!isHoliday) {
+            when (startOfCall.dayOfWeek!!) {
+                DayOfWeek.MONDAY -> 2
+                DayOfWeek.TUESDAY -> 3
+                DayOfWeek.WEDNESDAY -> 4
+                DayOfWeek.THURSDAY -> 5
+                DayOfWeek.FRIDAY -> 6
+                DayOfWeek.SATURDAY -> 7
+                DayOfWeek.SUNDAY -> 1
+            }
+        } else {
+            8
+        }
+    }
+
+    @Transactional
+    private fun getRate(
+        dayCode: Int,
+        providerFrom: String,
+        providerTo: String,
+        zone: String,
+        ratePageName: String?,
+        logger: SimpleLogger
+    ): Map<String, Any?>? {
+        val (rateList, measureRate) = measureTimedValue {
+            apiService.findListAll(
+                Rate::class.java, listOf("id", "zone.code", "tarif", "ratePage.name", "dayCode"), FilterData.and(
+                    FilterData.filter(
+                        "providerFrom.code", FilterData.FILTEROP.EQ, providerFrom
+                    ),
+                    FilterData.or(
+                        FilterData.filter(
+                            "providerTo.code", FilterData.FILTEROP.EQ, providerTo
+                        ),
+                        FilterData.filter(
+                            "providerTo.code", FilterData.FILTEROP.ISNULL, ""
+                        )
+                    )
+                )
+            ).filter { (it["dayCode"] as String).contains(dayCode.toString()) && zone == (it["zone.code"] as String) }
+        }
+
+        logger.info("Populate Rate data ${measureRate.inWholeMilliseconds}ms")
+
+        val byProvider = if (rateList.any { it["providerTo.code"] != null }) {
+            rateList.filter { it["providerTo.code"] != null }
+        } else {
+            rateList
+        }
+
+        val rate = if (ratePageName != null && byProvider.any { it["ratePage.name"] == ratePageName }) {
+            byProvider.firstOrNull { it["ratePage.name"] == ratePageName }
+        } else {
+            byProvider.firstOrNull()
+        }
+
+        return if (rate == null) {
+            null
+        } else {
+            mapOf(
+                "rateId" to rate["id"],
+                "tarif" to rate["tarif"] as String
+            )
+
+        }
+
+    }
+
+    val EARTH_RADIUS: Double = 6371.0
+
+    private fun haversine(`val`: Double): Double {
+        return sin(`val` / 2).pow(2.0)
+    }
+
+    private fun calculateDistance(startLat: Double, startLong: Double, endLat: Double, endLong: Double): Double {
+        val dLat = Math.toRadians(endLat - startLat)
+        val dLong = Math.toRadians(endLong - startLong)
+
+        val startLatRad = Math.toRadians(startLat)
+        val endLatRad = Math.toRadians(endLat)
+
+        val a: Double = haversine(dLat) + cos(startLatRad) * cos(endLatRad) * haversine(dLong)
+        val c = 2 * atan2(sqrt(a), sqrt(1 - a))
+
+        return EARTH_RADIUS * c
+    }
+
+
+}

+ 17 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/CallFrom.kt

@@ -0,0 +1,17 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.utility.EnumData
+import java.io.Serializable
+
+class CallFrom(
+    val areaCode: String,
+    val domain: String,
+    val latitude: Double,
+    val longitude: Double,
+    val providerCode: String,
+    val ratePageName: String?,
+    val pin: String?,
+    val ext: String?,
+    val phoneUserUid: String?,
+    val phoneType: EnumData.PhoneType?
+) : Serializable

+ 15 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/CallTo.kt

@@ -0,0 +1,15 @@
+package com.datacomsolusindo.cpx_processor
+
+import java.io.Serializable
+
+class CallTo(
+    val areaCode: String,
+    val areaUid: String,
+    val domain: String,
+    val latitude: Double,
+    val longitude: Double,
+    val providerCode: String,
+    val holidayPage: Int?,
+    val zone: String?,
+    val number: String?
+) : Serializable

+ 118 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/CpxProcessorApplication.kt

@@ -0,0 +1,118 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.utility.AppListener
+import org.springframework.boot.autoconfigure.SpringBootApplication
+import org.springframework.boot.autoconfigure.domain.EntityScan
+import org.springframework.boot.builder.SpringApplicationBuilder
+import org.springframework.context.annotation.ComponentScan
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.scheduling.annotation.EnableScheduling
+
+/**
+ * CDR,HO,G,2024-02-16 11:01:16,2024-02-16 11:01:20,2024-02-16 11:04:30,4,190,9,,11,,08121008912,,1201,Rina,101,,,D,S,V,,,,,,,
+ * CDR,HO,G,2024-02-16 12:02:22,2024-02-16 12:02:30,2024-02-16 12:12:40,8,620,,,12,,5824747,,1202,Joko,102,,,D,S,V,,,,,,,
+ * CDR,HO,G,2024-02-16 13:03:08,2024-02-16 13:03:20,2024-02-16 13:03:50,12,30,9,,14,,085623780984,,1203,Yudha,103,,108,TT,S,V,,,,,,,
+ * CDR,HO,G,2024-02-16 14:04:39,2024-02-16 14:04:40,2024-02-16 15:24:50,1,4810,0,,21,,001655824210,,,,104,0,,TF,S,V,,,,,,,
+ *
+ * Seg-1 : CDR : Kode bahwa ini adalah data CDR
+ * Seg-2 : HO : Kode PABX (alphanumeric, biasanya pada CP 01,02,dst)
+ * Seg-3 : G : Arah panggilan (G=outgoing, C=incoming, I=internal)
+ * Seg-4 : 2024-02-16 11:01:16 : Tgl.jam panggilan dimulai (start of call)
+ * Seg-5 : 2024-02-16 11:01:20 : Tgl.jam panggilan terjawab (start of connection/answer)
+ * Seg-6 : 2024-02-16 11:04:30 : Tgl.jam panggilan selesai (end of call)
+ * Seg-7 : 4 : Lamanya menunggu sebelum panggilan dijawab (answer delay, dalam detik)
+ * Seg-8 : 190 : Lamanya percakapan (answer duration, dalam detik)
+ * Seg-9 : 9 : Kode akses untuk panggilan outgoing
+ * Seg-10 :  : Nomor trunk route (kosong, tidak ada data)
+ * Seg-11 : 11 : Nomor trunk member
+ * Seg-12 :  : Kode account/project (kosong, tidak ada data. Biasanya untuk kode client pada konsultan/pengacara)
+ * Seg-13 : 08121008912 : Nomor tujuan (dialed number)
+ * Seg-14 :  : Nomor pemanggil dari luar (outside caller number, untuk panggilan incoming)
+ * Seg-15 : 1201 : PIN
+ * Seg-16 : Rina : Nama pemilik PIN (pada Cisco, bisa ditampilkan. Jika ada koma, sudah dibganti menjadi spasi atau dihapus)
+ * Seg-17 : 101 : Nomor extension yang digunakan untuk melakukan panggilan (used extension)
+ * Seg-18 :  : Nomor extension pemberi transfer (jika menerima transfer / transfer from)
+ * Seg-19 :  : Nomor extension penerima transfer (jika melakukan transfer / transfer to)
+ * Seg-20 : D : Kondisi transfer (D=direct, TF=transfer from, TT=transfer to, TE=transfer from and transfer to
+ * Seg-21 : S : Kondisi conference (S=single, C=Conference)
+ * Seg-22 : V : Jenis komunikasi (V=voice, D=data/fax, S=streaming video)
+ * Seg-23 :  : Jumlah pulsa (kosong, tiadak ada data answerback counter)
+ * Seg-selanjutnya : cadangan
+ */
+
+
+@SpringBootApplication
+@EnableScheduling
+@ComponentScan("com.datacomsolusindo")
+@EntityScan("com.datacomsolusindo")
+@EnableJpaRepositories("com.datacomsolusindo")
+class CpxProcessorApplication
+
+fun main(args: Array<String>) {
+    SpringApplicationBuilder(CpxProcessorApplication::class.java)
+        .banner { _, _, out ->
+            val banner: String = "\n --------------------------------\n" +
+                    " ____    _______    ____  \n" +
+                    " ]   \\      |      /    \\ \n" +
+                    " ]    |     |      |      \n" +
+                    " ]    |     |      |      \n" +
+                    " ]___/      |      \\____/ \n" +
+                    " Datacom Solusindo   2024 \n" +
+                    "                          \n" +
+                    " Call Master Processor      \n" +
+                    " --------------------------------\n"
+            out.print(banner)
+        }
+        .listeners(AppListener("prc"))
+        .run(
+            *args,
+            "--spring.config.location=classpath:/application.yml, ./config/cpx-processor-setting.yml, ./config/general-setting.yml"
+        )
+}
+
+/**
+ * Criteria attribute										operator list
+ * Code	Criteria attribute	Value									Code	Description	DB
+ * PBX	PBX					                                string					CO	contains	%###%
+ * DIR	Direction	G: Outgoing, C:Incoming, I:Internal	    string					NC	not contain	!%###%
+ * ACC	Account					                            string					IC	include	in (###,###)
+ * ACN	Access Number					                    string					XC	exclude	not in (###,###)
+ * TRN	Trunk					                            string					BG	begin with	###%
+ * NUM	Number					                            string					ND	end with	%###
+ * --NMI	Number Minimum Digit					            int					    EQ	equal	=
+ * --NMA	Number Maximum Digit					            int					    NE	not equal	!=
+ * EXT	Extension					                        string					LT	less than	<
+ * SOC	Start of Call (yyyy-mm-dd hh:mm:ss)					date					LE	less than or equal to	<=
+ * DUR	Duration (second)					                int					    GT	greater than	>
+ * PIN	PIN					                                string					GE	greater than or equal to	>=
+ * NDG	Number Digit					                    int					    BL	is blank	isnull
+ * 											NB	is not blank	not isnull
+ */
+
+/**
+ *
+ * Code	Description		Value									        contoh	value		hasil
+ * DEF	Delete x digit First Number		x		                        menghapus x digit dari karakter pertama number							NUM: '081'	1		NUM: '81'
+ * DEL	Delete x digit Last Number		x		                        menghapus x digit dari karakter terakhir number							NUM: '081'	2		NUM: '0'
+ * KEF	Keep x digit First Number		x		                        mengambil x digit dari karakter pertama number							NUM: '081'	1		NUM: '0'
+ * KEL	Keep x digit Last Number		x		                        mengambil x digit dari karakter terakhir number							NUM: '081'	2		NUM: '81'
+ * INF	Insert x at First Number		x		                        menambah value di awal number							                NUM: '081'	a		NUM: 'a081'
+ * INL	Insert x at Last Number		    x		                        menambah value di akhir number							                NUM: '081'	b		NUM: '081b'
+ * CNU	Change Number to				                                mengubah number ke value							                    NUM: '081'	999		NUM: '999'
+ * CAN	Change Access Number to				                            mengubah access number ke value							                ACN: '555'	222		ACN: '222'
+ * CTR	Change Trunk to				                                    mengubah trunk ke value							                        TRN: '01'	02		TRN: '02'
+ * CAC	Change Account to				                                mengubah account ke value							                    ACC: '222'	33		ACC: '33'
+ * CPI	Change PIN to				                                    mengubah pin ke value							                        PIN: '123'	456		PIN: '456'
+ * CDI	Change Direction to		G: Outgoing, C:Incoming, I:Internal		mengubah direction ke value							                    DIR: 'G'	O		DIR: 'O'
+ * STE	Switch Trunk to Extension		Y/N		                        mengubah trunk ke extension							                    TRN: '03' EXT: '11'"	Y		"TRN: '11' EXT: '11'"
+ * ADU	Add Duration (in second) to Start of Call				        menambah duration x detik ke start of call							    SOC: '2024-03-01 00:03:30'	25200		SOC: '2024-03-01 07:03:30'
+ * RDU	Reduce Duration (in second) to Start of Call				    mengurangi duration x detik ke start of call							SOC: '2024-03-01 00:03:30'	360		SOC: '2024-02-29 23:57:30'
+ * CDU	Change Duration (in second)				                        mengubah duration ke x detik 							                DUR: '18000'	30		DUR: '30'
+ *
+ */
+
+
+enum class ModifierCriteriaAttribute { PBX, DIR, ACC, ACN, TRN, NUM, EXT, SOC, DUR, PIN, NDG }
+enum class ModifierCriteriaOperator { CO, NC, IC, XC, BG, ND, EQ, NE, LT, LE, GT, GE, BL, NB }
+enum class ModifierActionAttribute { DEF, DEL, KEF, KEL, INF, INL, CNU, CAN, CTR, CAC, CPI, CDI, STE, ADU, RDU, CDU }
+

+ 12 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/Modifier.kt

@@ -0,0 +1,12 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.utility.EnumData
+import java.io.Serializable
+
+class Modifier(
+    val order: Int,
+    val match: EnumData.CdrMatch,
+    val criteria: List<ModifierCriteria>? = null,
+    val action: List<ModifierAction>? = null,
+    val cont: Boolean = true
+) : Serializable

+ 9 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/ModifierAction.kt

@@ -0,0 +1,9 @@
+package com.datacomsolusindo.cpx_processor
+
+import java.io.Serializable
+
+class ModifierAction(
+    val sequence: Int,
+    val attribute: ModifierActionAttribute,
+    val value: String
+) : Serializable

+ 10 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/ModifierCriteria.kt

@@ -0,0 +1,10 @@
+package com.datacomsolusindo.cpx_processor
+
+import java.io.Serializable
+
+class ModifierCriteria(
+    val sequence: Int,
+    val attribute: ModifierCriteriaAttribute,
+    val operator: ModifierCriteriaOperator,
+    val value: String
+) : Serializable

+ 22 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/PreTransactionData.kt

@@ -0,0 +1,22 @@
+package com.datacomsolusindo.cpx_processor
+
+import java.io.Serializable
+import java.time.LocalDateTime
+
+class PreTransactionData(
+//    var createdDate: LocalDateTime,
+    var pbxCode: String,
+    var direction: String,
+    var startOfCall: LocalDateTime,
+    var duration: Long,
+    var dialedNumber: String,
+//    var locationCode: String?,
+    var callerNumber: String?,
+    var trunkCode: String,
+    var ext: String?,
+    var extTransferFrom: String?,
+    var raw: String,
+    var account: String? = null,
+    var accessNumber: String? = null,
+    var pin: String? = null,
+) : Serializable

+ 42 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/ProcessorMessageHandler.kt

@@ -0,0 +1,42 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import org.apache.mina.core.service.IoHandlerAdapter
+import org.apache.mina.core.session.IoSession
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.stereotype.Component
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+@Component
+class ProcessorMessageHandler : IoHandlerAdapter() {
+    private val logger = SimpleLogger.getLogger(this.javaClass)
+    var executor: ExecutorService = Executors.newFixedThreadPool(4)
+
+    @Autowired
+    lateinit var processorService: ProcessorService
+
+    override fun sessionCreated(session: IoSession) {
+        super.sessionCreated(session)
+        logger.info("session created ${session.id} with address ${session.remoteAddress}")
+    }
+
+    override fun sessionOpened(session: IoSession) {
+        super.sessionOpened(session)
+        logger.info("session opened ${session.id} with address ${session.remoteAddress}")
+    }
+
+    override fun sessionClosed(session: IoSession) {
+        logger.info("session closed ${session.id} with address ${session.remoteAddress}")
+        super.sessionClosed(session)
+    }
+
+    override fun messageReceived(session: IoSession, message: Any) {
+        val cleanMessage = message.toString().trim()
+        logger.info("${session.id} : $cleanMessage")
+        if (cleanMessage.startsWith("CDR,")) {
+            println("process CDR")
+            executor.execute { processorService.processData(cleanMessage) }
+        }
+    }
+}

File diff ditekan karena terlalu besar
+ 715 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/ProcessorService.kt


+ 66 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/RawCallTransaction.kt

@@ -0,0 +1,66 @@
+package com.datacomsolusindo.cpx_processor
+
+import com.datacomsolusindo.cpx_shared_code.utility.EnumData
+
+class RawCallTransaction(
+    var cost: Double = 0.0,
+    var currency: String? = null,
+    var direction: String = "G",
+    var discount: Double = 0.0,
+    var duration: Long = 0,
+    var extension: String? = null,
+    var number: String = "",
+    var phoneType: Int = 0,
+    var pin: String? = null,
+    var rawData: String? = null,
+    var service: Double = 0.0,
+    var startOfCall: String = "1999-10-28 06:05:00",
+    var tag: String? = null,
+    var tax: Double = 0.0,
+    var accountUid: String? = null,
+    var areaUid: String? = null,
+    var costCenterUid: String? = null,
+    var destinationGroupUid: String? = null,
+    var organizationUid: String? = null,
+    var phoneUserUid: String? = null,
+    var zoneUid: String? = null,
+    var rateUid: String? = null,
+    var trunkUid: String? = null,
+    var pbxUid: String? = null,
+    //---------
+    var startOfAnswer: String? = null,
+    var endOfCall: String? = null,
+    var callerNumber: String? = null,
+    var ownerPin: String? = null,
+    var extTransferFrom: String? = null,
+    var extTransferTo: String? = null,
+    var pulse: String? = null,
+    var transferType: EnumData.TransferType? = null,
+    var conferenceType: EnumData.ConferenceType? = null,
+    var communicationType: EnumData.CommunicationType? = null
+) {
+//    "28500, " + //cost
+//    "NULL, " + //currency
+//    "NULL, " + //direction
+//    "0, " + //discount
+//    "190, " + //duration
+//    "'10108', " + //extension
+//    "'8900', " + //number
+//    "'0', " + //phone_type
+//    "NULL, " + //pin
+//    "NULL, " + //raw_data
+//    "0, " + //service
+//    "'2024-10-28T06:05:00.376Z', " + //start of call
+//    "NULL, " + // tag
+//    "0, " + // tax
+//    "NULL, " + // account_uid
+//    "NULL, " + // area_uid
+//    "NULL, " + // cost center uid
+//    "NULL, " + // destination group uid
+//    "'01JBJVDKZP2GC3D1CPEF5HFDZR', " + // organization_uid
+//    "'01JAS3NSHHMBY4CFHZG5GN3PVY', " + // phone user uid
+//    "'01JBDRQYG5PTWR6HTJMWKFYHNJ', " + //zone uid
+//    "NULL, " + //rate_uid
+//    "'01JAVMG99CM0AN0TJQW0BQB6XA', " + // trunk_uid
+//    "NULL" +
+}

+ 5 - 0
src/main/kotlin/com/datacomsolusindo/cpx_processor/TimeRate.kt

@@ -0,0 +1,5 @@
+package com.datacomsolusindo.cpx_processor
+
+import java.time.LocalDateTime
+
+class TimeRate(val startCall: LocalDateTime, var duration: Long)

+ 23 - 0
src/main/resources/application.yml

@@ -0,0 +1,23 @@
+server.port: 4200
+spring:
+  servlet:
+    multipart:
+      max-file-size: 10MB
+      max-request-size: 10MB
+  main.banner-mode: "LOG"
+  application.name: cpx_prc
+logging:
+  level:
+    root: INFO
+  file:
+    name: log/cpx-scheduler/processor.log
+  logback.rollingpolicy:
+    file-name-pattern: log/cpx-processor/processor-%d{yyyy-MM-dd}.%i.log
+    max-file-size: 1MB
+    total-size-cap: 1MB
+management:
+  endpoints:
+    web.exposure.include: "*"
+  endpoint:
+    threaddump.enabled: true
+    info.enabled: true

+ 13 - 0
src/test/kotlin/com/datacomsolusindo/cpx_processor/CpxProcessorApplicationTests.kt

@@ -0,0 +1,13 @@
+package com.datacomsolusindo.cpx_processor
+
+import org.junit.jupiter.api.Test
+import org.springframework.boot.test.context.SpringBootTest
+
+@SpringBootTest
+class CpxProcessorApplicationTests {
+
+	@Test
+	fun contextLoads() {
+	}
+
+}