masarifyuli пре 1 недеља
комит
b0b0b7b772

+ 2 - 0
.gitattributes

@@ -0,0 +1,2 @@
+/mvnw text eol=lf
+*.cmd text eol=crlf

+ 35 - 0
.gitignore

@@ -0,0 +1,35 @@
+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/
+
+log/

+ 3 - 0
.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip

+ 194 - 0
config/general-setting.yml

@@ -0,0 +1,194 @@
+web:
+  port: 8080
+  update: false
+sch:
+  port: 4200
+rep:
+  host: 127.0.0.1
+  port: 4300
+prc:
+  port: 4400
+  debug: true
+  tcp.server.port: 5000
+  allowed-recorder-ip:
+  - 127.0.0.1
+migration:
+  port: 4500
+cpx:
+  interval: 5
+  idle: 60
+  multiSession: false
+  multiApproval: true
+  percentage: 6
+  https: false
+  info:
+    companyName: Bank Ini Itu
+    lang: en
+  autoRegistration:
+    phoneUser: true
+    trunk: true
+    account: true
+  pin:
+    personalAccess: 2
+    min: 2
+    max: 4
+    patternStart: '01'
+    patternEnd: '7777'
+    byPass: true
+  email:
+    host: mail.datacomsolusindo.co.id
+    from: abidzar@datacomsolusindo.co.id
+    port: 587
+    username: exatest@datacomsolusindo.co.id
+    password: Exates2024@)@$
+    mailProtocol: smtp
+    mailAuth: true
+    mailStarttls: true
+    mailSsl: true
+    mailDebug: false
+  pdfPassword:
+    min: 3
+    max: 6
+  emailContent:
+    pin:
+      id:
+        subject: Pergantian PIN
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h4>Pergantian PIN</h4> <p>Kami ingin menginformasikan bahwa waktu
+          pergantian PIN sudah tiba nih, informasi PIN baru kami lampirkan dengan
+          FILE PDF terenkripsi.</p> <p><strong>Password info : {pin_length} digit
+          [{pin_column}] dimulai dari karakter ke-{pin_start}, contoh {pin_column}
+          adalah {ex_data} maka password nya {ex_password}. PDF Password: {password_pdf}</strong></p>
+          <p>Terima kasih, dan semoga informasi ini bermanfaat untuk kamu.</p> <p>Salam,</p>
+          <p>{company_name}</p>'
+      en:
+        subject: Change PIN
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h4>Change PIN</h4> <p>Kami ingin menginformasikan bahwa waktu pergantian
+          PIN sudah tiba nih, informasi PIN baru kami lampirkan dengan FILE PDF terenkripsi.</p>
+          <p><strong>Password info : {pin_length} digit [{pin_column}] dimulai dari
+          karakter ke-{pin_start}, contoh {pin_column} adalah {ex_data} maka password
+          nya {ex_password}. PDF Password: {password_pdf}</strong></p> <p>Terima kasih,
+          dan semoga informasi ini bermanfaat untuk kamu.</p> <p>Salam,</p> <p>[company_name]</p>'
+    report:
+      id:
+        subject: 'Callmaster Sceduller: {report.title} {period}'
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h3>Generate Laporan</h3> <p>Kami ingin menginformasikan bahwa laporan
+          untuk {report.title} sudah tersedia nih.</p> <p><strong>Periode Laporan
+          : {period}</strong></p> <p><strong>Deskripsi Laporan : {report.description}</strong></p>
+          <p>Terima kasih, dan semoga laporan ini bermanfaat untuk kamu.</p> <p>Salam,</p>
+          <p>{company}</p>'
+      en:
+        subject: 'Callmaster Sceduller: {report.title} {period}'
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h3>Generate Laporan</h3> <p>Kami ingin menginformasikan bahwa laporan
+          untuk {report.title} sudah tersedia nih.</p> <p><strong>Periode Laporan
+          : {period}</strong></p> <p><strong>Deskripsi Laporan : {report.description}</strong></p>
+          <p>Terima kasih, dan semoga laporan ini bermanfaat untuk kamu.</p> <p>Salam,</p>
+          <p>{company}</p>'
+    reportSchedule:
+      id:
+        subject: CallMaster Report
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h3>Laporan Terjadwal</h3> <p>Kami ingin menginformasikan bahwa
+          laporan terjadwal untuk {report_title} sudah tersedia nih.</p> <p><strong>Periode
+          Laporan : {period}</strong></p> <p><strong>Deskripsi Laporan : {report_description}</strong></p>
+          <p>Terima kasih, dan semoga laporan ini bermanfaat untuk kamu.</p> <p>Salam,</p>
+          <p>{company}</p>'
+      en:
+        subject: CallMaster Report
+        title: Judul - judulan
+        subtitle: Subjudul - judulan
+        content: '<h3>Laporan Terjadwal</h3> <p>Kami ingin menginformasikan bahwa
+          laporan terjadwal untuk {report_title} sudah tersedia nih.</p> <p><strong>Periode
+          Laporan : {period}</strong></p> <p><strong>Deskripsi Laporan : {report_description}</strong></p>
+          <p>Terima kasih, dan semoga laporan ini bermanfaat untuk kamu.</p> <p>Salam,</p>
+          <p>{company}</p>'
+    approver:
+      id:
+        subject: Tiket Menunggu Persetujuan Anda
+        title: Halo, Pengguna CallMaster
+        subtitle: Mohon tinjau permintaan yang masih menunggu secepatnya
+        content: <p>Anda memiliki satu atau lebih tiket yang sedang menunggu tindakan
+          Anda.</p> <p>Permintaan tersebut membutuhkan persetujuan atau penolakan
+          untuk diproses lebih lanjut.</p> <p>Terima kasih, dan semoga informasi ini
+          bermanfaat untuk kamu.</p> <p>Salam,</p> <p>{company} {year}</p>
+      en:
+        subject: Ticket(s) Awaiting Your Approval
+        title: Hello, CallMaster User
+        subtitle: Please review the pending request(s) as soon as possible
+        content: '<p>You have one or more ticket(s) currently awaiting your action.</p>
+          <p>Your approval or rejection is required to proceed with the request(s).</p>
+          <p>Thank you for your prompt attention.</p> <p>Regards,</p> <p>{company}
+          {year}</p> <p>Type: {type}</p> <p>Requester: {requester.name}</p>'
+  phonebook:
+    category:
+    - 1
+    - 2
+    - 3
+    email: true
+    organization: true
+    position: true
+    whatsapp: true
+  services:
+  - serviceName: Report Engine
+    key: report
+    path: D:\Runner\callmaster\wr\cpx-report-wr.exe
+    urlHealthCheck: http://localhost:4300/actuator/health
+  - serviceName: Recorder Satu
+    recorder: true
+    key: Recd1pro
+    path: D:\Runner\callmaster\Recorder1\Recd1pro
+    urlHealthCheck: http://localhost:4100/actuator/health
+  pbxSupporter:
+    type: FILE
+    period: 30
+  compare:
+    dataAllowance: 120
+    s:
+      A: 10
+      B: 60
+      C: 120
+    d:
+      A: 10
+      B: 30
+      C: 60
+    l:
+      A: 2
+      B: 5
+      C: 10
+pdKey: g87gO*&G87f6*&F67F%^dfD^%d7f9G78o6fUFi76f&F67*f7*f87F&f56^D%^E6&*T7H(*h8&G&O6f&^F7F6d%^%Df76D6sg(9H
+license:
+  phoneUser: 25000
+  pbx: 5
+  pbxSupport: 2
+  ldap: true
+  expired: 20270101
+redirectUrl:
+- http://192.168.100.18:8080/oauth2redirect
+- http://192.168.100.22:8080/oauth2redirect
+- http://192.168.100.25:8080/oauth2redirect
+- http://192.168.100.205:8080/oauth2redirect
+- http://192.168.100.212:8080/oauth2redirect
+- http://192.168.100.13:8080/oauth2redirect
+- https://cpx.telmessenger.com/oauth2redirect
+- https://oauth.pstmn.io/v1/callback
+- http://localhost:4200/oauth2redirect
+- https://cmpd.telmessenger.com/oauth2redirect
+- https://app.insomnia.rest/oauth/redirect
+dataKey: jRA4iyjy1ZCaIdlJBe6Cm%2BRPGb%2BwcO85%2FWR7Z9%2B8AFVDTPuvnJwmCw6pPbMrQP92CNB%2BMwAPuisTRE8%2FccPGKB%2FuKWIvPxBslzLvfX58IuH3nZB8bPrFiSZH2n5Q7RgjOxObPvHvOIpk4r0P6%2B%2BcJw%3D%3D
+
+#database: 
+#  type: sqlserver
+#  host: 127.0.0.1
+#  port: 1433
+#  name: dbname
+#  username: sa
+#  password: password
+#  properties: encrypt=true;trustServerCertificate=true;

+ 87 - 0
config/migration.yml

@@ -0,0 +1,87 @@
+organization:
+  id: history.organization_id
+  code: organization_code
+  name: organization_name
+  description: description
+  email: organization_email
+  emailOnOverBudget: sendemail_overbudget
+  parent_id: history.parent_organization_id
+  structure: history.organization_id_structure
+  appliedDate: history.app_datetime
+  expiredDate: history.exp_datetime
+costCenter:
+  id: history.costcenter_id
+  code: costcenter_code
+  name: costcenter_name
+  description: description
+  email: costcenter_email
+  parent_id: history.parent_costcenter_id
+  structure: history.costcenter_id_structure
+  appliedDate: history.app_datetime
+  expiredDate: history.exp_datetime
+pbx:
+  code: pbx_code
+  name: description
+  ipPbx: ip_pbx
+  pbxSupporter: pbx_supporter
+  sharePath: share_path
+  appliedDate: ext_start
+  expiredDate: ext_end
+trunk:
+  id: history.trunk_id
+  code: trunk_code
+  name: description
+  pbx_id: location_code
+  direction: cap_direction
+  appliedDate: history.app_datetime
+  expiredDate: history.exp_datetime
+callTransaction:
+  direction: direction
+  startOfCall: start_of_call
+  duration: duration
+  extension: ext_used
+  pin: pin
+  phoneUser_id: phoneuser_code
+  extTransferFrom: ext_transfer_from
+  extTransferTo: ext_transfer_to
+  number: dialed_number
+  callerNumber: caller_number
+  accessNumber: access_number
+  organization_id: organization_code
+  costCenter_id: costcenter_code
+  cost: cost_1
+  service: cost_service
+  tax: cost_tax1
+  currency: currency
+  pbx_id: pbx_code
+  terminationCode: call_termination
+  redirectReason: redirect_reason
+webUser:
+  username: login_id
+  password: login_password
+  name: description
+  phoneUser_id: phoneuser_code
+phoneUser:
+  id: history.phoneuser_id
+  code: phoneuser_code
+  name: phoneuser_name
+  email: phoneuser_email
+  whatsapp: phoneuser_mobile
+  position: position
+  emailOnOverBudget: sendemail_overbudget
+  pin: history.phoneuser_pin
+  extension: history.default_extension
+  organization_id: history.organization_code
+  costCenter_id: history.costcenter_code
+  pbx_id: history.pbx_code
+  pbxList: group.pbx_list
+  appliedDate: history.app_datetime
+  expiredDate: history.exp_datetime
+corcos:
+  command: command
+  name: short_desc
+  description: description
+provider:
+  code: provider_prefix
+  name: description
+  description: description

+ 295 - 0
mvnw

@@ -0,0 +1,295 @@
+#!/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.4
+#
+# 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:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# 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 <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.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${scriptName#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
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+  if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+    actualDistributionDir="$distributionUrlNameMain"
+  fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+  # enable globbing to iterate over items
+  set +f
+  for dir in "$TMP_DOWNLOAD_DIR"/*; do
+    if [ -d "$dir" ]; then
+      if [ -f "$dir/bin/$MVN_CMD" ]; then
+        actualDistributionDir="$(basename "$dir")"
+        break
+      fi
+    fi
+  done
+  set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+  verbose "Contents of $TMP_DOWNLOAD_DIR:"
+  verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+  die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"

+ 189 - 0
mvnw.cmd

@@ -0,0 +1,189 @@
+<# : 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.4
+@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 -eq $False) { "/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_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+  $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+    New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+  $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+  $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::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
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+  $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+  Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+    $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+    if (Test-Path -Path $testPath -PathType Leaf) {
+      $actualDistributionDir = $_.Name
+    }
+  }
+}
+
+if (!$actualDistributionDir) {
+  Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -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"

+ 107 - 0
pom.xml

@@ -0,0 +1,107 @@
+<?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.5</version>
+		<relativePath/> <!-- lookup parent from repository -->
+	</parent>
+	<groupId>com.datacomsolusindo</groupId>
+	<artifactId>migration</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+	<name>migration</name>
+	<description>Migration service data call partner to call master</description>
+	<url/>
+	<licenses>
+		<license/>
+	</licenses>
+	<developers>
+		<developer/>
+	</developers>
+	<scm>
+		<connection/>
+		<developerConnection/>
+		<tag/>
+		<url/>
+	</scm>
+	<properties>
+		<java.version>21</java.version>
+        <kotlin.version>2.0.0</kotlin.version>
+	</properties>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter</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.microsoft.sqlserver</groupId>
+			<artifactId>mssql-jdbc</artifactId>
+			<scope>runtime</scope>
+		</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>
+        <dependency>
+            <groupId>com.datacomsolusindo</groupId>
+            <artifactId>cpx-shared-code</artifactId>
+            <version>0.0.1-SNAPSHOT</version>
+        </dependency>
+	</dependencies>
+
+    <repositories>
+        <repository>
+            <id>shibboleth-releases</id>
+            <url>https://build.shibboleth.net/nexus/content/repositories/releases/</url>
+        </repository>
+    </repositories>
+
+	<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>
+						<arg>-Xannotation-default-target=param-property</arg>
+					</args>
+					<compilerPlugins>
+						<plugin>spring</plugin>
+					</compilerPlugins>
+				</configuration>
+				<dependencies>
+					<dependency>
+						<groupId>org.jetbrains.kotlin</groupId>
+						<artifactId>kotlin-maven-allopen</artifactId>
+						<version>${kotlin.version}</version>
+					</dependency>
+				</dependencies>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

+ 56 - 0
src/main/kotlin/com/datacomsolusindo/migration/MigrationApplication.kt

@@ -0,0 +1,56 @@
+package com.datacomsolusindo.migration
+
+import com.datacomsolusindo.cpx_shared_code.utility.AppListener
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import org.springframework.boot.autoconfigure.SpringBootApplication
+import org.springframework.boot.autoconfigure.domain.EntityScan
+import org.springframework.boot.builder.SpringApplicationBuilder
+import org.springframework.boot.context.event.ApplicationReadyEvent
+import org.springframework.context.annotation.ComponentScan
+import org.springframework.context.event.EventListener
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.stereotype.Component
+import java.nio.file.Paths
+
+@ComponentScan("com.datacomsolusindo")
+@EntityScan("com.datacomsolusindo")
+@EnableJpaRepositories("com.datacomsolusindo")
+@SpringBootApplication
+class MigrationApplication
+
+fun main(args: Array<String>) {
+    SpringApplicationBuilder(MigrationApplication::class.java)
+        .banner { _, _, out ->
+            val banner: String = "\n --------------------------------\n" +
+                    " ____    _______    ____  \n" +
+                    " ]   \\      |      /    \\ \n" +
+                    " ]    |     |      |      \n" +
+                    " ]    |     |      |      \n" +
+                    " ]___/      |      \\____/ \n" +
+                    " Datacom Solusindo   2025 \n" +
+                    "                          \n" +
+                    " Call Master Migration      \n" +
+                    " --------------------------------\n"
+            out.print(banner)
+        }
+        .listeners(AppListener("migration"))
+        .run(
+            *args,
+            "--spring.config.location=classpath:/application.yml, ./config/general-setting.yml"
+        )
+}
+
+@Suppress("UNCHECKED_CAST")
+@Component
+class AppEvent(val migrationService: MigrationService) {
+    private val logger = SimpleLogger.getLogger(this::class.java)
+
+    @EventListener(ApplicationReadyEvent::class)
+    fun doSomethingAfterStartup() {
+        logger.info("started service migration data with support mandiri menghidupi")
+        val folder = Paths.get("migration")
+        migrationService.scanAndQueue(folder)
+//        exitProcess(1)
+    }
+
+}

+ 435 - 0
src/main/kotlin/com/datacomsolusindo/migration/MigrationEntity.kt

@@ -0,0 +1,435 @@
+package com.datacomsolusindo.migration
+
+import com.datacomsolusindo.cpx_shared_code.entity.Account
+import com.datacomsolusindo.cpx_shared_code.entity.Area
+import com.datacomsolusindo.cpx_shared_code.entity.BaseEntity
+import com.datacomsolusindo.cpx_shared_code.entity.Budget
+import com.datacomsolusindo.cpx_shared_code.entity.CdrModifier
+import com.datacomsolusindo.cpx_shared_code.entity.Corcos
+import com.datacomsolusindo.cpx_shared_code.entity.CostCenter
+import com.datacomsolusindo.cpx_shared_code.entity.Organization
+import com.datacomsolusindo.cpx_shared_code.entity.Pbx
+import com.datacomsolusindo.cpx_shared_code.entity.PhoneUser
+import com.datacomsolusindo.cpx_shared_code.entity.PhoneUserPbx
+import com.datacomsolusindo.cpx_shared_code.entity.Provider
+import com.datacomsolusindo.cpx_shared_code.entity.Rate
+import com.datacomsolusindo.cpx_shared_code.entity.Rights
+import com.datacomsolusindo.cpx_shared_code.entity.Transaction
+import com.datacomsolusindo.cpx_shared_code.entity.Trunk
+import com.datacomsolusindo.cpx_shared_code.entity.WebUser
+import com.datacomsolusindo.cpx_shared_code.service.ApiService
+import com.datacomsolusindo.cpx_shared_code.service.CpDecrypt
+import com.datacomsolusindo.cpx_shared_code.utility.BudgetUserType
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import com.datacomsolusindo.cpx_shared_code.utility.ToolAes
+import com.datacomsolusindo.cpx_shared_code.utility.TransferType
+import com.datacomsolusindo.cpx_shared_code.utility.collectAllField
+import com.datacomsolusindo.cpx_shared_code.utility.findId
+import com.datacomsolusindo.cpx_shared_code.utility.value
+import io.github.semutkecil.simplecriteria.FilterData
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
+import org.springframework.security.crypto.factory.PasswordEncoderFactories
+import org.springframework.security.crypto.password.PasswordEncoder
+import org.springframework.stereotype.Service
+import java.io.File
+import java.nio.charset.StandardCharsets
+import java.util.UUID
+import kotlin.time.measureTime
+import kotlin.time.measureTimedValue
+
+
+@Service
+class MigrationEntity(val passwordEncoder: PasswordEncoder) {
+
+    @Autowired
+    lateinit var apiService: ApiService
+
+    @Autowired
+    lateinit var cpDecrypt: CpDecrypt
+
+    private val logger = SimpleLogger.getLogger(this::class.java)
+
+    fun <T> dataToMap(
+        clazz: Class<T>,
+        fields: Map<String, String>,
+        unique: String,
+        rootFile: File,
+        historyFile: File? = null,
+        groupFile: File? = null
+    ): List<MutableMap<String, Any?>> {
+        logger.info("prepare data migration class ${clazz.simpleName}")
+        val process = measureTimedValue {
+            val historyData = historyFile?.let { readQueryDataToMap(it) }
+            val groupData = groupFile?.let { readQueryDataToMap(it) }
+            val rootData = readQueryDataToMap(rootFile)
+            val mapRootData = rootData.map { map ->
+                val data: MutableMap<String, Any?> = mutableMapOf()
+                fields.forEach { (t, u) ->
+                    data[t] = when {
+                        u.startsWith("history.") -> getValueAnotherFile(fields, historyData, unique, data, t, u, "history")
+                        u.startsWith("group.") -> getValueAnotherFile(fields, groupData, unique, data, t, u, "group")
+                        else -> map[u]
+                    }
+                }
+                data
+            }
+            mapRootData
+        }
+        logger.info("finish prepare data [${process.value.size}] migration class ${clazz.simpleName} takes time ${process.duration.inWholeMilliseconds}ms")
+        return process.value
+    }
+
+    private fun getValueAnotherFile(
+        fields: Map<String, String>,
+        dataFile: List<Map<String, Any?>>?,
+        unique: String,
+        rootData: Map<String, Any?>,
+        keyRoot: String,
+        valRoot: String,
+        key: String
+    ): Any? {
+        val uniqueField = dataFile?.firstOrNull()?.let {
+            if (it.any { a -> a.key == fields[unique] }) unique else "id"
+        } ?: "id"
+        val fieldUnique = fields[uniqueField]!!.split(".").last()
+        val value = dataFile?.firstOrNull { f ->
+            f[fieldUnique].toString() == rootData[uniqueField].toString()
+        }?.get(valRoot.replace("${key}.", ""))
+
+        return if (keyRoot.contains("_")) value?.let { id ->
+            dataFile.firstOrNull { f ->
+                f[fields["id"]!!.split(".").last()].toString() == id.toString()
+            }?.get(fields["code"])
+        } else value
+    }
+
+    private fun readQueryDataToMap(file: File): List<Map<String, Any?>> {
+        val map = measureTimedValue {
+            file.bufferedReader(StandardCharsets.UTF_8)
+                .readLines().filter {
+                    it.startsWith("INSERT")
+                }.mapNotNull {
+                    try {
+                        insertSqlToMap(it)
+                    } catch (_: Exception) {
+                        null
+                    }
+                }
+        }
+        logger.info("migration read query data ${map.value.size} takes time ${map.duration.inWholeMilliseconds}")
+        return map.value
+    }
+
+    private fun insertSqlToMap(sql: String): Map<String, Any?> {
+        val splitSql = sql.split(") VALUES (")
+        val fieldColumn = splitSql[0].split("(").last().split(",")
+            .map { it.trim().removeSurrounding("[", "]") }
+        val valueColumn = splitValues(splitSql[1].dropLast(1))
+            .map { parseValue(it.trim()) }
+        val map: MutableMap<String, Any?> = mutableMapOf()
+        fieldColumn.mapIndexed { index, key ->
+            map[key] = valueColumn[index]
+        }
+        return map
+    }
+
+    private fun splitValues(input: String): List<String> {
+        val result = mutableListOf<String>()
+        var depth = 0
+        var current = StringBuilder()
+        for (c in input) {
+            when (c) {
+                '(' -> depth++
+                ')' -> depth--
+                ',' -> {
+                    if (depth == 0) {
+                        result.add(current.toString())
+                        current = StringBuilder()
+                        continue
+                    }
+                }
+            }
+            current.append(c)
+        }
+        result.add(current.toString())
+        return result
+    }
+
+    private fun parseValue(raw: String): Any? {
+        val value = raw.trim()
+        if (value.equals("NULL", true)) return null
+        // CAST(x AS ...)
+        if (value.startsWith("CAST", true)) {
+            val inner = Regex("CAST\\((.*)\\s+AS", RegexOption.IGNORE_CASE)
+                .find(value)?.groupValues?.get(1)?.trim()
+            return parseValue(inner ?: value)
+        }
+        // N'string'
+        if (value.startsWith("N'") && value.endsWith("'")) {
+            return value.substring(2, value.length - 1)
+        }
+        // 'string'
+        if (value.startsWith("'") && value.endsWith("'")) {
+            return value.substring(1, value.length - 1)
+        }
+        // number
+        return value.toLongOrNull()
+            ?: value.toDoubleOrNull()
+            ?: value
+    }
+
+    private val failed: MutableList<Any> = mutableListOf()
+    fun <T : BaseEntity> execute(
+        clazz: Class<T>,
+        fields: Map<String, String>,
+        rootFile: File,
+        historyFile: File?,
+        groupFile: File?
+    ) {
+        failed.clear()
+        val data = dataToMap(clazz, fields, "code", rootFile, historyFile, groupFile)
+
+        val process = measureTime { insertData(clazz, data) }
+
+        logger.info(
+            "finished process migration ${clazz.simpleName} " +
+                    "data ${data.size} " +
+                    "success ${data.size - failed.size} " +
+                    "failed ${failed.size} " +
+                    "takes time ${process.inWholeMilliseconds}ms"
+        )
+    }
+
+    fun clazzEntity(migrationTarget: String): Class<out BaseEntity>? {
+        return when (migrationTarget) {
+            "organization" -> Organization::class.java
+            "costCenter" -> CostCenter::class.java
+            "pbx" -> Pbx::class.java
+            "trunk" -> Trunk::class.java
+            "callTransaction" -> Transaction::class.java
+            "account" -> Account::class.java
+            "area" -> Area::class.java
+            "cdrModifier" -> CdrModifier::class.java
+            "phoneUser" -> PhoneUser::class.java
+            "provider" -> Provider::class.java
+            "rate" -> Rate::class.java
+            "webUser" -> WebUser::class.java
+            "corcos" -> Corcos::class.java
+            else -> null
+        }
+    }
+
+    private fun <T : BaseEntity> insertData(clazz: Class<T>, dataMap: List<MutableMap<String, Any?>>) {
+        val sortingData = if (dataMap.any { it.any { a -> a.key == "structure" } }) {
+            dataMap.sortedBy { f -> f["structure"].toString().length }
+        } else dataMap
+        sortingData.forEach { map ->
+            try {
+                val finalizer = finalizeMap(clazz.simpleName.camelCase(), map)
+                val phoneUserPin = finalizer["pin"]
+                val phoneUserExtension = finalizer["extension"]
+
+                // phoneUserPbx
+                val phoneUserPbxIds: MutableList<Any> = mutableListOf()
+                val data = if (clazz.simpleName == "PhoneUser") {
+                    finalizer["pbxList"]?.toString()?.let {
+                        it.split(";").forEach { fi ->
+                            findId(Pbx::class.java, fi)?.let { id -> phoneUserPbxIds.add(id) }
+                        }
+                    }
+                    finalizer["pbx_id"]?.toString()?.let {
+                        if (it.isNotBlank()) {
+                            phoneUserPbxIds.add(it)
+                        }
+                    }
+                    val finalMap = finalizer.filterNot { fi ->
+                        listOf("pbxList", "pbx_id", "extension", "pin").any { a -> a == fi.key }
+                    } as MutableMap<String, Any?>
+                    apiService.create(clazz, finalMap)
+                } else {
+                    apiService.create(clazz, finalizer)
+                }
+
+                // create budget
+                if (BudgetUserType.entries.any { a -> a.name.snakeToCamel() == clazz.simpleName.camelCase() }) {
+                    val id = clazz.collectAllField().findId().value(data)
+                    val res = apiService.findById(clazz, id!!, listOf("uid"))
+                    res?.get("uid")?.toString()?.let { uid ->
+                        apiService.create(
+                            Budget::class.java,
+                            mutableMapOf(
+                                "userType" to BudgetUserType.valueOf(
+                                    clazz.simpleName.camelCase().camelToSnake().uppercase()
+                                ),
+                                "userUid" to uid,
+                                "type" to "FLAT"
+                            ),
+                        )
+
+                        // create phoneUserPbx
+                        if (phoneUserPbxIds.isNotEmpty()) {
+                            phoneUserPbxIds.forEach { pbxId ->
+                                apiService.create(
+                                    PhoneUserPbx::class.java, mutableMapOf(
+                                        "pin" to phoneUserPin,
+                                        "extension" to phoneUserExtension,
+                                        "pbx_id" to pbxId,
+                                        "phoneUser_id" to id,
+                                    )
+                                )
+                            }
+                        }
+                    }
+                }
+            } catch (e: Exception) {
+                failed.add(map)
+                logger.error("failed insert data migration", e)
+            }
+        }
+    }
+
+    private fun finalizeMap(className: String, map: MutableMap<String, Any?>): MutableMap<String, Any?> {
+        val mapFinalize: MutableMap<String, Any?> = mutableMapOf()
+        map["code"]?.toString()?.let {
+            map["code"] = it.ifBlank { UUID.randomUUID().toString().take(6) }
+        }
+        map["name"]?.toString()?.let {
+            map["name"] = it.ifBlank { "Auto ${(0..99999).toString().padStart(5, '0')}" }
+        }
+
+        map["emailOnOverBudget"]?.let {
+            map["emailOnOverBudget"] = it.toString() == "1"
+        }
+
+        map["direction"]?.toString()?.let {
+            map["direction"] = it.split("").mapNotNull { m ->
+                when (m.trim()) {
+                    "C" -> "INCOMING"
+                    "G" -> "OUTGOING"
+                    "I" -> "INTERNAL"
+                    else -> null
+                }
+            }.joinToString(";")
+        }
+
+        map.filterNot { it.key == "id" || it.key == "structure" }.forEach { (t, u) ->
+            if (t.contains("_")) {
+                val isParent = t.startsWith("parent")
+                val value = if (t == "pbx_id") {
+                    findId(Pbx::class.java, u ?: "PBX01")
+                } else u?.toString()?.let { code ->
+                    val clazzEntity = clazzEntity(if (isParent) className else t.split("_")[0])
+                    clazzEntity?.let { findId(it, code) }
+                }
+
+                if (value != null) {
+                    mapFinalize[t] = value
+                }
+            } else {
+                mapFinalize[t] = u
+            }
+        }
+
+        mapFinalize["pin"]?.toString()?.let {
+            mapFinalize["pin"] = if (it.isBlank()) null
+            else cpDecrypt.decrypt(it)?.let { p -> ToolAes.encrypt(p) }
+        }
+
+        mapFinalize["password"]?.toString()?.let {
+            mapFinalize["password"] = if (it.isBlank()) ""
+            else cpDecrypt.decrypt(it)?.let { p -> passwordEncoder.encode(p) } ?: ""
+        }
+
+        if (className == "transaction") {
+            val to = mapFinalize["extTransferTo"]?.toString() ?: ""
+            val from = mapFinalize["extTransferFrom"]?.toString() ?: ""
+            mapFinalize["transferType"] = when {
+                to.isBlank() && from.isBlank() -> TransferType.DIRECT
+                to.isNotBlank() && from.isBlank() -> TransferType.TRANSFER_TO
+                to.isBlank() && from.isNotBlank() -> TransferType.TRANSFER_FROM
+                else -> TransferType.TRANSFER_FROM_AND_TRANSFER_TO
+            }
+        }
+
+        if (className == "webUser") {
+            defaultProfile?.let { mapFinalize["profile_id"] = it }
+        }
+
+        if (className == "corcos") {
+            mapFinalize["name"] = "Corcos ${map["name"]}"
+        }
+
+        return mapFinalize.mapValues { v -> v.value?.toString() } as MutableMap<String, Any?>
+    }
+
+    private val defaultProfile: Any? by lazy {
+        apiService.findListPage(
+            Rights::class.java,
+            listOf("id"),
+            FilterData.filter("name", FilterData.FILTEROP.EQ, "Default")
+        ).firstOrNull()?.get("id")
+    }
+
+    private fun toSnakeCase(input: String): String {
+        return input
+            .replace(Regex("([a-z0-9])([A-Z])"), "$1_$2")
+            .lowercase()
+    }
+
+    private fun <T : BaseEntity> findId(clazz: Class<T>, value: Any): String? {
+        return try {
+            val query = "SELECT id FROM ${toSnakeCase(clazz.simpleName)} WHERE code = :code "
+            val id = apiService.em.createNativeQuery(query, String::class.java)
+                .setParameter("code", value)
+                .singleResult as String
+            id
+        } catch (_: Exception) {
+            null
+        }
+    }
+
+}
+
+fun String.camelToSnake(): String =
+    replace(Regex("([a-z0-9])([A-Z])"), "$1_$2")
+        .lowercase()
+
+fun String.camelCase(): String {
+    return when {
+        this.contains("_") || this.contains("-") || this.contains(" ") -> {
+            this
+                .lowercase()
+                .split("_", "-", " ")
+                .filter { it.isNotBlank() }
+                .mapIndexed { index, word ->
+                    if (index == 0) word
+                    else word.replaceFirstChar { it.uppercase() }
+                }
+                .joinToString("")
+        }
+
+        else -> {
+            this.replaceFirstChar { it.lowercase() }
+        }
+    }
+}
+
+fun String.snakeToCamel(): String {
+    return this.lowercase()
+        .split("_")
+        .mapIndexed { index, s ->
+            if (index == 0) s else s.replaceFirstChar { it.uppercase() }
+        }
+        .joinToString("")
+}
+
+@Configuration
+class SecurityConfig {
+
+    @Bean
+    fun passwordEncoder(): PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
+
+}

+ 133 - 0
src/main/kotlin/com/datacomsolusindo/migration/MigrationService.kt

@@ -0,0 +1,133 @@
+package com.datacomsolusindo.migration
+
+import com.datacomsolusindo.cpx_shared_code.utility.SimpleLogger
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.launch
+import org.springframework.beans.factory.config.YamlPropertiesFactoryBean
+import org.springframework.core.io.FileSystemResource
+import org.springframework.stereotype.Service
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.StandardCopyOption
+import java.time.LocalDateTime
+import java.time.format.DateTimeFormatter
+import java.util.concurrent.Executors
+import kotlin.use
+
+@Service
+class MigrationService(val migrationEntity: MigrationEntity) {
+
+    private val logger = SimpleLogger.getLogger(this::class.java)
+    private val TEMP = "temp_"
+    private val MIGRATION = "_migration_"
+    private val MIGRATION_CONFIG = "config/migration.yml"
+
+    private val executor = Executors.newSingleThreadExecutor()
+
+    fun isMigrationFile(path: Path): Boolean = path.fileName.toString().contains(MIGRATION)
+
+    fun isTempFile(path: Path): Boolean = path.fileName.toString().startsWith(TEMP)
+
+    fun extractOrder(fileName: String): Int {
+        val cleanName = fileName.removePrefix(TEMP)
+        return cleanName.substringBefore("_").toIntOrNull() ?: Int.MAX_VALUE
+    }
+
+    fun renameToTemp(path: Path): Path {
+        val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
+        val newName = "temp_${time}_${path.fileName}"
+        val target = path.parent.resolve(newName)
+        return Files.move(path, target, StandardCopyOption.ATOMIC_MOVE)
+    }
+
+    fun toHistoryName(input: String, key: String): String {
+        val nameWithoutExt = input.substringBeforeLast(".")
+        val ext = input.substringAfterLast(".", "")
+        val base = nameWithoutExt.substringAfter("_").removeSuffix("_$key")
+        return if (ext.isNotEmpty()) "${base}_$key.$ext" else "${base}_$key"
+    }
+
+    fun scanAndQueue(folder: Path) {
+        logger.info("service migration read files")
+        Files.list(folder).use { stream ->
+            val tempFiles = stream
+                .filter { Files.isRegularFile(it) }
+                .filter { isMigrationFile(it) }
+                .filter { !isTempFile(it) }
+                .sorted(compareBy { extractOrder(it.fileName.toString()) })
+                .toList()
+            val migrationFiles = tempFiles.filterNot {
+                it.fileName.toString().contains("_history") || it.fileName.toString().contains("_group")
+            }
+            val additionalFiles = tempFiles.filter {
+                it.fileName.toString().contains("_history") || it.fileName.toString().contains("_group")
+            }
+
+            logger.info("register migration data ${migrationFiles.size} module")
+            migrationFiles.forEach { mi ->
+                executor.submit {
+                    val filename = mi.fileName.toString()
+                    val migrationTarget = filename.split("_")[2].replace(".txt", "")
+                    val fields = loadYamlAsMap(migrationTarget)
+
+                    if (fields.isNotEmpty()) {
+                        val rootFile = renameToTemp(mi)
+                        val historyFile = if (fields.any { a -> a.value.startsWith("history.") }) {
+                            additionalFiles.firstOrNull { f ->
+                                f.fileName.toString().endsWith(toHistoryName(filename, "history"))
+                            }?.let { addFile -> renameToTemp(addFile) }
+                        } else null
+                        val groupFile = if (fields.any { a -> a.value.startsWith("group.") }) {
+                            additionalFiles.firstOrNull { f ->
+                                f.fileName.toString().endsWith(toHistoryName(filename, "group"))
+                            }?.let { addFile -> renameToTemp(addFile) }
+                        } else null
+                        migrationEntity.clazzEntity(migrationTarget)?.let { clazz ->
+                            migrationEntity.execute(
+                                clazz,
+                                fields,
+                                rootFile.toFile(),
+                                historyFile?.toFile(),
+                                groupFile?.toFile()
+                            )
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    fun loadYamlAsMap(prefix: String): Map<String, String> {
+        val factory = YamlPropertiesFactoryBean()
+        factory.setResources(FileSystemResource(MIGRATION_CONFIG))
+
+        val props = factory.`object` ?: return emptyMap()
+
+        return props
+            .filterKeys { it.toString().startsWith("$prefix.") }
+            .mapKeys { it.key.toString().removePrefix("$prefix.") }
+            .mapValues { it.value.toString() }
+    }
+
+}
+
+//object TaskQueue {
+//    private val scope = CoroutineScope(Dispatchers.IO)
+//    private val channel = Channel<suspend () -> Unit>(Channel.UNLIMITED)
+//
+//    init {
+//        scope.launch {
+//            for (task in channel) {
+//                task()
+//            }
+//        }
+//    }
+//
+//    fun submit(task: suspend () -> Unit) {
+//        scope.launch {
+//            channel.send(task)
+//        }
+//    }
+//}

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

@@ -0,0 +1,15 @@
+#spring.application.name=migration
+spring:
+  port: 4444
+  application:
+    name: migration
+logging:
+  level:
+    root: INFO
+  file:
+    name: log/cpx-migration/migration.log
+  logback.rollingpolicy:
+    file-name-pattern: log/cpx-migration/migration-%d{yyyy-MM-dd}.%i.log
+    max-file-size: 1MB
+    total-size-cap: 256MB
+    max-history: 200

+ 13 - 0
src/test/kotlin/com/datacomsolusindo/migration/MigrationApplicationTests.kt

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