From bf0cc4af849ec21662f39b053c40876e2b2f64e8 Mon Sep 17 00:00:00 2001 From: sasadib Date: Wed, 6 May 2026 16:48:09 +0700 Subject: [PATCH] add more BE file from server --- .../masterdata/accounting/Approvelevel.php | 378 ++ .../mockup/masterdata/accounting/Bankcoa.php | 386 ++ .../masterdata/accounting/Beginingbalance.php | 499 +++ .../masterdata/accounting/Branchacc.php | 71 + .../masterdata/accounting/Departement.php | 301 ++ .../mockup/masterdata/accounting/Divisi.php | 314 ++ .../accounting/GatewayAutoJurnal.php | 177 + .../masterdata/accounting/Itemregional.php | 524 +++ .../mockup/masterdata/accounting/Itemunit.php | 702 ++++ .../masterdata/accounting/JournalItemOut.php | 366 ++ .../accounting/JournalItemUsage.php | 761 ++++ .../accounting/JournalPenyesuaian.php | 597 +++ .../accounting/JournalVerifEdit.php | 432 +++ .../masterdata/accounting/Journalar.php | 180 + .../accounting/Journalarpayment.php | 180 + .../accounting/Journalarpaymentv2.php | 761 ++++ .../masterdata/accounting/Journalarv2.php | 761 ++++ .../masterdata/accounting/Journalcash.php | 161 + .../masterdata/accounting/Journalcashv2.php | 761 ++++ .../masterdata/accounting/Journalfixasset.php | 762 ++++ .../accounting/Journalfixedasset.php | 224 ++ .../accounting/Journalgoodreceive.php | 764 ++++ .../accounting/Journalpaymentinv.php | 768 ++++ .../masterdata/accounting/Journalpv.php | 775 ++++ .../accounting/Journalsuratjalan.php | 763 ++++ .../accounting/Journalterimabarang.php | 694 ++++ .../accounting/Journaltukarfaktur.php | 761 ++++ .../masterdata/accounting/Jurnalbiaya.php | 1236 +++++++ .../masterdata/accounting/Jurnalgaji.php | 1228 +++++++ .../accounting/Jurnalpengeluaranbarang.php | 361 ++ .../masterdata/accounting/Jurnalsendreg.php | 558 +++ .../masterdata/accounting/Jurnalumum.php | 928 +++++ .../mockup/masterdata/accounting/Maprk.php | 560 +++ .../masterdata/accounting/Mdaccountsales.php | 357 ++ .../masterdata/accounting/Mdcategory.php | 255 ++ .../mockup/masterdata/accounting/Mdcoa.php | 274 ++ .../mockup/masterdata/accounting/Mditem.php | 944 +++++ .../masterdata/accounting/Mdperiode.php | 195 + .../mockup/masterdata/accounting/Mdtype.php | 205 ++ .../accounting/Mediajurnalauto-ori.php | 2580 +++++++++++++ .../masterdata/accounting/Mediajurnalauto.php | 2717 ++++++++++++++ .../accounting/Presentasecabang.php | 537 +++ .../masterdata/accounting/Presentasecost.php | 537 +++ .../accounting/Presentasefacabang.php | 529 +++ .../masterdata/accounting/Presetjurnal.http | 16 + .../masterdata/accounting/Presetjurnal.php | 866 +++++ .../accounting/Recrusivetemplate.php | 246 ++ .../mockup/masterdata/accounting/Reverse.php | 333 ++ .../mockup/masterdata/accounting/Supplier.php | 1003 +++++ .../masterdata/accounting/Supplier_bckp.php | 737 ++++ .../masterdata/accounting/Unitconvert.php | 526 +++ .../accounting/md-rochecklist/Rochecklist.php | 680 ++++ .../accounting/mediajurnalauto.http | 127 + .../ReceiveItemPoInventaris_bckup-260506.php | 3225 +++++++++++++++++ 54 files changed, 35583 insertions(+) create mode 100644 application/controllers/mockup/masterdata/accounting/Approvelevel.php create mode 100644 application/controllers/mockup/masterdata/accounting/Bankcoa.php create mode 100644 application/controllers/mockup/masterdata/accounting/Beginingbalance.php create mode 100644 application/controllers/mockup/masterdata/accounting/Branchacc.php create mode 100644 application/controllers/mockup/masterdata/accounting/Departement.php create mode 100644 application/controllers/mockup/masterdata/accounting/Divisi.php create mode 100644 application/controllers/mockup/masterdata/accounting/GatewayAutoJurnal.php create mode 100644 application/controllers/mockup/masterdata/accounting/Itemregional.php create mode 100644 application/controllers/mockup/masterdata/accounting/Itemunit.php create mode 100644 application/controllers/mockup/masterdata/accounting/JournalItemOut.php create mode 100644 application/controllers/mockup/masterdata/accounting/JournalItemUsage.php create mode 100644 application/controllers/mockup/masterdata/accounting/JournalPenyesuaian.php create mode 100644 application/controllers/mockup/masterdata/accounting/JournalVerifEdit.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalar.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalarpayment.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalarpaymentv2.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalarv2.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalcash.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalcashv2.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalfixasset.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalfixedasset.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalpaymentinv.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalpv.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalsuratjalan.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journalterimabarang.php create mode 100644 application/controllers/mockup/masterdata/accounting/Journaltukarfaktur.php create mode 100644 application/controllers/mockup/masterdata/accounting/Jurnalbiaya.php create mode 100644 application/controllers/mockup/masterdata/accounting/Jurnalgaji.php create mode 100644 application/controllers/mockup/masterdata/accounting/Jurnalpengeluaranbarang.php create mode 100644 application/controllers/mockup/masterdata/accounting/Jurnalsendreg.php create mode 100644 application/controllers/mockup/masterdata/accounting/Jurnalumum.php create mode 100644 application/controllers/mockup/masterdata/accounting/Maprk.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mdaccountsales.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mdcategory.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mdcoa.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mditem.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mdperiode.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mdtype.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mediajurnalauto-ori.php create mode 100644 application/controllers/mockup/masterdata/accounting/Mediajurnalauto.php create mode 100644 application/controllers/mockup/masterdata/accounting/Presentasecabang.php create mode 100644 application/controllers/mockup/masterdata/accounting/Presentasecost.php create mode 100644 application/controllers/mockup/masterdata/accounting/Presentasefacabang.php create mode 100644 application/controllers/mockup/masterdata/accounting/Presetjurnal.http create mode 100644 application/controllers/mockup/masterdata/accounting/Presetjurnal.php create mode 100644 application/controllers/mockup/masterdata/accounting/Recrusivetemplate.php create mode 100644 application/controllers/mockup/masterdata/accounting/Reverse.php create mode 100644 application/controllers/mockup/masterdata/accounting/Supplier.php create mode 100644 application/controllers/mockup/masterdata/accounting/Supplier_bckp.php create mode 100644 application/controllers/mockup/masterdata/accounting/Unitconvert.php create mode 100644 application/controllers/mockup/masterdata/accounting/md-rochecklist/Rochecklist.php create mode 100644 application/controllers/mockup/masterdata/accounting/mediajurnalauto.http create mode 100644 application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris_bckup-260506.php diff --git a/application/controllers/mockup/masterdata/accounting/Approvelevel.php b/application/controllers/mockup/masterdata/accounting/Approvelevel.php new file mode 100644 index 0000000..93eee2b --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Approvelevel.php @@ -0,0 +1,378 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_count = "SELECT count(*) as total + FROM m_approve_level + WHERE M_ApproveLevelIsActive = 'Y' + AND (M_ApproveLevelName LIKE ?)"; + $qry_count = $this->db->query($sql_count, [$search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("approve count error", $this->db); + exit; + } + + $sql = "SELECT M_ApproveLevelID, + M_ApproveLevelName, + M_ApproveLevelStartTotal, + M_ApproveLevelEndTotal + FROM m_approve_level + WHERE M_ApproveLevelIsActive = 'Y' + AND (M_ApproveLevelName LIKE ?) + ORDER BY M_ApproveLevelID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("approve list error", $this->db); + exit; + } + + foreach ($rows as $key => $value) { + $rows[$key]['rownumber'] = $key + 1; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save() + { + try { + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['name']) || trim($prm['name']) == "") { + $this->sys_error("Approve level name is required"); + exit; + } + + $name = trim($prm['name']); + $startTotal = trim($prm['startTotal']); + $endTotal = trim($prm['endTotal']); + + // Check for existing approve with same name + $sql_check = "SELECT COUNT(*) as total FROM m_approve_level + WHERE M_ApproveLevelName = ? AND M_ApproveLevelIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$name]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama approve level sudah ada"); + exit; + } + + $sql = "INSERT INTO m_approve_level( + M_ApproveLevelName, + M_ApproveLevelStartTotal, + M_ApproveLevelEndTotal, + M_ApproveLevelIsActive, + M_ApproveLevelUserID, + M_ApproveLevelCreated) VALUES(?,?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $name, + $startTotal, + $endTotal, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("approve level insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM m_approve_level WHERE M_ApproveLevelName = '{$name}' AND M_ApproveLevelIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function update() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['approveId']) || !is_numeric($prm['approveId'])) { + $this->sys_error("Approve level ID is required"); + exit; + } + if (!isset($prm['name']) || trim($prm['name']) == "") { + $this->sys_error("Approve level name is required"); + exit; + } + + $approveId = $prm['approveId']; + $name = trim($prm['name']); + $startTotal = trim($prm['startTotal']); + $endTotal = trim($prm['endTotal']); + + // Check if department exists + $sql_exist = "SELECT COUNT(*) as total FROM m_approve_level + WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'"; + $qry_exist = $this->db->query($sql_exist, [$approveId]); + if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) { + $this->sys_error("Approve level not found"); + exit; + } + + // Check for existing department with same name (excluding current department) + $sql_check = "SELECT COUNT(*) as total FROM m_approve_level + WHERE M_ApproveLevelName = ? AND M_ApproveLevelID != ? + AND M_ApproveLevelIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$name, $approveId]); + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama Approve level sudah ada"); + exit; + } + + // Update department + $sql = "UPDATE m_approve_level SET + M_ApproveLevelName = ?, + M_ApproveLevelStartTotal = ?, + M_ApproveLevelEndTotal = ?, + M_ApproveLevelUserID = ?, + M_ApproveLevelLastUpdated = NOW() + WHERE M_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [ + $name, + $startTotal, + $endTotal, + $userId, + $approveId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Approve level update error", $this->db); + exit; + } + + $this->db->trans_commit(); + + // Get updated record + $sql_get = "SELECT * FROM m_approve_level WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'"; + $records = $this->db->query($sql_get, [$approveId])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['approveId']) || !is_numeric($prm['approveId'])) { + $this->sys_error("Approve level ID is required"); + exit; + } + + $approveId = $prm['approveId']; + + // Check if approve exists and is active + $sql_exist = "SELECT COUNT(*) as total FROM m_approve_level + WHERE M_ApproveLevelID = ? AND M_ApproveLevelIsActive = 'Y'"; + $qry_exist = $this->db->query($sql_exist, [$approveId]); + if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) { + $this->sys_error("Approve level not found"); + exit; + } + + // Soft delete by updating IsActive to 'N' + $sql = "UPDATE m_approve_level SET + M_ApproveLevelIsActive = 'N', + M_ApproveLevelUserID = ?, + M_ApproveLevelLastUpdated = NOW() + WHERE M_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $approveId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("approve delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $this->sys_ok(array( + "message" => "Approve level deleted successfully", + "approveId" => $approveId + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUser() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $approveId = $prm["approveId"]; + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_count = "SELECT count(*) as total + FROM m_user + JOIN m_staff ON M_UserM_StaffID = M_StaffID AND M_StaffIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserM_ApproveLevelID = ? + AND (M_UserFullName LIKE ? OR M_StaffName LIKE ?)"; + $qry_count = $this->db->query($sql_count, [$approveId, $search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("m_user count error", $this->db); + exit; + } + + $sql = "SELECT + M_UserID, + M_UserM_BranchID, + M_UserS_RegionalID, + M_UserM_UserGroupID, + M_UserR_ReportGroupID, + M_UserM_StaffID, + M_UserUsername, + M_UserFullName, + M_UserIsCoordinator, + M_StaffName, + M_StaffPhone + FROM m_user + JOIN m_staff ON M_UserM_StaffID = M_StaffID AND M_StaffIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserM_ApproveLevelID = ? + AND (M_UserFullName LIKE ? OR M_StaffName LIKE ?) + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$approveId, $search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("m_user list error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Bankcoa.php b/application/controllers/mockup/masterdata/accounting/Bankcoa.php new file mode 100644 index 0000000..907c9ad --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Bankcoa.php @@ -0,0 +1,386 @@ +isLogin) { + $this->sys_error("Invalid Token"); + } + + $sql = "SELECT S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + ORDER BY S_RegionalName ASC"; + $qry = $this->db->query($sql, []); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = $prm["regionalId"]; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $regionalId = $prm['regionalId']; + // $filterregional = ""; + // if (intval($regionalId) > 0) { + // $filterregional .= " AND S_RegionalID = {$regionalId}"; + // } + + $branchCode = $prm['branchCode']; + $filterbranch = ""; + if ($branchCode != "") { + $filterbranch .= " AND MapBank_BranchCode = '{$branchCode}'"; + } + + $sql = "SELECT + MapBank_ID, + MapBank_BranchCode, + MapBank_NatBankID, + MapBank_NatBankCode, + MapBank_NatBankName, + MapBank_NatBankIsEDC, + MapBank_BankAccountNo, + MapBank_CoaID, + MapBank_CoaAccountNo, + MapBank_CoaDescription, + MapBank_EDC_CoaID, + MapBank_EDC_CoaAccountNo, + MapBank_EDC_CoaDescription, + MapBank_IsActive + FROM map_bank_coa + JOIN m_branch ON MapBank_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + AND S_RegionalID = {$regionalId} + WHERE MapBank_IsActive = 'Y' + AND (MapBank_NatBankName LIKE '{$search}' OR MapBank_NatBankCode LIKE '{$search}' OR MapBank_BankAccountNo LIKE '{$search}') + $filterbranch + "; + $sql_total = "SELECT count(*) as total FROM ($sql) as x"; + $qry_total = $this->db->query($sql_total, []); + + // print_r($this->db->last_query()); + // exit; + + $number_offset = 0; + $number_limit = 10; + + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $total_count = 0; + $total_page = 0; + if ($qry_total) { + $total_count = $qry_total->result_array()[0]["total"]; + $total_page = ceil($total_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select count bank coa count error", $this->db);; + exit; + } + + $sql_bank = $sql . " LIMIT $number_limit OFFSET $number_offset"; + $qry_bank = $this->db->query($sql_bank, []); + if ($qry_bank) { + $rows = $qry_bank->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select bank coa count error", $this->db);; + exit; + } + + $result = array( + "total_page" => $total_page, + "total_filter" => $total_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchCoaBank() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = $prm["search"]; + $search_name = '%' . $search . '%'; + $search_account = "$search%"; + + $number_limit = 10; + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}') + ORDER BY coaAccountNo ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($number_limit)); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchCoaEDC() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = $prm["search"]; + $search_name = '%' . $search . '%'; + $search_account = "$search%"; + + $number_limit = 10; + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}') + ORDER BY coaAccountNo ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($number_limit)); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveupdate() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $isEdc = $prm["isEdc"]; + $coaBankId = $prm["coaBankId"]; + $coaBankAccountNo = $prm["coaBankAccountNo"]; + $coaBankDescription = $prm["coaBankDescription"]; + $edcCoaId = $prm["edcCoaId"]; + $edcCoaAccountNo = $prm["edcCoaAccountNo"]; + $edcCoaDescription = $prm["edcCoaDescription"]; + $mapBankId = $prm["mapBankId"]; + + $sql = "UPDATE map_bank_coa SET + MapBank_NatBankIsEDC = ?, + MapBank_CoaID = ?, + MapBank_CoaAccountNo = ?, + MapBank_CoaDescription = ?, + MapBank_EDC_CoaID = ?, + MapBank_EDC_CoaAccountNo = ?, + MapBank_EDC_CoaDescription = ?, + MapBank_LastUpdatedAt = NOW() + WHERE MapBank_ID = ?"; + $qry = $this->db->query($sql, array( + $isEdc, + $coaBankId, + $coaBankAccountNo, + $coaBankDescription, + $edcCoaId, + $edcCoaAccountNo, + $edcCoaDescription, + $mapBankId + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("update map bank coa error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletebankcoa() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $mapBankId = $prm["mapBankId"]; + + $sql = "UPDATE map_bank_coa SET + MapBank_IsActive = 'N', + MapBank_LastUpdatedAt = NOW() + WHERE MapBank_ID = ?"; + $qry = $this->db->query($sql, array( + $mapBankId + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("delete map bank coa error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Beginingbalance.php b/application/controllers/mockup/masterdata/accounting/Beginingbalance.php new file mode 100644 index 0000000..35444b7 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Beginingbalance.php @@ -0,0 +1,499 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function getPeriode() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $sql = "SELECT + periodeID AS id, + periodeName as name, + CONCAT(DATE_FORMAT(periodeStartDate, '%d-%m-%Y'), ' - ',DATE_FORMAT(periodeEndDate, '%d-%m-%Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $rst = $qry->result_array(); + // $data = array( + // array("id" => "1", "name" => "Periode Januari", "periode" => '01-01-2024 - 31-01-2024'), + // array("id" => "2", "name" => "Periode Februari", "periode" => '01-02-2024 - 31-02-2024'), + // array("id" => "3", "name" => "Periode Maret", "periode" => '01-03-2024 - 31-03-2024'), + // ); + $this->sys_ok($rst); + } + function cek() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $sql = "SELECT COUNT(*) as total FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $rst = $qry->result_array()[0]['total']; + $this->sys_ok($rst); + } + function save() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $periode = $prm['periode']; + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT COUNT(*) as total FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $total = $qry->result_array()[0]['total']; + if (intval($total) > 0) { + $sql = "DELETE FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + $this->db->trans_rollback(); + exit; + } + } + + for ($i = 0; $i < count($data); $i++) { + $cekData = $data[$i]; + if (!array_key_exists('Number', $cekData)) { + $this->sys_error("Kolom Number tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Keterangan', $cekData)) { + $this->sys_error("Kolom Keterangan tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Debit', $cekData)) { + $this->sys_error("Kolom Debit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Kredit', $cekData)) { + $this->sys_error("Kolom Kredit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (floatval($cekData['Debit']) > 0 && floatval($cekData['Kredit']) > 0) { + $this->sys_error("Jumlah debit dan credit keduanya lebih besar dari 0"); + $this->db->trans_rollback(); + exit; + } + $sql = "SELECT coaID FROM coa + WHERE coaAccountNo = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$cekData['Number']]); + if (!$qry) { + $this->sys_error_db("cek coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->result_array(); + if (count($cek) == 0) { + $this->sys_error_db("{$cekData['Number']} tidak ada di coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $data[$i]['coaID'] = $cek[0]['coaID']; + } + + for ($i = 0; $i < count($data); $i++) { + $dataCoa = $data[$i]; + $debit = $dataCoa['Debit']; + $credit = $dataCoa['Kredit']; + $type = 'DB'; + if (floatval($dataCoa['Kredit']) > 0) { + $type = 'CR'; + } + + $sql = "INSERT INTO t_beginningbalance( + T_BeginningBalancePeriodeID, + T_BeginningBalanceCoaID, + T_BeginningBalanceCoaAccountNo, + T_BeginningBalanceDescription, + T_BeginningBalanceType, + T_BeginningBalanceStatus, + T_BeginningBalanceDebit, + T_BeginningBalanceCredit, + T_BeginningBalanceCreatedUserID, + T_BeginningBalanceCreated) + VALUES(?,?,?,?,?,?,?,?,?, NOW())"; + $qry = $this->db->query($sql, [ + $periode['id'], + $dataCoa['coaID'], + $dataCoa['Number'], + $dataCoa['Keterangan'], + $type, + 'N', + $debit, + $credit, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error insert beginning balance", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->sys_ok("OK"); + $this->db->trans_commit(); + } + function addData() + { + // $this->sys_error_db("error msg"); + // $this->sys_error("error msg"); + // exit; + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $periode = $prm['periode']; + $userid = $this->sys_user["M_UserID"]; + + + for ($i = 0; $i < count($data); $i++) { + $cekData = $data[$i]; + if (!array_key_exists('Number', $cekData)) { + $this->sys_error("Kolom Number tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Keterangan', $cekData)) { + $this->sys_error("Kolom Keterangan tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Debit', $cekData)) { + $this->sys_error("Kolom Debit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Kredit', $cekData)) { + $this->sys_error("Kolom Kredit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (floatval($cekData['Debit']) > 0 && floatval($cekData['Kredit']) > 0) { + $this->sys_error("Jumlah debit dan credit keduanya lebih besar dari 0"); + $this->db->trans_rollback(); + exit; + } + $sql = "SELECT coaID FROM coa + WHERE coaAccountNo = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$cekData['Number']]); + if (!$qry) { + $this->sys_error_db("cek coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->result_array(); + if (count($cek) == 0) { + $this->sys_error_db("{$cekData['Number']} tidak ada di coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $data[$i]['coaID'] = $cek[0]['coaID']; + } + + for ($i = 0; $i < count($data); $i++) { + $dataCoa = $data[$i]; + $debit = $dataCoa['Debit']; + $credit = $dataCoa['Kredit']; + $type = 'DB'; + if (floatval($dataCoa['Kredit']) > 0) { + $type = 'CR'; + } + + $sql = "INSERT INTO t_beginningbalance( + T_BeginningBalancePeriodeID, + T_BeginningBalanceCoaID, + T_BeginningBalanceCoaAccountNo, + T_BeginningBalanceDescription, + T_BeginningBalanceType, + T_BeginningBalanceStatus, + T_BeginningBalanceDebit, + T_BeginningBalanceCredit, + T_BeginningBalanceCreatedUserID, + T_BeginningBalanceCreated) + VALUES(?,?,?,?,?,?,?,?,?, NOW())"; + $qry = $this->db->query($sql, [ + $periode['id'], + $dataCoa['coaID'], + $dataCoa['Number'], + $dataCoa['Keterangan'], + $type, + 'N', + $debit, + $credit, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error insert beginning balance", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->sys_ok("OK"); + $this->db->trans_commit(); + } + + function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $dt_user = $this->sys_user; + $branch = $dt_user['M_BranchID']; + $branch_code = ''; + if(intval($branch) > 0){ + + $sql = "SELECT * FROM m_branch WHERE branchID = ?"; + $qry = $this->db->query($sql, [$branch]); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $branch = $qry->result_array()[0]; + $branch_code = $branch['M_BranchCode']; + } + + $pt_loginID = $dt_user['M_BranchCompanyID']; + $regionalID = $dt_user['S_RegionalID']; + + $sql = "SELECT + T_BeginningBalanceID as id, + T_BeginningBalanceCoaID as coaID, + T_BeginningBalancePeriodeID as periodeID, + T_BeginningBalanceCoaAccountNo as number, + T_BeginningBalanceDescription as keterangan, + T_BeginningBalanceType as type, + T_BeginningBalanceStatus as status, + CASE + WHEN T_BeginningBalanceType = 'DB' THEN T_BeginningBalanceDebit + WHEN T_BeginningBalanceType = 'CR' THEN T_BeginningBalanceCredit + END as value + FROM t_beginningbalance + WHERE + T_BeginningBalanceM_BranchCompanyID = ? + AND T_BeginningBalanceS_RegionalID = ? + AND T_BeginningBalanceM_BranchCode = ?"; + $qry = $this->db->query($sql, [$pt_loginID, $regionalID, $branch_code]); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $data = $qry->result_array(); + $totalDebit = 0; + $totalCredit = 0; + $totalBalance = 0; + $status = 'N'; + + for ($i = 0; $i < count($data); $i++) { + $dataCek = $data[$i]; + if ($dataCek['type'] == 'DB') { + $totalDebit = $totalDebit + floatval($dataCek['value']); + } + if ($dataCek['type'] == 'CR') { + $totalCredit = $totalCredit + floatval($dataCek['value']); + } + } + $totalBalance = $totalDebit - $totalCredit; + $periode = array(); + if (count($data) > 0) { + if ($data[0]['status'] == 'P') { + $status = 'P'; + } + $sql = "SELECT + periodeID AS id, + periodeName as name, + CONCAT(DATE_FORMAT(periodeStartDate, '%d-%m-%Y'), ' - ',DATE_FORMAT(periodeEndDate, '%d-%m-%Y')) as periode + FROM periode + WHERE periodeID = ?"; + $qry = $this->db->query($sql, [$data[0]['periodeID']]); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $periode = $qry->result_array()[0]; + } + + $rst = array( + 'data' => $data, + 'periode' => $periode, + 'status' => $status, + 'total' => array( + 'debit' => $totalDebit, + 'credit' => $totalCredit, + 'balance' => $totalBalance + ) + ); + $this->sys_ok($rst); + } + function updateData() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $userid = $this->sys_user["M_UserID"]; + $debit = 0; + $credit = 0; + $type = $data['type']; + if ($type == 'DB') { + $debit = $data['value']; + $credit = 0; + } + if ($type == 'CR') { + $credit = $data['value']; + $debit = 0; + } + + $sql = "UPDATE t_beginningbalance + SET T_BeginningBalanceDebit = ?, + T_BeginningBalanceCredit = ?, + T_BeginningBalanceType = ?, + T_BeginningBalanceLastUpdatedUserID = ? + WHERE T_BeginningBalanceID = ?"; + $qry = $this->db->query($sql, [$debit, $credit, $type, $userid, $data['id']]); + if (!$qry) { + $this->sys_error_db("update coa", $this->db); + exit; + } + $retval = array( + "debit" => $debit, + "type" => $type, + "credit" => $credit, + "last_qry" => $this->db->last_query() + ); + $this->sys_ok($retval); + } + function postData() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + + $userid = $this->sys_user["M_UserID"]; + + + $sql = "UPDATE t_beginningbalance + SET T_BeginningBalanceStatus = 'P', + T_BeginningBalanceLastUpdatedUserID = ? + "; + $qry = $this->db->query($sql, [$userid]); + if (!$qry) { + $this->sys_error_db("update coa", $this->db); + exit; + } + + $this->sys_ok('OK'); + } + function delete() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "DELETE FROM t_beginningbalance WHERE T_BeginningBalanceID = ?"; + $qry = $this->db->query($sql, [$prm['id']]); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok('OK'); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + T_BeginningBalanceID , + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, '-' ,coaDescription) as display + FROM coa + LEFT JOIN t_beginningbalance + ON coaID = T_BeginningBalanceCoaID + WHERE + coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND T_BeginningBalanceID IS NULL + AND (coaAccountNo LIKE ? OR coaDescription LIKE ?) + "; + $qry = $this->db->query($sql, [$search, $search]); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Branchacc.php b/application/controllers/mockup/masterdata/accounting/Branchacc.php new file mode 100644 index 0000000..187cc22 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Branchacc.php @@ -0,0 +1,71 @@ +db->query($sql); + if (!$query) { + $this->sys_error_db("Tidak menemukan data branch", $this->db); + exit; + } + $rows = $query->result_array(); + $result = array( + "records" => $rows, + ); + $this->sys_ok($result); + } + + public function validateDateRange($startDate, $endDate) + { + // Validasi input kosong + if (!$startDate || !$endDate) { + $this->sys_error("Parameter startdate dan enddate wajib diisi."); + exit; + } + + // Konversi ke timestamp + $startTimestamp = strtotime($startDate); + $endTimestamp = strtotime($endDate); + $today = date('Y-m-d'); + $hMinus2Timestamp = strtotime('-2 days'); // H-2 dari hari ini + + // Validasi startdate harus sebelum atau sama dengan H-2 + if ($startTimestamp > $hMinus2Timestamp) { + $this->sys_error("startdate harus sebelum atau sama dengan H-2 dari hari ini (" . date('Y-m-d', $hMinus2Timestamp) . ")"); + exit; + } + + // Validasi jika enddate sebelum startdate + if ($endTimestamp < $startTimestamp) { + $this->sys_error("enddate tidak boleh lebih awal dari startdate."); + exit; + } + + // Jika validasi lolos + $result = array( + "startdate" => $startDate, + "enddate" => $endDate + ); + $this->sys_ok($result); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Departement.php b/application/controllers/mockup/masterdata/accounting/Departement.php new file mode 100644 index 0000000..239f826 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Departement.php @@ -0,0 +1,301 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_count = "SELECT count(*) as total + FROM m_department + WHERE M_DepartmentIsActive = 'Y' + AND (M_DepartmentCode LIKE ? OR M_DepartmentName LIKE ?)"; + $qry_count = $this->db->query($sql_count, [$search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("department count error", $this->db); + exit; + } + + $sql = "SELECT M_DepartmentID, + M_DepartmentCode, + M_DepartmentName, + M_DepartmentCreated, + M_DepartmentLastUpdated, + '' as rownumber + FROM m_department + WHERE M_DepartmentIsActive = 'Y' + AND (M_DepartmentCode LIKE ? OR M_DepartmentName LIKE ?) + ORDER BY M_DepartmentID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("department list error", $this->db); + exit; + } + + foreach ($rows as $key => $value) { + $rows[$key]['rownumber'] = $key + 1; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['nameDepartment']) || trim($prm['nameDepartment']) == "") { + $this->sys_error("Department name is required"); + exit; + } + if (!isset($prm['codeDepartment']) || trim($prm['codeDepartment']) == "") { + $this->sys_error("Code name is required"); + exit; + } + + $nameDepartment = trim($prm['nameDepartment']); + $codeDepartment = trim($prm['codeDepartment']); + + // Check for existing department with same name + $sql_check = "SELECT COUNT(*) as total FROM m_department + WHERE M_DepartmentName = ? AND M_DepartmentIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$nameDepartment]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama department sudah ada"); + exit; + } + + $sql = "INSERT INTO m_department( + M_DepartmentCode, + M_DepartmentName, + M_DepartmentIsActive, + M_DepartmentUserID, + M_DepartmentCreated + ) VALUES(?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $codeDepartment, + $nameDepartment, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("department insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM m_department WHERE M_DepartmentCode = '{$codeDepartment}' AND M_DepartmentIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function update() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['departmentId']) || !is_numeric($prm['departmentId'])) { + $this->sys_error("Department ID is required"); + exit; + } + if (!isset($prm['nameDepartment']) || trim($prm['nameDepartment']) == "") { + $this->sys_error("Department name is required"); + exit; + } + if (!isset($prm['codeDepartment']) || trim($prm['codeDepartment']) == "") { + $this->sys_error("Code name is required"); + exit; + } + + $departmentId = $prm['departmentId']; + $nameDepartment = trim($prm['nameDepartment']); + $codeDepartment = trim($prm['codeDepartment']); + + // Check if department exists + $sql_exist = "SELECT COUNT(*) as total FROM m_department + WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'"; + $qry_exist = $this->db->query($sql_exist, [$departmentId]); + if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) { + $this->sys_error("Department not found"); + exit; + } + + // Check for existing department with same name (excluding current department) + $sql_check = "SELECT COUNT(*) as total FROM m_department + WHERE M_DepartmentName = ? AND M_DepartmentID != ? + AND M_DepartmentIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$nameDepartment, $departmentId]); + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama department sudah ada"); + exit; + } + + // Update department + $sql = "UPDATE m_department SET + M_DepartmentCode = ?, + M_DepartmentName = ?, + M_DepartmentUserID = ?, + M_DepartmentLastUpdated = NOW() + WHERE M_DepartmentID = ?"; + $qry = $this->db->query($sql, [ + $codeDepartment, + $nameDepartment, + $userId, + $departmentId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("department update error", $this->db); + exit; + } + + $this->db->trans_commit(); + + // Get updated record + $sql_get = "SELECT * FROM m_department WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'"; + $records = $this->db->query($sql_get, [$departmentId])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['departmentId']) || !is_numeric($prm['departmentId'])) { + $this->sys_error("Department ID is required"); + exit; + } + + $departmentId = $prm['departmentId']; + + // Check if department exists and is active + $sql_exist = "SELECT COUNT(*) as total FROM m_department + WHERE M_DepartmentID = ? AND M_DepartmentIsActive = 'Y'"; + $qry_exist = $this->db->query($sql_exist, [$departmentId]); + if ($qry_exist && $qry_exist->result_array()[0]['total'] == 0) { + $this->sys_error("Department not found"); + exit; + } + + // Soft delete by updating IsActive to 'N' + $sql = "UPDATE m_department SET + M_DepartmentIsActive = 'N', + M_DepartmentUserID = ?, + M_DepartmentLastUpdated = NOW() + WHERE M_DepartmentID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $departmentId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("department delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $this->sys_ok(array( + "message" => "Department deleted successfully", + "departmentId" => $departmentId + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Divisi.php b/application/controllers/mockup/masterdata/accounting/Divisi.php new file mode 100644 index 0000000..0a91a5a --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Divisi.php @@ -0,0 +1,314 @@ +"; + } + + function search() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $sql_data = ""; + $sql_filter = ""; + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $all = $prm['all']; + $limit = ''; + if ($all == 'N') { + $limit = ' LIMIT 10'; + } + + // sort + $sortBy = $prm['sortBy']; + $sortStatus = $prm['sortStatus']; + if ($sortBy) { + $q_sort = "ORDER BY " . $sortBy . " " . $sortStatus; + } + + $number_offset = 0; + $number_limit = 10; + // $number_limit = 1; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + // $number_offset = ($prm['current_page'] - 1) * $number_limit; + + // $sql_filter .= "select count(distinct ItemUnitID, ItemUnitCode, + // ItemUnitName) + // as total + // from itemunit + // where ItemUnitIsActive = 'Y' + // AND ( + // ItemUnitCode like ? + // OR ItemUnitName like ? + // )"; + + + $sql_filter .= " + select count(*) as total from division where DivisionIsActive = 'Y' AND ( DivisionName like ? OR DivisionCode like ?)"; + + $qry_filter = $this->db->query($sql_filter, [$search, $search]); + // echo $this->db->last_query(); + + $tot_count = 0; + $tot_page = 0; + if ($qry_filter) { + // $tot_count = $qry_filter->result_array()[0]["total"]; + $tot_count = $qry_filter->row()->total; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("itemunit count", $this->db); + exit; + } + + $sql_data .= "select + distinct + DivisionCode as code, + DivisionName as name, + DivisionID as id, + DivisionKodeSurat + from division + where DivisionIsActive = 'Y' + AND ( + DivisionCode like ? + OR DivisionName like ? + ) + $q_sort + limit ? offset ?"; + + $qry_data = $this->db->query($sql_data, [ + $search, + $search, + $number_limit, + $number_offset + ]); + + // var_dump($this->db->last_query()); + + if ($qry_data) { + $rows = $qry_data->result_array(); + } else { + $this->sys_error_db("division select"); + exit; + } + + $result = array( + "total" => $tot_page, + "total_filter" => count($rows), + "records" => $rows, + "qry" => $sql_data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function add() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + + $userid = $this->sys_user['M_UserID']; + // $userid = 3; + + $divisi_name = $prm['name']; + $lettercode = $prm['lettercode']; + + if($divisi_name != ""){ + $sql = "SELECT COUNT(*) as exist + FROM division + WHERE DivisionIsActive = 'Y' + AND (DivisionName = ? OR DivisionKodeSurat = ?)"; + $query_count = $this->db->query($sql,[$divisi_name, $lettercode]); + $get_count = $query_count->row_array(); + if($get_count['exist'] != 0){ + $this->db->trans_rollback(); + $this->sys_error_db("division name already exist"); + exit; + } + $sql = "INSERT INTO division ( + DivisionCode, + DivisionName, + DivisionKodeSurat, + DivisionIsActive, + DivisionCreated, + DivisionCreatedUserID + ) VALUES (fn_numbering('DV'), ?, ?, 'Y', NOW(), ?)"; + $query_insert = $this->db->query($sql,[$divisi_name, $lettercode, $userid]); + if(!$query_insert){ + $this->db->trans_rollback(); + $this->sys_error_db("division insert"); + exit; + } + $this->db->trans_commit(); + $divisi_id = $this->db->insert_id(); + $sql = "SELECT + DivisionID as id, + DivisionCode as code, + DivisionName as name , + DivisionKodeSurat + FROM division + WHERE DivisionIsActive = 'Y' AND DivisionID = ?"; + $query_select = $this->db->query($sql,[$divisi_id]); + $result = array( + "total" => 1, + "records" => $query_select->row_array() + ); + $this->sys_ok($result); + }else{ + $this->db->trans_rollback(); + $this->sys_error_db("division name is required"); + exit; + } + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edit() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + + $userid = $this->sys_user['M_UserID']; + // $userid = 1; + $id = $prm['id']; + $divisi_name = $prm['name']; + $lettercode = $prm['lettercode']; + + if($divisi_name != "" && $id != "" && $id != 0){ + $sql = "SELECT COUNT(*) as exist + FROM division + WHERE DivisionIsActive = 'Y' + AND (DivisionName = ? OR DivisionKodeSurat = ?) + AND DivisionID != ?"; + $query_count = $this->db->query($sql,[$divisi_name, $lettercode, $id]); + $get_count = $query_count->row_array(); + if($get_count['exist'] != 0){ + $this->db->trans_rollback(); + $this->sys_error_db("division name already exist"); + exit; + } + + $sql = "UPDATE division SET + DivisionName = ?, + DivisionKodeSurat = ?, + DivisionLastUpdated = now(), + DivisionLastUpdatedUserID = ? + WHERE DivisionID = ?"; + $query_update = $this->db->query($sql,[$divisi_name, $lettercode, $userid, $id]); + if(!$query_update){ + $this->db->trans_rollback(); + $this->sys_error_db("division update"); + exit; + } + $this->db->trans_commit(); + $sql = "SELECT + DivisionID as id, + DivisionCode as code, + DivisionName as name, + DivisionKodeSurat + FROM division + WHERE DivisionIsActive = 'Y' AND DivisionID = ?"; + $query_select = $this->db->query($sql,[$id]); + $result = array( + "total" => 1, + "records" => $query_select->row_array() + ); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + $id = $prm['id']; + $userid = $this->sys_user['M_UserID']; + // $userid = 1; + if($id != "" && $id != 0){ + $sql = "UPDATE division SET DivisionIsActive = 'N', DivisionDeleted = now(), DivisionDeletedUserID = ? WHERE DivisionID = ?"; + $query_update = $this->db->query($sql,[$userid, $id]); + if(!$query_update){ + $this->db->trans_rollback(); + $this->sys_error_db("division delete"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + $this->sys_ok($result); + } + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/GatewayAutoJurnal.php b/application/controllers/mockup/masterdata/accounting/GatewayAutoJurnal.php new file mode 100644 index 0000000..25aaa82 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/GatewayAutoJurnal.php @@ -0,0 +1,177 @@ + 'insertSales', + 'AR' => 'insertAr', + 'ARPAYMENT' => 'insertArPayment', + 'RKTAGIHAN' => 'insertRkTagihan', + 'RKPELUNASAN' => 'insertRkPelunasan' + ]; + + public function __construct() { + parent::__construct(); + $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; + $this->host = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/one-api/mockup/masterdata/accounting/Mediajurnalauto'; + } + + public function index() + { + echo "GATEWAY INJECT AUTO COUNT MEDIA JURNAL CABANG PER TANGGAL"; + } + + /** + * API endpoint to inject data based on POST parameters + */ + public function inject($branchCode, $startDate, $endDate, $autoJurnalType) { + // Validate required fields + $requiredFields = ['branchCode' => $branchCode, 'startDate' => $startDate, 'endDate' => $endDate, 'autoJurnalType' => $autoJurnalType]; + foreach ($requiredFields as $field => $value) { + if (empty($value)) { + $this->sys_error("Missing required parameter: {$field}"); + return; + } + } + + // Process the request + $result = $this->injectData( + $startDate, + $endDate, + $branchCode, + $autoJurnalType + ); + + // Send response + $this->sys_ok($result); + } + + public function injectData($startDate, $endDate, $branchCode, $endpointType = 'ALL', $verbose = false) { + // Validate inputs + if (!$this->validateDate($startDate) || !$this->validateDate($endDate)) { + $this->sys_error("Invalid date format. Use Y-m-d format."); + exit; + } + + if (empty($branchCode)) { + $this->sys_error("Branch code is required."); + exit; + } + + if (strtotime($startDate) > strtotime($endDate)) { + $this->sys_error("Start date cannot be greater than end date."); + exit; + } + + // Define endpoints to use based on type + $selectedEndpoints = []; + + // Process single or multiple endpoint types + $typesToProcess = is_array($endpointType) ? $endpointType : [$endpointType]; + + foreach ($typesToProcess as $type) { + $type = strtoupper($type); + + // If 'ALL' is specified, use all endpoints + if ($type === 'ALL') { + foreach ($this->endpointTypes as $key => $endpoint) { + $selectedEndpoints[$endpoint] = "{$this->host}/{$endpoint}/{$branchCode}/%s"; + } + break; + } + + // Check if the specified type exists + if (isset($this->endpointTypes[$type])) { + $endpointName = $this->endpointTypes[$type]; + $selectedEndpoints[$endpointName] = "{$this->host}/{$endpointName}/{$branchCode}/%s"; + } + } + + // If no valid endpoint types were provided + if (empty($selectedEndpoints)) { + $this->sys_error("Invalid endpoint type specified. Valid types are: " . implode(', ', array_keys($this->endpointTypes)) . ", or ALL"); + exit; + } + + // Convert dates to DateTime objects for iteration + $currentDate = new DateTime($startDate); + $end = new DateTime($endDate); + + $results = []; + + // Loop through each day in the range + while ($currentDate <= $end) { + $dateStr = $currentDate->format('Y-m-d'); + + // Call each selected endpoint for the current date + foreach ($selectedEndpoints as $endpointName => $endpointUrl) { + $url = sprintf($endpointUrl, $dateStr); + $response = $this->curlGet($url); + + $results[$dateStr][$endpointName] = $response; + + // Optional: Add delay to prevent overwhelming the API + usleep(100000); // 0.1 second delay + } + + // Move to next day + $currentDate->modify('+1 day'); + } + + return [ + 'status' => 'success', + 'data' => $results, + 'summary' => [ + 'startDate' => $startDate, + 'endDate' => $endDate, + 'branchCode' => $branchCode, + 'endpointTypes' => $typesToProcess, + 'totalDays' => count($results) + ] + ]; + } + + private function curlGet($url) { + $ch = curl_init($url); + + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_SSL_VERIFYHOST => false, + CURLOPT_TIMEOUT => 30, + CURLOPT_CONNECTTIMEOUT => 30 + ]); + + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error = curl_error($ch); + + curl_close($ch); + + if ($error) { + return [ + 'success' => false, + 'code' => 0, + 'message' => $error + ]; + } + + return [ + 'success' => ($httpCode >= 200 && $httpCode < 300), + 'code' => $httpCode, + 'response' => $response + ]; + } + + /** + * Validate date format + * + * @param string $date Date to validate + * @return bool Whether the date is valid + */ + private function validateDate($date) { + $d = DateTime::createFromFormat('Y-m-d', $date); + return $d && $d->format('Y-m-d') === $date; + } +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Itemregional.php b/application/controllers/mockup/masterdata/accounting/Itemregional.php new file mode 100644 index 0000000..6111f18 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Itemregional.php @@ -0,0 +1,524 @@ +db_onedev = $this->load->database("onedev", true); + } + + // search + function search() +{ + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? trim($prm["search"]) : ''; + $search = ($search !== '') ? "%$search%" : "%%"; + + $number_limit = 10; + $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0; + + $sql = "SELECT + M_ItemID, + M_ItemCode, + M_ItemDesc, + M_ItemItem_CategoryID, + M_ItemInventoryCode, + M_ItemNat_GroupID, + M_ItemNat_SubGroupID, + M_ItemFa_ClassID, + + -- Data item regional + M_ItemRegionalID, + M_ItemRegionalS_RegionalID, + M_ItemRegionalMinQty, + M_ItemRegionalItemUnitID, + + -- Data Satuan + ItemUnitID, + ItemUnitCode, + ItemUnitName, + + -- Regional + S_RegionalID, + S_RegionalName + + +FROM m_itemregional +JOIN m_item ON M_ItemID = M_ItemRegionalM_ItemID +JOIN s_regional ON S_RegionalID = M_ItemRegionalS_RegionalID +JOIN itemunit ON ItemUnitID = M_ItemRegionalItemUnitID + + +WHERE M_ItemRegionalIsActive = 'Y' + AND ( + M_ItemDesc LIKE CONCAT('%', '$search', '%') + OR S_RegionalName LIKE CONCAT('%', '$search', '%') + ) +ORDER BY M_ItemRegionalID DESC"; + + $sql_total = "SELECT count(*) as total FROM ($sql) as x"; + $qry_total = $this->db_onedev->query($sql_total); + + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("select m_itemregional count error", $this->db_onedev);; + exit; + } + + $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset"; + + $qry = $this->db_onedev->query($sql_select); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db_onedev->trans_rollback(); + $this->sys_error_db("select m_itemregional error", $this->db_onedev); + exit; + } + + $response = [ + "total" => $totalPage, + "totalFilter" => $totalCount, + "records" => $rows, + "sql" => $this->db_onedev->last_query() + ]; + + $this->sys_ok($response); + } catch (Exception $exc) { + $this->sys_error($exc->getMessage()); + } +} + + + + function getItem() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $search = $prm['search']; + // $where_search = "%%"; + $where_search_desc = '%'.$search.'%'; + $where_search_acc = "$search%"; + + $sql = "SELECT + M_ItemID, + M_ItemCode, + M_ItemDesc, + M_ItemItem_CategoryID, + M_ItemInventoryCode, + M_ItemNat_GroupID, + M_ItemNat_SubGroupID, + M_ItemM_InventarisGolID, + M_ItemPurchaseUOM, + M_ItemBaseUOM, + M_ItemItem_UnitID + FROM m_item + WHERE M_ItemIsActive = 'Y' + AND + ( + M_ItemDesc LIKE '$where_search_desc' + OR M_ItemCode LIKE '$where_search_acc' + )"; + + // echo $sql; + // die(); + $qry = $this->db_onedev->query($sql, array()); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get coa pendapatan"); + exit; + } + $result = $qry->result_array(); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $search = $prm['search']; + // $where_search = "%%"; + $where_search_desc = '%'.$search.'%'; + $where_search_acc = "$search%"; + + $sql = "SELECT + S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND + S_RegionalName LIKE '$where_search_acc'"; + + // echo $sql; + // die(); + $qry = $this->db_onedev->query($sql, array()); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get coa pendapatan"); + exit; + } + $result = $qry->result_array(); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUnit() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $search = $prm['search']; + // $where_search = "%%"; + $where_search_desc = '%'.$search.'%'; + $where_search_acc = "$search%"; + + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND + ( + ItemUnitName LIKE '$where_search_desc' + OR ItemUnitCode LIKE '$where_search_acc' + )"; + + // echo $sql; + // die(); + $qry = $this->db_onedev->query($sql, array()); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get unit"); + exit; + } + $result = $qry->result_array(); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // addData + function addData() +{ + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + + + // Extract input parameters + $M_ItemRegionalS_RegionalID = isset($prm['M_ItemRegionalS_RegionalID']) ? $prm['M_ItemRegionalS_RegionalID'] : 0; + $M_ItemRegionalM_ItemID = isset($prm['M_ItemRegionalM_ItemID']) ? $prm['M_ItemRegionalM_ItemID'] : 0; + $M_ItemRegionalQty = isset($prm['M_ItemRegionalQty']) ? $prm['M_ItemRegionalQty'] : 0; + $M_ItemRegionalItemUnitID = isset($prm['M_ItemRegionalItemUnitID']) ? $prm['M_ItemRegionalItemUnitID'] : 0; + + // Construct SQL query + $sql = "INSERT INTO m_itemregional ( + M_ItemRegionalM_ItemID, + M_ItemRegionalS_RegionalID, + M_ItemRegionalMinQty, + M_ItemRegionalItemUnitID, + M_ItemRegionalUserID, + M_ItemRegionalCreated, + M_ItemRegionalLastUpdated + ) VALUES ( + '$M_ItemRegionalM_ItemID', + '$M_ItemRegionalS_RegionalID', + '$M_ItemRegionalQty', + '$M_ItemRegionalItemUnitID', + '$userid', + NOW(), + NOW() + )"; + + // Execute query + $qry = $this->db_onedev->query($sql); + if (!$qry) { + $this->db_onedev->trans_rollback(); + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $this->db_onedev->last_query() + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $this->db_onedev->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } +} + + + // get_by_id + function get_by_id() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + // m_itemregional + $M_ItemRegionalID = isset($prm['M_ItemRegionalID']) ? $prm['M_ItemRegionalID'] : 0; + + $sql_m = "SELECT * FROM m_itemregional where M_ItemRegionalID = '$M_ItemRegionalID'"; + + $qry_m = $this->db_onedev->query($sql_m); + if (!$qry_m) { + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $this->db_onedev->last_query() + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $rows_m = $qry_m->result_array(); + + // coa start + $M_ItemRegionalCoaID = isset($prm['M_ItemRegionalCoaID']) ? $prm['M_ItemRegionalCoaID'] : 0; + $sql_u = "SELECT * FROM coa where coaID = '$M_ItemRegionalCoaID' + AND coaIsInput = 'Y' + AND coaIsActive = 'Y' + "; + + $qry_u = $this->db_onedev->query($sql_u); + if (!$qry_u) { + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $this->db_onedev->last_query() + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $rows_u = $qry_u->result_array(); + + // empty $rows_u + if (empty($rows_u)) { + $rows_u = [[ + "coaID" => 0, + "coaAccountNo" => '', + "coaDescription" => '', + "coaSubDescription" => '', + "coaAccountType" => '', + "coaSpecialAccountType" => '', + "coaIsInput" => 'N', + "coaReportSchedule" => '', + "coaCurrencyCode" => '', + "coaCashFlowCategory" => '', + "coaCreated" => '', + "coaLastUpdated" => '', + "coaIsActive" => 'Y', + "coaLevel" => 1 + ]]; + } + + // coa end + + // accum depre start + $M_ItemRegionalAccumDepreCoaID = $prm['M_ItemRegionalAccumDepreCoaID']; + $sql_h = "SELECT * FROM coa where coaID = '$M_ItemRegionalAccumDepreCoaID' + AND coaIsInput = 'Y' + AND coaIsActive = 'Y'"; + + $qry_h = $this->db_onedev->query($sql_h); + if (!$qry_h) { + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $this->db_onedev->last_query() + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $rows_h = $qry_h->result_array(); + // empty $rows_h + if (empty($rows_h)) { + $rows_h = [[ + "coaID" => 0, + "coaAccountNo" => '', + "coaDescription" => '', + "coaSubDescription" => '', + "coaAccountType" => '', + "coaSpecialAccountType" => '', + "coaIsInput" => 'N', + "coaReportSchedule" => '', + "coaCurrencyCode" => '', + "coaCashFlowCategory" => '', + "coaCreated" => '', + "coaLastUpdated" => '', + "coaIsActive" => 'Y', + "coaLevel" => 1 + ]]; + } + // accum depre end + + + + $response = [ + "record_m_itemregional" => $rows_m, + "records_coa" => $rows_u, + "records_accum_depre" => $rows_h, + "sql" => $this->db_onedev->last_query() + ]; + + $this->sys_ok($response); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // editData + function editData() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $M_ItemRegionalID = $prm['M_ItemRegionalID']; + $M_ItemRegionalS_RegionalID = isset($prm['M_ItemRegionalS_RegionalID']) ? $prm['M_ItemRegionalS_RegionalID'] : 0; + $M_ItemRegionalM_ItemID = isset($prm['M_ItemRegionalM_ItemID']) ? $prm['M_ItemRegionalM_ItemID'] : 0; + $M_ItemRegionalQty = isset($prm['M_ItemRegionalQty']) ? $prm['M_ItemRegionalQty'] : 0; + $M_ItemRegionalItemUnitID = isset($prm['M_ItemRegionalItemUnitID']) ? $prm['M_ItemRegionalItemUnitID'] : 0; + + $sql = "UPDATE m_itemregional SET + M_ItemRegionalS_RegionalID = '{$M_ItemRegionalS_RegionalID}', + M_ItemRegionalM_ItemID = '{$M_ItemRegionalM_ItemID}', + M_ItemRegionalMinQty = '{$M_ItemRegionalQty}', + M_ItemRegionalItemUnitID = '{$M_ItemRegionalItemUnitID}', + M_ItemRegionalUserID = '{$userid}', + M_ItemRegionalLastUpdated = now() + WHERE M_ItemRegionalID = '$M_ItemRegionalID' + "; + + + // echo $sql; + + $qry = $this->db_onedev->query($sql); + if (!$qry) { + $this->db_onedev->trans_rollback(); + $error = array( + "message" => $this->db_onedev->error()["message"], + // "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $this->db_onedev->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // deleteData + function deleteData() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $M_ItemRegionalID = $prm['M_ItemRegionalID']; + + + $sql = "UPDATE m_itemregional + SET + M_ItemRegionalIsActive = 'N', + M_ItemRegionalLastUpdated = now(), + M_ItemRegionalUserID = '$userid' + WHERE M_ItemRegionalID = '$M_ItemRegionalID'"; + + $qry = $this->db_onedev->query($sql); + if (!$qry) { + $this->db_onedev->trans_rollback(); + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db_onedev); + exit; + } + + $this->db_onedev->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} +?> \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Itemunit.php b/application/controllers/mockup/masterdata/accounting/Itemunit.php new file mode 100644 index 0000000..e448c95 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Itemunit.php @@ -0,0 +1,702 @@ +"; + } + + function search() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $sql_data = ""; + $sql_filter = ""; + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $all = $prm['all']; + $limit = ''; + if ($all == 'N') { + $limit = ' LIMIT 10'; + } + + // sort + $sortBy = $prm['sortBy']; + $sortStatus = $prm['sortStatus']; + if ($sortBy) { + $q_sort = "ORDER BY " . $sortBy . " " . $sortStatus; + } + + $number_offset = 0; + $number_limit = 10; + // $number_limit = 1; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + // $number_offset = ($prm['current_page'] - 1) * $number_limit; + + // $sql_filter .= "select count(distinct ItemUnitID, ItemUnitCode, + // ItemUnitName) + // as total + // from itemunit + // where ItemUnitIsActive = 'Y' + // AND ( + // ItemUnitCode like ? + // OR ItemUnitName like ? + // )"; + + + $sql_filter .= " + select count(*) as total from ( + select distinct ItemUnitID, ItemUnitCode, + ItemUnitName + from itemunit + where ItemUnitIsActive = 'Y' + AND ( + ItemUnitCode like ? + OR ItemUnitName like ?) + ) x"; + + $qry_filter = $this->db->query($sql_filter, [$search, $search]); + // echo $this->db->last_query(); + + $tot_count = 0; + $tot_page = 0; + if ($qry_filter) { + // $tot_count = $qry_filter->result_array()[0]["total"]; + $tot_count = $qry_filter->row()->total; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("itemunit count", $this->db); + exit; + } + + $sql_data .= "select + distinct ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCode as code, + ItemUnitName as name, + ItemUnitID as id + from itemunit + where ItemUnitIsActive = 'Y' + AND ( + ItemUnitCode like ? + OR ItemUnitName like ? + ) + $q_sort + limit ? offset ?"; + + $qry_data = $this->db->query($sql_data, [ + $search, + $search, + $number_limit, + $number_offset + ]); + + // var_dump($this->db->last_query()); + + if ($qry_data) { + $rows = $qry_data->result_array(); + } else { + $this->sys_error_db("itemunit select"); + exit; + } + + $result = array( + "total" => $tot_page, + "total_filter" => count($rows), + "records" => $rows, + "qry" => $sql_data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function add() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + + $userid = $this->sys_user['M_UserID']; + // $userid = 3; + + $unit_name_search = ""; + $unit_name = ""; + if (isset($prm['unit_name'])) { + $unit_name_search = trim($prm["unit_name"]); + $unit_name = trim($prm['unit_name']); + if ($unit_name_search != "") { + $unit_name_search = $prm['unit_name']; + } + } + + $sql_count = "SELECT COUNT(*) as exist + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName = ?"; + $query_count = $this->db->query($sql_count, [ + $unit_name_search + ]); + + $last_query_count = $this->db->last_query(); + + if (!$query_count) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit search & count by name"); + exit; + } else { + // substring date + // $date = date('Y'); + // $substring_date = substr($date,-2); + + // var_dump($substring_date); + + $unit_code_generate = "UI"; + + $get_count = $query_count->row_array(); + if ($get_count['exist'] == 0) { + // call fungsi untuk generate code + $sql_generate_code = "select fn_numbering(?) as code"; + $query_generate_code = $this->db->query( + $sql_generate_code, + [ + $unit_code_generate + ] + ); + + if (!$query_generate_code) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit call sp"); + exit; + } + + $get_unit_code = $query_generate_code->row_array(); + $unit_code = $get_unit_code['code']; + + // query insert + $sql_insert = "INSERT INTO itemunit + ( + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitUserID + ) + VALUES (?, ?, now(), now(), ?)"; + + $query_insert = $this->db->query($sql_insert, [ + $unit_code, + $unit_name, + $userid + ]); + + if (!$query_insert) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit insert"); + exit; + } + + // var_dump($this->db->affected_rows()); + $insert_id = $this->db->insert_id(); + // print_r($insert_id); + + $sql_json_before = "SELECT * + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitID = ?"; + + $qry_json_before = $this->db->query( + $sql_json_before, + [ + $insert_id + ] + ); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit select json"); + exit; + } + + $data_by_id = $qry_json_before->row(); + + $json_after_log = json_encode($data_by_id); + + // print_r($json_after_log); + + $sql_insert_log = "INSERT INTO acc_one_log.itemunit_log( + ItemUnitLogItemUnitID, + ItemUnitLogStatus, + ItemUnitLogJSONBefore, + ItemUnitLogJSONAfter, + ItemUnitLogUserID, + ItemUnitLogCreated + ) VALUES ( + ?, + 'ADD', + null, + ?, + ?, + now() + )"; + + $qry_insert_log = $this->db->query( + $sql_insert_log, + [ + $insert_id, + $json_after_log, + $userid + ] + ); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit insert log"); + exit; + } + + // sukses + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + $this->sys_ok($result); + } else { + $errors = array(); + if ($get_count['exist'] != 0) { + array_push($errors, array( + 'field' => 'name', + 'msg' => 'Nama sudah ada' + )); + } + + $insert_id = $this->db->insert_id(); + // print_r($insert_id); + + $sql_json_before = "SELECT * + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitID = ?"; + + $qry_json_before = $this->db->query( + $sql_json_before, + [ + $insert_id + ] + ); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit select json"); + exit; + } + + $data_by_id = $qry_json_before->row(); + + $json_after_log = json_encode($data_by_id); + + // print_r($json_after_log); + + $sql_insert_log = "INSERT INTO acc_one_log.itemunit_log( + ItemUnitLogItemUnitID, + ItemUnitLogStatus, + ItemUnitLogJSONBefore, + ItemUnitLogJSONAfter, + ItemUnitLogUserID, + ItemUnitLogCreated + ) VALUES ( + ?, + 'DELETE', + null, + ?, + ?, + now() + )"; + + $qry_insert_log = $this->db->query( + $sql_insert_log, + [ + $insert_id, + $json_after_log, + $userid + ] + ); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit insert log"); + exit; + } + + + // sukses + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + $this->sys_ok($result); + } + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edit() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + + $userid = $this->sys_user['M_UserID']; + // $userid = 1; + $id = $prm['id']; + + $unit_name_search = ""; + $unit_name = ""; + if (isset($prm['unit_name'])) { + $unit_name_search = trim($prm["unit_name"]); + $unit_name = trim($prm['unit_name']); + if ($unit_name_search != "") { + $unit_name_search = $prm['unit_name']; + } + } + + $sql_count = "SELECT COUNT(*) as exist + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName = ?"; + $query_count = $this->db->query($sql_count, [ + $unit_name_search + ]); + + $last_query_count = $this->db->last_query(); + + if (!$query_count) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit search & count by name"); + exit; + } else { + // substring date + // $date = date('Y'); + // $substring_date = substr($date,-2); + + // var_dump($substring_date); + + // $unit_code_generate = "UI"; + + $get_count = $query_count->row_array(); + // if($get_count['exist'] == 0) + // { + // call fungsi untuk generate code + // $sql_generate_code = "select fn_numbering(?) as code"; + // $query_generate_code = $this->db->query($sql_generate_code, + // [ + // $unit_code_generate + // ]); + + // if(!$query_generate_code){ + // $this->db->trans_rollback(); + // $this->sys_error_db("itemunit call sp"); + // exit; + // } + + // $get_unit_code = $query_generate_code->row_array(); + // $unit_code = $get_unit_code['code']; + + // json before + $sql_json_before = "SELECT * + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitID = ?"; + + $qry_json_before = $this->db->query( + $sql_json_before, + [ + $id + ] + ); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit select json before"); + exit; + } + + $data_before_by_id = $qry_json_before->row(); + + $json_before_log = json_encode($data_before_by_id); + + // print_r($json_before_log); + + // query update + $sql_update = "UPDATE itemunit + set + ItemUnitName = ?, + ItemUnitLastUpdated = now(), + ItemUnitUserID = ? + WHERE ItemUnitID = ?"; + + $query_update = $this->db->query($sql_update, [ + $unit_name, + $userid, + $id + ]); + + if (!$query_update) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit insert"); + exit; + } + + // print_r($json_before_log); + + // print_r($query_data); + + // json after + $sql_json_after = "SELECT * + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitID = ?"; + + $qry_json_after = $this->db->query( + $sql_json_after, + [ + $id + ] + ); + + if (!$qry_json_after) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit select json after"); + exit; + } + + $data_after_by_id = $qry_json_after->row(); + + $json_after_log = json_encode($data_after_by_id); + + $sql_insert_log = "INSERT INTO acc_one_log.itemunit_log( + ItemUnitLogItemUnitID, + ItemUnitLogStatus, + ItemUnitLogJSONBefore, + ItemUnitLogJSONAfter, + ItemUnitLogUserID, + ItemUnitLogCreated + ) VALUES ( + ?, + 'EDIT', + ?, + ?, + ?, + now() + )"; + + $qry_insert_log = $this->db->query( + $sql_insert_log, + [ + $id, + $json_before_log, + $json_after_log, + $userid + ] + ); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit edit log"); + exit; + } + + // sukses + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + $this->sys_ok($result); + // } + // else + // { + // $errors = array(); + // if($get_count['exist'] != 0){ + // array_push($errors,array( + // 'field'=>'name', + // 'msg'=>'Nama sudah ada' + // )); + // } + + // $result = array ( + // "total" => -1, + // "errors" => $errors, + // "records" => 0); + // $this->sys_ok($result); + // } + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //begin transaction + $this->db->trans_begin(); + + //# ambil parameter input + $prm = $this->sys_input; + $id = $prm['id']; + $userid = $this->sys_user['M_UserID']; + // $userid = 1; + + $sql_delete = "UPDATE itemunit + SET ItemUnitIsActive = 'N', + ItemUnitLastUpdated = now(), + ItemUnitUserID = ? + WHERE ItemUnitID = ?"; + + $query_delete = $this->db->query($sql_delete, [ + $userid, + $id + ]); + + if (!$query_delete) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit delete"); + exit; + } + + // var_dump($this->db->affected_rows()); + // print_r($insert_id); + + $sql_json_before = "SELECT * + FROM itemunit + WHERE ItemUnitIsActive = 'N' + AND ItemUnitID = ?"; + + $qry_json_before = $this->db->query( + $sql_json_before, + [ + $id + ] + ); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit select json"); + exit; + } + + $data_by_id = $qry_json_before->row(); + + $json_after_log = json_encode($data_by_id); + + // print_r($json_after_log); + + $sql_insert_log = "INSERT INTO acc_one_log.itemunit_log( + ItemUnitLogItemUnitID, + ItemUnitLogStatus, + ItemUnitLogJSONBefore, + ItemUnitLogJSONAfter, + ItemUnitLogUserID, + ItemUnitLogCreated + ) VALUES ( + ?, + 'DELETE', + null, + ?, + ?, + now() + )"; + + $qry_insert_log = $this->db->query( + $sql_insert_log, + [ + $id, + $json_after_log, + $userid + ] + ); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunit delete log"); + exit; + } + + // sukses + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + $this->sys_ok($result); + + // sukses + // $this->db->trans_commit(); + // $result = array ("total" => 1, "records" => array("xid" => 0)); + // $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/JournalItemOut.php b/application/controllers/mockup/masterdata/accounting/JournalItemOut.php new file mode 100644 index 0000000..952a672 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/JournalItemOut.php @@ -0,0 +1,366 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $regionalId = $prm['regionalId'] ?? null; + $branchCode = $prm['branchCode'] ?? null; + $periodeid = $prm['periodeid'] ?? null; + $xdate = $prm['xdate'] ?? null; + $search = $prm['search'] ?? ''; + $search = '%' . trim($search) . '%'; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?" + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOITEMOUT' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int)($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit; + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit; + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, array($value["jurnalID"])); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit; + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row['JurnalErr_Msg'] = json_decode($row['JurnalErr_Msg'], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = 'Y'; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = 'N'; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'AUTOITEMOUT') + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, array($value["jurnalID"])); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = array( + 'total' => $totalPage, + 'totalfilter' => $totalCount, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm['regionalId'] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit; + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r['S_RegionalID'] == $regionalId) { + $selected = $r; + break; + } + } + + + $result = array( + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit; + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "" + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r['M_BranchCode'] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = array( + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/JournalItemUsage.php b/application/controllers/mockup/masterdata/accounting/JournalItemUsage.php new file mode 100644 index 0000000..4b174ba --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/JournalItemUsage.php @@ -0,0 +1,761 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOITEMUSAGE' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'AUTOITEMUSAGE') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTOITEMUSAGE' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $para = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = ""; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $para["periodeID"], + $para["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $e) { + $message = $e->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $para = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTOITEMUSAGE' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $para["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $e) { + $message = $e->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/JournalPenyesuaian.php b/application/controllers/mockup/masterdata/accounting/JournalPenyesuaian.php new file mode 100644 index 0000000..bba7885 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/JournalPenyesuaian.php @@ -0,0 +1,597 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT + periodeID, + periodeName, + DATE_FORMAT(periodeStartDate, '%d %M %Y') AS periodeStartDate, + DATE_FORMAT(periodeEndDate, '%d %M %Y') AS periodeEndDate + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC"; + $que = $this->db->query($sql, []); + if (!$que) { + $this->sys_error_db("[Error] get daftar periode"); + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDaftarTipeJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + $sql = "SELECT + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName + FROM jurnal_type + WHERE JurnalTypeIsActive = 'Y'"; + $que = $this->db->query($sql, []); + if (!$que) { + $this->sys_error_db("[Error] get daftar tipe jurnal"); + exit; + } + + $data = $que->result_array(); + $all = [ + 'JurnalTypeID' => 0, + 'JurnalTypeCode' => "X", + 'JurnalTypeName' => "SEMUA" + ]; + array_unshift($data, $all); + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDaftarJournalClosed() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $isFromBranch = " "; + if ($user['M_BranchID'] != "0") { + $isFromBranch .= " AND jurnalM_BranchCode = '{$user['M_BranchCode']}'"; + } + + $keyword = "%"; + if ($param['search'] != '') { + $keyword .= $param['search'] . "%"; + } + + $row_limit = 5; + $curr_page = (int)($param['currpage'] ?? 1); + $row_offset = max(0, ($curr_page - 1) * $row_limit); + + $sql_base = "SELECT + jurnalID, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + S_RegionalName, + M_BranchName, + M_BranchCompanyName + FROM jurnal + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeIsActive = 'Y' + JOIN m_branch_company ON M_BranchCompanyID = jurnalM_BranchCompanyID + JOIN s_regional ON S_RegionalID = JurnalS_RegionalID + LEFT JOIN m_branch ON M_BranchCode = jurnalM_BranchCode + WHERE jurnalperiodeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsClosed = 'Y' + AND (jurnalJurnalTypeID = ? OR 0 = ?) + AND jurnalDate BETWEEN DATE(?) AND DATE(?) + AND jurnalNo LIKE ? + AND jurnalIsPosted = 'Y' + AND jurnalDalamPenyesuaian = 'N' + AND jurnalIsActive = 'Y'" . $isFromBranch; + + $sql_data = $sql_base . " LIMIT ? OFFSET ? "; + $que_data = $this->db->query($sql_data, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], $keyword, + $row_limit, $row_offset + ]); + if (!$que_data) { + $this->sys_error_db("[Error] get listing jurnal closed"); + exit; + } + + // get total jurnal is closed + $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) as x"; + $que_total = $this->db->query($sql_total, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], $keyword, + ]); + if (!$que_total) { + $this->sys_error_db("[Error] get total all jurnal closed"); + exit; + } + + $data = [ + "records" => $que_data->result_array(), + "total" => $que_total->row_array()['total'] + ]; + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDetailJournalClosed() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + + $sql = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaAccountNo, + coaDescription, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID + AND jurnalAddOnIsActive = 'Y' + WHERE jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y' + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, jurnalTxID ASC"; + $que = $this->db->query($sql, [$param['jurnalID']]); + if (!$que) { + $this->sys_error_db("[Error] get detail data jurnal"); + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDaftarAccount() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $keyword = "%"; + if ($param['keyword'] != '') { + $keyword = $param['keyword'] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDaftarJournalBalik() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $isFromBranch = " "; + if ($user['M_BranchID'] != "0") { + $isFromBranch .= " AND jurnalM_BranchCode = '{$user['M_BranchCode']}' "; + } + + $keyword = "%"; + if ($param['search'] != '') { + $keyword .= $param['search'] . "%"; + } + + $row_limit = 5; + $curr_page = (int)($param['currpage'] ?? 1); + $row_offset = max(0, ($curr_page - 1) * $row_limit); + + $sql_base = "SELECT + jurnalID, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + jurnalPenyesuaianStatus, + S_RegionalName, + M_BranchName, + M_BranchCompanyName + FROM jurnal + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeIsActive = 'Y' + JOIN m_branch_company ON M_BranchCompanyID = jurnalM_BranchCompanyID + JOIN s_regional ON S_RegionalID = JurnalS_RegionalID + LEFT JOIN m_branch ON M_BranchCode = jurnalM_BranchCode + WHERE jurnalperiodeID = ? + AND JurnalS_RegionalID = ? + AND (jurnalJurnalTypeID = ? OR 0 = ?) + AND jurnalDate BETWEEN DATE(?) AND DATE(?) + AND jurnalNo LIKE ? + AND jurnalIsPenyesuaian = 'Y' + AND jurnalIsActive = 'Y'" . $isFromBranch; + + $sql_data = $sql_base . " LIMIT ? OFFSET ? "; + $que_data = $this->db->query($sql_data, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], $keyword, + $row_limit, $row_offset + ]); + if (!$que_data) { + $this->sys_error_db("[Error] get listing jurnal closed"); + exit; + } + + // get total jurnal is closed + $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) as x"; + $que_total = $this->db->query($sql_total, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], $keyword, + ]); + if (!$que_total) { + $this->sys_error_db("[Error] get total all jurnal closed"); + exit; + } + + $data = [ + "records" => $que_data->result_array(), + "total" => $que_total->row_array()['total'] + ]; + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDetailJournalBalik() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + + $sql = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaAccountNo, + coaDescription, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID + AND jurnalAddOnIsActive = 'Y' + WHERE jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y' + GROUP BY jurnalTxID + ORDER BY jurnalTxID ASC"; + $que = $this->db->query($sql, [$param['jurnalID']]); + if (!$que) { + $this->sys_error_db("[Error] get detail data jurnal penyesuaian"); + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + # MUTATIONS # + public function saveKoreksiJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # Update old jurnal # + $sql_oldjurnal = "UPDATE jurnal + SET jurnalDalamPenyesuaian = 'Y' + WHERE jurnalID = ?"; + $que_oldjurnal = $this->db->query($sql_oldjurnal, [$param['oldJurnalID']]); + if (!$que_oldjurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status penyesuaian"); + exit; + } + + # Generate jurnal number # + $sql_jurnalno = "SELECT `fn_numbering`('J') AS numbering"; + $que_jurnalno = $this->db->query($sql_jurnalno, []); + if (!$que_jurnalno) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] generate jurnal number"); + exit; + } + $JurnalNo = $que_jurnalno->row_array()['numbering']; + + # GET current periode id # + $sql_periode = "SELECT periodeID FROM periode WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + AND DATE(NOW()) BETWEEN DATE(periodeStartDate) AND DATE(periodeEndDate)"; + $que_periode = $this->db->query($sql_periode, []); + if (!$que_periode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get periode id"); + exit; + } + if (!$que_periode->num_rows() === 0) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] waktu periode tidak ditemukan"); + exit; + } + $JurnalPeriodeID = $que_periode->row_array()['periodeID']; + + # GET jurnal type # + $JurnalTypeCode = $param['jurnalTypeCode']; + if ($JurnalTypeCode != '' && substr($JurnalTypeCode, 0, 4) === 'AUTO') { + $JurnalTypeCode = substr($JurnalTypeCode, 4); + } + + $sql_jurnaltype = "SELECT JurnalTypeID FROM jurnal_type WHERE JurnalTypeCode LIKE ? + AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N'"; + $que_jurnaltype = $this->db->query($sql_jurnaltype, ['%' . $JurnalTypeCode]); + if (!$que_jurnaltype) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get jurnal type id/code"); + exit; + } + $JurnalTypeID = $que_jurnaltype->row_array()['JurnalTypeID']; + + # INSERT jurnal header # + $title = "Jurnal Penyesuaian dari Jurnal Nomor " . $param['jurnalNo']; + $descp = "Penyesuaian Jurnal Nomor {$param['jurnalNo']} tanggal {$param['jurnalDate']}"; + + $sql_header_jurnal = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalIsPenyesuaian, + jurnalPenyesuaianStatus, + jurnalM_UserID + ) VALUES (?,?,?,?,?,?,?,NOW(),?,'Y','draft', ?)"; + $que_header_jurnal = $this->db->query($sql_header_jurnal, [ + $user['M_BranchCompanyID'], $user['S_RegionalID'], $user['M_BranchCode'], + $JurnalPeriodeID, $JurnalNo, $title, $descp, $JurnalTypeID, $user['M_UserID'] + ]); + if (!$que_header_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal header"); + exit; + } + $JurnalID = $this->db->insert_id(); + + foreach ($param['detailtrx'] as $key => $obj) { + $sql_transac_jurnal = "INSERT INTO jurnal_tx ( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID + ) VALUES (?,?,?,?,?,?)"; + $que_transac_jurnal = $this->db->query($sql_transac_jurnal, [ + $JurnalID, $obj['coaID'], $obj['coaDescription'], + $obj['debit'], $obj['kredit'], $user['M_UserID'] + ]); + if (!$que_transac_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal tx"); + exit; + } + $JurnalTxID = $this->db->insert_id(); + + $sql_addon_jurnal = "INSERT INTO jurnal_addon ( + jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID + ) VALUES (?,?,?,?,NOW(),?)"; + $que_addon_jurnal = $this->db->query($sql_addon_jurnal, [ + $JurnalID, $JurnalTxID, $obj['infocode'], $obj['info'], $user['M_UserID'] + ]); + if (!$que_addon_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal addon"); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] insert Jurnal Penyesuaian"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function updateStatusKoreksiJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error('Invalid Token'); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + + $sql_update = "UPDATE jurnal SET + jurnalPenyesuaianStatus = ?, + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_update = $this->db->query($sql_update, [ + $param['status'], $param['jurnalID'] + ]); + if (!$que_update) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status {$param['status']} jurnal koreksi"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[success] jurnal koreksi {$param['status']}"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserID = ?"; + $que = $this->db->query($sql, [$user['M_UserID']]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit; + } + + $result = $que->row_array(); + if (!$result) { + $result = array( + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => '' + ); + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/JournalVerifEdit.php b/application/controllers/mockup/masterdata/accounting/JournalVerifEdit.php new file mode 100644 index 0000000..f2a01cd --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/JournalVerifEdit.php @@ -0,0 +1,432 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT + periodeID, + periodeName, + DATE_FORMAT(periodeStartDate, '%d %M %Y') AS periodeStartDate, + DATE_FORMAT(periodeEndDate, '%d %M %Y') AS periodeEndDate + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC"; + $que = $this->db->query($sql, []); + if (!$que) { + $this->sys_error_db("[Error] get daftar periode"); + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getListTypeJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + $sql = "SELECT + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName + FROM jurnal_type + WHERE JurnalTypeIsActive = 'Y'"; + $que = $this->db->query($sql, []); + if (!$que) { + $this->sys_error_db("[Error] get daftar tipe jurnal"); + exit; + } + + $data = $que->result_array(); + $all = [ + 'JurnalTypeID' => 0, + 'JurnalTypeCode' => "X", + 'JurnalTypeName' => "SEMUA" + ]; + array_unshift($data, $all); + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getListJournalEdit() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $isBranch = " "; + if ($user['M_BranchID'] != '0') { + $isBranch .= " AND jurnalM_BranchCode = '{$user['M_BranchCode']}'"; + } + + $keyword = "%"; + if ($param['search'] != '') { + $keyword = $param['search'] . "%"; + } + + $row_limit = 10; + $curr_page = (int)($param['page'] ?? 1); + $row_ofset = max(0, ($curr_page - 1) * $row_limit); + + $sql_base = "SELECT + jurnalID, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalEditStatus, + jurnalDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalRequestEditID, + JurnalRequestEditStaffID, + JurnalRequestEditStaffName, + JurnalRequestEditStatusRequest, + apr.M_UserUsername AS RequestApprovedBy, + JurnalRequestEditStatusEdit, + ape.M_UserUsername AS EditApprovedBy, + S_RegionalName, + M_BranchName, + M_BranchCompanyName + FROM jurnal + JOIN jurnal_request_edit ON JurnalRequestEditJurnalID = jurnalID + AND JurnalRequestEditIsActive = 'Y' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeIsActive = 'Y' + JOIN m_branch_company ON M_BranchCompanyID = jurnalM_BranchCompanyID + JOIN s_regional ON S_RegionalID = JurnalS_RegionalID + LEFT JOIN m_branch ON M_BranchCode = jurnalM_BranchCode + LEFT JOIN m_user apr ON apr.M_UserID = JurnalRequestEditApproveRequestBy + LEFT JOIN m_user ape ON ape.M_UserID = JurnalRequestEditApproveEditBy + WHERE jurnalperiodeID = ? + AND JurnalS_RegionalID = ? + AND (jurnalJurnalTypeID = ? OR 0 = ?) + AND jurnalDate BETWEEN DATE(?) AND DATE(?) + AND jurnalNo LIKE ? + AND jurnalIsActive = 'Y' + " . $isBranch; + + $sql_data = $sql_base . " LIMIT ? OFFSET ?"; + $que_data = $this->db->query($sql_data, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], + $keyword, $row_limit, $row_ofset + ]); + if (!$que_data) { + $this->sys_error_db("[Error] get daftar journal edit"); + exit; + } + + // get total all journal edit + $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) as x"; + $que_total = $this->db->query($sql_total, [ + $param['periodeID'], $user['S_RegionalID'], + $param['typeJournalID'], $param['typeJournalID'], + $param['startdate'], $param['enddate'], $keyword + ]); + if (!$que_total) { + $this->sys_error_db("[Error] get total all journal edit"); + exit; + } + + $data = [ + "records" => $que_data->result_array(), + "total" => $que_total->row_array()['total'] + ]; + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDetailJournalEdit() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $param = $this->sys_input; + + ## get latest edit change log data ## + $sql_data = "SELECT + JurnalEditLogID, + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID AS StaffUserID, + IFNULL(NULLIF(M_UserFullName, ''), M_UserUsername) AS StaffName + FROM acc_one_log.jurnal_edit_log + JOIN m_user ON M_UserID = JurnalEditLogUserID + WHERE JurnalEditLogIDJurnalID = ? + AND JurnalEditLogIsActive = 'Y' + ORDER BY JurnalEditLogID DESC + LIMIT 1"; + $que_data = $this->db->query($sql_data, [$param['jurnalID']]); + if (!$que_data) { + $this->sys_error_db("[Error] get data change jurnal"); + exit; + } + $data = $que_data->result_array()[0]; + + $before = json_decode($data['JurnalEditLogIDJsonBefore'], true); + $after = json_decode($data['JurnalEditLogIDJsonAfter'], true); + + unset($data['JurnalEditLogIDJsonBefore']); + unset($data['JurnalEditLogIDJsonAfter']); + + $data['changeBefore'] = $before; + $data['changeAfter'] = $after; + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + # MUTATION # + public function requestEditJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # insert into request jurnal edit # + $sqlreq = "INSERT INTO jurnal_request_edit ( + JurnalRequestEditJurnalID, + JurnalRequestEditStaffID, + JurnalRequestEditStaffName, + JurnalRequestEditUserID, + JurnalRequestEditCreated + ) VALUES (?,?,?,?,NOW())"; + $quereq = $this->db->query($sqlreq, [ + $param['jurnalID'], $param['staffID'], + $param['staffName'], $user['M_UserID'] + ]); + if (!$quereq) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert request edit into table jurnal request edit"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("Request edit jurnal berhasil dibuat"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function updateRequestEditJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # update request jurnal edit status # + $sqlreq = "UPDATE jurnal_request_edit SET + JurnalRequestEditStatusRequest = ?, + JurnalRequestEditApproveRequestBy = ?, + JurnalRequestEditUpdated = NOW() + WHERE JurnalRequestEditID = ?"; + $quereq = $this->db->query($sqlreq, [ + $param['status'], $user['M_UserID'], + $param['JurnalRequestEditID'] + ]); + if (!$quereq) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update request edit status"); + exit; + } + + # update data header jurnal status edit # + $sqlheader = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $queheader = $this->db->query($sqlheader, [$param['jurnalID']]); + if (!$queheader) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update header jurnal"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status request"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function saveEditJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + $old_jurnaltx = $param['oldjurnaltx']; + $new_jurnaltx = $param['newjurnaltx']; + + # log the data in accone log # + $sql_addlog = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_addlog = $this->db->query($sql_addlog, [ + $param['jurnalID'], json_encode($old_jurnaltx), + json_encode($new_jurnaltx), $user['M_UserID'] + ]); + if (!$que_addlog) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit; + } + $jurnalEditLogID = $this->db->insert_id(); + + # UPDATE table jurnal request edit # + $sql_req = "UPDATE jurnal_request_edit SET + JurnalRequestEditJurnalEditLogID = ? + WHERE JurnalRequestEditID = ?"; + $que_req = $this->db->query($sql_req, [ + $jurnalEditLogID, $param['jurnalRequestEditID'] + ]); + if (!$que_req) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update table jurnal request edit"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] save edit jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function verifEditJurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # UPDATE jurnal tx # + $newtrx = $param['newtrx']; + $sqltrx = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + foreach ($newtrx as $key => $obj) { + $quetrx = $this->db->query($sqltrx, [ + $obj['coaID'], $obj['coaDescription'], $user['M_UserID'], + $obj['jurnalTxID'], $obj['jurnalTxJurnalID'] + ]); + if (!$quetrx) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update new jurnal tx"); + exit; + } + } + + # UPDATE jurnal header edit status # + $sql = "UPDATE jurnal + SET jurnalEditStatus = 'N', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que = $this->db->query($sql, [$param['jurnalID']]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status edit"); + exit; + } + + # UPDATE jurnal status edit jurnal # + $sqlreq = "UPDATE jurnal_request_edit SET + JurnalRequestEditStatusEdit = ?, + JurnalRequestEditApproveEditBy = ?, + JurnalRequestEditUpdated = NOW() + WHERE JurnalRequestEditID = ?"; + $quereq = $this->db->query($sqlreq, [ + $param['status'], $user['M_UserID'], + $param['JurnalRequestEditID'] + ]); + if (!$quereq) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status edit jurnal"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] approve edit jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Journalar.php b/application/controllers/mockup/masterdata/accounting/Journalar.php new file mode 100644 index 0000000..d77ae4e --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalar.php @@ -0,0 +1,180 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $periodeid = $prm["periodeid"]; + $xdate = $prm["xdate"]; + + $sql = "SELECT + jurnalID, + jurnalM_BranchCode, + jurnalNo, + jurnalTitle, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + DATE_FORMAT(jurnalDate, '%d %M %Y') as jurnalDatexx, + jurnalType, + jurnalTxID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + CONCAT(IFNULL(coaDescription, ''), ' | ', IFNULL(jurnalArM_CompanyName, '')) as descriptionAndCompanyName, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + periodeIsClosed, + CASE + WHEN coaAccountType = 'DB' THEN jurnalTxDebit + WHEN coaAccountType = 'CR' THEN jurnalTxCredit + END as value, + jurnalArID, + jurnalArRefNo, + jurnalArM_CompanyCode, + jurnalArM_CompanyName, + 0 as subtotal + FROM jurnal + JOIN jurnal_tx ON jurnalID = jurnalTxJurnalID + AND jurnalTxIsActive = 'Y' + LEFT JOIN jurnal_ar ON jurnalTxID = jurnalArJurnalTxID + AND jurnalArIsActive = 'Y' + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + WHERE jurnalIsActive = 'Y' + AND jurnalperiodeID = ? + AND jurnalType = 'AR' + AND jurnalDate = ?"; + $qry = $this->db->query($sql, [$periodeid, $xdate]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("select jurnal", $this->db); + exit; + } + + $totalDebit = 0; + $totalCredit = 0; + $totalBalance = 0; + + for ($i = 0; $i < count($rows); $i++) { + // print_r($rows[$i]); + // exit; + $data = $rows[$i]; + if ($data['coaAccountType'] == 'DB') { + $totalDebit = $totalDebit + floatval($data['value']); + } + if ($data['coaAccountType'] == 'CR') { + $totalCredit = $totalCredit + floatval($data['value']); + } + } + + $totalBalance = $totalDebit - $totalCredit; + $arrTotal = array('debit' => $totalDebit, 'credit' => $totalCredit, 'balance' => $totalBalance); + + foreach ($rows as $key => $value) { + // print_r($value); + // exit; + $debittot = 0; + $credittot = 0; + $xsubtotal = 0; + + if ($value['coaAccountType'] == 'DB') { + $debittot = floatval($value['value']); + } + if ($value['coaAccountType'] == 'CR') { + $credittot = floatval($value['value']); + } + $xsubtotal = $debittot + $credittot; + $rows[$key]['subtotal'] = $xsubtotal; + } + + $result = array( + 'records' => $rows, + 'total' => $arrTotal + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalarpayment.php b/application/controllers/mockup/masterdata/accounting/Journalarpayment.php new file mode 100644 index 0000000..4f4a623 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalarpayment.php @@ -0,0 +1,180 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $periodeid = $prm["periodeid"]; + $xdate = $prm["xdate"]; + + $sql = "SELECT + jurnalID, + jurnalM_BranchCode, + jurnalNo, + jurnalTitle, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + DATE_FORMAT(jurnalDate, '%d %M %Y') as jurnalDatexx, + jurnalType, + jurnalTxID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + CONCAT(IFNULL(coaDescription, ''), ' | ', IFNULL(jurnalArM_CompanyName, '')) as descriptionAndCompanyName, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + periodeIsClosed, + CASE + WHEN coaAccountType = 'DB' THEN jurnalTxDebit + WHEN coaAccountType = 'CR' THEN jurnalTxCredit + END as value, + jurnalArID, + jurnalArRefNo, + jurnalArM_CompanyCode, + jurnalArM_CompanyName, + 0 as subtotal + FROM jurnal + JOIN jurnal_tx ON jurnalID = jurnalTxJurnalID + AND jurnalTxIsActive = 'Y' + LEFT JOIN jurnal_ar ON jurnalTxID = jurnalArJurnalTxID + AND jurnalArIsActive = 'Y' + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + WHERE jurnalIsActive = 'Y' + AND jurnalperiodeID = ? + AND jurnalType = 'ARPay' + AND jurnalDate = ?"; + $qry = $this->db->query($sql, [$periodeid, $xdate]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("select jurnal", $this->db); + exit; + } + + $totalDebit = 0; + $totalCredit = 0; + $totalBalance = 0; + + for ($i = 0; $i < count($rows); $i++) { + // print_r($rows[$i]); + // exit; + $data = $rows[$i]; + if ($data['coaAccountType'] == 'DB') { + $totalDebit = $totalDebit + floatval($data['value']); + } + if ($data['coaAccountType'] == 'CR') { + $totalCredit = $totalCredit + floatval($data['value']); + } + } + + $totalBalance = $totalDebit - $totalCredit; + $arrTotal = array('debit' => $totalDebit, 'credit' => $totalCredit, 'balance' => $totalBalance); + + foreach ($rows as $key => $value) { + // print_r($value); + // exit; + $debittot = 0; + $credittot = 0; + $xsubtotal = 0; + + if ($value['coaAccountType'] == 'DB') { + $debittot = floatval($value['value']); + } + if ($value['coaAccountType'] == 'CR') { + $credittot = floatval($value['value']); + } + $xsubtotal = $debittot + $credittot; + $rows[$key]['subtotal'] = $xsubtotal; + } + + $result = array( + 'records' => $rows, + 'total' => $arrTotal + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalarpaymentv2.php b/application/controllers/mockup/masterdata/accounting/Journalarpaymentv2.php new file mode 100644 index 0000000..fd4e734 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalarpaymentv2.php @@ -0,0 +1,761 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeID IN (11, 12,13) + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'ARDATE' OR jurnalAddOnCode = 'CMPNYNAME' OR jurnalAddOnCode = 'CMPNYNUM') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeID IN (11,12,13) + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeID IN (11,12,13) + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalarv2.php b/application/controllers/mockup/masterdata/accounting/Journalarv2.php new file mode 100644 index 0000000..acf4f86 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalarv2.php @@ -0,0 +1,761 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTODAILYAR' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'CMPNYNAME' OR jurnalAddOnCode = 'CMPNYNUM') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTODAILYAR' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTODAILYAR' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalcash.php b/application/controllers/mockup/masterdata/accounting/Journalcash.php new file mode 100644 index 0000000..c14f1ca --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalcash.php @@ -0,0 +1,161 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $periodeid = $prm["periodeid"]; + $xdate = $prm["xdate"]; + + $sql = "SELECT + jurnalID, + jurnalM_BranchCode, + jurnalNo, + jurnalTitle, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalTxID, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + periodeIsClosed, + CASE + WHEN coaAccountType = 'DB' THEN jurnalTxDebit + WHEN coaAccountType = 'CR' THEN jurnalTxCredit + END as value, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + JurnalTypeIsAuto + FROM jurnal + JOIN jurnal_tx ON jurnalID = jurnalTxJurnalID + AND jurnalTxIsActive = 'Y' + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' + AND JurnalTypeIsAuto = 'Y' AND JurnalTypeCode = 'AUTODAILYSALES' + WHERE jurnalIsActive = 'Y' + AND jurnalperiodeID = ? + AND jurnalDate = ?"; + $qry = $this->db->query($sql, [$periodeid, $xdate]); + + // echo $this->db->last_query(); + // exit; + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("select jurnal", $this->db); + exit; + } + + $totalDebit = 0; + $totalCredit = 0; + $totalBalance = 0; + + for ($i = 0; $i < count($rows); $i++) { + // print_r($rows[$i]); + // exit; + $data = $rows[$i]; + if ($data['coaAccountType'] == 'DB') { + $totalDebit = $totalDebit + floatval($data['value']); + } + if ($data['coaAccountType'] == 'CR') { + $totalCredit = $totalCredit + floatval($data['value']); + } + } + + $totalBalance = $totalDebit - $totalCredit; + $arrTotal = array('debit' => $totalDebit, 'credit' => $totalCredit, 'balance' => $totalBalance); + + $result = array( + 'records' => $rows, + 'total' => $arrTotal + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalcashv2.php b/application/controllers/mockup/masterdata/accounting/Journalcashv2.php new file mode 100644 index 0000000..13792a4 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalcashv2.php @@ -0,0 +1,761 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTODAILYSALES' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND jurnalAddOnCode = 'OMZNAME' + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTODAILYSALES' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTODAILYSALES' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalfixasset.php b/application/controllers/mockup/masterdata/accounting/Journalfixasset.php new file mode 100644 index 0000000..d8244d5 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalfixasset.php @@ -0,0 +1,762 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'FIXASSET' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'JFA') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'FIXASSET' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'FIXASSET' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalfixedasset.php b/application/controllers/mockup/masterdata/accounting/Journalfixedasset.php new file mode 100644 index 0000000..16e1dba --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalfixedasset.php @@ -0,0 +1,224 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $periodeid = $prm["periodeid"]; + $xdate = $prm["xdate"]; + + $branchid = $prm["branchid"]; + $regionalid = $prm["regionalid"]; + + $filter_regional = ""; + $filter_cabang = ""; + $join_regional = ""; + $join_cabang = ""; + + if (intval($branchid) === 0) { + $filter_regional = " AND S_RegionalID = {$regionalid}"; + $join_regional = " LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } else { + $filter_cabang = " AND S_RegionalID = {$regionalid} AND M_BranchID = {$branchid}"; + $join_cabang = " JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } + + $sql = "SELECT +M_ItemCode CodeFixedAsset, +M_ItemDesc NameFixedAsset, +Fa_ItemAcquisitionPrice AcquisitionPrice, +IFNULL(Fa_ClassDepreCorp,0) DepreRateFixedAsset, +IFNULL(Fa_ClassDepreGov,0) DepreGovPercent, +0 DebitFixedAsset, +0 CreditFixedAsset, +IFNULL(Fa_ClassDepreCorp,0)/12*Fa_ItemAcquisitionPrice AccumDepreFixedAsset, +Fa_ItemAcquisitionPrice - IFNULL(Fa_ClassDepreCorp,0)/12*Fa_ItemAcquisitionPrice RemainingValueFixedAsset, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx +FROM fa_item +JOIN m_item ON M_ItemID = Fa_ItemM_ItemID +JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID +WHERE Fa_ItemIsActive = 'Y' +ORDER BY M_ItemCode ASC"; + + + $sql_total = "SELECT count(*) as total FROM ($sql) as x"; + $qry_total = $this->db->query($sql_total); + + $number_offset = 0; + $number_limit = 10; + + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db);; + exit; + } + + $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset"; + $qry = $this->db->query($sql_select); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit; + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, array($value["jurnalID"])); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit; + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row['JurnalErr_Msg'] = json_decode($row['JurnalErr_Msg'], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = 'Y'; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = 'N'; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'PVNO') + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID"; + $qry_detail = $this->db->query($sql_detail, array($value["jurnalID"])); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = array( + 'total' => $totalPage, + 'totalfilter' => $totalCount, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php b/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php new file mode 100644 index 0000000..5033c84 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php @@ -0,0 +1,764 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? $user["S_RegionalID"]; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOGOODRECEIVE' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + -- AND (jurnalAddOnCode = 'RONUMB') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + // "sql" => $sql, + // "bcode" => $branchCode, + // "user" => $user, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTOGOODRECEIVE' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTOGOODRECEIVE' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalpaymentinv.php b/application/controllers/mockup/masterdata/accounting/Journalpaymentinv.php new file mode 100644 index 0000000..9e259d5 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalpaymentinv.php @@ -0,0 +1,768 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + jurnalIsClosed, + jurnalEditStatus, + JurnalRequestEditID, + JurnalRequestEditStaffName, + JurnalRequestEditStatusRequest, + JurnalRequestEditStatusEdit, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + LEFT JOIN jurnal_request_edit ON JurnalRequestEditJurnalID = jurnalID + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N' + AND JurnalTypeCode = 'PAYMENTINV' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'JFA') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'PAYMENTINV' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'PAYMENTINV' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalpv.php b/application/controllers/mockup/masterdata/accounting/Journalpv.php new file mode 100644 index 0000000..c852395 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalpv.php @@ -0,0 +1,775 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? $user["S_RegionalID"]; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + jurnalIsClosed, + jurnalEditStatus, + JurnalRequestEditID, + JurnalRequestEditStaffName, + JurnalRequestEditStatusRequest, + JurnalRequestEditStatusEdit, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + LEFT JOIN jurnal_request_edit ON JurnalRequestEditJurnalID = jurnalID + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOPV' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'PVNO') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaAccountType, + coaCurrencyCode, + coaIsInput, + coaReportSchedule, + coaCashFlowCategory, + coaSubDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTOPV' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTOPV' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalsuratjalan.php b/application/controllers/mockup/masterdata/accounting/Journalsuratjalan.php new file mode 100644 index 0000000..c90d670 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalsuratjalan.php @@ -0,0 +1,763 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOSENDGOODR' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') AS jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') AS jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'SENDGOODRDST') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_ApproveLevelIsActive = 'Y' + AND M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM + TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTOSENDGOODR' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTOSENDGOODR' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalterimabarang.php b/application/controllers/mockup/masterdata/accounting/Journalterimabarang.php new file mode 100644 index 0000000..2643203 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journalterimabarang.php @@ -0,0 +1,694 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT + * + FROM jurnal_type + WHERE JurnalTypeIsActive = 'Y'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("getTipeJurnal: ", $this->db); + exit; + } + $rst = $qry->result_array(); + foreach ($rst as $key => $value) { + if ($value['JurnalTypeCode'] == 'GOODRECEIVE') { + $default = $value; + } + } + $this->sys_ok([ + "default" => $default, + "records" => $rst + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getPeriode() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as displayPeriode, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + AND CONCAT(periodeYear, ' - ', periodeName) LIKE ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get periode", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getSupplier() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = '%%'; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $search . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + CONCAT(SupplierCode, ' - ', SupplierName) as displaySupplier, + supplier.* + FROM supplier + WHERE SupplierIsActive = 'Y' + AND CONCAT(SupplierCode, ' - ', SupplierName) LIKE ?"; + + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("select supplier", $this->db); + exit; + } + + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getCoa() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $limit = 70; // dihapus jika perlu tampil semua + + $sql = "SELECT + * + FROM coa + WHERE coaIsActive = 'Y' + -- AND coaIsInput = 'Y' -- TODO: uncomment setelah diinject + AND coaAccountNo != '' + AND (coaDescription LIKE ? OR coaSubDescription LIKE ? OR coaAccountNo LIKE ?) + ORDER BY coaAccountNo ASC + LIMIT ?"; + $qry = $this->db->query($sql, [$search, $search, $search, $limit]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa", $this->db); + exit; + } + + $result = array( + "records" => $rows, + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function createJurnal() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + // Get Parameter + $userID = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $jurnalTypeID = $prm['jurnalType'] ?? 2; // Harusnya 2 : GOODRECEIVE + $details = $prm['details']; + + // TODO: Dihapus jika sudah ada M_BranchCode di parameter + $sql = "SELECT M_BranchCode FROM m_branch WHERE M_BranchID = ?"; + $qry = $this->db->query($sql, [$prm['M_BranchID']]); + if (!$qry) { + $this->sys_error_db("Failed to get branch code", $this->db); + exit; + } + $rst = $qry->row(); + $branchCode = $rst->M_BranchCode; + + $sql = "SELECT `fn_numbering`('J') as jurnalNo"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Failed to get jurnal number", $this->db); + exit; + } + $rst = $qry->row(); + $jurnalNo = $rst->jurnalNo; + + // Start Transaction + $this->db->trans_start(); + + $sqlHeader = "INSERT INTO jurnal + (jurnalM_BranchCompanyID, JurnalS_RegionalID, jurnalM_BranchCode, + jurnalperiodeID, jurnalNo, jurnalTitle, + jurnalDescription, jurnalDate, jurnalJurnalTypeID, + jurnalM_UserID, jurnalCreated) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())"; + + $this->db->query($sqlHeader, [ + $prm['M_BranchCompanyID'], + $prm['S_RegionalID'], + $branchCode, + $prm['periodeID'], + $jurnalNo, + $prm['jurnalTitle'], + $prm['jurnalDescription'], + $prm['jurnalDate'], + $jurnalTypeID, + $userID + ]); + + $jurnalID = $this->db->insert_id(); + + foreach ($details as $detail) { + $this->createFormDetail($detail, $jurnalID); // Child Transaction + } + $this->db->trans_complete(); + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db('Failed to create jurnal: ', $this->db); + exit; + } else { + $this->sys_ok("Berhasil simpan jurnal"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function deleteJurnal() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $jurnalID = $prm['jurnalID']; + $userID = $this->sys_user["M_UserID"]; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa dihapus"); + exit; + } + + // Start Transaction + $this->db->trans_start(); + // 1. Update jurnal where jurnalID = ? + $this->db->set('jurnalIsActive', 'N'); + $this->db->set('jurnalLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalM_UserID', $userID); + $this->db->where('jurnalID', $jurnalID); + $this->db->update('jurnal'); + + // 2. Update jurnal_tx where jurnalTxJurnalID = ? + $this->db->set('jurnalTxIsActive', 'N'); + $this->db->set('jurnalTxLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalTxM_UserID', $userID); + $this->db->where('jurnalTxJurnalID', $jurnalID); + $this->db->update('jurnal_tx'); + + // 3. Update jurnal_addon where jurnalAddOnJurnalID = ? + $this->db->set('jurnalAddOnIsActive', 'N'); + $this->db->set('jurnalAddOnLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalAddOnLastUpdatedUserID', $userID); + $this->db->where('jurnalAddOnJurnalID', $jurnalID); + $this->db->update('jurnal_addon'); + + $this->db->trans_complete(); + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db('Failed to delete jurnal: ', $this->db); + exit; + } else { + $this->sys_ok("Berhasil hapus jurnal"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // TODO: Mungkin ini nanti bisa lebih efektif untuk addOns + public function loadEditDialog() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + // Get jurnal, jurnal_tx, and jurnal_addon by jurnalID + $sql = "SELECT jurnalID, jurnalperiodeID, jurnalNo, jurnalTitle, jurnalDescription, + DATE_FORMAT(jurnalDate, '%Y-%m-%d') as jurnalDate, jurnalIsPosted, + M_BranchCompanyName, S_RegionalName, M_BranchName, + M_BranchCompanyID, S_RegionalID, M_BranchID, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight + FROM jurnal + JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' + WHERE jurnalID = ? AND jurnalIsActive = 'Y'"; + + $qryj = $this->db->query($sql, [$prm['jurnalID']]); + + if (!$qryj) { + $this->sys_error_db("Failed to get jurnal", $this->db); + exit; + } + $jurnal = $qryj->row_array(); + if ($jurnal == null) { + $this->sys_error("JurnalID: " . $prm['jurnalID'] . " tidak ditemukan"); + exit; + } + $result['jurnalHead'] = $jurnal; + + // Get Selected Periode + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as displayPeriode, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode, + periode.* + FROM jurnal + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' AND periodeIsClosed = 'N' + WHERE jurnalID = ? AND jurnalIsActive = 'Y'"; + $periode = $this->db->query($sql, [$prm['jurnalID']])->row_array(); + if (!$periode) { + $this->sys_error_db("Failed to get periode", $this->db); + exit; + } + $result['periode'] = $periode; + + // Get suppliercode and grni/invoice code result object + $sql = "SELECT * FROM jurnal_addon WHERE jurnalAddOnJurnalID = ? AND jurnalAddOnIsActive = 'Y'"; + $qryaddon = $this->db->query($sql, [$prm['jurnalID']]); + if (!$qryaddon) { + $this->sys_error_db("Failed to get jurnal_addon", $this->db); + exit; + } + $addon = $qryaddon->result_array(); + foreach ($addon as $key => $value) { + $result['jurnalHead'][$value['jurnalAddOnCode']] = $value['jurnalAddOnValue']; + if ($value['jurnalAddOnCode'] == 'SUPCD') { + $supcd = $value['jurnalAddOnValue']; + } + } + + // Get supplier + $sql = "SELECT + CONCAT(SupplierCode, ' - ', SupplierName) as displaySupplier, + supplier.* + FROM supplier WHERE SupplierCode = ? AND SupplierIsActive = 'Y'"; + $qrysupplier = $this->db->query($sql, [$supcd]); + if (!$qrysupplier) { + $this->sys_error_db("Failed to get supplier", $this->db); + exit; + } + $supplier = $qrysupplier->row_array(); + $result['supplier'] = $supplier; + + $txsql = "SELECT jurnalTxID, jurnalTxCoaID as coaID, jurnalTxDescription as coaDescription, + jurnalTxDebit, jurnalTxCredit, coaAccountNo + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID + WHERE jurnalTxJurnalID = ? AND jurnalTxIsActive = 'Y'"; + $qrytx = $this->db->query($txsql, [$prm['jurnalID']]); + if (!$qrytx) { + $this->sys_error_db("Failed to get jurnal tx", $this->db); + exit; + } + $tx = $qrytx->result_array(); + $result['details'] = $tx; + + foreach ($result['details'] as $key => $value) { + if ($value['jurnalTxCredit'] > 0) { + $addonsql = "SELECT jurnalAddOnID, jurnalAddOnCode, jurnalAddOnValue FROM jurnal_addon WHERE jurnalAddOnJurnalTxID = ? AND jurnalAddOnIsActive = 'Y'"; + $qryaddon = $this->db->query($addonsql, [$value['jurnalTxID']]); + if (!$qryaddon) { + $this->sys_error_db("Failed to get jurnal_addon", $this->db); + exit; + } + $addon = $qryaddon->result_array(); + $result['details'][$key]['addOns'] = $addon; + } + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function updateJurnal() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userID = $this->sys_user["M_UserID"]; + $jurnalID = $prm['jurnalID']; + $details = $prm['details']; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa diubah"); + exit; + } + + // Start Transaction + $this->db->trans_start(); + + // 1. Update jurnal + $sql = "UPDATE jurnal + SET jurnalDate = ?, jurnalperiodeID = ?, + jurnalTitle = ?, jurnalDescription = ?, + jurnalLastUpdated = NOW(), jurnalM_UserID = ? + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, [$prm['jurnalDate'], $prm['periodeID'], $prm['jurnalTitle'], $prm['jurnalDescription'], $userID, $jurnalID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update jurnal", $this->db); + exit; + } + + // 2. Soft delete semua existing jurnal_tx and jurnal_addon where jurnalID = ? + $tx = "UPDATE jurnal_tx SET jurnalTxIsActive = 'N' WHERE jurnalTxJurnalID = ?"; + $qrytx = $this->db->query($tx, [$jurnalID]); + if (!$qrytx) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update jurnal", $this->db); + exit; + } + + $addon = "UPDATE jurnal_addon SET jurnalAddOnIsActive = 'N' WHERE jurnalAddOnJurnalID = ?"; + $qryaddon = $this->db->query($addon, [$jurnalID]); + if (!$qryaddon) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update jurnal", $this->db); + exit; + } + + // 3. Insert new jurnal_tx and jurnal_addon records + foreach ($details as $detail) { + $this->createFormDetail($detail, $jurnalID); + } + + $this->db->trans_complete(); + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db('Failed to update jurnal: ', $this->db); + exit; + } else { + $this->sys_ok("Berhasil update jurnal"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + //* --- bandingkan dulu baru hapus --- + public function updateJurnalV2() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userID = $this->sys_user["M_UserID"]; + $jurnalID = $prm['jurnalID']; + $details = $prm['details']; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa diubah"); + exit; + } + + // Start Transaction + $this->db->trans_start(); + + // 1. Update jurnal + $sql = "UPDATE jurnal + SET jurnalDate = ?, jurnalperiodeID = ?, + jurnalTitle = ?, jurnalDescription = ?, + jurnalLastUpdated = NOW(), jurnalM_UserID = ? + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, [$prm['jurnalDate'], $prm['periodeID'], $prm['jurnalTitle'], $prm['jurnalDescription'], $userID, $jurnalID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update jurnal", $this->db); + exit; + } + + // 2. Ambil data existing jurnal_tx and jurnal_addon where jurnalID = ? + $tx = "SELECT * FROM jurnal_tx WHERE jurnalTxJurnalID = ? AND jurnalTxIsActive = 'Y'"; + $oldTx = $this->db->query($tx, [$jurnalID])->result_array() ?? null; + if (!$oldTx) { + $this->sys_error_db("Failed to get jurnalTx", $this->db); + exit; + } + + // 3. Bandingin data jurnalTx: coaAccountNo, jurnalTxDebit, jurnalTxCredit + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function diffJurnalTx() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $jurnalID = $prm['jurnalID']; + $details = $prm['details']; + + $tx = "SELECT * FROM jurnal_tx WHERE jurnalTxJurnalID = ? AND jurnalTxIsActive = 'Y'"; + $oldTx = $this->db->query($tx, [$jurnalID])->result_array() ?? null; + if (!$oldTx) { + $this->sys_error_db("Failed to get jurnalTx", $this->db); + exit; + } + + var_dump($oldTx); + + var_dump($details); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + /* + * --- HELPER FUNCTION --- * + */ + private function createFormDetail($prm, $jurnalID) + { + $userid = $this->sys_user["M_UserID"]; + + $coaID = $prm['coaID']; + $jurnalTxDescription = $prm['coaDescription']; + $jurnalTxDebit = $prm['jurnalTxDebit']; + $jurnalTxCredit = $prm['jurnalTxCredit']; + $addOns = $prm['addOns']; // array + + // Validasi debit dan kredit + if ($jurnalTxCredit == 0 && $jurnalTxDebit > 0) { + $isDebit = true; + $isCredit = false; + } else if ($jurnalTxDebit == 0 && $jurnalTxCredit > 0) { + $isDebit = false; + $isCredit = true; + } else { + $isDebit = false; + $isCredit = false; + $this->sys_error("Debit atau Kredit harus diisi"); + exit; + } + + + if ($isDebit && $isCredit) { + $this->sys_error("Debit dan Kredit tidak boleh diisi bersamaan"); + exit; + } + // Jika kredit, maka masuk ke jurnal_tx dan jurnal_addon + else if ($isCredit && !$isDebit) { + $insertTx = "INSERT INTO jurnal_tx + (jurnalTxJurnalID, jurnalTxCoaID, jurnalTxDescription, jurnalTxCredit, + jurnalTxIsActive, jurnalTxCreated, jurnalTxLastUpdated, jurnalTxM_UserID) + VALUES (?, ?, ?, ?, 'Y', NOW(), NOW(), ?)"; + + $insertAddOn = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnIsActive, jurnalAddOnCreated, + jurnalAddOnCreatedUserID, jurnalAddOnLastUpdated, jurnalAddOnLastUpdatedUserID) + VALUES (?, ?, ?, ?, 'Y', NOW(), ?, NOW(), ?)"; + + // Ikut parents transaction agar rollbacknya bisa langsung semua + $insertTxCr = $this->db->query($insertTx, [$jurnalID, $coaID, $jurnalTxDescription, $jurnalTxCredit, $userid]); + if (!$insertTxCr) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed Insert JurnalTx Credit", $this->db); + exit; + } + + $getTxId = $this->db->insert_id(); + + // Insert jurnalAddOn 1 kredit bisa ada 2-3 addOn + foreach ($addOns as $item) { + + $addOnState = $this->db->query($insertAddOn, [$jurnalID, $getTxId, $item['jurnalAddOnCode'], $item['jurnalAddOnValue'], $userid, $userid]); + + if (!$addOnState) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed Insert JurnalAddOn Credit", $this->db); + exit; + } + } + } + + // Jika debit maka hanya masuk ke jurnal_tx + else if ($isDebit && !$isCredit) { + $sql = "INSERT INTO jurnal_tx + (jurnalTxJurnalID, jurnalTxCoaID, jurnalTxDescription, jurnalTxDebit, + jurnalTxIsActive, jurnalTxCreated, jurnalTxLastUpdated, jurnalTxM_UserID) + VALUES (?, ?, ?, ?, 'Y', NOW(), NOW(), ?)"; + $qry = $this->db->query($sql, [$jurnalID, $coaID, $jurnalTxDescription, $jurnalTxDebit, $userid]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed Insert JurnalTx Debit", $this->db); + exit; + } + } else { + $this->sys_error("Debit atau Kredit harus diisi"); + exit; + } + } + + + public function getListFormDetail() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $jurnalID = $this->sys_input['jurnalID']; + + $sql = "SELECT * FROM jurnal_tx + WHERE jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + $qry = $this->db->query($sql, [$jurnalID]); + if (!$qry) { + $this->sys_error_db("select jurnal_tx", $this->db); + exit; + } + + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journaltukarfaktur.php b/application/controllers/mockup/masterdata/accounting/Journaltukarfaktur.php new file mode 100644 index 0000000..141f88e --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Journaltukarfaktur.php @@ -0,0 +1,761 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeID DESC, periodeMonth DESC + LIMIT 18"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit(); + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit(); + } + $prm = $this->sys_input; + $user = $this->sys_user; + + $regionalId = $prm["regionalId"] ?? null; + $branchCode = $prm["branchCode"] == "" ? $user["M_BranchCode"] : $prm["branchCode"]; + $periodeid = $prm["periodeid"] ?? null; + $xdate = $prm["xdate"] ?? null; + $search = $prm["search"] ?? ""; + $search = "%" . trim($search) . "%"; + + $loginLevel = $this->sys_user["loginLevel"]; + $where_conditions = [ + "jurnalIsActive = 'Y'", + "jurnalperiodeID = ?", + "DATE(jurnalDate) = ?", + "jurnalNo LIKE ?", + ]; + $params = [$periodeid, $xdate, $search]; + + // Filter login level + if ($loginLevel == "branch") { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } elseif ($loginLevel == "regional") { + $where_conditions[] = "jurnalS_RegionalID = ?"; + $params[] = $regionalId; + + if (!empty($branchCode)) { + $where_conditions[] = "jurnalM_BranchCode = ?"; + $params[] = $branchCode; + } + } + + // Gabungkan WHERE SQL + $where_sql = implode(" AND ", $where_conditions); + + // SQL utama + $sql = "SELECT + jurnalID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + '' as ErrStatus, + '' as ErrMsg, + '' as detailtx + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'Y' + AND JurnalTypeCode = 'AUTOINVOICE' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE $where_sql + GROUP BY jurnalID + ORDER BY jurnalID DESC + "; + + // Ambil total count + $sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x"; + $qry_total = $this->db->query($sql_total, $params); + + $number_limit = 10; + $current_page = (int) ($prm["current_page"] ?? 1); + $number_offset = max(0, ($current_page - 1) * $number_limit); + + // Hitung total halaman + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->row()->total ?? 0; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db); + exit(); + } + + // Tambahkan LIMIT OFFSET + $sql_paginated = $sql . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry = $this->db->query($sql_paginated, $params_paginated); + + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit(); + } + + foreach ($rows as $key => $value) { + $sql_err = "SELECT JurnalErr_ID, + JurnalErr_Msg + FROM jurnal_errors + WHERE JurnalErr_IsActive = 'Y' + AND JurnalErr_JurnalID = ?"; + $qry_err = $this->db->query($sql_err, [$value["jurnalID"]]); + if (!$qry_err) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal msg error", $this->db); + exit(); + } + + $rows_err = $qry_err->result_array(); + + // Decode JSON di dalam kolom JurnalErr_Msg + foreach ($rows_err as &$row) { + $row["JurnalErr_Msg"] = json_decode($row["JurnalErr_Msg"], true); + } + if (count($rows_err) > 0) { + $rows[$key]["ErrStatus"] = "Y"; + $rows[$key]["ErrMsg"] = $rows_err; + } else { + $rows[$key]["ErrStatus"] = "N"; + $rows[$key]["ErrMsg"] = []; + } + + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + GROUP_CONCAT(jurnalAddOnCode SEPARATOR ', ') as jurnalAddOnCode, + GROUP_CONCAT(jurnalAddOnValue SEPARATOR ' | ') as jurnalAddOnValue, + GROUP_CONCAT(M_ItemDesc SEPARATOR ', ') AS jurnalAddOnItem + FROM jurnal_tx + JOIN coa ON jurnalTxCoaID = coaID AND coaIsActive = 'Y' + LEFT JOIN jurnal_addon ON jurnalTxID = jurnalAddOnJurnalTxID AND jurnalAddOnIsActive = 'Y' + AND (jurnalAddOnCode = 'INVGR') + LEFT JOIN m_item ON M_ItemID = jurnalAddOnM_ItemID + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + GROUP BY jurnalTxID + ORDER BY + CASE + WHEN jurnalTxDebit > 0 THEN 0 + ELSE 1 + END, + jurnalTxID ASC"; + $qry_detail = $this->db->query($sql_detail, [$value["jurnalID"]]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit(); + } + + // echo $this->db->last_query(); + // exit; + + $rows_detail = $qry_detail->result_array(); + if (count($rows_detail) > 0) { + $rows[$key]["detailtx"] = $rows_detail; + } else { + $rows[$key]["detailtx"] = []; + } + } + + $result = [ + "total" => $totalPage, + "totalfilter" => $totalCount, + "records" => $rows, + ]; + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $regionalId = $prm["regionalId"] ?? null; + + $sql = "SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalID = ? + ORDER BY S_RegionalName ASC"; + + $qry = $this->db->query($sql, [$regionalId]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit(); + } + + $rows = $qry->result_array(); + $selected = null; + + // Cari regional yang sesuai dengan regionalId + foreach ($rows as $r) { + if ($r["S_RegionalID"] == $regionalId) { + $selected = $r; + break; + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = isset($prm["regionalId"]) ? $prm["regionalId"] : null; + $branchCode = isset($prm["branchCode"]) ? $prm["branchCode"] : null; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit(); + } + + $rows = $exec->result_array(); + $selected = [ + "M_BranchCode" => "", + "M_BranchName" => "", + ]; + + // Cari regional yang sesuai dengan regionalId + if (!empty($branchCode)) { + foreach ($rows as $r) { + if ($r["M_BranchCode"] == $branchCode) { + $selected = $r; + break; + } + } + } + + $result = [ + "records" => $rows, + "selected" => $selected, + "sql" => $this->db->last_query(), + ]; + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getUserApproveLevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $user = $this->sys_user; + $sql = "SELECT + M_ApproveLevelID, + M_ApproveLevelName, + DivisionID, + DivisionName, + DivisionKodeSurat + FROM m_user + LEFT JOIN m_approve_level ON M_ApproveLevelID = M_UserM_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON DivisionID = M_UserDivisionDivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserID = ?"; + $que = $this->db->query($sql, [$user["M_UserID"]]); + if (!$que) { + $this->sys_error_db("[Error] get user approve level"); + exit(); + } + + $result = $que->row_array(); + if (!$result) { + $result = [ + "M_ApproveLevelID" => 0, + "M_ApproveLevelName" => "", + ]; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListingCOA() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + + $keyword = "%"; + if ($param["keyword"] != "") { + $keyword = $param["keyword"] . "%"; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND coaDescription LIKE ?"; + $que = $this->db->query($sql, [$keyword]); + if (!$que) { + $this->sys_error_db("[Error] get listint account"); + exit(); + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditJurnal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + + $param = $this->sys_input; + $user = $this->sys_user; + + // get current jurnal data + $sql_data = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit + FROM jurnal_tx + WHERE jurnalTxJurnalID = ?"; + $que_current = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_current) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get current jurnal tx data"); + exit(); + } + $curr_jurnal = $que_current->result_array(); + + $sql_header = "UPDATE jurnal SET + jurnalEditStatus = 'Y', + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $que_header = $this->db->query($sql_header, [$param["jurnalID"]]); + if (!$que_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal edit"); + exit(); + } + + $jurnaldetail = $param["jurnaldetail"]; + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y'"; + + foreach ($jurnaldetail as $key => $obj) { + $que = $this->db->query($sql, [ + $obj["coaID"], + $obj["coaDescription"], + $user["M_UserID"], + $obj["jurnalTxID"], + $obj["jurnalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data jurnal tx"); + exit(); + } + } + + // get new jurnal data + $que_latest = $this->db->query($sql_data, [$param["jurnalID"]]); + if (!$que_latest) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest jurnal tx data"); + exit(); + } + $new_jurnal = $que_latest->result_array(); + + $sql_log = "INSERT INTO acc_one_log.jurnal_edit_log ( + JurnalEditLogIDJurnalID, + JurnalEditLogIDJsonBefore, + JurnalEditLogIDJsonAfter, + JurnalEditLogUserID, + JurnalEditLogCreated + ) VALUES (?,?,?,?,NOW())"; + $que_log = $this->db->query($sql_log, [ + $param["jurnalID"], + json_encode($curr_jurnal), + json_encode($new_jurnal), + $user["M_UserID"], + ]); + if (!$que_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into acc one jurnal log"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("success update jurnal"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function changeJurnalToPosted() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sqlbranch = " "; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = " . $user["M_BranchCode"]; + } + + $sql = "UPDATE jurnal SET + jurnalIsPosted = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'N' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $param["periodeID"], + $param["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke posting"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status posting jurnal pada periode ini"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getTotalJurnalNotPostedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + $param = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ) + SELECT + JurnalTypeID, + TS.status AS jurnalEditStatus, + COALESCE(COUNT(J.jurnalEditStatus), 0) AS total_jurnal + FROM TargetStatuses TS + LEFT JOIN jurnal J ON TS.status = J.jurnalEditStatus + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsPosted = 'N' + JOIN jurnal_type ON JurnalTypeID = jurnalJurnalTypeID + AND JurnalTypeCode = 'AUTOINVOICE' + GROUP BY TS.status + ORDER BY TS.status"; + + $que = $this->db->query($sql, [ + $param["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not posted"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function closeJurnalPerPeriode() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $para = $this->sys_input; + $user = $this->sys_user; + + $this->db->trans_begin(); + $sqlbranch = ""; + if ($user["M_BranchID"] != "0") { + $sqlbranch .= " AND jurnalM_BranchCode = '{$user["M_BranchCode"]}'"; + } + + $sql = "UPDATE jurnal SET + jurnalIsClosed = 'Y', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalperiodeID = ? + AND jurnalJurnalTypeID = ? + AND JurnalS_RegionalID = ? + AND jurnalIsPosted = 'Y' + AND jurnalEditStatus = 'N' + AND jurnalIsActive = 'Y'"; + $sql .= $sqlbranch; + $que = $this->db->query($sql, [ + $user["M_UserID"], + $para["periodeID"], + $para["jurnalTypeID"], + $user["S_RegionalID"], + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status jurnal ke closed"); + exit(); + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] update status closed jurnal pada periode ini"); + } catch (Exception $e) { + $message = $e->getMessage(); + $this->sys_error($message); + } + } + + public function getDataJurnalNotClosedPerPeriod() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit(); + } + + $para = $this->sys_input; + $user = $this->sys_user; + + $branchcode = "X"; + if ($user["M_BranchCode"] != "") { + $branchcode = $user["M_BranchCode"]; + } + + $sql = "WITH TargetStatuses AS ( + SELECT 'N' AS status + UNION ALL + SELECT 'Y' AS status + ), + TargetType AS ( + SELECT JurnalTypeID + FROM jurnal_type + WHERE JurnalTypeCode = 'AUTOINVOICE' + ) + SELECT + TT.JurnalTypeID, + TS.status AS jurnalIsPosted, + COUNT(J.jurnalID) AS total_jurnal + FROM TargetStatuses TS + CROSS JOIN TargetType TT + LEFT JOIN jurnal J ON TS.status = J.jurnalIsPosted + AND J.jurnalJurnalTypeID = TT.JurnalTypeID + AND J.jurnalperiodeID = ? + AND J.JurnalS_RegionalID = ? + AND (J.jurnalM_BranchCode = ? OR ? = 'X') + AND J.jurnalIsActive = 'Y' + AND J.jurnalIsClosed = 'N' + GROUP BY TT.JurnalTypeID, TS.status + ORDER BY TS.status"; + $que = $this->db->query($sql, [ + $para["periodeID"], + $user["S_RegionalID"], + $branchcode, + $branchcode, + ]); + if (!$que) { + $this->sys_error_db("[Error] get total jurnal not closed"); + exit(); + } + + $total = $que->result_array(); + $this->sys_ok($total); + } catch (Exception $e) { + $message = $e->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Jurnalbiaya.php b/application/controllers/mockup/masterdata/accounting/Jurnalbiaya.php new file mode 100644 index 0000000..4c30c55 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Jurnalbiaya.php @@ -0,0 +1,1236 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function getuser() + { + echo json_encode($this->sys_user); + } + function saveJurnalBiaya() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $detail = $prm['detail']; + $jurnalRegional = $prm['jurnalRegional']; + $costs = $prm['costs']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + + + + + $kreditTotal = 0; + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $kredit = 0; + $debet = doubleval($value['debet']); + foreach ($detail as $j => $dtl) { + if ($dtl['type'] == 'K' && $value['branchID'] == $dtl['branchID']) { + $kredit = $kredit + doubleval($dtl['kredit']); + } + } + if ($debet != $kredit) { + $this->sys_error("Jumlah debet dan kredit tidak balance di cabang " . $value['branchName'] . "Debet " . strval($debet) . " ,Kredit " . strval($kredit)); + exit; + } + } else if ($value['type'] == 'K') { + $kreditTotal = $kreditTotal + doubleval($value['kredit']); + } + # code... + } + if (doubleval($costs) != $kreditTotal) { + $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . "Total Biaya Per PT " . strval($costs) . " ,Kredit " . strval($kreditTotal)); + exit; + } + + $sql = "INSERT INTO jurnal_biaya_header + (JurnalBiayaHeaderCreatedUserID, + JurnalBiayaHeaderBranchCostPercentID + ) + VALUES(?, ?)"; + $qry = $this->db->query($sql, array($userid, $prm['branchCostPrecenID'])); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya header"); + exit; + } + $insertedJurnalBiayaHeader = $this->db->insert_id(); + // echo ($insertedJurnalBiayaHeader); + // exit; + + //insert jurnal regional + $sql = "SELECT `fn_numbering`('BY') as number"; + $qry = $this->db->query($sql, array()); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get number"); + exit; + } + $numberingCounter = $qry->row_array()['number']; + $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format angka dua digit + $currentYear = date('Y'); // Mendapatkan tahun saat ini + + + $numbering = 'BY/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter); + + $sql = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID) + VALUES(?,?,?,?,?,?,?,?,?,?)"; + $qry = $this->db->query($sql, array( + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + '', + $prm['periodeID'], + $numbering, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnalTypeID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + $insertedJurnalRegID = $this->db->insert_id(); + $sql = "INSERT INTO jurnal_biaya_detail( + JurnalBiayaDetailJurnalBiayaHeaderID, + JurnalBiayaDetailJurnalID, + JurnalBiayaDetailCreatedUserID, + JurnalBiayaDetailType + )VALUES ({$insertedJurnalBiayaHeader},{$insertedJurnalRegID},{$userid}, 'R')"; + $qry = $this->db->query($sql, array()); + if (!$qry) { + // print_r($this->db->last_query()); + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya detail"); + exit; + } + + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID) + VALUES({$insertedJurnalRegID},'ACCOSREG',{$value['coaNo']},NOW(),{$userid});"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya addon regional"); + exit; + } + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,NOW(),?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + 'AMCOSREG', + $prm['costs'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya addon amcos regional"); + exit; + } + + //insert jurnal regional + foreach ($jurnalRegional as $i => $value) { + $kredit = 0; + $debet = doubleval($value['debet']); + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx regional"); + exit; + } + $insertedJurnalTxRegID = $this->db->insert_id(); + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,?,NOW(),?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + $insertedJurnalTxRegID, + 'BYREGBR', + $value['branchID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya detail"); + exit; + } + } + //insert jurnal branch + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $kredit = 0; + $debet = doubleval($value['debet']); + $sql = "SELECT + M_BranchID as branchID, + M_BranchS_RegionalID as branchRegionalID, + M_BranchCode as branchCode , + M_BranchName as branchName, + M_BranchCompanyDetailM_BranchCompanyID branchCompanyID + FROM m_branch + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchID = ?"; + $qry = $this->db->query($sql, array($value['branchID'])); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get branch"); + exit; + } + $dataBranch = $qry->row_array(); + + $sql = "SELECT `fn_numbering`('BY') as number"; + $qry = $this->db->query($sql, array()); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get number"); + exit; + } + $numberingCounter = $qry->row_array()['number']; + $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format string + $currentYear = date('Y'); // Mendapatkan tahun saat ini + + + $numbering = 'BY/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter) . "/" . $dataBranch['branchCode']; + + $sql = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID) + VALUES(?,?,?,?,?,?,?,?,?,?)"; + $qry = $this->db->query($sql, array( + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + $dataBranch['branchCode'], + $prm['periodeID'], + $numbering, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnalTypeID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + $insertedJurnalID = $this->db->insert_id(); + + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx debet"); + exit; + } + $sql = "INSERT INTO jurnal_biaya_detail( + JurnalBiayaDetailJurnalBiayaHeaderID, + JurnalBiayaDetailJurnalID, + JurnalBiayaDetailCreatedUserID, + JurnalBiayaDetailType + )VALUES ({$insertedJurnalBiayaHeader},{$insertedJurnalID},{$userid}, 'B')"; + $qry = $this->db->query($sql, array()); + if (!$qry) { + // print_r($this->db->last_query()); + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya detail"); + exit; + } + + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,NOW(),?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + 'ACCOSREG', + $value['coaNo'], + $userid + )); + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya detail"); + exit; + } + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,NOW(),?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + 'AMCOSREG', + $prm['costs'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal biaya detail"); + exit; + } + + foreach ($detail as $j => $dtl) { + if ($dtl['type'] == 'K' && $value['branchID'] == $dtl['branchID']) { + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + $dtl['coaID'], + $dtl['coaName'], + $dtl['debet'], + $dtl['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx kredit"); + exit; + } + } + } + } + } + $this->db->trans_commit(); + $this->sys_ok('OK'); + } + function getDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + + $sql = "SELECT * + FROM jurnal_biaya_header + JOIN jurnal_biaya_detail + ON JurnalBiayaHeaderID = JurnalBiayaDetailJurnalBiayaHeaderID + AND JurnalBiayaDetailIsActive = 'Y' + AND + JurnalBiayaHeaderID IN + (SELECT JurnalBiayaDetailJurnalBiayaHeaderID FROM jurnal_biaya_detail WHERE JurnalBiayaDetailJurnalID = ?) + AND JurnalBiayaHeaderIsActive = 'Y' + JOIN jurnal + ON JurnalBiayaDetailJurnalID = jurnalID + AND jurnalIsActive = 'Y'"; + $qry = $this->db->query($sql, array($id)); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx kredit"); + exit; + } + $jurnalHeader = $qry->result_array(); + $result = array(); + $type = ''; + $dataHeaderBranch = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalBiayaDetailJurnalID'] == $id) { + $type = $value['JurnalBiayaDetailType']; + $dataHeaderBranch = $value; + } + } + $sql = "SELECT * + FROM branch_cost_percent + WHERE BranchCostPercentID = ? + "; + $qry = $this->db->query($sql, [$dataHeaderBranch['JurnalBiayaHeaderBranchCostPercentID']]); + if (!$qry) { + $this->sys_error_db("Error get branch_cost_percent", $this->db); + exit; + } + $branchCostPercent = $qry->row_array(); + // "companyID": "1", + // "regionalID": "1", + // "jurnalTypeID": "1", + // "date": "2025-01-15", + // "periodeID": "4", + // "title": "JURNAL GAJI REGIONAL 2025 COBA", + // "coaID": "881", + // "coaName": "BIAYA GAJI TENAGA TEHNIS - REGIONAL", + // "coaNo": "51102", + // "coaKasID": "6", + // "coaKasName": "BANK", + // "coaKasNo": "11102", + // "sallary": "100000000", + // "description": "", + // "branchPrecenID": "1", + $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' AND JurnalTypeID = ? + "; + $qry = $this->db->query($sql, [$jurnalHeader[0]['jurnalJurnalTypeID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal Type"); + exit; + } + $jurnalType = $qry->row_array(); + $date = $jurnalHeader[0]['jurnalDate']; + $title = $jurnalHeader[0]['jurnalTitle']; + $description = $jurnalHeader[0]['jurnalDescription']; + $costs = 0; + $coaBank = (object) []; + $coaReg = (object) []; + $coa = (object) []; + $jurnalRegional = []; + $jurnalBranch = []; + + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeID = ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$jurnalHeader[0]['jurnalperiodeID']]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $jurnalPeriode = $qry->row_array(); + if ($type == 'R') { + $dataJurnalRegional = array(); + $arrJurnalBranchID = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalBiayaDetailType'] == 'R') { + $dataJurnalRegional = $value; + } + if ($value['JurnalBiayaDetailType'] == 'B') { + $arrJurnalBranchID[] = $value['JurnalBiayaDetailJurnalID']; + } + } + + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID = ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN jurnal_addon + ON jurnalAddOnJurnalID = jurnalID + AND jurnalAddOnJurnalTxID = jurnalTxID + AND jurnalAddOnCode = 'BYREGBR' + LEFT JOIN m_branch + ON jurnalAddOnValue = M_BranchID + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$dataJurnalRegional['JurnalBiayaDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx regional"); + exit; + } + $jurnalRegional = $qry->result_array(); + + foreach ($jurnalRegional as $key => $value) { + if (intval($value['kredit']) > 0) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + $coaBank = $qry->row_array(); + } + } + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID IN ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$arrJurnalBranchID]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx cabang"); + exit; + } + $jurnalBranch = $qry->result_array(); + + foreach ($jurnalBranch as $key => $value) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + if (intval($value['debet']) > 0) { + $coa = $qry->row_array(); + } else { + $coaReg = $qry->row_array(); + } + } + + $sql = "SELECT jurnalAddOnJurnalID, + jurnalAddOnValue + FROM jurnal_addon + WHERE jurnalAddOnJurnalID = ? + AND jurnalAddOnCode = 'AMCOSREG' + AND jurnalAddOnIsActive = 'Y';"; + $qry = $this->db->query($sql, [$dataJurnalRegional['JurnalBiayaDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx", $this->db); + exit; + } + $costs = $qry->row_array()['jurnalAddOnValue']; + } else if ($type == 'B') { + $jurnalRegional = []; + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID = ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$dataHeaderBranch['JurnalBiayaDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx cabang"); + exit; + } + $jurnalBranch = $qry->result_array(); + foreach ($jurnalBranch as $key => $value) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + + if (intval($value['debet']) > 0) { + $coa = $qry->row_array(); + } else { + $coaReg = $qry->row_array(); + } + + // break; + } + $coaBank = (object) []; + } + $result = array( + 'dataHeader' => $dataHeaderBranch, + "type" => $type, + "date" => $date, + "periode" => $jurnalPeriode, + "title" => $title, + "coa" => $coa, + "coaKas" => $coaBank, + "coaReg" => $coaReg, + "costs" => $costs, + "description" => $description, + "branchPrecent" => $branchCostPercent, + "jurnalDetail" => $jurnalBranch, + "jurnalDetailRegional" => $jurnalRegional, + ); + $this->sys_ok($result); + } + function deleteJurnalBiaya() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + + $sql = "SELECT * + FROM jurnal_biaya_header + JOIN jurnal_biaya_detail + ON JurnalBiayaHeaderID = JurnalBiayaDetailJurnalBiayaHeaderID + AND JurnalBiayaDetailIsActive = 'Y' + AND + JurnalBiayaHeaderID IN + (SELECT JurnalBiayaDetailJurnalBiayaHeaderID FROM jurnal_biaya_detail WHERE JurnalBiayaDetailJurnalID = ?) + AND JurnalBiayaHeaderIsActive = 'Y' + JOIN jurnal + ON JurnalBiayaDetailJurnalID = jurnalID + AND jurnalIsActive = 'Y'"; + $qry = $this->db->query($sql, array($id)); + if (!$qry) { + $this->sys_error_db("Error insert jurnal tx kredit"); + $this->db->trans_rollback(); + exit; + } + $jurnalHeader = $qry->result_array(); + $result = array(); + $type = ''; + $dataHeaderBranch = array(); + $arrJurnalID = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalBiayaDetailJurnalID'] == $id) { + $type = $value['JurnalBiayaDetailType']; + $dataHeaderBranch = $value; + } + $arrJurnalID[] = $value['jurnalID']; + if ($value['jurnalIsPosted'] == 'Y') { + $this->sys_error('Jurnal yang sudah di post tidak bisa di hapus'); + exit; + } + } + // echo json_encode($jurnalHeader); + // exit; + + if ($type == 'B') { + $this->sys_error('Menghapus data harus melalui jurnal regionalnya'); + exit; + } + + $sql = "UPDATE jurnal_biaya_header + SET JurnalBiayaHeaderIsActive = 'N', + JurnalBiayaHeaderDeletedUserID = ? + WHERE + JurnalBiayaHeaderID = ?"; + $qry = $this->db->query($sql, array($userid, $dataHeaderBranch['JurnalBiayaHeaderID'])); + if (!$qry) { + $this->sys_error_db("Error delet jurnal biaya header"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_biaya_detail + SET JurnalBiayaDetailIsActive = 'N', + JurnalBiayaDetailDeletedUserID = ? + WHERE + JurnalBiayaDetailJurnalBiayaHeaderID = ?"; + $qry = $this->db->query($sql, array($userid, $dataHeaderBranch['JurnalBiayaHeaderID'])); + if (!$qry) { + $this->sys_error_db("Error delet jurnal biaya detail"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal + SET jurnalIsActive = 'N', + jurnalM_UserID = ? + WHERE + jurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal biaya"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_tx + SET jurnalTxIsActive = 'N', + jurnalTxM_UserID = ? + WHERE + jurnalTxJurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal biaya tx"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_addon + SET jurnalAddOnIsActive = 'N', + jurnalAddOnDeletedUserID = ? + WHERE + jurnalAddOnJurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal biaya tx"); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok('Success delete jurnal biaya'); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70 + + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function searchCoaDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $regional = $prm['regional']; + $branch = $prm['branch']; + $company = $prm['company']; + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + JOIN coa_branch + ON coaID = CoaBranchCoaID + AND CoaBranchIsActive = 'Y' + JOIN m_branch + ON CoaBranchM_BranchID = M_BranchID + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchS_RegionalID = ? + AND M_BranchCompanyDetailIsActive = 'Y' + AND M_BranchCompanyDetailM_BranchCompanyID = ? + AND M_BranchIsActive = 'Y' + AND M_BranchID = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70 + + "; + $qry = $this->db->query($sql, [$regional, $company, $branch, $search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function searchBranchPercent() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $regional = $prm['regional']; + $sql = "SELECT * + FROM branch_cost_percent + JOIN branch_cost_percent_detail + ON BranchCostPercentID = BranchCostPercentDetailBranchCostPercentID + AND BranchCostPercentIsActive = 'Y' + AND BranchCostPercentDetailIsActive = 'Y' + AND BranchCostPercentDetailS_RegionalID = ? + JOIN coa + ON BranchCostPercentDetailAccountNumber = coaAccountNo + AND coaIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$regional]); + if (!$qry) { + $this->sys_error_db("Error get branch cost percent", $this->db); + exit; + } + $data = $qry->result_array(); + // echo (json_encode($data)); + + $tmpID = array(); + $rst = array(); + foreach ($data as $key => $value) { + if (!in_array($value['BranchCostPercentID'], $tmpID)) { + $tmpID[] = $value['BranchCostPercentID']; + $rst[] = $value; + } + } + // echo (json_encode($rst)); + $tmpDetail = array(); + foreach ($rst as $i => $value) { + foreach ($data as $j => $detail) { + if ( + !in_array($detail['BranchCostPercentDetailID'], $tmpDetail) + && $detail['BranchCostPercentDetailBranchCostPercentID'] == $value['BranchCostPercentID'] + ) { + $tmpDetail[] = $detail['BranchCostPercentDetailID']; + $rst[$i]['detail'][] = $detail; + # code... + } + } + } + $this->sys_ok($rst); + } + function searchPeriode() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + AND CONCAT(periodeYear, ' - ', periodeName) LIKE ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getBranch() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT + M_BranchID as branchID, + M_BranchS_RegionalID as branchRegionalID, + M_BranchCode as branchCode , + M_BranchName as branchName, + M_BranchCompanyDetailM_BranchCompanyID branchCompanyID + FROM m_branch + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchS_RegionalID = ? + AND M_BranchCompanyDetailIsActive = 'Y' + AND M_BranchCompanyDetailM_BranchCompanyID = ? + AND M_BranchIsActive = 'Y'"; + $qry = $this->db->query($sql, array($prm['regional'], $prm['company'])); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get branch"); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getJurnalType() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $default = array(); + $data = $qry->result_array(); + foreach ($data as $key => $value) { + if ($value['JurnalTypeCode'] == 'COSTREG') { + $default = $value; + } + } + $this->sys_ok([ + "records" => $data, + "default" => $default + ]); + } + function insertTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + $sql = "SELECT fn_numbering('RJT') as number + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get number", $this->db); + exit; + } + $number = $qry->row_array()['number']; + $sql = "INSERT INTO t_recrusivejurnaltemplate( + T_RecrusiveJurnalTemplateNumber, + T_RecrusiveJurnalTemplateStartDate, + T_RecrusiveJurnalTemplateEndDate, + T_RecrusiveJurnalTemplateTenor, + T_RecrusiveJurnalTemplatePrePaid, + T_RecrusiveJurnalTemplateCreditCoaID, + T_RecrusiveJurnalTemplateDebetCoaID, + T_RecrusiveJurnalTemplateMonthly, + T_RecrusiveJurnalTemplateCreatedUserID, + T_RecrusiveJurnalTemplateCreated + ) + VALUES(?, + ?,?,?,?,?,?,?,?,NOW() + )"; + $qry = $this->db->query($sql, [ + $number, + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error Insert Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success tambah data"); + } + function updateTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $id = $prm['id']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateStartDate = ?, + T_RecrusiveJurnalTemplateEndDate = ?, + T_RecrusiveJurnalTemplateTenor = ?, + T_RecrusiveJurnalTemplatePrePaid = ?, + T_RecrusiveJurnalTemplateCreditCoaID = ?, + T_RecrusiveJurnalTemplateDebetCoaID = ?, + T_RecrusiveJurnalTemplateMonthly = ?, + T_RecrusiveJurnalTemplateLastUpdatedUserID = '{$userid}', + T_RecrusiveJurnalTemplateLastUpdated = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $id + ]); + if (!$qry) { + $this->sys_error_db("Error Update Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success update data"); + } + function deleteTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + + $id = $prm['id']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateIsActive = 'N', + T_RecrusiveJurnalTemplateDeletedUserID = '{$userid}', + T_RecrusiveJurnalTemplateDeleted = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $id + ]); + if (!$qry) { + $this->sys_error_db("Error delete Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success delete data"); + } + function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + + $ROW_PER_PAGE = 5; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sql = "SELECT + COUNT(T_RecrusiveJurnalTemplateID) as total + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + "; + $qry = $this->db->query($sql, [ + $search, + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $total = $qry->row_array()['total']; + $sql = "SELECT + T_RecrusiveJurnalTemplateID as id, + c.coaID as creditCoaID, + CONCAT(c.coaAccountNo, '-' ,c.coaDescription) as creditName, + d.coaID as debitCoaID, + CONCAT(d.coaAccountNo, '-' ,d.coaDescription) as debitName, + T_RecrusiveJurnalTemplateNumber as number, + T_RecrusiveJurnalTemplatePrePaid as prePaid, + DATE_FORMAT(T_RecrusiveJurnalTemplateStartDate , '%d-%m-%Y') as startDate, + T_RecrusiveJurnalTemplateStartDate as startDateVal, + DATE_FORMAT(T_RecrusiveJurnalTemplateEndDate, '%d-%m-%Y') as endDate, + T_RecrusiveJurnalTemplateEndDate as endDateVal, + T_RecrusiveJurnalTemplateTenor as tenor, + T_RecrusiveJurnalTemplateMonthly as bulanan + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $search, + $ROW_PER_PAGE, + $start_offset + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $rst = array( + "total" => ceil($total / $ROW_PER_PAGE), + "records" => $qry->result_array() + ); + $this->sys_ok($rst); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Jurnalgaji.php b/application/controllers/mockup/masterdata/accounting/Jurnalgaji.php new file mode 100644 index 0000000..b5d9743 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Jurnalgaji.php @@ -0,0 +1,1228 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function getuser() + { + echo json_encode($this->sys_user); + } + function saveJurnalGaji() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $detail = $prm['detail']; + $jurnalRegional = $prm['jurnalRegional']; + $sallary = $prm['sallary']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + + + + + $kreditTotal = 0; + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $kredit = 0; + $debet = doubleval($value['debet']); + foreach ($detail as $j => $dtl) { + if ($dtl['type'] == 'K' && $value['branchID'] == $dtl['branchID']) { + $kredit = $kredit + doubleval($dtl['kredit']); + } + } + if ($debet != $kredit) { + $this->sys_error("Jumlah debet dan kredit tidak balance di cabang " . $value['branchName'] . "Debet " . strval($debet) . " ,Kredit " . strval($kredit)); + exit; + } + } else if ($value['type'] == 'K') { + $kreditTotal = $kreditTotal + doubleval($value['kredit']); + } + # code... + } + if (doubleval($sallary) != $kreditTotal) { + $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . "Total Gaji Per PT " . strval($sallary) . " ,Kredit " . strval($kreditTotal)); + exit; + } + + $sql = "INSERT INTO jurnal_gaji_header + (JurnalGajiHeaderCreatedUserID, + JurnalGajiHeaderBranchPercentID + ) + VALUES(?, ?)"; + $qry = $this->db->query($sql, array($userid, $prm['branchPrecenID'])); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji header"); + exit; + } + $insertedJurnalGajiHeader = $this->db->insert_id(); + // echo ($insertedJurnalGajiHeader); + // exit; + + //insert jurnal regional + $sql = "SELECT `fn_numbering`('GJ') as number"; + $qry = $this->db->query($sql, array()); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get number"); + exit; + } + $numberingCounter = $qry->row_array()['number']; + $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format angka dua digit + $currentYear = date('Y'); // Mendapatkan tahun saat ini + + + $numbering = 'GJ/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter); + + $sql = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID) + VALUES(?,?,?,?,?,?,?,?,?,?)"; + $qry = $this->db->query($sql, array( + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + '', + $prm['periodeID'], + $numbering, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnalTypeID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + $insertedJurnalRegID = $this->db->insert_id(); + $sql = "INSERT INTO jurnal_gaji_detail( + JurnalGajiDetailJurnalGajiHeaderID, + JurnalGajiDetailJurnalID, + JurnalGajiDetailCreatedUserID, + JurnalGajiDetailType + )VALUES ({$insertedJurnalGajiHeader},{$insertedJurnalRegID},{$userid}, 'R')"; + $qry = $this->db->query($sql, array()); + if (!$qry) { + // print_r($this->db->last_query()); + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji detail"); + exit; + } + + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES({$insertedJurnalRegID},'ACSALREG',{$value['coaNo']},{$userid});"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji addon regional"); + exit; + } + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + 'AMSALREG', + $prm['sallary'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji addon amsal regional"); + exit; + } + + //insert jurnal regional + foreach ($jurnalRegional as $i => $value) { + $kredit = 0; + $debet = doubleval($value['debet']); + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx regional"); + exit; + } + $insertedJurnalTxRegID = $this->db->insert_id(); + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,?,?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + $insertedJurnalTxRegID, + 'GJREGBR', + $value['branchID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji detail"); + exit; + } + } + //insert jurnal branch + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $kredit = 0; + $debet = doubleval($value['debet']); + $sql = "SELECT + M_BranchID as branchID, + M_BranchS_RegionalID as branchRegionalID, + M_BranchCode as branchCode , + M_BranchName as branchName, + M_BranchCompanyDetailM_BranchCompanyID branchCompanyID + FROM m_branch + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchID = ?"; + $qry = $this->db->query($sql, array($value['branchID'])); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get branch"); + exit; + } + $dataBranch = $qry->row_array(); + + $sql = "SELECT `fn_numbering`('GJ') as number"; + $qry = $this->db->query($sql, array()); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get number"); + exit; + } + $numberingCounter = $qry->row_array()['number']; + $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format string + $currentYear = date('Y'); // Mendapatkan tahun saat ini + + + $numbering = 'GJ/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter) . "/" . $dataBranch['branchCode']; + + $sql = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID) + VALUES(?,?,?,?,?,?,?,?,?,?)"; + $qry = $this->db->query($sql, array( + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + $dataBranch['branchCode'], + $prm['periodeID'], + $numbering, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnalTypeID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + $insertedJurnalID = $this->db->insert_id(); + + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx debet"); + exit; + } + $sql = "INSERT INTO jurnal_gaji_detail( + JurnalGajiDetailJurnalGajiHeaderID, + JurnalGajiDetailJurnalID, + JurnalGajiDetailCreatedUserID, + JurnalGajiDetailType + )VALUES ({$insertedJurnalGajiHeader},{$insertedJurnalID},{$userid}, 'B')"; + $qry = $this->db->query($sql, array()); + if (!$qry) { + // print_r($this->db->last_query()); + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji detail"); + exit; + } + + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + 'ACSALREG', + $value['coaNo'], + $userid + )); + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji detail"); + exit; + } + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES(?,?,?,?) + "; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + 'AMSALREG', + $prm['sallary'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji detail"); + exit; + } + + foreach ($detail as $j => $dtl) { + if ($dtl['type'] == 'K' && $value['branchID'] == $dtl['branchID']) { + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalID, + $dtl['coaID'], + $dtl['coaName'], + $dtl['debet'], + $dtl['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx kredit"); + exit; + } + } + } + } + } + $this->db->trans_commit(); + $this->sys_ok('OK'); + } + function getDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + + $sql = "SELECT * + FROM jurnal_gaji_header + JOIN jurnal_gaji_detail + ON JurnalGajiHeaderID = JurnalGajiDetailJurnalGajiHeaderID + AND JurnalGajiDetailIsActive = 'Y' + AND + JurnalGajiHeaderID IN + (SELECT JurnalGajiDetailJurnalGajiHeaderID FROM jurnal_gaji_detail WHERE JurnalGajiDetailJurnalID = ?) + AND JurnalGajiHeaderIsActive = 'Y' + JOIN jurnal + ON JurnalGajiDetailJurnalID = jurnalID + AND jurnalIsActive = 'Y'"; + $qry = $this->db->query($sql, array($id)); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx kredit"); + exit; + } + $jurnalHeader = $qry->result_array(); + $result = array(); + $type = ''; + $dataHeaderBranch = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalGajiDetailJurnalID'] == $id) { + $type = $value['JurnalGajiDetailType']; + $dataHeaderBranch = $value; + } + } + $sql = "SELECT * + FROM branch_percent + WHERE BranchPercentID = ? + "; + $qry = $this->db->query($sql, [$dataHeaderBranch['JurnalGajiHeaderBranchPercentID']]); + if (!$qry) { + $this->sys_error_db("Error get branch_percent", $this->db); + exit; + } + $branchPercent = $qry->row_array(); + // "companyID": "1", + // "regionalID": "1", + // "jurnalTypeID": "1", + // "date": "2025-01-15", + // "periodeID": "4", + // "title": "JURNAL GAJI REGIONAL 2025 COBA", + // "coaID": "881", + // "coaName": "BIAYA GAJI TENAGA TEHNIS - REGIONAL", + // "coaNo": "51102", + // "coaKasID": "6", + // "coaKasName": "BANK", + // "coaKasNo": "11102", + // "sallary": "100000000", + // "description": "", + // "branchPrecenID": "1", + $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' AND JurnalTypeID = ? + "; + $qry = $this->db->query($sql, [$jurnalHeader[0]['jurnalJurnalTypeID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal Type"); + exit; + } + $jurnalType = $qry->row_array(); + $date = $jurnalHeader[0]['jurnalDate']; + $title = $jurnalHeader[0]['jurnalTitle']; + $description = $jurnalHeader[0]['jurnalDescription']; + $sallary = 0; + $coaBank = (object) []; + $coa = (object) []; + $coaReg = (object) []; + $jurnalRegional = []; + $jurnalBranch = []; + + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeID = ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$jurnalHeader[0]['jurnalperiodeID']]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $jurnalPeriode = $qry->row_array(); + if ($type == 'R') { + $dataJurnalRegional = array(); + $arrJurnalBranchID = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalGajiDetailType'] == 'R') { + $dataJurnalRegional = $value; + } + if ($value['JurnalGajiDetailType'] == 'B') { + $arrJurnalBranchID[] = $value['JurnalGajiDetailJurnalID']; + } + } + + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID = ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN jurnal_addon + ON jurnalAddOnJurnalID = jurnalID + AND jurnalAddOnJurnalTxID = jurnalTxID + AND jurnalAddOnCode = 'GJREGBR' + LEFT JOIN m_branch + ON jurnalAddOnValue = M_BranchID + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$dataJurnalRegional['JurnalGajiDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx regional"); + exit; + } + $jurnalRegional = $qry->result_array(); + + foreach ($jurnalRegional as $key => $value) { + if (intval($value['kredit']) > 0) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + $coaBank = $qry->row_array(); + } + } + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID IN ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$arrJurnalBranchID]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx cabang"); + exit; + } + $jurnalBranch = $qry->result_array(); + + foreach ($jurnalBranch as $key => $value) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + if (intval($value['debet']) > 0) { + $coa = $qry->row_array(); + } else { + $coaReg = $qry->row_array(); + } + } + + $sql = "SELECT jurnalAddOnJurnalID, + jurnalAddOnValue + FROM jurnal_addon + WHERE jurnalAddOnJurnalID = ? + AND jurnalAddOnCode = 'AMSALREG' + AND jurnalAddOnIsActive = 'Y';"; + $qry = $this->db->query($sql, [$dataJurnalRegional['JurnalGajiDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx", $this->db); + exit; + } + $sallary = $qry->row_array()['jurnalAddOnValue']; + } else if ($type == 'B') { + $jurnalRegional = []; + $sql = "SELECT + jurnalTxID as id, + IFNULL(M_BranchID, '') as branchID, + IFNULL(M_BranchName, '') as branchName, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + 0 as precentage, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + jurnalID + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID = ? + LEFT JOIN jurnal + ON JurnalID = jurnalTxJurnalID + LEFT JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$dataHeaderBranch['JurnalGajiDetailJurnalID']]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx cabang"); + exit; + } + $jurnalBranch = $qry->result_array(); + foreach ($jurnalBranch as $key => $value) { + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + -- AND coaIsInput = 'Y' + AND coaID = ? + "; + $qry = $this->db->query($sql, [$value['coaID']]); + if (!$qry) { + $this->sys_error_db("Error get coa"); + exit; + } + if (intval($value['debet']) > 0) { + $coa = $qry->row_array(); + } else { + $coaReg = $qry->row_array(); + } + } + $coaBank = (object) []; + } + $result = array( + 'dataHeader' => $dataHeaderBranch, + "type" => $type, + "date" => $date, + "periode" => $jurnalPeriode, + "title" => $title, + "coa" => $coa, + "coaKas" => $coaBank, + "coaReg" => $coaReg, + "sallary" => $sallary, + "description" => $description, + "branchPrecent" => $branchPercent, + "jurnalDetail" => $jurnalBranch, + "jurnalDetailRegional" => $jurnalRegional, + ); + $this->sys_ok($result); + } + function deleteJurnalgaji() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + + $sql = "SELECT * + FROM jurnal_gaji_header + JOIN jurnal_gaji_detail + ON JurnalGajiHeaderID = JurnalGajiDetailJurnalGajiHeaderID + AND JurnalGajiDetailIsActive = 'Y' + AND + JurnalGajiHeaderID IN + (SELECT JurnalGajiDetailJurnalGajiHeaderID FROM jurnal_gaji_detail WHERE JurnalGajiDetailJurnalID = ?) + AND JurnalGajiHeaderIsActive = 'Y' + JOIN jurnal + ON JurnalGajiDetailJurnalID = jurnalID + AND jurnalIsActive = 'Y'"; + $qry = $this->db->query($sql, array($id)); + if (!$qry) { + $this->sys_error_db("Error insert jurnal tx kredit"); + $this->db->trans_rollback(); + exit; + } + $jurnalHeader = $qry->result_array(); + $result = array(); + $type = ''; + $dataHeaderBranch = array(); + $arrJurnalID = array(); + foreach ($jurnalHeader as $key => $value) { + if ($value['JurnalGajiDetailJurnalID'] == $id) { + $type = $value['JurnalGajiDetailType']; + $dataHeaderBranch = $value; + } + $arrJurnalID[] = $value['jurnalID']; + if ($value['jurnalIsPosted'] == 'Y') { + $this->sys_error('Jurnal yang sudah di post tidak bisa di hapus'); + exit; + } + } + // echo json_encode($jurnalHeader); + // exit; + + if ($type == 'B') { + $this->sys_error('Menghapus data harus melalui jurnal regionalnya'); + exit; + } + + $sql = "UPDATE jurnal_gaji_header + SET JurnalGajiHeaderIsActive = 'N', + JurnalGajiHeaderDeletedUserID = ? + WHERE + JurnalGajiHeaderID = ?"; + $qry = $this->db->query($sql, array($userid, $dataHeaderBranch['JurnalGajiHeaderID'])); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji header"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_gaji_detail + SET JurnalGajiDetailIsActive = 'N', + JurnalGajiDetailDeletedUserID = ? + WHERE + JurnalGajiDetailJurnalGajiHeaderID = ?"; + $qry = $this->db->query($sql, array($userid, $dataHeaderBranch['JurnalGajiHeaderID'])); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji detail"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal + SET jurnalIsActive = 'N', + jurnalM_UserID = ? + WHERE + jurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_tx + SET jurnalTxIsActive = 'N', + jurnalTxM_UserID = ? + WHERE + jurnalTxJurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji tx"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_addon + SET jurnalAddOnIsActive = 'N', + jurnalAddOnDeletedUserID = ? + WHERE + jurnalAddOnJurnalID IN ?"; + $qry = $this->db->query($sql, array($userid, $arrJurnalID)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji tx"); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok('Success delete jurnal gaji'); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70 + + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function searchCoaDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $regional = $prm['regional']; + $branch = $prm['branch']; + $company = $prm['company']; + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + JOIN coa_branch + ON coaID = CoaBranchCoaID + AND CoaBranchIsActive = 'Y' + JOIN m_branch + ON CoaBranchM_BranchID = M_BranchID + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchS_RegionalID = ? + AND M_BranchCompanyDetailIsActive = 'Y' + AND M_BranchCompanyDetailM_BranchCompanyID = ? + AND M_BranchIsActive = 'Y' + AND M_BranchID = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70 + + "; + $qry = $this->db->query($sql, [$regional, $company, $branch, $search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function searchBranchPercent() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $regional = $prm['regional']; + $sql = "SELECT * + FROM branch_percent + JOIN branch_percent_detail + ON BranchPercentID = BranchPercentDetailBranchPercentID + AND BranchPercentIsActive = 'Y' + AND BranchPercentDetailIsActive = 'Y' + AND BranchPercentDetailS_RegionalID = ? + JOIN coa + ON BranchPercentDetailAccountNumber = coaAccountNo + AND coaIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$regional]); + if (!$qry) { + $this->sys_error_db("Error get branch_percent", $this->db); + exit; + } + $data = $qry->result_array(); + // echo (json_encode($data)); + + $tmpID = array(); + $rst = array(); + foreach ($data as $key => $value) { + if (!in_array($value['BranchPercentID'], $tmpID)) { + $tmpID[] = $value['BranchPercentID']; + $rst[] = $value; + } + } + // echo (json_encode($rst)); + $tmpDetail = array(); + foreach ($rst as $i => $value) { + foreach ($data as $j => $detail) { + if ( + !in_array($detail['BranchPercentDetailID'], $tmpDetail) + && $detail['BranchPercentDetailBranchPercentID'] == $value['BranchPercentID'] + ) { + $tmpDetail[] = $detail['BranchPercentDetailID']; + $rst[$i]['detail'][] = $detail; + # code... + } + } + } + $this->sys_ok($rst); + } + function searchPeriode() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + AND CONCAT(periodeYear, ' - ', periodeName) LIKE ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getBranch() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT + M_BranchID as branchID, + M_BranchS_RegionalID as branchRegionalID, + M_BranchCode as branchCode , + M_BranchName as branchName, + M_BranchCompanyDetailM_BranchCompanyID branchCompanyID + FROM m_branch + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchS_RegionalID = ? + AND M_BranchCompanyDetailIsActive = 'Y' + AND M_BranchCompanyDetailM_BranchCompanyID = ? + AND M_BranchIsActive = 'Y'"; + $qry = $this->db->query($sql, array($prm['regional'], $prm['company'])); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get branch"); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getJurnalType() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $default = array(); + $data = $qry->result_array(); + foreach ($data as $key => $value) { + if ($value['JurnalTypeCode'] == 'SALARYREG') { + $default = $value; + } + } + $this->sys_ok([ + "records" => $data, + "default" => $default + ]); + } + function insertTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + $sql = "SELECT fn_numbering('RJT') as number + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get number", $this->db); + exit; + } + $number = $qry->row_array()['number']; + $sql = "INSERT INTO t_recrusivejurnaltemplate( + T_RecrusiveJurnalTemplateNumber, + T_RecrusiveJurnalTemplateStartDate, + T_RecrusiveJurnalTemplateEndDate, + T_RecrusiveJurnalTemplateTenor, + T_RecrusiveJurnalTemplatePrePaid, + T_RecrusiveJurnalTemplateCreditCoaID, + T_RecrusiveJurnalTemplateDebetCoaID, + T_RecrusiveJurnalTemplateMonthly, + T_RecrusiveJurnalTemplateCreatedUserID, + T_RecrusiveJurnalTemplateCreated + ) + VALUES(?, + ?,?,?,?,?,?,?,?,NOW() + )"; + $qry = $this->db->query($sql, [ + $number, + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error Insert Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success tambah data"); + } + function updateTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $id = $prm['id']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateStartDate = ?, + T_RecrusiveJurnalTemplateEndDate = ?, + T_RecrusiveJurnalTemplateTenor = ?, + T_RecrusiveJurnalTemplatePrePaid = ?, + T_RecrusiveJurnalTemplateCreditCoaID = ?, + T_RecrusiveJurnalTemplateDebetCoaID = ?, + T_RecrusiveJurnalTemplateMonthly = ?, + T_RecrusiveJurnalTemplateLastUpdatedUserID = '{$userid}', + T_RecrusiveJurnalTemplateLastUpdated = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $id + ]); + if (!$qry) { + $this->sys_error_db("Error Update Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success update data"); + } + function deleteTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + + $id = $prm['id']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateIsActive = 'N', + T_RecrusiveJurnalTemplateDeletedUserID = '{$userid}', + T_RecrusiveJurnalTemplateDeleted = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $id + ]); + if (!$qry) { + $this->sys_error_db("Error delete Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success delete data"); + } + function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + + $ROW_PER_PAGE = 5; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sql = "SELECT + COUNT(T_RecrusiveJurnalTemplateID) as total + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + "; + $qry = $this->db->query($sql, [ + $search, + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $total = $qry->row_array()['total']; + $sql = "SELECT + T_RecrusiveJurnalTemplateID as id, + c.coaID as creditCoaID, + CONCAT(c.coaAccountNo, '-' ,c.coaDescription) as creditName, + d.coaID as debitCoaID, + CONCAT(d.coaAccountNo, '-' ,d.coaDescription) as debitName, + T_RecrusiveJurnalTemplateNumber as number, + T_RecrusiveJurnalTemplatePrePaid as prePaid, + DATE_FORMAT(T_RecrusiveJurnalTemplateStartDate , '%d-%m-%Y') as startDate, + T_RecrusiveJurnalTemplateStartDate as startDateVal, + DATE_FORMAT(T_RecrusiveJurnalTemplateEndDate, '%d-%m-%Y') as endDate, + T_RecrusiveJurnalTemplateEndDate as endDateVal, + T_RecrusiveJurnalTemplateTenor as tenor, + T_RecrusiveJurnalTemplateMonthly as bulanan + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $search, + $ROW_PER_PAGE, + $start_offset + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $rst = array( + "total" => ceil($total / $ROW_PER_PAGE), + "records" => $qry->result_array() + ); + $this->sys_ok($rst); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Jurnalpengeluaranbarang.php b/application/controllers/mockup/masterdata/accounting/Jurnalpengeluaranbarang.php new file mode 100644 index 0000000..640107e --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Jurnalpengeluaranbarang.php @@ -0,0 +1,361 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + periodeStartDate, + periodeEndDate, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND (periodeYear LIKE ? OR periodeName LIKE ?)"; + $query = $this->db->query($sql, [$search, $search]); + if (!$query) { + $this->sys_error_db("error get periode", $this->db); + exit; + } + + $rows = $query->result_array(); + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } + + function searchcoa() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + + $rows = $qry->result_array(); + $result = array( + "records" => $rows, + "total" => sizeof($rows) + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } + + function simpanjurnal() { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $user = $this->sys_user; + $userid = $user['M_UserID']; + $prm = $this->sys_input; + + // get jurnal number + $sql_no = "SELECT `fn_numbering`('PBC') as no_jurnal"; + $qry_no = $this->db->query($sql_no, []); + if (!$qry_no) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get no jurnal"); + exit; + } + $numbering = $qry_no->row_array()['no_jurnal']; + $currMonth = date('m'); + $currYear = date('Y'); + + $no_jurnal = 'PBC/' . $currYear . '/' . $currMonth . '/' . strval($numbering); + + $sql_jurnal = "INSERT INTO jurnal( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalCreated, + jurnalM_UserID + ) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?)"; + $qry_jurnal = $this->db->query($sql_jurnal, [ + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + $user['M_BranchCode'], + $prm['periodeid'], + $no_jurnal, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnaltypeid'], + $userid + ]); + if (!$qry_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal ", $this->db); + exit; + } + $lastJurnalInserted = $this->db->insert_id(); + + $sql_addon = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID + ) VALUES ({$lastJurnalInserted}, 'OGB', '{$user['M_BranchCode']}', NOW(),{$userid});"; + $qry_addon = $this->db->query($sql_addon, []); + if (!$qry_addon) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert jurnal_addon ", $this->db); + exit; + } + + $detail = $prm["detail"]; + foreach ($detail as $key => $value) { + $sql_tx = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxCreated, + jurnalTxM_UserID + ) VALUES (?,?,?,?,?,NOW(),?)"; + $qry_tx = $this->db->query($sql_tx, [ + $lastJurnalInserted, + $value["coaid"], + $value["coadesc"], + $value["debet"], + $value["kredit"], + $userid + ]); + if (!$qry_tx) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert jurnal_tx ", $this->db); + exit; + } + } + $this->db->trans_commit(); + $this->sys_ok("success"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editjurnal() { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $user = $this->sys_user; + $userid = $user['M_UserID']; + $prm = $this->sys_input; + $jurnalid = $prm["jurnalid"]; + + $sql_jurnal = "UPDATE jurnal SET + jurnalperiodeID = ?, + jurnalTitle = ?, + jurnalDescription = ?, + jurnalDate = ?, + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ? + "; + $qry_jurnal = $this->db->query($sql_jurnal, [ + $prm["periodeid"], + $prm["title"], + $prm["description"], + $prm["date"], + $userid, + $jurnalid + ]); + if (!$qry_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("error update jurnal"); + exit; + } + + $sql_n = "UPDATE jurnal_tx SET jurnalTxIsActive = 'N' WHERE jurnalTxJurnalID = ?"; + $qry_n = $this->db->query($sql_n, [$jurnalid]); + if (!$qry_n) { + $this->db->trans_rollback(); + $this->sys_error_db("error update non active jurnal tx"); + exit; + } + + $detail = $prm["detail"]; + foreach ($detail as $key => $value) { + $sql_tx = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxCreated, + jurnalTxM_UserID + ) VALUES (?,?,?,?,?,NOW(),?)"; + $qry_tx = $this->db->query($sql_tx, [ + $jurnalid, + $value["coaid"], + $value["coadesc"], + $value["debet"], + $value["kredit"], + $userid + ]); + if (!$qry_tx) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert jurnal_tx ", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("success"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getdetailjurnal() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $jurnalid = $prm['jurnalid']; + + $sql_a = "SELECT jurnalID, jurnalperiodeID, jurnalNo, jurnalTitle, jurnalDescription, + DATE_FORMAT(jurnalDate, '%Y-%m-%d') as jurnalDate, jurnalIsPosted, + M_BranchCompanyName, S_RegionalName, M_BranchName, + M_BranchCompanyID, S_RegionalID, M_BranchID, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight + FROM jurnal + JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' + WHERE jurnalID = ? AND jurnalIsActive = 'Y'"; + + $qry_a = $this->db->query($sql_a, [$jurnalid]); + if (!$qry_a) { + $this->sys_error_db("error get jurnal data"); + exit; + } + $rows = $qry_a->row_array(); + + $sql_b = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as displayPeriode, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode, + periode.* + FROM jurnal + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' AND periodeIsClosed = 'N' + WHERE jurnalID = ? AND jurnalIsActive = 'Y'"; + $qry_b = $this->db->query($sql_b, [$jurnalid]); + if (!$qry_b) { + $this->sys_error_db("error get data periode"); + exit; + } + $periode = $qry_b->row_array(); + + $sql_tx = "SELECT + jurnalTxID, + jurnalTxCoaID as coaid, + jurnalTxDescription as coadesc, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + coaAccountNo as coano + FROM jurnal + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalID AND jurnalTxIsActive = 'Y' + JOIN coa ON coaID = jurnalTxCoaID AND coaIsActive = 'Y' + WHERE jurnalID = ? AND jurnalIsActive = 'Y'"; + $qry_tx = $this->db->query($sql_tx, [$jurnalid]); + if (!$qry_tx) { + $this->sys_error_db("error get jurnal tx"); + exit; + } + $detailjurnal = $qry_tx->result_array(); + + $result = array( + "jurnal" => $rows, + "periode" => $periode, + "jurnaldetail" => $detailjurnal + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Jurnalsendreg.php b/application/controllers/mockup/masterdata/accounting/Jurnalsendreg.php new file mode 100644 index 0000000..bf83810 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Jurnalsendreg.php @@ -0,0 +1,558 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function searchPeriode() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + AND CONCAT(periodeYear, ' - ', periodeName) LIKE ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getBranch() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT + M_BranchID as branchID, + M_BranchS_RegionalID as branchRegionalID, + M_BranchCode as branchCode , + M_BranchName as branchName, + M_BranchCompanyDetailM_BranchCompanyID branchCompanyID + FROM m_branch + JOIN m_branch_companydetail + ON M_BranchCode = M_BranchCompanyDetailM_BranchCode + WHERE M_BranchS_RegionalID = ? + AND M_BranchCompanyDetailIsActive = 'Y' + AND M_BranchCompanyDetailM_BranchCompanyID = ? + AND M_BranchIsActive = 'Y'"; + $qry = $this->db->query($sql, array($prm['regional'], $prm['company'])); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get branch"); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function getJurnalType() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "SELECT * FROM jurnal_type WHERE JurnalTypeIsActive = 'Y' + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $default = array(); + $data = $qry->result_array(); + foreach ($data as $key => $value) { + if ($value['JurnalTypeCode'] == 'SENDGOODR') { + $default = $value; + } + } + $this->sys_ok([ + "records" => $data, + "default" => $default + ]); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE + coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 70 + + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function saveJurnal() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $detail = $prm['detail']; + $jurnalRegional = $prm['jurnalRegional']; + $sallary = $prm['sallary']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + $kreditTotal = 0; + $debetTotal = 0; + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $debetTotal = $debetTotal + doubleval($value['debet']); + } else if ($value['type'] == 'K') { + $kreditTotal = $kreditTotal + doubleval($value['kredit']); + } + # code... + } + if ($debetTotal != $kreditTotal) { + $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . ", debet " . strval($debetTotal) . " ,Kredit " . strval($kreditTotal)); + exit; + } + //insert jurnal regional + $sql = "SELECT `fn_numbering`('PBR') as number"; + $qry = $this->db->query($sql, array()); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error get number"); + exit; + } + $numberingCounter = $qry->row_array()['number']; + $currentMonth = date('m'); // Mendapatkan bulan saat ini dalam format angka dua digit + $currentYear = date('Y'); // Mendapatkan tahun saat ini + + + $numbering = 'PBR/' . $currentYear . "/" . $currentMonth . "/" . strval($numberingCounter); + + $sql = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID) + VALUES(?,?,?,?,?,?,?,?,?,?)"; + $qry = $this->db->query($sql, array( + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + '', + $prm['periodeID'], + $numbering, + $prm['title'], + $prm['description'], + $prm['date'], + $prm['jurnalTypeID'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + $insertedJurnalRegID = $this->db->insert_id(); + $sql = "INSERT INTO jurnal_addon( + jurnalAddOnJurnalID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreatedUserID) + VALUES({$insertedJurnalRegID},'SENDGOODRDST','{$prm['branchCode']}',{$userid});"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal gaji addon regional"); + exit; + } + foreach ($detail as $i => $value) { + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $insertedJurnalRegID, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx regional"); + exit; + } + } + $this->db->trans_commit(); + $this->sys_ok("Success"); + } + + + function getDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $user = $this->sys_user; + + $sql = "SELECT + jurnal.*, + M_BranchID as branchID, + M_BranchName as branchName, + M_branchCode as branchCode + FROM jurnal + JOIN jurnal_addon + ON jurnalID = jurnalAddOnJurnalID + AND jurnalAddOnCode = 'SENDGOODRDST' + JOIN m_branch + ON jurnalAddOnValue = M_BranchCode + AND M_BranchIsActive = 'Y' + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $id + )); + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("error get jurnal"); + exit; + } + $jurnal = $qry->row_array(); + $isEdit = 'Y'; + if ($jurnal['jurnalIsPosted'] === 'Y') { + $isEdit = 'N'; + } + $destination = [ + "branchID" => $jurnal['branchID'], + "branchName" => $jurnal['branchName'], + "branchCode" => $jurnal['branchCode'], + ]; + $date = $jurnal['jurnalDate']; + $title = $jurnal['jurnalTitle']; + $description = $jurnal['jurnalDescription']; + $jurnalDetail = []; + + $sql = "SELECT + CONCAT(periodeYear, ' - ', periodeName) as display, + periode.* + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeID = ? + LIMIT 70 + "; + $qry = $this->db->query($sql, [$jurnal['jurnalperiodeID']]); + if (!$qry) { + $this->sys_error_db("Error get coa", $this->db); + exit; + } + $jurnalPeriode = $qry->row_array(); + $sql = "SELECT + jurnalTxID as id, + coaDescription as description, + jurnalTxDebit as debet, + jurnalTxCredit as kredit, + CASE + WHEN jurnalTxDebit > 0 THEN 'D' + WHEN jurnalTxCredit > 0 THEN 'K' + else '' + END as type, + 'Y' as dataType, + coaID, + coaDescription as coaName, + coaAccountNo as coaNo, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM jurnal_tx + JOIN coa + ON jurnalTxCoaID = coaID + AND jurnalTxJurnalID = ? + AND jurnalTxIsActive = 'Y' + "; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get jurnal tx"); + exit; + } + $jurnalDetail = $qry->result_array(); + $result = array( + "date" => $date, + "isEdit" => $isEdit, + "jurnal" => $jurnal, + "destination" => $destination, + "periode" => $jurnalPeriode, + "title" => $title, + "description" => $description, + "jurnalDetail" => $jurnalDetail, + + ); + $this->sys_ok($result); + } + + function editJurnal() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $detail = $prm['detail']; + $id = $prm['id']; + + $user = $this->sys_user; + $userid = $user["M_UserID"]; + $kreditTotal = 0; + $debetTotal = 0; + + $sql = "SELECT * + FROM jurnal + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $id + )); + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error cek jurnal jurnal"); + exit; + } + $cekJurnal = $qry->row_array(); + if ($cekJurnal['jurnalIsPosted'] == 'Y') { + $this->sys_error('Jurnal sudah di post tidak bisa di ubah'); + exit; + } + + foreach ($detail as $i => $value) { + if ($value['type'] == 'D') { + $debetTotal = $debetTotal + doubleval($value['debet']); + } else if ($value['type'] == 'K') { + $kreditTotal = $kreditTotal + doubleval($value['kredit']); + } + # code... + } + if ($debetTotal != $kreditTotal) { + $this->sys_error("Jumlah debet dan kredit secara total tidak balance" . ", debet " . strval($debetTotal) . " ,Kredit " . strval($kreditTotal)); + exit; + } + + + $sql = "UPDATE jurnal SET + jurnalperiodeID = ?, + jurnalTitle = ?, + jurnalDescription = ?, + jurnalDate = ?, + jurnalM_UserID = ?, + jurnalLastUpdated = NOW() + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $prm['periodeID'], + $prm['title'], + $prm['description'], + $prm['date'], + $userid, + $id + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal"); + exit; + } + + $sql = "UPDATE jurnal_addon SET + jurnalAddOnValue = ?, + jurnalAddOnLastUpdatedUserID = ?, + jurnalAddOnLastUpdated = NOW() + WHERE jurnalAddOnJurnalID = ? + AND jurnalAddOnCode = 'SENDGOODRDST' + "; + $qry = $this->db->query($sql, [$prm['branchCode'], $userid, $id]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal addon regional"); + exit; + } + + $sql = " UPDATE jurnal_tx SET jurnalTxIsActive = 'N' WHERE jurnalTxJurnalID = ? "; + $qry = $this->db->query($sql, array( + $id + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error jurnal tx regional"); + exit; + } + + foreach ($detail as $i => $value) { + if ($value['dataType'] == 'N') { + $sql = 'INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,?)'; + $qry = $this->db->query($sql, array( + $id, + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx regional"); + exit; + } + } else { + $sql = "UPDATE jurnal_tx SET + jurnalTxCoaID = ?, + jurnalTxDescription = ?, + jurnalTxDebit = ?, + jurnalTxCredit = ?, + jurnalTxM_UserID = ?, + jurnalTxIsActive = 'Y', + jurnalTxLastUpdated = NOW() + WHERE jurnalTxID = ?"; + $qry = $this->db->query($sql, array( + $value['coaID'], + $value['coaName'], + $value['debet'], + $value['kredit'], + $userid, + $value['id'] + )); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert jurnal tx regional"); + exit; + } + } + } + $this->db->trans_commit(); + $this->sys_ok("Success"); + } + + function deleteJurnal() + { + $this->db->trans_begin(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $detail = $prm['detail']; + $id = $prm['id']; + + $sql = "SELECT * + FROM jurnal + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $id + )); + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error cek jurnal jurnal"); + exit; + } + $cekJurnal = $qry->row_array(); + if ($cekJurnal['jurnalIsPosted'] == 'Y') { + $this->sys_error('Jurnal sudah di post tidak bisa di hapus'); + exit; + } + + $user = $this->sys_user; + $userid = $user["M_UserID"]; + $sql = "UPDATE jurnal + SET jurnalIsActive = 'N', + jurnalM_UserID = ? + WHERE + jurnalID = ?"; + $qry = $this->db->query($sql, array($userid, $id)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_tx + SET jurnalTxIsActive = 'N', + jurnalTxM_UserID = ? + WHERE + jurnalTxJurnalID = ?"; + $qry = $this->db->query($sql, array($userid, $id)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji tx"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE jurnal_addon + SET jurnalAddOnIsActive = 'N', + jurnalAddOnDeletedUserID = ? + WHERE + jurnalAddOnJurnalID = ?"; + $qry = $this->db->query($sql, array($userid, $id)); + if (!$qry) { + $this->sys_error_db("Error delet jurnal gaji tx"); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok("Success"); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Jurnalumum.php b/application/controllers/mockup/masterdata/accounting/Jurnalumum.php new file mode 100644 index 0000000..e5c70d4 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Jurnalumum.php @@ -0,0 +1,928 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $number_offset = 0; + $number_limit = 20; + + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $startdate = $prm["startdate"]; + $enddate = $prm["enddate"]; + + $branchid = $prm["branchid"]; + $regionalid = $prm["regionalid"]; + + $filter_regional = ""; + $filter_cabang = ""; + $join_regional = ""; + $join_cabang = ""; + if (intval($branchid) === 0) { + $filter_regional = " AND S_RegionalID = {$regionalid}"; + $join_regional = " LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } else { + $filter_cabang = " AND S_RegionalID = {$regionalid} AND M_BranchID = {$branchid}"; + $join_cabang = " JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } + // print_r($branchid); + // exit; + + $sql = "SELECT + jurnalID as id, + jurnalM_BranchCompanyID as branchcompanyid, + JurnalS_RegionalID as regionalid, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + jurnalAddOnCode, + jurnalAddOnValue, + '' as detail + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + $join_cabang + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N' + $join_regional + LEFT JOIN jurnal_addon ON jurnalID = jurnalAddOnJurnalID AND jurnalAddOnIsActive = 'Y' + WHERE jurnalIsActive = 'Y' + AND DATE(jurnalDate) BETWEEN '{$startdate}' AND '{$enddate}' + AND (jurnalNo LIKE '{$search}' OR jurnalTitle LIKE '{$search}') + $filter_regional $filter_cabang + GROUP BY jurnalID + ORDER BY jurnalID DESC"; + + $sql_total = "SELECT count(*) as total FROM ($sql) as x"; + $qry_total = $this->db->query($sql_total); + + $totalCount = 0; + $totalPage = 0; + if ($qry_total) { + $totalCount = $qry_total->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db);; + exit; + } + + + $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset"; + + $qry = $this->db->query($sql_select); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit; + } + + foreach ($rows as $k => $v) { + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID as coaid, + jurnalTxDescription as description, + jurnalTxDebit as debit, + jurnalTxCredit as credit, + '' as account + FROM jurnal_tx + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ?"; + $qry_detail = $this->db->query($sql_detail, array($v["id"])); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit; + } + + $detail_rows = $qry_detail->result_array(); + + // Tambahkan account dari COA untuk setiap baris detail + foreach ($detail_rows as $dk => $dv) { + $sql_coa = "SELECT + coaID, + coaAccountNo as account + FROM coa + WHERE coaIsActive = 'Y' + AND coaID = ?"; + $qry_coa = $this->db->query($sql_coa, array($dv["coaid"])); + if ($qry_coa->num_rows() > 0) { + $coa_row = $qry_coa->row_array(); + $detail_rows[$dk]["account"] = $coa_row["account"]; + } else { + $detail_rows[$dk]["account"] = ""; + } + } + + $rows[$k]["detail"] = $detail_rows; + } + + $result = array( + "total" => $totalPage, + "totalFilter" => $totalCount, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search_old() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $number_offset = 0; + $number_limit = 20; + + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $startdate = $prm["startdate"]; + $enddate = $prm["enddate"]; + + $branchid = $prm["branchid"]; + $regionalid = $prm["regionalid"]; + + $filter_regional = ""; + $filter_cabang = ""; + $join_regional = ""; + $join_cabang = ""; + if (intval($branchid) === 0) { + $filter_regional = " AND S_RegionalID = {$regionalid}"; + $join_regional = " LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } else { + $filter_cabang = " AND S_RegionalID = {$regionalid} AND M_BranchID = {$branchid}"; + $join_cabang = " JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' "; + } + // print_r($branchid); + // exit; + + $sql_filter = "SELECT count(*) as total + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + $join_cabang + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N' + $join_regional + LEFT JOIN jurnal_addon ON jurnalID = jurnalAddOnJurnalID AND jurnalAddOnIsActive = 'Y' + WHERE jurnalIsActive = 'Y' + AND DATE(jurnalDate) BETWEEN ? AND ? + AND (jurnalNo LIKE ? OR jurnalTitle LIKE ?) + $filter_regional $filter_cabang + -- GROUP BY jurnalID + ORDER BY jurnalID ASC"; + $qry_filter = $this->db->query($sql_filter, array( + $startdate, + $enddate, + $search, + $search + )); + $totalCount = 0; + $totalPage = 0; + + // echo $this->db->last_query(); + // exit; + + if ($qry_filter) { + $totalCount = $qry_filter->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal count error", $this->db);; + exit; + } + + + $sql = "SELECT + jurnalID as id, + jurnalM_BranchCompanyID as branchcompanyid, + JurnalS_RegionalID as regionalid, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalM_BranchCode, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalIsPosted, + M_BranchCompanyName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + jurnalAddOnCode, + jurnalAddOnValue, + '' as detail + FROM jurnal + JOIN m_branch_company ON jurnalM_BranchCompanyID = M_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN s_regional ON JurnalS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + $join_cabang + JOIN periode ON jurnalperiodeID = periodeID AND periodeIsActive = 'Y' + JOIN jurnal_type ON jurnalJurnalTypeID = JurnalTypeID AND JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N' + $join_regional + LEFT JOIN jurnal_addon ON jurnalID = jurnalAddOnJurnalID AND jurnalAddOnIsActive = 'Y' + WHERE jurnalIsActive = 'Y' + AND DATE(jurnalDate) BETWEEN ? AND ? + AND (jurnalNo LIKE ? OR jurnalTitle LIKE ?) + $filter_regional $filter_cabang + GROUP BY jurnalID + ORDER BY jurnalID ASC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, array( + $startdate, + $enddate, + $search, + $search, + $number_limit, + $number_offset, + )); + // echo $this->db->last_query(); + // exit; + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal error", $this->db); + exit; + } + + foreach ($rows as $k => $v) { + $sql_detail = "SELECT + jurnalTxID, + jurnalTxJurnalID, + jurnalTxCoaID as coaid, + jurnalTxDescription as description, + jurnalTxDebit as debit, + jurnalTxCredit as credit, + '' as account + FROM jurnal_tx + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ?"; + $qry_detail = $this->db->query($sql_detail, array($v["id"])); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit; + } + + $detail_rows = $qry_detail->result_array(); + + // Tambahkan account dari COA untuk setiap baris detail + foreach ($detail_rows as $dk => $dv) { + $sql_coa = "SELECT + coaID, + coaAccountNo as account + FROM coa + WHERE coaIsActive = 'Y' + AND coaID = ?"; + $qry_coa = $this->db->query($sql_coa, array($dv["coaid"])); + if ($qry_coa->num_rows() > 0) { + $coa_row = $qry_coa->row_array(); + $detail_rows[$dk]["account"] = $coa_row["account"]; + } else { + $detail_rows[$dk]["account"] = ""; + } + } + + $rows[$k]["detail"] = $detail_rows; + } + + $result = array( + "total" => $totalPage, + "totalFilter" => $totalCount, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getjurnaltype() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $sql = "SELECT JurnalTypeID, + JurnalTypeCode, + JurnalTypeName, + JurnalTypeAccesRight, + JurnalTypeIsActive + FROM jurnal_type + WHERE JurnalTypeIsActive = 'Y' AND JurnalTypeIsAuto = 'N'"; + $qry = $this->db->query($sql); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal type error", $this->db); + exit; + } + $defaultju = []; + foreach ($rows as $value) { + if ($value["JurnalTypeCode"] == "GENERAL") { + $defaultju = $value; + } + } + + $result = array( + "records" => $rows, + "defaultju" => $defaultju, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getperiode() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + periodeID, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + periodeStartDate, + periodeEndDate, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND (periodeYear LIKE ? OR periodeName LIKE ?)"; + $qry = $this->db->query($sql, array( + $search, + $search + )); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select periode error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchcoa() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = $prm["search"]; + $search_name = '%' . $search . '%'; + $search_account = "$search%"; + + $number_limit = 10; + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}') + ORDER BY coaAccountNo ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($number_limit)); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getbranch() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $branchid = $prm["branchid"]; + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry = $this->db->query($sql, array($branchid)); + if ($qry) { + $row = $qry->row_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch error", $this->db); + exit; + } + + $result = array( + "records" => $row, + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function savejurnalumum() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $branchid = $prm["branchid"]; + $branchcompanyid = $prm["branchcompanyid"]; + $date = $prm["date"]; + $description = $prm["description"]; + $periodeid = $prm["periodeid"]; + $regionalid = $prm["regionalid"]; + $title = $prm["title"]; + $typeid = $prm["typeid"]; + $detailjurnal = $prm["detailjurnal"]; + + $sql_branch = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry_branch = $this->db->query($sql_branch, array($branchid)); + if ($qry_branch) { + $branchcodex = $qry_branch->row()->M_BranchCode; + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch error", $this->db); + exit; + } + + $sql = "INSERT INTO jurnal( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalIsActive, + jurnalCreated, + jurnalM_UserID + ) VALUES(?,?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)"; + $qry = $this->db->query($sql, array( + $branchcompanyid, + $regionalid, + $branchcodex, + $periodeid, + $title, + $description, + $date, + $typeid, + $userid + )); + $last_qry = $this->db->last_query(); + if (!$qry) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db); + exit; + } + + $last_id = $this->db->insert_id(); + + foreach ($detailjurnal as $key => $value) { + $sql_detail = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxIsActive, + jurnalTxCreated, + jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, array( + $last_id, + $value["coaid"], + $value["description"], + $value["debit"], + $value["credit"], + $userid + )); + $last_qry = $this->db->last_query(); + if (!$qry_detail) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db); + exit; + } + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editjurnalumum() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $branchid = $prm["branchid"]; + $branchcompanyid = $prm["branchcompanyid"]; + $date = $prm["date"]; + $description = $prm["description"]; + $periodeid = $prm["periodeid"]; + $regionalid = $prm["regionalid"]; + $title = $prm["title"]; + $typeid = $prm["typeid"]; + $detailjurnal = $prm["detailjurnal"]; + $id = $prm["id"]; + + $sql_branch = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry_branch = $this->db->query($sql_branch, array($branchid)); + if ($qry_branch) { + $branchcodex = $qry_branch->row()->M_BranchCode; + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch error", $this->db); + exit; + } + + $sql = "UPDATE jurnal SET + jurnalM_BranchCompanyID = ?, + JurnalS_RegionalID = ?, + jurnalM_BranchCode = ?, + jurnalperiodeID = ?, + jurnalTitle = ?, + jurnalDescription = ?, + jurnalDate = ?, + jurnalJurnalTypeID = ?, + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $branchcompanyid, + $regionalid, + $branchcodex, + $periodeid, + $title, + $description, + $date, + $typeid, + $userid, + $id + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("edit jurnal", $this->db); + exit; + } + + // Ambil data lama dari database + $sql_select_jurnaltx = "SELECT * FROM jurnal_tx WHERE jurnalTxJurnalID = ? AND jurnalTxIsActive = 'Y'"; + $qry_select_jurnattx = $this->db->query($sql_select_jurnaltx, array($id)); + + if ($qry_select_jurnattx) { + $rows_jurnaltx = $qry_select_jurnattx->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select jurnal tx error", $this->db); + exit; + } + + // print_r($rows_jurnaltx); + + // Konversi existingData menjadi array dengan key jurnalTxID + $existingDataAssoc = []; + foreach ($rows_jurnaltx as $row) { + $existingDataAssoc[$row['jurnalTxID']] = $row; + } + + // print_r($existingDataAssoc); + $toInsert = []; + $toUpdate = []; + $existingIDs = array_keys($existingDataAssoc); + $newIDs = []; + + foreach ($detailjurnal as $item) { + $newIDs[] = $item['jurnalTxID'] ?? null; + + // print_r($newIDs); + // exit; + if (!isset($existingDataAssoc[$item['jurnalTxID']])) { + // Data baru + $toInsert[] = $item; + } + } + + $toDelete = array_diff($existingIDs, $newIDs); + + // print_r($toInsert); + // print_r($toDelete); + // exit; + + // hapus data yang sudah ada + foreach ($toDelete as $value) { + $sql_del = "UPDATE jurnal_tx SET + jurnalTxIsActive = 'N', + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ?"; + $qry_del = $this->db->query($sql_del, array( + $userid, + $value + )); + if (!$qry_del) { + $this->db->trans_rollback(); + $this->sys_error_db("delete jurnal tx error", $this->db); + exit; + } + // $lastqry = $this->db->last_query(); + // echo $lastqry; + } + + // tambah data baru + foreach ($toInsert as $val) { + $sql_detail = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxIsActive, + jurnalTxCreated, + jurnalTxM_UserID) VALUES(?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, array( + $id, + $val["coaid"], + $val["description"], + $val["debit"], + $val["credit"], + $userid + )); + $last_qry = $this->db->last_query(); + if (!$qry_detail) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db); + exit; + } + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletejurnalumum() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $id = $prm["id"]; + $detailjurnal = $prm["detailjurnal"]; + + $sql = "UPDATE jurnal SET + jurnalIsActive = 'N', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ?"; + $qry = $this->db->query($sql, array( + $userid, + $id + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("delete jurnal error", $this->db); + exit; + } + + foreach ($detailjurnal as $key => $value) { + $sql_detail = "UPDATE jurnal_tx SET + jurnalTxIsActive = 'N', + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxID = ? AND jurnalTxJurnalID = ?"; + $qry_detail = $this->db->query($sql_detail, array( + $userid, + $value["jurnalTxID"], + $id + )); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("delete jurnal tx error", $this->db); + exit; + } + } + + $addonSql = "UPDATE jurnal_addon + SET jurnalAddOnIsActive = 'N', jurnalAddOnLastUpdated = NOW(), + jurnalAddOnLastUpdatedUserID = ? + WHERE jurnalAddOnJurnalID = ?"; + $addonqry = $this->db->query($addonSql, [$userid, $id]); + if (!$addonqry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to delete jurnal_addon", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Maprk.php b/application/controllers/mockup/masterdata/accounting/Maprk.php new file mode 100644 index 0000000..8562a53 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Maprk.php @@ -0,0 +1,560 @@ +isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT * FROM ( + SELECT '0' AS S_RegionalID, 'Kantor Pusat' AS S_RegionalName + UNION + SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + ) AS x + ORDER BY S_RegionalName ASC"; + $qry = $this->db->query($sql, []); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRegional() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT * FROM ( + SELECT '0' AS S_RegionalID, 'Kantor Pusat' AS S_RegionalName + UNION + SELECT S_RegionalID, S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + ) AS x + WHERE S_RegionalName LIKE '{$search}' + ORDER BY S_RegionalName ASC"; + $qry = $this->db->query($sql, []); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select regional", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = $prm["regionalId"]; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function getBranchFilter() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $regionalId = $prm["regionalId"]; + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, [$regionalId]); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $regionalId = $prm['regionalId']; + $branchCode = $prm['branchCode']; + + $filter_regional = ""; + $join_reg_pusat = ""; + $join_regional = ""; + + // jika regionalid 0 maka kantor pusat + if ($regionalId === 0 || $regionalId === "0") { + $filter_regional .= " AND Map_RkCabang_SRegionalID = {$regionalId}"; + $join_reg_pusat .= " LEFT JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'"; + } + + // jika regionalid > 0 maka filter berdasarkan regional + if (intval($regionalId) > 0) { + $filter_regional .= " AND Map_RkCabang_SRegionalID = {$regionalId}"; + $join_regional .= " JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'"; + } + + // untuk load listing pada saat buka master rk + if ($regionalId === "") { + $join_regional .= " LEFT JOIN s_regional ON Map_RkCabang_SRegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON Map_RkCabang_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y'"; + } + + $filter_branch = ""; + // filter branch + if ($branchCode != "") { + $filter_branch .= " AND Map_RkCabang_BranchCode = '{$branchCode}'"; + } + + $sql = "SELECT + Map_RkCabang_ID, + Map_RkCabang_Rk_TypeID, + Map_RkCabang_SRegionalID, + Map_RkCabang_BranchCode, + Map_RkCabang_CoaID, + Map_RkCabang_CoaAccountNo, + Map_RkCabang_CoaDescription, + Rk_TypeID, + Rk_TypeCode, + Rk_TypeName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchCode, + M_BranchName + FROM map_rk_cabang + JOIN rk_type ON Map_RkCabang_Rk_TypeID = Rk_TypeID AND Rk_TypeIsActive = 'Y' + $join_reg_pusat + $join_regional + WHERE Map_RkCabang_IsActive = 'Y' + $filter_regional + $filter_branch + AND (Map_RkCabang_CoaAccountNo LIKE '{$search}' OR Map_RkCabang_CoaDescription LIKE '{$search}') + ORDER BY Map_RkCabang_ID DESC + "; + $sql_total = "SELECT count(*) as total FROM ($sql) as x"; + $qry_total = $this->db->query($sql_total, []); + + // print_r($this->db->last_query()); + // exit; + + $number_offset = 0; + $number_limit = 10; + + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $total_count = 0; + $total_page = 0; + if ($qry_total) { + $total_count = $qry_total->result_array()[0]["total"]; + $total_page = ceil($total_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select count bank coa count error", $this->db);; + exit; + } + + $sql_bank = $sql . " LIMIT $number_limit OFFSET $number_offset"; + $qry_bank = $this->db->query($sql_bank, []); + if ($qry_bank) { + $rows = $qry_bank->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select bank coa count error", $this->db);; + exit; + } + + foreach ($rows as $key => $value) { + if (intval($value["Map_RkCabang_SRegionalID"]) === 0) { + $rows[$key]["S_RegionalID"] = "0"; + $rows[$key]["S_RegionalName"] = "Kantor Pusat"; + } + } + + $result = array( + "total_page" => $total_page, + "total_filter" => $total_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getType() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + Rk_TypeID, + Rk_TypeCode, + Rk_TypeName + FROM rk_type + WHERE Rk_TypeIsActive = 'Y' + AND (Rk_TypeName LIKE ?)"; + $qry = $this->db->query($sql, array( + $search + )); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select type error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchCoaEDC() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = $prm["search"]; + $search_name = '%' . $search . '%'; + $search_account = "$search%"; + + $number_limit = 10; + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + CONCAT(coaAccountNo, ' - ', coaDescription) as accountNoDescription + FROM coa + WHERE coaIsActive = 'Y' + AND coaIsInput = 'Y' + AND (coaDescription LIKE '{$search_name}' OR coaAccountNo LIKE '{$search_account}') + ORDER BY coaAccountNo ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($number_limit)); + + // echo $this->db->last_query(); + // exit; + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveRkCabang() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $rkCabangTypeId = $prm["rkCabangTypeId"]; + $rkCabangRegionalId = $prm["rkCabangRegionalId"]; + $rkCabangBranchCode = $prm["rkCabangBranchCode"]; + $rkCabangCoaId = $prm["rkCabangCoaId"]; + $rkCabangCoaAccountNo = $prm["rkCabangCoaAccountNo"]; + $rkCabangCoaDescription = $prm["rkCabangCoaDescription"]; + + $sql = "INSERT INTO map_rk_cabang( + Map_RkCabang_Rk_TypeID, + Map_RkCabang_SRegionalID, + Map_RkCabang_BranchCode, + Map_RkCabang_CoaID, + Map_RkCabang_CoaAccountNo, + Map_RkCabang_CoaDescription, + Map_RkCabang_IsActive, + Map_RkCabang_CreatedAt) VALUES(?,?,?,?,?,?,'Y',NOW())"; + $exec = $this->db->query($sql, [ + $rkCabangTypeId, + $rkCabangRegionalId, + $rkCabangBranchCode, + $rkCabangCoaId, + $rkCabangCoaAccountNo, + $rkCabangCoaDescription + ]); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("map rk cabang insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function updateRkCabang() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $rkCabangTypeId = $prm["rkCabangTypeId"]; + $rkCabangRegionalId = $prm["rkCabangRegionalId"]; + $rkCabangBranchCode = $prm["rkCabangBranchCode"]; + $rkCabangCoaId = $prm["rkCabangCoaId"]; + $rkCabangCoaAccountNo = $prm["rkCabangCoaAccountNo"]; + $rkCabangCoaDescription = $prm["rkCabangCoaDescription"]; + $rkCabangId = $prm["rkCabangId"]; + + $sql = "UPDATE map_rk_cabang SET + Map_RkCabang_Rk_TypeID = ?, + Map_RkCabang_SRegionalID = ?, + Map_RkCabang_BranchCode = ?, + Map_RkCabang_CoaID = ?, + Map_RkCabang_CoaAccountNo = ?, + Map_RkCabang_CoaDescription = ?, + Map_RkCabang_LastUpdatedAt= NOW() + WHERE Map_RkCabang_ID = ?"; + $qry = $this->db->query($sql, array( + $rkCabangTypeId, + $rkCabangRegionalId, + $rkCabangBranchCode, + $rkCabangCoaId, + $rkCabangCoaAccountNo, + $rkCabangCoaDescription, + $rkCabangId + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("update rk cabang error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteRkCabang() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + + $rkCabangId = $prm["rkCabangId"]; + + $sql = "UPDATE map_rk_cabang SET + Map_RkCabang_IsActive = 'N', + Map_RkCabang_LastUpdatedAt = NOW() + WHERE Map_RkCabang_ID = ?"; + $qry = $this->db->query($sql, array( + $rkCabangId + )); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("delete rk cabang error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mdaccountsales.php b/application/controllers/mockup/masterdata/accounting/Mdaccountsales.php new file mode 100644 index 0000000..88758ce --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mdaccountsales.php @@ -0,0 +1,357 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $payload = $this->sys_input; + + $searchSubGroupName = ""; + $searchOmzet = ""; + + if (isset($payload['searchSubGroupName']) || isset($payload['searchOmzet'])) { + $searchSubGroupName = trim($payload["searchSubGroupName"]); + $searchOmzet = trim($payload["searchOmzet"]); + if ($searchSubGroupName !== "") { + $searchSubGroupName = "%" . $payload["searchSubGroupName"] . "%"; + } else { + $searchSubGroupName = "%%"; + } + + if ($searchOmzet !== "") { + $searchOmzet = $payload["searchOmzet"]; + } else { + $searchOmzet = "%%"; + } + } + + $queryFilter = "SELECT count(*) as total + FROM map_AccSales + WHERE map_AccSalesNat_SubGroupIsActive = 'Y' + AND map_AccSalesNat_SubGroupName LIKE ? + AND map_AccSalesM_OmzetTypeID LIKE ?"; + $exec = $this->db->query($queryFilter, [$searchSubGroupName, $searchOmzet]); + + $numberLimit = 20; + $numberOffset = 0; + if ($payload["currentPage"] > 0) { + $numberOffset = ($payload["currentPage"] - 1) * $numberLimit; + } + + $totalCount = 0; + $totalPage = 0; + + if ($exec) { + $totalCount = $exec->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $numberLimit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select account sales", $this->db);; + exit; + } + + $query = "SELECT + map_AccSalesNat_SubGroupID, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + map_AccSalesNat_SubGroupCode, + map_AccSalesNat_SubGroupName, + map_AccSalesM_OmzetTypeID, + map_AccSalesM_OmzetTypeName + FROM map_AccSales + LEFT JOIN coa ON map_AccSales.map_AccSalesNat_SubGroupCoaID=coa.coaID + INNER JOIN m_omzettype ON map_AccSales.map_AccSalesM_OmzetTypeID=m_omzettype.M_OmzetTypeID + WHERE map_AccSalesNat_SubGroupIsActive = 'Y' + AND M_OmzetTypeIsActive = 'Y' + AND map_AccSalesNat_SubGroupName LIKE ? + AND map_AccSalesM_OmzetTypeID LIKE ? + ORDER BY map_AccSalesNat_SubGroupID ASC + LIMIT ? OFFSET ?"; + $exec = $this->db->query($query, [$searchSubGroupName, $searchOmzet, $numberLimit, $numberOffset]); + + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select account sales", $this->db); + exit; + } + + $result = array( + "total" => $totalPage, + "totalFilter" => $totalCount, + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function subGroupName() + { + try { + $query = "SELECT DISTINCT + map_AccSalesNat_SubGroupName + FROM map_AccSales + WHERE map_AccSalesNat_SubGroupIsActive = 'Y' + ORDER BY map_AccSalesNat_SubGroupName ASC"; + $exec = $this->db->query($query, []); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select sub group name", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function coa() + { + try { + $query = "SELECT DISTINCT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription + FROM coa + WHERE coaIsActive = 'Y' + ORDER BY coaAccountNo ASC"; + $exec = $this->db->query($query, []); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function omzet() + { + try { + $query = "SELECT DISTINCT + M_OmzetTypeID, + M_OmzetTypeName + FROM m_omzettype + WHERE M_OmzetTypeIsActive = 'Y' + ORDER BY M_OmzetTypeID ASC"; + $exec = $this->db->query($query, []); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select omzet", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function addNewAccountSales() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $coaId = $payload["coaId"]; + $subGroupCode = $payload["subGroupCode"]; + $subGroupName = $payload["subGroupName"]; + $omzetId = $payload["omzetId"]; + + $query = "SELECT COUNT(*) as exist FROM map_AccSales WHERE map_AccSalesNat_SubGroupIsActive = 'Y' AND map_AccSalesNat_SubGroupCode = ? AND map_AccSalesNat_SubGroupName = ? AND map_AccSalesNat_SubGroupCoaID = ? AND map_AccSalesM_OmzetTypeID = ?"; + $exist = $this->db->query($query, [$subGroupCode, $subGroupName, $coaId, $omzetId]); + if ($exist) { + $row = $exist->row()->exist; + } else { + $this->sys_error_db("exist error", $this->db); + exit; + } + + if ($row == 0) { + $queryOmzet = "SELECT M_OmzetTypeName FROM m_omzettype WHERE M_OmzetTypeID = ?"; + $exec = $this->db->query($queryOmzet, [$omzetId]); + $omzetName = $exec->result_array()[0]["M_OmzetTypeName"]; + + $sql = "INSERT INTO map_AccSales( + map_AccSalesNat_SubGroupCoaID, + map_AccSalesNat_SubGroupCode, + map_AccSalesNat_SubGroupName, + map_AccSalesM_OmzetTypeID, + map_AccSalesM_OmzetTypeName, + map_AccSalesNat_SubGroupCreated, + map_AccSalesNat_SubGroupLastUpdated, + map_AccSalesNat_SubGroupUserID, + map_AccSalesNat_SubGroupIsActive + ) VALUES (?, ?, ?, ?, ?, NOW(), NOW(), ?, 'Y')"; + $exec = $this->db->query($sql, [ + $coaId, + $subGroupCode, + $subGroupName, + $omzetId, + $omzetName, + $userid + ]); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("account sales insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xId" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + if ($row != 0) { + array_push($errors, array('msg' => 'Data sudah ada')); + } + + $result = array("total" => -1, "errors" => $errors, "records" => array('status' => 'ERROR')); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editAccountSales() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $subGroupId = $payload["subGroupId"]; + $coaId = $payload["coaId"]; + $subGroupCode = $payload["subGroupCode"]; + $subGroupName = $payload["subGroupName"]; + $omzetId = $payload["omzetId"]; + + $queryOmzet = "SELECT M_OmzetTypeName FROM m_omzettype WHERE M_OmzetTypeID = ?"; + $exec = $this->db->query($queryOmzet, [$omzetId]); + $omzetName = $exec->result_array()[0]["M_OmzetTypeName"]; + + $sql = "UPDATE map_AccSales SET + map_AccSalesNat_SubGroupCoaID = ?, + map_AccSalesNat_SubGroupCode = ?, + map_AccSalesNat_SubGroupName = ?, + map_AccSalesM_OmzetTypeID = ?, + map_AccSalesM_OmzetTypeName = ?, + map_AccSalesNat_SubGroupLastUpdated = NOW() + WHERE map_AccSalesNat_SubGroupID = ?"; + $exec = $this->db->query($sql, [$coaId, $subGroupCode, $subGroupName, $omzetId, $omzetName, $subGroupId]); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("account sales update error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xId" => $subGroupId)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function softDelete() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $subGroupId = $payload["subGroupId"]; + + $sql = "UPDATE map_AccSales SET + map_AccSalesNat_SubGroupLastUpdated = NOW(), + map_AccSalesNat_SubGroupIsActive = 'N' + WHERE map_AccSalesNat_SubGroupID = ?"; + $exec = $this->db->query($sql, [$subGroupId]); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("account sales delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xId" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mdcategory.php b/application/controllers/mockup/masterdata/accounting/Mdcategory.php new file mode 100644 index 0000000..dc74f23 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mdcategory.php @@ -0,0 +1,255 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + itemCategoryID, + itemCategoryName, + itemCategoryRk_TypeID, + itemCategoryIsActive, + Rk_TypeID, + Rk_TypeCode, + Rk_TypeName + FROM item_category + LEFT JOIN rk_type ON itemCategoryRk_TypeID = Rk_TypeID AND Rk_TypeIsActive = 'Y' + WHERE itemCategoryIsActive = 'Y' + AND (itemCategoryName LIKE ?) + ORDER BY itemCategoryID DESC"; + $query = $this->db->query($sql, [$search]); + if (!$query) { + $this->sys_error_db("type list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $sql_tot = "SELECT count(*) as total + FROM item_category + LEFT JOIN rk_type ON itemCategoryRk_TypeID = Rk_TypeID AND Rk_TypeIsActive = 'Y' + WHERE itemCategoryIsActive = 'Y' + AND (itemCategoryName LIKE ?)"; + + $query_tot = $this->db->query($sql_tot, [$search]); + $total_list = 0; + if ($query_tot) { + $total_list = $query_tot->result_array()[0]['total']; + } else { + $this->sys_error_db("type count", $this->db); + exit; + } + + foreach ($rows as $k => $v) { + $rows[$k]['rownumber'] = $k + 1; + } + + $result = array( + "total" => $total_list, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function gettype() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + Rk_TypeID, + Rk_TypeCode, + Rk_TypeName + FROM rk_type + WHERE Rk_TypeIsActive = 'Y' + AND (Rk_TypeCode LIKE ? OR Rk_TypeName LIKE ?) + ORDER BY Rk_TypeName ASC"; + $query = $this->db->query($sql, [$search, $search]); + if (!$query) { + $this->sys_error_db("type list", $this->db); + exit; + } + + $rows = $query->result_array(); + $result = array( + "total" => count($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $categoryid = $prm['categoryid']; + + $sql = "UPDATE item_category SET + itemCategoryIsActive = 'N', + itemCategoryM_UserID = ?, + itemCategoryLastUpdated = NOW() + WHERE itemCategoryID = ?"; + + $query = $this->db->query( + $sql, + array($userid, $categoryid) + ); + if (!$query) { + $this->sys_error_db("delete category"); + exit; + } + + $result = array( + "total" => 1, + "data" => array('status' => 'OK') + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function addCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $categoryname = $prm["categoryname"]; + $typeid = $prm["typeid"]; + + $sql = "INSERT INTO `item_category` ( + itemCategoryName, + itemCategoryRk_TypeID, + itemCategoryIsActive, + itemCategoryM_UserID, + itemCategoryCreated + ) VALUES (?,?,'Y',?,NOW())"; + + $qry = $this->db->query($sql, [ + $categoryname, + $typeid, + $userid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("category insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $categoryname = $prm["categoryname"]; + $typeid = $prm["typeid"]; + $categoryid = $prm["categoryid"]; + + $sql = "UPDATE item_category SET + itemCategoryName = ?, + itemCategoryRk_TypeID = ?, + itemCategoryM_UserID = ?, + itemCategoryLastUpdated = NOW() + WHERE itemCategoryID = ?"; + $qry = $this->db->query($sql, [ + $categoryname, + $typeid, + $userid, + $categoryid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("category error edit", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("itemCategoryID" => $categoryid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mdcoa.php b/application/controllers/mockup/masterdata/accounting/Mdcoa.php new file mode 100644 index 0000000..2b83067 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mdcoa.php @@ -0,0 +1,274 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + + function search() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_filter = "SELECT count(*) as total + FROM coa + WHERE coaIsActive = 'Y' + AND (coaDescription LIKE ? OR coaSubDescription LIKE ? OR coaAccountNo LIKE ?)"; + $qry_filter = $this->db->query($sql_filter, [$search, $search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_filter) { + $tot_count = $qry_filter->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("coa count", $this->db); + exit; + } + + $sql = "SELECT + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + coaLevel + FROM coa + WHERE coaIsActive = 'Y' + AND (coaDescription LIKE ? OR coaSubDescription LIKE ? OR coaAccountNo LIKE ?) + ORDER BY coaAccountNo ASC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select coa", $this->db); + exit; + } + + $result = array( + "total" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function addnewcoa() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + + $prm = $this->sys_input; + $accountno = $prm["accountno"]; + $description = $prm["description"]; + $subdescription = $prm["subdescription"]; + $accounttype = $prm["accounttype"]; + $currencycode = $prm["currencycode"]; + $cashflowcategory = $prm["cashflowcategory"]; + $reportschedule = $prm["reportschedule"]; + $level = $prm["level"]; + $isinput = $prm["isinput"]; + + $query = "SELECT COUNT(*) as exist FROM coa WHERE coaIsActive = 'Y' AND coaAccountNo = ?"; + $exist_accountno = $this->db->query($query, [$accountno]); + if ($exist_accountno) { + $row = $exist_accountno->row()->exist; + } else { + $this->sys_error_db("exist error", $this->db); + exit; + } + + if ($row == 0) { + $sql = "INSERT INTO coa( + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + coaCreated, + coaIsActive, + coaLevel + ) VALUES(?,?,?,?,?,?,?,?,NOW(),'Y',?)"; + $qry = $this->db->query($sql, [ + $accountno, + $description, + $subdescription, + $accounttype, + $isinput, + $reportschedule, + $currencycode, + $cashflowcategory, + $level + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("coa insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + if ($row != 0) { + array_push($errors, array('field' => 'account no', 'msg' => 'Account No sudah digunakan')); + } + + $result = array("total" => -1, "errors" => $errors, "records" => array('status' => 'ERROR')); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editcoa() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + + $prm = $this->sys_input; + $coaid = $prm["coaid"]; + $accountno = $prm["accountno"]; + $description = $prm["description"]; + $subdescription = $prm["subdescription"]; + $accounttype = $prm["accounttype"]; + $currencycode = $prm["currencycode"]; + $cashflowcategory = $prm["cashflowcategory"]; + $reportschedule = $prm["reportschedule"]; + $level = $prm["level"]; + $isinput = $prm["isinput"]; + + $sql = "UPDATE coa SET + coaAccountNo = ?, + coaDescription = ?, + coaSubDescription = ?, + coaAccountType = ?, + coaIsInput = ?, + coaReportSchedule = ?, + coaCurrencyCode = ?, + coaCashFlowCategory = ?, + coaLastUpdated = NOW(), + coaLevel = ? + WHERE coaID = ?"; + $qry = $this->db->query($sql, [ + $accountno, + $description, + $subdescription, + $accounttype, + $isinput, + $reportschedule, + $currencycode, + $cashflowcategory, + $level, + $coaid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("coa update error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => $coaid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletecoa() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + + $prm = $this->sys_input; + $coaid = $prm["coaid"]; + + $sql = "UPDATE coa SET + coaLastUpdated = NOW(), + coaIsActive = 'N' + WHERE coaID = ?"; + $qry = $this->db->query($sql, [$coaid]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("coa delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mditem.php b/application/controllers/mockup/masterdata/accounting/Mditem.php new file mode 100644 index 0000000..bcd6d20 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mditem.php @@ -0,0 +1,944 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $where = "M_ItemIsActive = 'Y'"; + + // Filter by category + // if (isset($prm['category_id']) && $prm['category_id'] != '' && intval($prm['category_id']) > 0) { + // $where .= " AND M_ItemItem_CategoryID = " . $prm['category_id']; + // } + + // Filter by group + if (isset($prm['group_id']) && $prm['group_id'] != '' && intval($prm['group_id']) > 0) { + $where .= " AND M_ItemNat_GroupID = " . $prm['group_id']; + } + + // Search by name + if (isset($prm['search']) && trim($prm['search']) != '') { + $search = trim($prm['search']); + $where .= " AND M_ItemDesc LIKE '%" . $search . "%'"; + } + + // Pagination + $number_limit = 20; + $number_offset = 0; + if (isset($prm['current_page']) && $prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql = "SELECT + M_ItemID, + M_ItemCode, + M_ItemDesc, + M_ItemInventoryCode, + M_ItemItem_CategoryID, + M_ItemNat_GroupID, + M_ItemNat_SubGroupID, + M_ItemFa_ClassID, + M_ItemItem_UnitID, + itemCategoryID, + itemCategoryName, + Nat_GroupID, + Nat_GroupName, + Nat_SubGroupID, + Nat_SubGroupName, + Fa_ClassID, + Fa_ClassName, + Fa_ClassFlagType, + Fa_InventarisGolID, + Fa_InventarisGolName, + ItemUnitID, + ItemUnitCode, + GROUP_CONCAT(ItemUnitName) as ItemUnitName, + '' as satuan + FROM m_item + LEFT JOIN item_category ON M_ItemItem_CategoryID = itemCategoryID + LEFT JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID + LEFT JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID + LEFT JOIN fa_class ON M_ItemFa_ClassID = Fa_ClassID + LEFT JOIN fa_inventaris_gol ON M_ItemM_InventarisGolID = Fa_InventarisGolID + LEFT JOIN itemunitmap ON M_ItemID = ItemUnitMapM_ItemID + AND ItemUnitMapIsActive = 'Y' + LEFT JOIN itemunit ON ItemUnitMapItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + WHERE $where + GROUP BY M_ItemID + ORDER BY M_ItemID DESC + LIMIT $number_limit OFFSET $number_offset"; + + $query = $this->db->query($sql); + // echo $this->db->last_query(); + // exit; + + if (!$query) { + $this->sys_error_db("item list", $this->db); + exit; + } + + $rows = $query->result_array(); + + if (count($rows) > 0) { + foreach ($rows as $key => $value) { + $sql = "SELECT ItemUnitMapID as id, + ItemUnitMapM_ItemID, + ItemUnitMapItemUnitID, + ItemUnitMapIsPurchase, + ItemUnitMapIsReport, + ItemUnitMapIsBase, + CASE + WHEN ItemUnitMapIsPurchase = 'Y' THEN 'purchase' + WHEN ItemUnitMapIsReport = 'Y' THEN 'report' + WHEN ItemUnitMapIsBase = 'Y' THEN 'base' + END as detail_tipe_itemunit, + ItemUnitName as item_unit_name, + ItemUnitID as item_unit_id, + ItemUnitID, + ItemUnitName, + ItemUnitMapMin as item_unit_min + from itemunitmap + JOIN itemunit + ON ItemUnitMapItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + Where + ItemUnitMapIsActive = 'Y' + AND ItemUnitMapM_ItemID = ?"; + $qry = $this->db->query($sql, array($value['M_ItemID'])); + if ($qry) { + $rows_satuan = $qry->result_array(); + $rows[$key]['satuan'] = $rows_satuan; + } + } + } + + // Get total count + $sql_count = "SELECT COUNT(*) as total FROM ( + SELECT M_ItemID + FROM m_item + LEFT JOIN item_category ON M_ItemItem_CategoryID = itemCategoryID + LEFT JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID + LEFT JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID + LEFT JOIN fa_class ON M_ItemFa_ClassID = Fa_ClassID + LEFT JOIN fa_inventaris_gol ON M_ItemM_InventarisGolID = Fa_InventarisGolID + LEFT JOIN itemunitmap ON M_ItemID = ItemUnitMapM_ItemID + AND ItemUnitMapIsActive = 'Y' + LEFT JOIN itemunit ON ItemUnitMapItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + WHERE $where + GROUP BY M_ItemID + ) x"; + + $query_count = $this->db->query($sql_count); + $total = 0; + if ($query_count) { + $total = $query_count->row()->total; + $total_page = ceil($total / $number_limit); + } else { + $this->sys_error_db("item count", $this->db); + exit; + } + + $result = array( + "total" => $total, + "total_page" => $total_page, + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function get_category() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm["search"]; + + $where = "itemCategoryIsActive = 'Y'"; + if (!empty($search)) { + $where .= " AND itemCategoryName LIKE '%$search%'"; + } + + $sql = "SELECT + itemCategoryID, + itemCategoryName + FROM item_category + WHERE $where + ORDER BY itemCategoryID ASC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("category list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function get_group_filter() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + // $search = $prm["search"]; + + // $where = "Nat_GroupIsActive = 'Y'"; + // if (!empty($search)) { + // $where .= " AND Nat_GroupName LIKE '%$search%'"; + // } + + $sql = "SELECT + Nat_GroupID, + Nat_GroupName + FROM nat_group + WHERE Nat_GroupIsActive = 'Y' + ORDER BY Nat_GroupID DESC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("group list", $this->db); + exit; + } + + $rows = $query->result_array(); + + if ($rows) { + array_push($rows, ["Nat_GroupID" => "0", "Nat_GroupName" => "All"]); + } + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function get_group() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm["search"]; + + $where = "Nat_GroupIsActive = 'Y'"; + if (!empty($search)) { + $where .= " AND Nat_GroupName LIKE '%$search%'"; + } + + $sql = "SELECT + Nat_GroupID, + Nat_GroupCode, + Nat_GroupName + FROM nat_group + WHERE Nat_GroupIsActive = 'Y' + ORDER BY Nat_GroupID ASC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("group list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function get_subgroup() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $groupId = $prm["group_id"]; + + $sql = "SELECT + Nat_SubGroupID, + Nat_SubGroupNat_GroupID, + Nat_SubGroupCode, + Nat_SubGroupName, + Nat_SubGroupLangName, + Nat_SubGroupIsResult, + Nat_SubGroupReportTitle + FROM nat_subgroup + WHERE Nat_SubGroupIsActive = 'Y' + AND Nat_SubGroupName LIKE '%$search%' + AND Nat_SubGroupNat_GroupID = $groupId + ORDER BY Nat_SubGroupID DESC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("subgroup list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function get_fa_class() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $flag_type = isset($prm["flag_type"]) ? $prm["flag_type"] : ""; + + $sql = "SELECT + Fa_ClassID, + Fa_ClassName, + Fa_ClassFlagType, + Fa_ClassCoaID, + Fa_ClassCoaAccountNo, + Fa_ClassCoaDesc, + Fa_ClassDepreCorp, + Fa_ClassDepreGov, + Fa_ClassAccumDepreCoaID, + Fa_ClassAccumDepreCoaAccountNo, + Fa_ClassAccumDepreCoaDesc, + Fa_ClassAccumNote, + Fa_ClassAccumCreated, + Fa_ClassAccumLastUpdated, + Fa_ClassIsActive, + Fa_ClassM_UserID + FROM fa_class + WHERE Fa_ClassIsActive = 'Y' + AND Fa_ClassFlagType = '{$flag_type}' + AND Fa_ClassName LIKE '%$search%' + ORDER BY Fa_ClassID DESC"; + + $query = $this->db->query($sql); + // echo $this->db->last_query(); + // exit; + + if (!$query) { + $this->sys_error_db("fa class list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function get_fa_inventaris_gol() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + + $sql = "SELECT + Fa_InventarisGolID, + Fa_InventarisGolName, + Fa_InventarisGolCreated, + Fa_InventarisGolLastUpdated, + Fa_InventarisGolIsActive, + Fa_InventarisGolUserID + FROM fa_inventaris_gol + WHERE Fa_InventarisGolIsActive = 'Y' + + ORDER BY Fa_InventarisGolID DESC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("fa inventaris gol list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function get_unit() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitIsActive, + ItemUnitUserID + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE '%$search%' + ORDER BY ItemUnitID DESC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("item unit list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save_item() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $item_group_id = $prm['itemgroupid']; + $item_sub_group_id = $prm['itemsubgroupid']; + $item_fa_class_id = $prm['itemfaclassid']; + $item_fa_inventaris_id = $prm['itemfainventarisid']; + $item_name = $prm['itemname']; + $inventory_code = $prm['inventory_code']; + $item_category_id = $prm['itemcategoryid']; + + $item_name_search = ""; + $item_name = ""; + if (isset($prm['itemname'])) { + $item_name_search = trim($prm["itemname"]); + $item_name = trim($prm['itemname']); + if ($item_name_search != "") { + $item_name_search = $prm['itemname']; + } + } + + $sql_count = "SELECT COUNT(*) as exist + FROM m_item + WHERE M_ItemIsActive = 'Y' + AND M_ItemDesc = ?"; + + $query_count = $this->db->query($sql_count, [ + $item_name_search + ]); + + if (!$query_count) { + $this->db->trans_rollback(); + $this->sys_error_db("item search & count by name"); + exit; + } + + $get_count = $query_count->row_array(); + if ($get_count['exist'] == 0) { + // Continue with insert logic + $sqlfn = "SELECT fn_numbering('I') as item"; + $queryfn = $this->db->query($sqlfn); + + if (!$queryfn) { + $this->db->trans_rollback(); + $this->sys_error_db("item call sp"); + exit; + } else { + $get_item_code = $queryfn->result_array()[0]["item"]; + } + + $sql_insert = "INSERT INTO m_item ( + M_ItemCode, + M_ItemDesc, + M_ItemItem_CategoryID, + M_ItemInventoryCode, + M_ItemNat_GroupID, + M_ItemNat_SubGroupID, + M_ItemFa_ClassID, + M_ItemM_InventarisGolID, + M_ItemIsActive, + M_ItemCreated, + M_ItemLastUpdated, + M_ItemM_UserID + ) VALUES ( + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + 'Y', + NOW(), + NOW(), + ? + )"; + + $query_insert = $this->db->query($sql_insert, [ + $get_item_code, + $item_name, + $item_category_id, + $inventory_code, + $item_group_id, + $item_sub_group_id, + $item_fa_class_id, + $item_fa_inventaris_id, + $userid + ]); + + if (!$query_insert) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert item"); + exit; + } + + $last_id = $this->db->insert_id(); + + // Insert batch item unit map + if (isset($prm['satuan']) && count($prm['satuan']) > 0) { + foreach ($prm['satuan'] as $key => $value) { + $ItemUnitMapItemUnitID = trim($value['item_unit_id']); + $itemunitpurchase = 'N'; + $itemunitbase = 'N'; + $itemunitreport = 'N'; + $item_unit_min = trim($value['item_unit_min']); + + if ($value['detail_tipe_itemunit'] == "purchase") { + $itemunitpurchase = 'Y'; + } else if ($value['detail_tipe_itemunit'] == "base") { + $itemunitbase = 'Y'; + } else if ($value['detail_tipe_itemunit'] == "report") { + $itemunitreport = 'Y'; + } + + $sql = "INSERT INTO itemunitmap( + ItemUnitMapM_ItemID, + ItemUnitMapItemUnitID, + ItemUnitMapIsPurchase, + ItemUnitMapIsReport, + ItemUnitMapIsBase, + ItemUnitMapMin, + ItemUnitMapIsActive, + ItemUnitMapCreated, + ItemUnitMapLastUpdated, + ItemUnitMapUserID + ) VALUES ( + ?,?,?,?,?,?,?,NOW(),NOW(),? + )"; + + $query = $this->db->query($sql, [ + $last_id, + $ItemUnitMapItemUnitID, + $itemunitpurchase, + $itemunitreport, + $itemunitbase, + $item_unit_min, + 'Y', + $userid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert item unit map"); + exit; + } + } + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array( + "M_ItemCode" => $get_item_code, + "M_ItemDesc" => $item_name + ) + ); + $this->sys_ok($result); + } else { + $errors = array(); + array_push($errors, array( + 'field' => 'name', + 'msg' => 'Nama ' . $item_name . ' sudah ada' + )); + + $result = array( + "total" => -1, + "errors" => $errors, + "records" => 0 + ); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function update_item() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $item_group_id = $prm['itemgroupid']; + $item_sub_group_id = $prm['itemsubgroupid']; + $item_fa_class_id = $prm['itemfaclassid']; + $item_fa_inventaris_id = $prm['itemfainventarisid']; + $item_name = $prm['itemname']; + $inventory_code = $prm['inventory_code']; + $item_category_id = $prm['itemcategoryid']; + $item_id = $prm['itemid']; + + $item_name_search = ""; + $item_name = ""; + if (isset($prm['itemname'])) { + $item_name_search = trim($prm["itemname"]); + $item_name = trim($prm['itemname']); + if ($item_name_search != "") { + $item_name_search = $prm['itemname']; + } + } + + $sql_count = "SELECT COUNT(*) as exist + FROM m_item + WHERE M_ItemIsActive = 'Y' + AND M_ItemDesc = ?"; + + $query_count = $this->db->query($sql_count, [ + $item_name_search + ]); + + if (!$query_count) { + $this->db->trans_rollback(); + $this->sys_error_db("item search & count by name"); + exit; + } else { + + // $get_count = $query_count->row_array(); + // if ($get_count['exist'] == 0) { + + $sql_update = "UPDATE m_item SET + M_ItemDesc = ?, + M_ItemItem_CategoryID = ?, + M_ItemInventoryCode = ?, + M_ItemNat_GroupID = ?, + M_ItemNat_SubGroupID = ?, + M_ItemFa_ClassID = ?, + M_ItemM_InventarisGolID = ?, + M_ItemIsActive = 'Y', + M_ItemLastUpdated = NOW(), + M_ItemM_UserID = ? + WHERE M_ItemID = ?"; + + $query_update = $this->db->query($sql_update, [ + $item_name, + $item_category_id, + $inventory_code, + $item_group_id, + $item_sub_group_id, + $item_fa_class_id, + $item_fa_inventaris_id, + $userid, + $item_id + ]); + + + if (!$query_update) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update item"); + exit; + } + + $sql_update_itemunitmap = "UPDATE itemunitmap SET + ItemUnitMapIsActive = 'N' + WHERE ItemUnitMapM_ItemID = ?"; + $query_update_itemunitmap = $this->db->query($sql_update_itemunitmap, [ + $item_id + ]); + + if (!$query_update_itemunitmap) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update item unit map"); + exit; + } + + // Insert batch item unit map + if (isset($prm['satuan']) && count($prm['satuan']) > 0) { + foreach ($prm['satuan'] as $key => $value) { + $ItemUnitMapItemUnitID = trim($value['item_unit_id']); + $itemunitpurchase = 'N'; + $itemunitbase = 'N'; + $itemunitreport = 'N'; + $item_unit_min = trim($value['item_unit_min']); + + if ($value['detail_tipe_itemunit'] == "purchase") { + $itemunitpurchase = 'Y'; + } else if ($value['detail_tipe_itemunit'] == "base") { + $itemunitbase = 'Y'; + } else if ($value['detail_tipe_itemunit'] == "report") { + $itemunitreport = 'Y'; + } + + if (intval($value['id']) > 0) { + // update + $sql = "UPDATE itemunitmap SET + ItemUnitMapItemUnitID = ?, + ItemUnitMapIsPurchase = ?, + ItemUnitMapIsReport = ?, + ItemUnitMapIsBase = ?, + ItemUnitMapMin = ?, + ItemUnitMapIsActive = 'Y', + ItemUnitMapLastUpdated = NOW(), + ItemUnitMapUserID = ? + WHERE ItemUnitMapID = ?"; + + $query = $this->db->query($sql, [ + $ItemUnitMapItemUnitID, + $itemunitpurchase, + $itemunitreport, + $itemunitbase, + $item_unit_min, + $userid, + $value['id'] + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to update item unit map"); + exit; + } + } else { + // insert + $sql = "INSERT INTO itemunitmap( + ItemUnitMapM_ItemID, + ItemUnitMapItemUnitID, + ItemUnitMapIsPurchase, + ItemUnitMapIsReport, + ItemUnitMapIsBase, + ItemUnitMapMin, + ItemUnitMapIsActive, + ItemUnitMapCreated, + ItemUnitMapLastUpdated, + ItemUnitMapUserID + ) VALUES ( + ?,?,?,?,?,?,?,NOW(),NOW(),? + )"; + + $query = $this->db->query($sql, [ + $prm['itemid'], + $ItemUnitMapItemUnitID, + $itemunitpurchase, + $itemunitreport, + $itemunitbase, + $item_unit_min, + 'Y', + $userid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert item unit map"); + exit; + } + } + } + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array( + "M_ItemDesc" => $item_name + ) + ); + $this->sys_ok($result); + // } else { + // $errors = array(); + // array_push($errors, array( + // 'field' => 'name', + // 'msg' => 'Nama ' . $item_name . ' sudah ada' + // )); + + // $result = array( + // "total" => -1, + // "errors" => $errors, + // "records" => 0 + // ); + // $this->sys_ok($result); + // } + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete_item() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $item_id = $prm['itemid']; + $userid = $this->sys_user["M_UserID"]; + + $sql_delete = "UPDATE m_item SET + M_ItemIsActive = 'N', + M_ItemLastUpdated = NOW(), + M_ItemM_UserID = ? + WHERE M_ItemID = ?"; + + $query_delete = $this->db->query($sql_delete, [ + $userid, + $item_id + ]); + + if (!$query_delete) { + $this->sys_error_db("Failed to delete item"); + exit; + } + + $sql_delete_itemunitmap = "UPDATE itemunitmap SET + ItemUnitMapIsActive = 'N', + ItemUnitMapLastUpdated = NOW(), + ItemUnitMapUserID = ? + WHERE ItemUnitMapM_ItemID = ?"; + $query_delete_itemunitmap = $this->db->query($sql_delete_itemunitmap, [ + $userid, + $item_id + ]); + + if (!$query_delete_itemunitmap) { + $this->sys_error_db("Failed to delete item unit map"); + exit; + } + + $this->sys_ok(array( + "total" => 1, + "records" => array( + "M_ItemID" => $item_id + ) + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mdperiode.php b/application/controllers/mockup/masterdata/accounting/Mdperiode.php new file mode 100644 index 0000000..c0621fc --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mdperiode.php @@ -0,0 +1,195 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + periodeIsActive, + periodeIsClosed + FROM periode + WHERE periodeIsActive = 'Y'"; + $query = $this->db->query($sql); + $rows = $query->result_array(); + + $sql_tot = "SELECT count(periodeID) as total + FROM periode + WHERE periodeIsActive = 'Y'"; + + $query_tot = $this->db->query($sql_tot); + $total_list = 0; + if ($query_tot) { + $total_list = $query_tot->result_array()[0]['total']; + } else { + $this->sys_error_db("periode count", $this->db); + exit; + } + + $result = array( + "total" => $total_list, + "records" => $rows + ); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteperiode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $periodeID = $prm['id']; + + $sql = "UPDATE periode SET + periodeIsActive = 'N', + periodeLastUpdated = now() + WHERE periodeID = ?"; + + $query = $this->db->query( + $sql, + array($periodeID) + ); + if (!$query) { + $this->sys_error_db("update periode active"); + exit; + } + + $result = array( + "total" => 1, + "data" => array('status' => 'OK') + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function addperiode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $periodeyear = $prm["periodeYear"]; + $periodemonth = $prm["periodeMonth"]; + $periodename = $prm["periodeName"]; + $periodestart = $prm["periodeStartDate"]; + $periodeend = $prm["periodeEndDate"]; + + $sql = "INSERT INTO `periode` ( + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate + ) VALUES (?,?,?,?,?)"; + + $qry = $this->db->query($sql, [ + $periodeyear, + $periodemonth, + $periodename, + $periodestart, + $periodeend + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("periode insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editperiode() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $periodeid = $prm["periodeID"]; + $periodeyear = $prm["periodeYear"]; + $periodemonth = $prm["periodeMonth"]; + $periodename = $prm["periodeName"]; + $periodestart = $prm["periodeStartDate"]; + $periodeend = $prm["periodeEndDate"]; + + $sql = "UPDATE periode SET + periodeYear = ?, + periodeMonth = ?, + periodeName = ?, + periodeStartDate = ?, + periodeEndDate = ? + WHERE periodeID = ?"; + + $qry = $this->db->query($sql, [ + $periodeyear, + $periodemonth, + $periodename, + $periodestart, + $periodeend, + $periodeid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("periode error edit", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("periodeID" => $periodeid)); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Mdtype.php b/application/controllers/mockup/masterdata/accounting/Mdtype.php new file mode 100644 index 0000000..87460dc --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mdtype.php @@ -0,0 +1,205 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sql = "SELECT + Rk_TypeID, + Rk_TypeCode, + Rk_TypeName, + Rk_TypeIsActive, + '' as rownumber + FROM rk_type + WHERE Rk_TypeIsActive = 'Y' + AND (Rk_TypeCode LIKE ? OR Rk_TypeName LIKE ?) + ORDER BY Rk_TypeID DESC"; + $query = $this->db->query($sql, [$search, $search]); + if (!$query) { + $this->sys_error_db("type list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $sql_tot = "SELECT count(Rk_TypeID) as total + FROM rk_type + WHERE Rk_TypeIsActive = 'Y' + AND (Rk_TypeCode LIKE ? OR Rk_TypeName LIKE ?)"; + + $query_tot = $this->db->query($sql_tot, [$search, $search]); + $total_list = 0; + if ($query_tot) { + $total_list = $query_tot->result_array()[0]['total']; + } else { + $this->sys_error_db("type count", $this->db); + exit; + } + + foreach ($rows as $k => $v) { + $rows[$k]['rownumber'] = $k + 1; + } + + $result = array( + "total" => $total_list, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteType() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $typeid = $prm['typeid']; + + $sql = "UPDATE rk_type SET + Rk_TypeIsActive = 'N', + Rk_TypeM_UserID = ?, + Rk_TypeLastUpdated = now() + WHERE Rk_TypeID = ?"; + + $query = $this->db->query( + $sql, + array($userid, $typeid) + ); + if (!$query) { + $this->sys_error_db("update type"); + exit; + } + + $result = array( + "total" => 1, + "data" => array('status' => 'OK') + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function addType() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $typecode = $prm["typecode"]; + $typename = $prm["typename"]; + + $sql = "INSERT INTO `rk_type` ( + Rk_TypeCode, + Rk_TypeName, + Rk_TypeIsActive, + Rk_TypeM_UserID, + Rk_TypeCreated + ) VALUES (?,?,'Y',?,NOW())"; + + $qry = $this->db->query($sql, [ + $typecode, + $typename, + $userid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("type insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function editType() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $typecode = $prm["typecode"]; + $typename = $prm["typename"]; + $typeid = $prm["typeid"]; + + $sql = "UPDATE rk_type SET + Rk_TypeCode = ?, + Rk_TypeName = ?, + Rk_TypeM_UserID = ?, + Rk_TypeLastUpdated = NOW() + WHERE Rk_TypeID = ?"; + $qry = $this->db->query($sql, [ + $typecode, + $typename, + $userid, + $typeid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("type error edit", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("typeID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mediajurnalauto-ori.php b/application/controllers/mockup/masterdata/accounting/Mediajurnalauto-ori.php new file mode 100644 index 0000000..f51bb91 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mediajurnalauto-ori.php @@ -0,0 +1,2580 @@ +input->get('jurnalno', true) ?? ""; + $isRegen = $this->input->get('isregen', true) ?? false; + + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Cek kalau API insert di HIT 2x + if (strlen($jurnalNo) == 0 || !$isRegen) { + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALES'); + if ($existJurnal) { + $noCab = $existJurnal->jurnalNo; + $noReg = substr($noCab, 0, -3); + $this->sys_error("Sudah ada jurnal di Jurnal Sales Cabang No: {$noCab} dan Jurnal Sales Regional No: {$noReg}"); + exit; + } + } + // Cek Panjang $jurnalNo. Jika == 16 maka Regional. Contoh: ACSL/202502/0002 + else if (strlen($jurnalNo) == 16 && $isRegen) { + // Get BranchCode from JurnalNo + $regBranchCode = $this->getBranchCodeRegenSalesReg($jurnalNo); + if ($regBranchCode == null) { + $this->sys_error("Tidak ditemukan jurnal cabang untuk di regenerate dari Jurnal Regional Nomor {$jurnalNo}"); + exit; + } + $branchCode = &$regBranchCode; + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESREG', $jurnalNo); + } + // Regional generate cabang + else if (strlen($jurnalNo) == 19 && $isRegen && $branchCode == "ZZ") { + // Get BranchCode from JurnalNo + $regBranchCode = substr($jurnalNo, -2); + if ($regBranchCode == null) { + $this->sys_error("Tidak ditemukan jurnal cabang untuk di regenerate dari Jurnal Regional Nomor {$jurnalNo}"); + exit; + } + $branchCode = &$regBranchCode; + $jurnalNo = substr($jurnalNo, 0, -3); + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESREG', $jurnalNo); + } + // Jika == 19 maka Cabang. Contoh: ACSL/202502/0002/BB. Cabang generate cabang + else if (strlen($jurnalNo) == 19 && $isRegen && $branchCode != "ZZ") { + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESCAB', $jurnalNo); + } else { + $this->sys_error("Jurnal No tidak valid. Jangan ngaco yaa.."); + exit; + } + + // if isRegen true, but existJurnal is empty + if ($isRegen && !$existJurnal) { + $this->sys_error("Tidak ada jurnal yang bisa di regenerate"); + exit; + } + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + $this->db->trans_start($isDebug == 'true'); + + if ($isRegen) { + foreach ($existJurnal as $jurnal) { + $jurnalID = $jurnal->jurnalID; + $this->deleteJurnal($jurnalID); + } + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/sales/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + $rawsCopy = array_map(function ($obj) { + return clone $obj; + }, $raws); + + // 2. Mapping untuk Regional + $detailsReg = []; + $balancesReg = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + [$detailsReg, $balancesReg, $errMapReg] = $this->mappingSalesRegional($raws, $branchCode); + + // 3. Compose info jurnal regional + $jurnalInfoReg = $this->composeJurnalInfo($branchCode, $searchDate, 'SALESREG'); + $jurnalRegNo = $jurnalInfoReg['jurnalNo']; + + // 4. Insert Regional + [$jurnalIDReg, $errInsertReg] = $this->injectJurnal($jurnalInfoReg, $detailsReg); + + // 8. Combines Errors allow duplicate + $jurnalErrReg = array_merge($errMapReg, $errInsertReg); + $this->injectErrors($jurnalErrReg, $jurnalIDReg); + + // 5. Mapping cabang + $detailsCab = []; + $balancesCab = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + + [$detailsCab, $balancesCab, $errMapCab] = $this->mappingSalesCabang($rawsCopy, $jurnalRegNo); + + // 6. Compose jurnal info + $jurnalInfoCab = $this->composeJurnalInfo($branchCode, $searchDate, 'SALESCAB'); + $jurnalInfoCab['jurnalNo'] = $jurnalRegNo . "/{$branchCode}"; // * Khusus Auto Count Sales + + // 7. Inject Cabang + [$jurnalIDCab, $errInsertCab] = $this->injectJurnal($jurnalInfoCab, $detailsCab); + $jurnalInfoCab['jurnalID'] = $jurnalIDCab; + + if ($this->db->trans_status() === FALSE) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert {$jurnalInfoCab['jurnalTitle']} : ", $this->db); + exit; + } + + // 8. Combines Errors allow duplicate + $jurnalErrCab = array_merge($errMapCab, $errInsertCab); + $this->injectErrors($jurnalErrCab, $jurnalIDCab); + + $this->db->trans_complete(); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfoCab['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfoCab['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balancesReg' => $balancesReg, + 'balancesCab' => $balancesCab, + 'jurnalInfoReg' => $jurnalInfoReg, + 'jurnalInfoCab' => $jurnalInfoCab, + 'jurnalErrorsReg' => $jurnalErrReg, + 'jurnalErrorsCab' => $jurnalErrCab, + 'detailsReg' => $detailsReg, + 'detailsCab' => $detailsCab, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + public function insertAr($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'AR'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/ar/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingAr($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'AR'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + var_dump($this->db); + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertArPayment($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'ARPAYMENT'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPayment/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayment($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'ARPAYMENT'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + // Print last query + var_dump($this->db->last_query()); + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertRkTagihan($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'RKTAGIHAN'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPaymentRkTagihan/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + // Print last query + var_dump($this->db->last_query()); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayRkTagihan($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'RKTAGIHAN'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertRkPelunasan($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'RKPELUNASAN'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPaymentRkPelunasan/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayRkPelunasan($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'RKPELUNASAN'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapBank($regID) + { + try { + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); + } else { + $this->db->trans_start(); + } + + $sql = "SELECT M_BranchCode, M_BranchIPAddress, M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? ORDER BY M_BranchCode ASC"; + $qry = $this->db->query($sql, [$regID]); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan cabang yang aktif", $this->db); + exit; + } + $rst = $qry->result(); + $errMap = []; + $inserted = []; + $existData = []; + + foreach ($rst as $row) { + $ipBranch = $row->M_BranchIPAddress; + $url = "http://$ipBranch/one-api/keu/Acc_one/getBanks"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $errMap[] = [ + "err_type" => "Get JSON Cabang {$ipBranch}", + "err_msg" => $raws['message'] + ]; + continue; + } + + // 2. Mapping each item + [$uniqueRows, $err, $exist] = $this->insertMapBank($raws); + $inserted = array_merge($inserted, $uniqueRows); + $errMap = array_merge($errMap, $err); + $existData = array_merge($existData, $exist); + } + + $sql = "SELECT S_RegionalName FROM s_regional WHERE S_RegionalID = ?"; + $qry = $this->db->query($sql, [$regID]); + $regName = $qry->row()->S_RegionalName; + $this->db->trans_complete(); + + $this->sys_ok([ + 'msg' => "Berhasil inject mapping bank Regional {$regName}", + 'branches' => $rst, + 'exist_data' => $existData, + 'failed_row' => $errMap, + 'total_success_row' => count($inserted), + 'inserted_rows' => $inserted + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapBankCab($branchCode) + { + try { + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); + } else { + $this->db->trans_start(); + } + + $sql = "SELECT M_BranchCode, M_BranchIPAddress, M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchCode = ? ORDER BY M_BranchCode ASC"; + $qry = $this->db->query($sql, [$branchCode]); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan cabang yang aktif", $this->db); + exit; + } + $rst = $qry->row(); + $errMap = []; + $inserted = []; + $existData = []; + + + $ipBranch = $rst->M_BranchIPAddress; + $url = "http://$ipBranch/one-api/keu/Acc_one/getBanks"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $errMap[] = [ + "err_type" => "Get JSON Cabang {$ipBranch}", + "err_msg" => $raws['message'] + ]; + } + + // 2. Mapping each item + [$uniqueRows, $err, $exist] = $this->insertMapBank($raws); + $inserted = array_merge($inserted, $uniqueRows); + $errMap = array_merge($errMap, $err); + $existData = array_merge($existData, $exist); + + + $branchName = $qry->row()->M_BranchName; + $this->db->trans_complete(); + + $this->sys_ok([ + 'msg' => "Berhasil inject mapping bank Cabang {$branchName}", + 'branches' => $rst, + 'exist_data' => $existData, + 'failed_row' => $errMap, + 'total_success_row' => count($inserted), + 'inserted_rows' => $inserted + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapNatSubGroup() + { + // Goal: Insert CoaID and CoaDesc to map_nat_subgroup from coa table based MapNatSub_PendapatanCoaAccountNo + $this->db->trans_start(); + + $sql = "SELECT MapNatSub_ID, MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON coaAccountNo = MapNatSub_PendapatanCoaAccountNo + ORDER BY MapNatSub_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + // sql for update + $sql = "UPDATE map_nat_subgroup + SET MapNatSub_PendapatanCoaID = ?, MapNatSub_PendapatanCoaDescription = ? + WHERE MapNatSub_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapNatSub_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data map_nat_subgroup", $this->db); + exit; + } + } + + // Jika tidak ada error return OK + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Gagal insert data map_nat_subgroup", $this->db); + exit; + } + + $this->db->trans_complete(); + $this->sys_ok("Berhasil insert data map_nat_subgroup"); + } + + public function injectMapBankByCoaNo() + { + $this->db->trans_start(); + // NON EDC + $sql = "SELECT MapBank_ID, MapBank_CoaAccountNo, coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_CoaAccountNo + ORDER BY MapBank_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + $sql = "UPDATE map_bank_coa + SET MapBank_CoaID = ?, MapBank_CoaDescription = ? + WHERE MapBank_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapBank_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data mapBank", $this->db); + exit; + } + } + + // EDC + $sql = "SELECT MapBank_ID, MapBank_EDC_CoaAccountNo, coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_EDC_CoaAccountNo + ORDER BY MapBank_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + $sql = "UPDATE map_bank_coa + SET MapBank_EDC_CoaID = ?, MapBank_EDC_CoaDescription = ? + WHERE MapBank_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapBank_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data mapBank EDC", $this->db); + exit; + } + } + // Jika tidak ada error return OK + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Gagal insert data map bank", $this->db); + exit; + } + + $this->db->trans_complete(); + $this->sys_ok("Berhasil insert data map_nat_subgroup"); + } + + public function injectMapRkCabang() + { + $sql = "INSERT INTO map_rk_cabang + (Map_RkCabang_Rk_TypeID, Map_RkCabang_BranchCode, Map_RkCabang_SRegionalID, + Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription) + VALUES + ('RUJ', 'BA', 8, 674, '3160400001', 'R/K CAB. MATRAMAN - RUJUKAN'), + ('KEU', 'BA', 8, 675, '3160400002', 'R/K CAB. MATRAMAN - KEUANGAN'), + ('STOK', 'BA', 8, 677, '3160400004', 'R/K CAB. MATRAMAN - PERSEDIAAN'), + ('AKTIVA', 'BA', 8, 678, '3160400005', 'R/K CAB. MATRAMAN - AKTIVA,ASSET,PERALATAN & PERLENGKAPAN'), + ('POINT', 'BA', 8, 679, '3160400006', 'R/K CAB. MATRAMAN - POINT REWARD PELANGGAN'), + + ('RUJ', '', 8, 828, '3169200001', 'R/K REGIONAL JAKARTA - RUJUKAN'), + ('KEU', '', 8, 829, '3169200002', 'R/K REGIONAL JAKARTA - KEUANGAN'), + ('ARPAY', '', 8, 830, '3169200003', 'R/K REGIONAL JAKARTA - PELUNASAN PIUTANG'), + ('STOK', '', 8, 831, '3169200004', 'R/K REGIONAL JAKARTA - PERSEDIAAN'), + ('AKTIVA', '', 8, 832, '3169200005', 'R/K REGIONAL JAKARTA - AKTIVA,PERALATAN & PERLENGKAPAN'), + ('POINT', '', 8, 832, '3169200005', 'R/K REGIONAL JAKARTA - AKTIVA,PERALATAN & PERLENGKAPAN') + "; + } + + /* + * ------------------------* + * PRIVATE HELPER FUNCTION * + * ------------------------* + */ + + private function getIpBranch($branchCode) + { + $sql = "SELECT M_BranchName, M_BranchIPAddress + FROM m_branch + WHERE M_BranchIsActive = 'Y' AND M_BranchCode = ? LIMIT 1"; + $qry = $this->db->query($sql, [$branchCode]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Tidak ditemukan cabang dengan kode {$branchCode}. Tidak bisa membuat jurnal", $this->db); + exit; + } + $rst = $qry->row(); + $ipBranch = $rst->M_BranchIPAddress; + return $ipBranch; + } + + private function getJsonCabang($url) + { + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + )); + $resp = curl_exec($curl); + curl_close($curl); + + // Cek resp + if ($resp === false) { + $message = "Curl error: " . curl_error($curl); + $this->sys_error($message); + exit; + } + + $resp = json_decode($resp, true); + + if ($resp['status'] == 'OK') { + $data = $resp['data']; + return json_encode($data); + } else { + $message = $resp['message']; + return [ + 'status' => 'ERROR', + 'message' => $message + ]; + } + } + + private function mappingSalesRegional($raws, $branchCode) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + foreach ($raws as $r) { + // 1. Hanya ambil yang Bank Non EDC untuk Debit dengan CoA Bank + // ? Apakah perlu cek $r->NatBankIsEDC = 'N' ? + if ($r->M_BankAccountNo != "" && $r->M_BankAccountNo != "EDC") { + $sql = "SELECT MapBank_CoaID, MapBank_CoaAccountNo, MapBank_CoaDescription + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT('%',$r->M_BankAccountNo, '%') + AND MapBank_IsActive = 'Y' + AND MapBank_BranchCode = ? + AND MapBank_NatBankIsEDC = 'N' + ORDER BY MapBank_ID DESC LIMIT 1"; + $qry = $this->db->query($sql, [$r->BranchCode]); + if ($qry->row() == null) { + // continue; + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank {$r->M_BankAccountNo} di Regional untuk Cabang {$r->BranchCode} tidak ditemukan. Norek: {$r->M_BankAccountNo} | Ref: {$r->Ref} || Debit: {$r->Debit} || Kredit: {$r->Kredit}" + ]; + continue; + } + + $coaID = $qry->row()->MapBank_CoaID; + $coaAccNo = $qry->row()->MapBank_CoaAccountNo; + $coaDescription = $qry->row()->MapBank_CoaDescription; + + if ($coaID == null || $coaAccNo == null || $coaID == '' || $coaAccNo == '') { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank Account Number di Regional untuk Cabang {$r->BranchCode} tidak ditemukan. Norek: {$r->M_BankAccountNo} | Ref: {$r->Ref} || Debit: {$r->Debit} || Kredit: {$r->Kredit}" + ]; + continue; + } + + $r->coaID = $coaID; + $r->coaAccNo = $coaAccNo; + $r->coaDescription = $coaDescription; + $details[] = $r; + + $balances['totalDebit'] += $r->Debit; + $balances['totalKredit'] += $r->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + } + + // 2. Jika ada Debit maka Insert 1 row Credit dengan CoA R/K Cabang dan Kreditnya sesuai dengan total Debit + if ($balances['totalDebit'] > 0 && count($details) > 0) { + $sql = "SELECT Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription + FROM map_rk_cabang + WHERE Map_RkCabang_Rk_TypeID = 3 + AND Map_RkCabang_BranchCode = ? AND Map_RkCabang_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$branchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping R/K Cabang tidak ditemukan. BranchCode: {$branchCode}" + ]; + return [$details, $balances, $errMap]; + } + $kredit = $balances['totalDebit'] - $balances['totalKredit']; + $item = (object) [ + 'Ref' => 'Kredit R/K Cabang ' . $branchCode . ' di Regional', + 'Note' => 'Kredit R/K Cabang ' . $branchCode . ' di Regional', + 'coaID' => $qry->row()->Map_RkCabang_CoaID, + 'coaAccNo' => $qry->row()->Map_RkCabang_CoaAccountNo, + 'coaDescription' => $qry->row()->Map_RkCabang_CoaDescription, + 'Debit' => 0, + 'Kredit' => $kredit + ]; + $details[] = $item; + } + return [$details, $balances, $errMap]; + } + + private function mappingSalesCabang($raws, $jurnalRegNo) + { + try { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + foreach ($raws as $raw) { + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Kredit, 2); + + // Handle Array Bank Map. Masuk Debit + if ( + isset($raw->M_BankAccountNo) && $raw->M_BankAccountNo != "" && + strtolower($raw->M_PaymentTypeCode) != "regonline" + ) { + // Cek jika EDC atau Non EDC dari Tabel map_bank_coa + $sql = "SELECT MapBank_NatBankIsEDC, + MapBank_EDC_CoaID, MapBank_EDC_CoaAccountNo,MapBank_EDC_CoaDescription, + MapBank_CoaID, MapBank_CoaAccountNo, MapBank_CoaDescription + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT('%',?, '%') + AND MapBank_NatBankID = ? + AND MapBank_BranchCode = ? + AND MapBank_IsActive = 'Y' + ORDER BY MapBank_ID DESC LIMIT 1"; + $qry = $this->db->query($sql, [$raw->M_BankAccountNo, $raw->Nat_BankID, $raw->BranchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank di Cabang {$raw->BranchCode} tidak ditemukan. Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + $isEdc = $qry->row()->MapBank_NatBankIsEDC; + + // Jika EDC, pakai mapping piutang EDC + if ($isEdc == 'Y' || $isEdc == 'y') { + $raw->coaID = $qry->row()->MapBank_EDC_CoaID; + $raw->coaAccNo = $qry->row()->MapBank_EDC_CoaAccountNo; + $raw->coaDescription = $qry->row()->MapBank_EDC_CoaDescription; + + // Jika salah satu dari coaID atau CoaAccNo kosong atau null maka error + if ($raw->coaID == 0 || $raw->coaID == '' || $raw->coaAccNo == null || $raw->coaAccNo == '') { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank EDC di Cabang {$raw->BranchCode} tidak ditemukan. Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + $details[] = $raw; + } + // Jika Non EDC, pakai mapping R/K Regional dan bawa AddOn jurnalRegNo + else { + $sql = "SELECT Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription + FROM m_branch + JOIN map_rk_cabang ON Map_RkCabang_SRegionalID = M_BranchS_RegionalID + WHERE M_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 3 + AND (Map_RkCabang_BranchCode = '' OR Map_RkCabang_BranchCode IS NULL) + LIMIT 1"; + $qry = $this->db->query($sql, [$raw->BranchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping R/K Regional Keu tidak ditemukan. Cabang {$raw->BranchCode}| Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaID = $qry->row()->Map_RkCabang_CoaID; + $raw->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + $raw->coaDescription = $qry->row()->Map_RkCabang_CoaDescription; + $raw->addOns = [ + [ + 'jurnalAddOnCode' => 'NOJURNALREG', + 'jurnalAddOnValue' => $jurnalRegNo + ] + ]; + $details[] = $raw; + } + } + + // Handle regonline + else if (stripos(strtolower($raw->M_PaymentTypeCode), 'regonline') !== false) { + $raw->coaAccNo = "2140000001"; + $raw->coaID = 613; + $raw->coaDescription = "PENDAPATAN DITERIMA DIMUKA"; + $details[] = $raw; + } + + // Handle Cash/Tunai. Masuk Debit + else if (stripos(strtolower($raw->M_PaymentTypeCode), 'cash') !== false || stripos($raw->Ref, 'tunai') !== false) { + $raw->coaAccNo = "1110100001"; + $raw->coaID = 5; + $raw->coaDescription = "TUNAI"; + $details[] = $raw; + } + + // Handle Array Sales Nat Map Pendapatan (ada natgroup and natsubgroupID). Pasti Kredit + else if (isset($raw->NatGroupID) && isset($raw->NatSubGroupID)) { + $natGroupID = $raw->NatGroupID; + $natSubGroupID = $raw->NatSubGroupID; + // Mapping Nat SubGroup -> pendapatan + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON coaAccountNo = MapNatSub_PendapatanCoaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$natGroupID, $natSubGroupID]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$natGroupID} | NatSubGroupID: {$natSubGroupID} | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + + // Cek if kredit >= debit valid + if ($raw->Kredit >= $raw->Debit) { + $raw->Debit = 0; + $raw->addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ] + ]; + } else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Kredit Sales lebih kecil dari Debit. Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $details[] = $raw; + } + + // Handle Mapping Nat Group -> diskon. Hanya ada NatGroupID tanpa NatSubGroupID. Pasti Debit + else if (stripos($raw->Ref, 'diskon') !== false) { + $sql = "SELECT MapNatGroup_Disc_coaID, + MapNatGroup_Disc_coaAccNo, + MapNatGroup_Disc_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->NatGroupID]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Diskon tidak ditemukan. NatGroupID: {$raw->NatGroupID} | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + $details[] = $raw; + } + + // Handle Mapping Nat Group -> retur. Masuk Debit + else if (stripos($raw->Ref, 'retur') !== false) { + $raw->Ref = substr($raw->Ref, strpos($raw->Ref, ' ') + 1); + $sql = "SELECT MapNatGroup_Retur_coaID, + MapNatGroup_Retur_coaAccNo, + MapNatGroup_Retur_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->Ref]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Retur tidak ditemukan. Ref: {$raw->Ref}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + $details[] = $raw; + } + + // Handle Mapping round + else if (stripos($raw->Ref, 'round') !== false) { + $sql = "SELECT coaID, coaDescription FROM coa + WHERE coaAccountNo = '1141100002' AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping Round tidak ditemukan. Ref: {$raw->Ref}" + ]; + continue; + } + $raw->coaAccNo = "1141100002"; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + $details[] = $raw; + } else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak bisa mapping, di luar dugaan. Ref: {$raw->Ref}. Debit: {$raw->Debit}. Kredit: {$raw->Kredit}" + ]; + continue; + } + $balances['totalDebit'] += $raw->Debit; + $balances['totalKredit'] += $raw->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + + return [$details, $balances, $errMap]; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function mappingAr($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + // 1. Foreach sampai len-1 karena yang terakhir (len-1) adalah total + $i = 0; + $lastIdx = count($raws) - 1; + foreach ($raws as $raw) { + if ($i == $lastIdx) { + break; + } + $i++; + // Parse string to decimal then round 2 decimal + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Kredit, 2); + + // Total debit, kredit, dan balance. Di atas biar selalu diexecute walau ada continue + $balances['totalDebit'] += $raw->Debit; + $balances['totalKredit'] += $raw->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + + // 2. Kalau is_parent = 1, maka CoA pakai Piutang + if (isset($raw->is_parent) && $raw->is_parent == 1) { + // 2a. Kalau M_CompanyID 1235 (PASIEN KLINISI), pakai coaNo 1120100002 + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // 2b. Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // 2c. Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + $qry = $this->db->query($sql); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref}" + ]; + continue; + } + // * Untuk Parent: dibuat menjadi 2 jurnal_tx + // * 1. Debit Pakai coaCompany (Piutang). rawDbt + // * 2. Kredit Pakai mapping NatSubGroup. rawCr + $rawDbt = clone $raw; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->coaDescription; + $rawDbt->coaAccNo = $qry->row()->coaAccountNo; + $rawDbt->Kredit = 0; + + $rawCr = clone $raw; + $rawCr->Debit = 0; + $natGroupID = $rawCr->NatGroupID; + $natSubGroupID = $rawCr->NatSubGroupID; + + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON MapNatSub_PendapatanCoaAccountNo = coaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$natGroupID, $natSubGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Ref: {$raw->Ref} | Error DB: {$error} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | Deskripsi: {$raw->Deskripsi}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$natGroupID} | NatSubGroupID: {$natSubGroupID} | Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | Deskripsi: {$raw->Deskripsi}" + ]; + continue; + } + $rawCr->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + + $addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + continue; // Agar tidak execute luar if else dan $raw tidak masuk ke details lagi + } + + // 3. Kalau !is_parent dan !is_diskon , maka CoA pakai mapping NatSubGroup (Product) + else if (!isset($raw->is_parent) && !isset($raw->is_diskon)) { + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON MapNatSub_PendapatanCoaAccountNo = coaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$raw->NatGroupID, $raw->NatSubGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Failed mapping natsubgroup AR. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$raw->NatGroupID} | NatSubGroupID: {$raw->NatSubGroupID} | Ref: {$raw->Ref}" + ]; + continue; + } + + $raw->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + + // Kalau kredit negatif, jadikan debit + if ($raw->Kredit < 0) { + $raw->Debit = abs($raw->Kredit); + $raw->Kredit = 0; + } + } + // 4. Kalau is_diskon = 1, maka CoA pakai mapping NatGroup + else if (isset($raw->is_diskon) && $raw->is_diskon == 1) { + $sql = "SELECT MapNatGroup_Disc_coaID, + MapNatGroup_Disc_coaAccNo, + MapNatGroup_Disc_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->NatGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Failed mapping diskon natgroup AR. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Diskon tidak ditemukan. NatGroupID: {$raw->NatGroupID} | Ref: {$raw->Ref}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + // Kalau kredit negatif, jadikan debit + if ($raw->Kredit < 0) { + $raw->Debit = abs($raw->Kredit); + $raw->Kredit = 0; + } + } else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak bisa mapping, di luar dugaan. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + // Add addOns untuk yang selain is_parent = 1 + $addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + $raw->addOns = $addOns; + $details[] = $raw; + } + + return [$details, $balances, $errMap]; + } + + private function mappingArPayment($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + $i = 0; + /* + Setiap item di $raws jadi 2 jurnal_tx dan 7 addOn: + 1. Debit dari Bank + 2. Kredit ke Piutang Company + */ + foreach ($raws as $raw) { + $i++; + //! Kalau Tipe Bayar RK skip dulu karena jurnal terpisah + if ($raw->Tipe_Bayar == "RK") { + continue; + } + + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Debit, 2); //* Karena ini payment, maka Kredit dibuat = Debit + + // 1a. Debit dari Bank + if ($raw->IsBank) { + if ($raw->M_BankAccountNo == "") { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "No Rekening Bank tidak ditemukan. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $norek = str_replace(['-', '.'], '', $raw->M_BankAccountNo); + + $sql = "SELECT MapBank_CoaAccountNo, MapBank_CoaDescription, + MapBank_BankAccountNo, MapBank_BranchCode, + coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_CoaAccountNo + WHERE MapBank_BankAccountNo = ? + AND MapBank_IsActive = 'Y' + LIMIT 1"; + $qry = $this->db->query($sql, [$norek]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping bank Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + + $rst = $qry->row(); + + if ($rst == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Mapping Bank tidak ditemukan. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawDbt = clone $raw; + $rawDbt->coaAccNo = $rst->MapBank_CoaAccountNo; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->coaDescription; + + if ($rawDbt->coaID == "" || $rawDbt->coaID == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Mapping CoA Bank tidak ditemukan. Ref: {$rawDbt->Ref} || Desc: {$rawDbt->Deskripsi} || TipeBayar: {$rawDbt->Tipe_Bayar} || Debit: {$rawDbt->Debit} || Kredit: {$rawDbt->Kredit}" + ]; + continue; + } + } + + // 1b. Debit dari Cash + if (!$raw->IsBank) { + if ($raw->Tipe_Bayar !== 'Cash') { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Belum punya mapping untuk selain Bank dan Cash. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawDbt = clone $raw; + $rawDbt->coaAccNo = "1110100001"; + $rawDbt->coaID = 5; + $rawDbt->coaDescription = "TUNAI"; + } + + // 2. Kredit ke Piutang Company. + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // 2b. Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // 2c. Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + + $qry = $this->db->query($sql); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping AR Company Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawCr = clone $raw; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + $rawCr->coaAccNo = $qry->row()->coaAccountNo; + + + $addOns = [ + [ + "jurnalAddOnCode" => "ARDATE", + "jurnalAddOnValue" => $raw->AR_Date + ], + [ + "jurnalAddOnCode" => "PAYTYPE", + "jurnalAddOnValue" => $raw->Tipe_Bayar + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + + $rawCr->Debit = 0; + $rawDbt->Kredit = 0; + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + return [$details, $balances, $errMap]; + } + + private function mappingArPayRkTagihan($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + /* + Tiap item di $raws jadi 2 jurnal_tx dan 7 addOn: + 1. Debit pakai coa RK + 2. Kredit pakai coa Piutang Company + */ + foreach ($raws as $raw) { + $rawDbt = clone $raw; + $rawCr = clone $raw; + $rawDbt->Debit = round(abs($rawDbt->Total_RkAmount), 2); + $rawCr->Kredit = round(abs($rawDbt->Total_RkAmount), 2); + + //* Jika Total_RkAmount < 0 (nitip tagih) + if ($rawDbt->Total_RkAmount < 0) { + // 1. Debit pakai coa RK + $sql = "SELECT Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription, Map_RkCabang_BranchCode, coaID + FROM map_rk_cabang + JOIN coa ON Map_RkCabang_CoaAccountNo = coaAccountNo + WHERE Map_RkCabang_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 1 + AND Map_RkCabang_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->BranchCode]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping coa RK Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK tidak ditemukan. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | RK_BranchCode: {$raw->RK_BranchCode}" + ]; + continue; + } + $rawDbt->Kredit = 0; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->Map_RkCabang_CoaDesc; + $rawDbt->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + + // 2. Kredit pakai coa Piutang Company + // Kalau M_CompanyID 1235 (PASIEN DOKTER/KLINIS), pakai coaNo 1120100002 + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // Selain itu, pakai coaNo 1120200001 PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + $qry = $this->db->query($sql); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping AR Company Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref} Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | RK_BranchCode: {$raw->RK_BranchCode}" + ]; + continue; + } + + $rawCr->Debit = 0; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + $rawCr->coaAccNo = $qry->row()->coaAccountNo; + } else { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Total_RkAmount >= 0 tidak termasuk nitip tagih (tagihan). Ref: {$raw->Ref}" + ]; + continue; + } + + $addOns = [ + [ + "jurnalAddOnCode" => "ARDATE", + "jurnalAddOnValue" => $raw->AR_Date + ], + [ + "jurnalAddOnCode" => "PAYTYPE", + "jurnalAddOnValue" => $raw->Tipe_Bayar + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + return [$details, $balances, $errMap]; + } + + private function mappingArPayRkPelunasan($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + + /* --------- BRIEF: ------------ + Setiap item di $raws masing-masing menjadi 1 jurnal_tx dan berbeda AddOn + - Debit dari Client + - Coa: coa Bank + - Addon: companyid, companynum, companyname, paytypeID, paymentpusatDate + - Kredit ke R/K cabang lain + - CoA : pakai coa R/K cabang lain + - Addon: companyid, companynum, companyname, paytypeID, paymentpusatDate + - Kredit ke A/R cabang sendiri + - CoA : piutang perusahaan + - AddOn : ARdate, paytypeID, omzettypeid, omzettypename, companyid, companynum, companyname + */ + + // 1. Debit dari Client -> Mapping Bank CoA + // * Pisah foreach, agar kalau continue tidak menganggu foreach kredit yang levelnya lebih rendah + foreach ($raws as $raw) { + $rawDbt = clone $raw->Debit; + $norek = preg_replace('/[^0-9]/', '', $rawDbt->M_BankAccountNo); + $sql = "SELECT MapBank_CoaAccountNo, MapBank_CoaDescription, MapBank_BankAccountNo, MapBank_BranchCode, coaID + FROM map_bank_coa + JOIN coa ON MapBank_CoaAccountNo = coaAccountNo + WHERE MapBank_BankAccountNo = ? AND MapBank_IsActive = 'Y' AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$norek]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping coa RK Ar Payment. Ref: {$rawDbt->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK tidak ditemukan. Desc: {$rawDbt->Desc}" + ]; + continue; + } + $rawDbt->Debit = $rawDbt->F_BillPaymentPusatAmount; + $rawDbt->Kredit = 0; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->MapBank_CoaDescription; + $rawDbt->coaAccNo = $qry->row()->MapBank_CoaAccountNo; + $rawDbt->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawDbt->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawDbt->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawDbt->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawDbt->M_PaymentTypeID + ], + [ + 'jurnalAddOnCode' => 'PAYMENTPUSATDATE', + 'jurnalAddOnValue' => $rawDbt->F_BillPaymentPusatDate + ] + ]; + + $details[] = $rawDbt; + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawDbt->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + // 2 dan 3 untuk Kredit AR R/K cabang lain dan A/R cabang sendiri + foreach ($raws as $raw) { + $rawCabLain = $raw->AR_RK_Cabang_Lain; + $rawCabIni = $raw->AR_Cabang_Ini; + + // 2. Kredit ke R/K cabang lain -> mapping coa R/K cabang lain + // TODO: Reconfirm Map_RkCabang_Rk_TypeID = 'ARPAY' or 'RK' + foreach ($rawCabLain as &$rawCr) { + $sql = "SELECT Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription, Map_RkCabang_BranchCode, coaID + FROM map_rk_cabang + JOIN coa ON Map_RkCabang_CoaAccountNo = coaAccountNo + WHERE Map_RkCabang_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 1 + AND Map_RkCabang_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$rawCr->RK_BranchCode]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping coa RK Ar Payment. Desc: {$rawCr->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK tidak ditemukan. Desc: {$rawCr->Desc}" + ]; + continue; + } + $rawCr->Debit = 0; + $rawCr->Kredit = $rawCr->F_BillIssuePusatDetailTotal; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->Map_RkCabang_CoaDesc; + $rawCr->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + $rawCr->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawCr->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawCr->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawCr->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawCr->M_PaymentTypeID + ] + ]; + + $details[] = $rawCr; + + $balances['totalDebit'] += $rawCr->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + unset($rawCr); + + // 3. Kredit ke A/R cabang sendiri -> mapping coa A/R cabang sendiri + foreach ($rawCabIni as &$rawCr2) { + // PASIEN DOKTER/KLINISI + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + //Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + + $qry = $this->db->query($sql); + + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping coa RK Ar Payment. Desc: {$rawCr2->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK tidak ditemukan. Desc: {$rawCr2->Desc}" + ]; + continue; + } + $rawCr2->Debit = 0; + $rawCr2->Kredit = $rawCr2->SumBillDetailTotal; + $rawCr2->coaID = $qry->row()->coaID; + $rawCr2->coaDescription = $qry->row()->coaDescription; + $rawCr2->coaAccNo = $qry->row()->coaAccountNo; + $rawCr2->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawCr2->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawCr2->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawCr2->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawCr2->M_PaymentTypeID + ], + [ + 'jurnalAddOnCode' => 'ARDATE', + 'jurnalAddOnValue' => $rawCr2->ArDate + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $rawCr2->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $rawCr2->M_OmzetTypeName + ] + ]; + + $details[] = $rawCr2; + + $balances['totalDebit'] += $rawCr2->Debit; + $balances['totalKredit'] += $rawCr2->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + unset($rawCr2); + } + + return [$details, $balances, $errMap]; + } + + private function insertMapBank($raws) + { + $sqlCheck = "SELECT MapBank_BankAccountNo, MapBank_NatBankID, MapBank_BranchCode + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT ('%', ?, '%') AND MapBank_NatBankID = ? AND MapBank_BranchCode = ? + AND MapBank_IsActive = 'Y'"; + + $sql = "INSERT INTO map_bank_coa + (MapBank_BranchCode, MapBank_NatBankName, MapBank_BankAccountNo, + MapBank_NatBankID, MapBank_NatBankCode, MapBank_NatBankIsEDC, + MapBank_IsActive, MapBank_CreatedAt, MapBank_LastUpdatedAt) + VALUES (?, ?, ?, ?, ?, ?, 'Y', NOW(), NOW())"; + $errMap = []; + $seenAcc = []; + $seenNatBank = []; + $seenBranch = []; + $uniqueRows = []; + $existingRows = []; + + foreach ($raws as $raw) { + // * Check existing rows + $qryCheck = $this->db->query($sqlCheck, [ + $raw->M_BankAccountNo, + $raw->Nat_BankID, + $raw->M_BranchCode + ]); + if ($qryCheck->num_rows() > 0 || $qryCheck->row() != null) { + $existingRows[] = [ + 'BankAccountNo' => $raw->M_BankAccountNo, + 'NatBankID' => $raw->Nat_BankID, + 'BranchCode' => $raw->M_BranchCode, + ]; + continue; + } + + //* AVOID DUPLICATION * Skip jika ada row dengan norek dan natbankID yang sama + if (in_array($raw->M_BankAccountNo, $seenAcc)) { + if (in_array($raw->Nat_BankID, $seenNatBank)) { + if (in_array($raw->M_BranchCode, $seenBranch)) { + continue; + } + } + } + $seenAcc[] = $raw->M_BankAccountNo; + $seenNatBank[] = $raw->Nat_BankID; + $seenBranch[] = $raw->M_BranchCode; + $uniqueRows[] = $raw; + + $qry = $this->db->query($sql, [ + $raw->M_BranchCode, + $raw->Nat_BankName, + $raw->M_BankAccountNo, + $raw->Nat_BankID, + $raw->Nat_BankCode, + $raw->Nat_BankIsEDC + ]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Inject', + 'err_msg' => "Failed Inject mapping bank. BranchCode: {$raw->_BranchCode} | BankAccountNo: {$raw->M_BankAccountNo} | NatBankID: {$raw->Nat_BankID} | Error DB: {$error}" + ]; + continue; + } + } + return [$uniqueRows, $errMap, $existingRows]; + } + + private function composeJurnalInfo($branchCode, $searchDate, $jurnalType) + { + $jurnalInfo = []; + // * Sudah pasti success karena di awal sudah ada yang mirip (tidak perlu cek eror) + $sql = "SELECT M_BranchID, M_BranchM_CompanyID, M_BranchS_RegionalID, + M_BranchName, S_RegionalName + FROM m_branch + JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID + WHERE M_BranchCode = ? "; + $qry = $this->db->query($sql, [$branchCode]); + + $regID = $qry->row()->M_BranchS_RegionalID; + $regName = $qry->row()->S_RegionalName; + $branchName = $qry->row()->M_BranchName; + $jurnalInfo['S_RegionalID'] = $regID; + $jurnalInfo['M_BranchID'] = $qry->row()->M_BranchID; + $jurnalInfo['M_BranchName'] = $branchName; + $jurnalInfo['M_BranchCode'] = $branchCode; + $jurnalInfo['jurnalDate'] = $searchDate; + + $jurnalInfo['M_UserID'] = 500; //* 500 untuk autocount + + $sqlcom = "SELECT M_BranchCompanyDetailM_BranchCompanyID, M_BranchCompanyDetailM_BranchCode + FROM m_branch_companydetail + WHERE M_BranchCompanyDetailM_BranchCode = ? + AND M_BranchCompanyDetailIsActive = 'Y' LIMIT 1"; + $qrycom = $this->db->query($sqlcom, [$branchCode]); + if (!$qrycom) { + $this->sys_error_db("Tidak menemukan M_BranchCompany ID untuk branch {$branchCode}", $this->db); + exit; + } + $jurnalInfo['M_BranchCompanyID'] = $qrycom->row()->M_BranchCompanyDetailM_BranchCompanyID; + + // * Get Periode by Inserted Date + $sql = "SELECT periodeID FROM periode WHERE ? BETWEEN periodeStartDate AND periodeEndDate"; + $qry = $this->db->query($sql, [$searchDate]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Tidak menemukan periode jurnal untuk tanggal {$searchDate}", $this->db); + exit; + } + $jurnalInfo['periodeID'] = $qry->row()->periodeID; + + $sqlJurnalNo = "SELECT `fn_numbering`('J') as jurnalNo"; + + switch ($jurnalType) { + case 'SALESREG': + $jurnalInfo['M_BranchCode'] = ''; + $jurnalInfo['jurnalTitle'] = "Auto Daily Sales {$searchDate} Regional: {$regName} Cabang: {$branchName}"; + $jurnalInfo['jurnalDescription'] = "Auto Daily Sales Regional {$regName} pada {$searchDate} untuk Cabang {$branchName}"; + $jurnalInfo['jurnalTypeID'] = 7; //AUTODAILYSALES + $sqlJurnalNo = "SELECT `fn_numbering`('ACSL') as jurnalNo"; + $jurnalNoSuffix = ''; + break; + case 'SALESCAB': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily Sales {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily Sales Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 7; //AUTODAILYSALES + $jurnalInfo['jurnalNo'] = ''; //* Jurnal No Cabang akan dioverwrite dengan jurnal regional + return $jurnalInfo; + break; + case 'AR': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily AR {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily AR Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 10; //AUTODAILYAR + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'ARPAYMENT': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily AR Payment {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily AR Payment Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 11; //AUTODAILYARPAYMENT + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'RKTAGIHAN': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily RK Tagihan Terpusat {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily RK Tagihan Cabang Terpusat {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 12; //AUTODAILYRKTAGIHAN + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'RKPELUNASAN': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily RK Pelunasan Terpusat {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily RK Pelunasan Cabang Terpusat {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 13; //AUTODAILYRKPELUNASAN + $jurnalNoSuffix = "/{$branchCode}"; + break; + + default: + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Jurnal {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Jurnal Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalNoSuffix = "/{$branchCode}"; + break; + } + + $qry = $this->db->query($sqlJurnalNo, []); + if (!$qry) { + $this->sys_error_db("Gagal generate nomor jurnal", $this->db); + exit; + } + $rst = $qry->row(); + $jurnalInfo['jurnalNo'] = $rst->jurnalNo . $jurnalNoSuffix; + + return $jurnalInfo; + } + + private function injectJurnal($jurnalInfo, $details) + { + $sqlHeader = "INSERT INTO jurnal + (jurnalM_BranchCompanyID, JurnalS_RegionalID, jurnalM_BranchCode, + jurnalperiodeID, jurnalNo, jurnalTitle, + jurnalDescription, jurnalDate, jurnalJurnalTypeID, + jurnalCreated, jurnalM_UserID) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)"; + + $qryHead = $this->db->query($sqlHeader, [ + $jurnalInfo['M_BranchCompanyID'], + $jurnalInfo['S_RegionalID'], + $jurnalInfo['M_BranchCode'], + $jurnalInfo['periodeID'], + $jurnalInfo['jurnalNo'], + $jurnalInfo['jurnalTitle'], + $jurnalInfo['jurnalDescription'], + $jurnalInfo['jurnalDate'], + $jurnalInfo['jurnalTypeID'], + $jurnalInfo['M_UserID'] + ]); + if (!$qryHead) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed Insert Jurnal: ", $this->db); + exit; + } + + $jurnalID = $this->db->insert_id(); + $errInsert = []; + + foreach ($details as $detail) { + // Cek If coaID kosong, skip + if ($detail->coaID == "" || !isset($detail->coaID)) { + $errInsert[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA ID untuk {$detail->Ref} tidak ditemukan. Debit: {$detail->Debit} || Kredit: {$detail->Kredit}" + ]; + continue; + } + + [$status, $errDetail] = $this->injectDetailJurnal($detail, $jurnalID); // Child Transaction + if (!$status) { + $errInsert = array_merge($errInsert, $errDetail); + continue; + } + } + + return [$jurnalID, $errInsert]; + } + + private function injectDetailJurnal($prm, $jurnalID) + { + $coaID = $prm->coaID; + $jurnalTxDescription = $prm->coaDescription; + $jurnalTxDebit = $prm->Debit; + $jurnalTxCredit = $prm->Kredit; + $addOns = $prm->addOns; // array + $errDetail = []; + + // * Debit atau Kredit bisa masuk ke Add On (karena AR Payment Debitnya perlu addOn) + + // ? Kalau debit dan kredit kosong, apakah di skip? + // if ($jurnalTxDebit == 0 && $jurnalTxCredit == 0) { + // return; + // } + $insertTx = "INSERT INTO jurnal_tx + (jurnalTxJurnalID, jurnalTxCoaID, jurnalTxDescription, jurnalTxCredit, + jurnalTxDebit, jurnalTxIsActive, jurnalTxCreated, jurnalTxLastUpdated, jurnalTxM_UserID) + VALUES (?, ?, ?, ?, ?, 'Y', NOW(), NOW(), 500)"; + + $insertAddOn = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnIsActive, jurnalAddOnCreated, + jurnalAddOnLastUpdated, jurnalAddOnCreatedUserID) + VALUES (?, ?, ?, ?, 'Y', NOW(), NOW(), 500)"; + + $insertTxCr = $this->db->query($insertTx, [$jurnalID, $coaID, $jurnalTxDescription, $jurnalTxCredit, $jurnalTxDebit]); + if (!$insertTxCr) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errDetail[] = [ + 'err_type' => 'Insert', + 'err_msg' => "Gagal Insert Jurnal Tx. Error: $error" + ]; + return [false, $errDetail]; + } else { + $getTxId = $this->db->insert_id(); + + // Jika punya addOn + if (isset($addOns)) { + foreach ($addOns as $item) { + $addOnState = $this->db->query($insertAddOn, [$jurnalID, $getTxId, $item['jurnalAddOnCode'], $item['jurnalAddOnValue']]); + + if (!$addOnState) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errDetail[] = [ + 'err_type' => 'Insert', + 'err_msg' => "Gagal Insert Jurnal Tx. Error: $error" + ]; + continue; + } + } + } + return [true, $errDetail]; + } + } + + private function injectErrors($jurnalErr, $jurnalID) + { + $sql = "INSERT INTO jurnal_errors + (JurnalErr_JurnalID, JurnalErr_Msg, JurnalErr_CreatedAt, JurnalErr_LastUpdatedAt) + VALUES (?, ?, NOW(), NOW())"; // NOW() is handled by MySQL, so no placeholder is needed + + foreach ($jurnalErr as $err) { + $errEncoded = json_encode($err); + $qry = $this->db->query($sql, [$jurnalID, $errEncoded]); + if (!$qry) { + $this->sys_error_db("Insert Error saja gagal. Coba dicek lagi deh", $this->db); + exit; + } + } + } + + private function getBranchCodeRegenSalesReg($jurnalNo) + { + $sql = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalNo LIKE CONCAT('%', ?, '%') + AND jurnalJurnalTypeID = 7 + AND jurnalIsActive = 'Y' ORDER BY jurnalNo DESC"; //! Harus DESC agar nomor jurnal Cabang ada di index 0 dan diquery row() langsung dapat"; + $qry = $this->db->query($sql, [$jurnalNo]); + if (!$qry) { + $this->sys_error_db("Failed to get branch code for regen sales reg", $this->db); + exit; + } + $rst = $qry->row(); + if ($rst == null || !$rst) { + return null; + } + // Ambil 2 digit terakhir dari $rst->jurnalNo + $branchCode = substr($rst->jurnalNo, -2); + return $branchCode; + } + + private function checkExistingJurnal($branchCode, $searchDate, $jurnalType, $jurnalNo = "") + { + $sql = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalM_BranchCode = ? + AND jurnalDate = ? AND jurnalJurnalTypeID = ? + AND jurnalIsActive = 'Y' ORDER BY jurnalID DESC"; + + switch ($jurnalType) { + case 'SALES': + $jurnalTypeID = 7; //AUTODAILYSALES + break; + case 'SALESCAB': + $jurnalTypeID = 7; //AUTODAILYSALES + $regenFromCab = true; + $noJurCab = $jurnalNo; + $noJurReg = substr($noJurCab, 0, -3); // $noJurReg = $noJur dengan hapus 3 digit terakhir + break; + case 'SALESREG': + $jurnalTypeID = 7; //AUTODAILYSALES + $regenFromReg = true; + $noJurReg = $jurnalNo; + $noJurCab = $jurnalNo . "/{$branchCode}"; + break; + case 'AR': + $jurnalTypeID = 10; //AUTODAILYAR + break; + case 'ARPAYMENT': + $jurnalTypeID = 11; //AUTODAILYARPAYMENT + break; + case 'RKTAGIHAN': + $jurnalTypeID = 12; //AUTODAILYRKTAGIHAN + break; + case 'RKPELUNASAN': + $jurnalTypeID = 13; //AUTODAILYRKPELUNASAN + break; + default: + break; + } + + // * Sementara khusus regen SALES karena harus 2 jurnalID + if ($regenFromCab || $regenFromReg) { + $sql_2 = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalNo LIKE CONCAT(?, '%') + AND jurnalJurnalTypeID = ? + AND jurnalIsActive = 'Y' AND jurnalIsPosted = 'N' ORDER BY jurnalNo ASC"; // ASC Nomor Regional di Atas + $qry_2 = $this->db->query($sql_2, [$noJurReg, $jurnalTypeID]); // Cari dari no jurRegional agar keluar semua + if (!$qry_2) { + $this->sys_error_db("Failed to check existing jurnal", $this->db); + exit; + } + + $rst_2 = $qry_2->result(); + if (!$rst_2 || $rst_2 == null) { + return null; + } + return $rst_2; + } + + $qry = $this->db->query($sql, [$branchCode, $searchDate, $jurnalTypeID]); + if (!$qry) { + $this->sys_error_db("Failed to check existing jurnal", $this->db); + exit; + } + return $qry->row(); + } + + private function jurnalErrors($jurnalID, $type, $msg) + { + // Log jurnal error by insert it to jurnal_errors with jurnalId and Err Message + $fullmsg = [ + 'err_type' => $type, + 'err_msg' => $msg + ]; + $fullmsg = json_encode($fullmsg, JSON_PRETTY_PRINT); + + $sql = "INSERT INTO jurnal_errors + (JurnalErr_JurnalID, JurnalErr_Msg, JurnalErr_CreatedAt, JurnalErr_LastUpdatedAt) + VALUES (?, ?, NOW(), NOW())"; + $qry = $this->db->query($sql, [$jurnalID, $fullmsg]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert jurnal error", $this->db); + exit; + } + $jurnalErrID = $this->db->insert_id(); + return $jurnalErrID; + } + + private function deleteJurnal($jurnalID) + { + $userID = $this->sys_user["M_UserID"]; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa dihapus"); + exit; + } + + // 1. Update jurnal where jurnalID = ? + $this->db->set('jurnalIsActive', 'N'); + $this->db->set('jurnalLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalM_UserID', $userID); + $this->db->where('jurnalID', $jurnalID); + $this->db->update('jurnal'); + + // 2. Update jurnal_tx where jurnalTxJurnalID = ? + $this->db->set('jurnalTxIsActive', 'N'); + $this->db->set('jurnalTxLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalTxM_UserID', $userID); + $this->db->where('jurnalTxJurnalID', $jurnalID); + $this->db->update('jurnal_tx'); + + // 3. Update jurnal_addon where jurnalAddOnJurnalID = ? + $this->db->set('jurnalAddOnIsActive', 'N'); + $this->db->set('jurnalAddOnLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalAddOnLastUpdatedUserID', $userID); + $this->db->where('jurnalAddOnJurnalID', $jurnalID); + $this->db->update('jurnal_addon'); + } + + // Hard Delete (Hanya untuk debugging) + public function deleteDummyData() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $jurnalID = $prm['jurnalID']; + $userID = $this->sys_user["M_UserID"]; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa dihapus"); + exit; + } + + // Start Transaction + $this->db->trans_start(); + + // 1. Delete from jurnal where jurnalID = ? + $this->db->where('jurnalID', $jurnalID); + $this->db->delete('jurnal'); + + // 2. Delete from jurnal_tx where jurnalTxJurnalID = ? + $this->db->where('jurnalTxJurnalID', $jurnalID); + $this->db->delete('jurnal_tx'); + + // 3. Delete from jurnal_addon where jurnalAddOnJurnalID = ? + $this->db->where('jurnalAddOnJurnalID', $jurnalID); + $this->db->delete('jurnal_addon'); + + // 4. Delete from jurnal_errors where JurnalErr_JurnalID = ? + $this->db->where('JurnalErr_JurnalID', $jurnalID); + $this->db->delete('jurnal_errors'); + + // Complete Transaction + $this->db->trans_complete(); + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db('Failed to delete jurnal: ', $this->db); + exit; + } else { + $this->sys_ok("Berhasil hapus jurnal"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function injectSalesManual() + { + $jurnal = "INSERT INTO `jurnal` (`jurnalM_BranchCompanyID`, `JurnalS_RegionalID`, `jurnalM_BranchCode`, `jurnalperiodeID`, `jurnalNo`, `jurnalTitle`, `jurnalDescription`, `jurnalDate`, `jurnalIsPosted`, `jurnalJurnalTypeID`, `jurnalIsActive`, `jurnalCreated`, `jurnalLastUpdated`, `jurnalM_UserID`) VALUES (1, 8, 'BA', 4, 'autosales001', 'Media Jurnal Penjualan ', 'description', '2025-01-09', 'N', 7, 'Y',NOW(), NOW(),345)"; + + $tx = "INSERT INTO `jurnal_tx` (`jurnalTxJurnalID`, `jurnalTxCoaID`, `jurnalTxDescription`, + `jurnalTxDebit`, `jurnalTxCredit`, `jurnalTxIsActive`, `jurnalTxCreated`, + `jurnalTxLastUpdated`, `jurnalTxM_UserID`) VALUES + (96, 5, 'TUNAI', 1850000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 4393950, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 2336050, 0, 'Y', NOW(), NOW(), 345), + (96, 80, 'MANDIRI PT PRAMITA (6455)', 255000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 10827650, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 38022900, 0, 'Y', NOW(), NOW(), 345), + (96, 42, 'BNI PT PRAMITA (5688)', 5766950, 0, 'Y', NOW(), NOW(), 345), + (96, 80, 'MANDIRI PT PRAMITA (6455)', 6458400, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 420000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 1512100, 0, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 4294000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 2189000, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 975000, 'Y', NOW(), NOW(), 345), + (96, 823, 'PENDAPATAN URINALIS', 0, 560000, 'Y', NOW(), NOW(), 345), + (96, 846, 'PEND. RAD. FOTO POLOS', 0, 367000, 'Y', NOW(), NOW(), 345), + (96, 856, 'PENDAPATAN LAYANAN KLINIK', 0, 236000, 'Y', NOW(), NOW(), 345), + (96, 825, 'PENDAPATAN ANALISA KLINIK RUTIN', 0, 564000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 18812000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 25948000, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 5000000, 'Y', NOW(), NOW(), 345), + (96, 823, 'PENDAPATAN URINALIS', 0, 776000, 'Y', NOW(), NOW(), 345), + (96, 846, 'PEND. RAD. FOTO POLOS', 0, 1896000, 'Y', NOW(), NOW(), 345), + (96, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 7090000, 'Y', NOW(), NOW(), 345), + (96, 848, 'PEND. RAD. FOTO KONTRAS', 0, 1748000, 'Y', NOW(), NOW(), 345), + (96, 856, 'PENDAPATAN LAYANAN KLINIK', 0, 0, 'Y', NOW(), NOW(), 345), + (96, 865, 'PEND. LAYANAN JASA MEDIS LAINNYA', 0, 103000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 840000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 687000, 'Y', NOW(), NOW(), 345), + (96, 830, 'PENDAPATAN LAB PATHOLOGI ANATOMI', 0, 503500, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 538000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 420000, 'Y', NOW(), NOW(), 345), + (96, 828, 'PENDAPATAN MIKROBIOLOGI', 0, 1618000, 'Y', NOW(), NOW(), 345), + (96, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 1547000, 'Y', NOW(), NOW(), 345), + (96, 847, 'DISCOUNT PENDAPATAN LABORATORIUM', 4623550, 0, 'Y', NOW(), NOW(), 345), + (96, 854, 'DISC PEND. RADIODIAGNOSTIK', 243550, 0, 'Y', NOW(), NOW(), 345), + -- diskon layanan medis lainnya pakai disc layanan klinik + (96, 867, 'DISC PEND. LAYANAN KLINIK', 0, 0, 'Y', NOW(), NOW(), 345), + (96, 195, 'PEMBULATAN', 1400, 0, 'Y', NOW(), NOW(), 345), + "; + + $addOn = "INSERT INTO `jurnal_addon` (`jurnalAddOnJurnalID`, `jurnalAddOnJurnalTxID`, + `jurnalAddOnCode`, `jurnalAddOnValue`, `jurnalAddOnIsActive`, `jurnalAddOnCreated`, + `jurnalAddOnCreatedUserID`, `jurnalAddOnDeleted`, `jurnalAddOnDeletedUserID`, + `jurnalAddOnLastUpdatedUserID`, `jurnalAddOnLastUpdated`) VALUES + (96, 316,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 316,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 317,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 317,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 318,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 318,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 319,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 319,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 320,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 320,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 321,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 321,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 322,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 322,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 323,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 323,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 324,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 324,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 325,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 325,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 326,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 326,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 327,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 327,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 328,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 328,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 329,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 329,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 330,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 330,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 331,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 331,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 332,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 332,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 333,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 333,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 334,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 334,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 335,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 335,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 336,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 336,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 337,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 337,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 338,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 338,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()) + "; + } + + private function injectArManual() + { + $jurnal = "INSERT INTO `jurnal` (`jurnalM_BranchCompanyID`, `JurnalS_RegionalID`, + `jurnalM_BranchCode`, `jurnalperiodeID`, `jurnalNo`, `jurnalTitle`, `jurnalDescription`, + `jurnalDate`, `jurnalIsPosted`, `jurnalJurnalTypeID`, `jurnalIsActive`, `jurnalCreated`, + `jurnalLastUpdated`, `jurnalM_UserID`) VALUES (1, 8, 'BA', 4, 'autoAR001', + 'Media Jurnal AR', 'inject manual AR belum balance', '2025-01-09', 'N', 10, 'Y', + NOW(), NOW(),345)"; + + $jurnalID = 144; + + $tx = "INSERT INTO `jurnal_tx` (`jurnalTxJurnalID`, `jurnalTxCoaID`, `jurnalTxDescription`, + `jurnalTxDebit`, `jurnalTxCredit`, `jurnalTxIsActive`, `jurnalTxCreated`, + `jurnalTxLastUpdated`, `jurnalTxM_UserID`) VALUES + (144, 199, 'PASIEN DOKTER / KLINISI', 585600, 0, 'Y', NOW(), NOW(), 345), + (144, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 732000, 'Y', NOW(), NOW(), 345), + (144, 854, 'DISC PEND. RADIODIAGNOSTIK', 0, -146400, 'Y', NOW(), NOW(), 345), + + (144, 595, 'HUTANG BPJS KESEHATAN', 24520000, 0, 'Y', NOW(), NOW(), 345), + (144, 823, 'PENDAPATAN URINALISIS ', 0, 10856000, 'Y', NOW(), NOW(), 345), + (144, 826, 'PENDAPATAN KIMIA KLINIK', 0, 37806000, 'Y', NOW(), NOW(), 345), + (144, 847, 'DISCOUNT PENDAPATAN LABORATORIUM', 0, -24142000, 'Y', NOW(), NOW(), 345), + + "; + + $addOn = "INSERT INTO `jurnal_addon` (`jurnalAddOnJurnalID`, `jurnalAddOnJurnalTxID`, + `jurnalAddOnCode`, `jurnalAddOnValue`, `jurnalAddOnIsActive`, `jurnalAddOnCreated`, + `jurnalAddOnCreatedUserID`, `jurnalAddOnDeleted`, `jurnalAddOnDeletedUserID`, + `jurnalAddOnLastUpdatedUserID`, `jurnalAddOnLastUpdated`) VALUES + (144, 913,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 913,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 913,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (144, 916,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 916,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 916,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + "; + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Mediajurnalauto.php b/application/controllers/mockup/masterdata/accounting/Mediajurnalauto.php new file mode 100644 index 0000000..6bf1af4 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Mediajurnalauto.php @@ -0,0 +1,2717 @@ +input->get('jurnalno', true) ?? ""; + $isRegen = $this->input->get('isregen', true) ?? false; + + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Cek kalau API insert di HIT 2x + if (strlen($jurnalNo) == 0 || !$isRegen) { + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALES'); + if ($existJurnal) { + $noCab = $existJurnal->jurnalNo; + $noReg = substr($noCab, 0, -3); + $this->sys_error("Sudah ada jurnal di Jurnal Sales Cabang No: {$noCab} dan Jurnal Sales Regional No: {$noReg}"); + exit; + } + } + // Cek Panjang $jurnalNo. Jika == 16 maka Regional. Contoh: ACSL/202502/0002 + else if (strlen($jurnalNo) == 16 && $isRegen) { + // Get BranchCode from JurnalNo + $regBranchCode = $this->getBranchCodeRegenSalesReg($jurnalNo); + if ($regBranchCode == null) { + $this->sys_error("Tidak ditemukan jurnal cabang untuk di regenerate dari Jurnal Regional Nomor {$jurnalNo}"); + exit; + } + $branchCode = &$regBranchCode; + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESREG', $jurnalNo); + } + // Regional generate cabang + else if (strlen($jurnalNo) == 19 && $isRegen && $branchCode == "ZZ") { + // Get BranchCode from JurnalNo + $regBranchCode = $this->getBranchCodeRegenSalesReg($jurnalNo); + if ($regBranchCode == null) { + $this->sys_error("Tidak ditemukan jurnal cabang untuk di regenerate dari Jurnal Regional Nomor {$jurnalNo}"); + exit; + } + $branchCode = &$regBranchCode; + $jurnalNo = substr($jurnalNo, 0, -3); + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESREG', $jurnalNo); + } + // Jika == 19 maka Cabang. Contoh: ACSL/202502/0002/BB. Cabang generate cabang + else if (strlen($jurnalNo) == 19 && $isRegen && $branchCode != "ZZ") { + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'SALESCAB', $jurnalNo); + } else { + $this->sys_error("Jurnal No tidak valid. Jangan ngaco yaa.."); + exit; + } + + // if isRegen true, but existJurnal is empty + if ($isRegen && !$existJurnal) { + $this->sys_error("Tidak ada jurnal yang bisa di regenerate"); + exit; + } + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + $this->db->trans_start($isDebug == 'true'); + + if ($isRegen) { + foreach ($existJurnal as $jurnal) { + $jurnalID = $jurnal->jurnalID; + $this->deleteJurnal($jurnalID); + } + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/sales/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + $rawsCopy = array_map(function ($obj) { + return clone $obj; + }, $raws); + + // 2. Mapping untuk Regional + $detailsReg = []; + $balancesReg = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + [$detailsReg, $balancesReg, $errMapReg] = $this->mappingSalesRegional($raws, $branchCode); + + // 3. Compose info jurnal regional + $jurnalInfoReg = $this->composeJurnalInfo($branchCode, $searchDate, 'SALESREG'); + $jurnalRegNo = $jurnalInfoReg['jurnalNo']; + + // 4. Insert Regional + [$jurnalIDReg, $errInsertReg] = $this->injectJurnal($jurnalInfoReg, $detailsReg); + + // 8. Combines Errors allow duplicate + $jurnalErrReg = array_merge($errMapReg, $errInsertReg); + $this->injectErrors($jurnalErrReg, $jurnalIDReg); + + // 5. Mapping cabang + $detailsCab = []; + $balancesCab = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + + [$detailsCab, $balancesCab, $errMapCab] = $this->mappingSalesCabang($rawsCopy, $jurnalRegNo); + + // 6. Compose jurnal info + $jurnalInfoCab = $this->composeJurnalInfo($branchCode, $searchDate, 'SALESCAB'); + $jurnalInfoCab['jurnalNo'] = $jurnalRegNo . "/{$branchCode}"; // * Khusus Auto Count Sales + + // 7. Inject Cabang + [$jurnalIDCab, $errInsertCab] = $this->injectJurnal($jurnalInfoCab, $detailsCab); + $jurnalInfoCab['jurnalID'] = $jurnalIDCab; + + if ($this->db->trans_status() === FALSE) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert {$jurnalInfoCab['jurnalTitle']} : ", $this->db); + exit; + } + + // 8. Combines Errors allow duplicate + $jurnalErrCab = array_merge($errMapCab, $errInsertCab); + $this->injectErrors($jurnalErrCab, $jurnalIDCab); + + $this->db->trans_complete(); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfoCab['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfoCab['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balancesReg' => $balancesReg, + 'balancesCab' => $balancesCab, + 'jurnalInfoReg' => $jurnalInfoReg, + 'jurnalInfoCab' => $jurnalInfoCab, + 'jurnalErrorsReg' => $jurnalErrReg, + 'jurnalErrorsCab' => $jurnalErrCab, + 'detailsReg' => $detailsReg, + 'detailsCab' => $detailsCab, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + public function insertAr($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'AR'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/ar/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingAr($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'AR'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + var_dump($this->db); + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertArPayment($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'ARPAYMENT'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPayment/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayment($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'ARPAYMENT'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + // Print last query + var_dump($this->db->last_query()); + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertRkTagihan($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'RKTAGIHAN'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPaymentRkTagihan/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + // Print last query + var_dump($this->db->last_query()); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayRkTagihan($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'RKTAGIHAN'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertRkPelunasan($branchCode, $searchDate, $isRegen = "", $jurnalID = "") + { + try { + // Validasi tanggal + $date = date('Y-m-d', strtotime($searchDate)); + if ($date != $searchDate) { + $this->sys_error("Tanggal tidak valid. Format: YYYY-MM-DD"); + exit; + } + if ($date > date('Y-m-d')) { + $this->sys_error("Tanggal tidak boleh lebih dari hari ini"); + exit; + } + + // Check if there is a jurnal in the same date + $existJurnal = $this->checkExistingJurnal($branchCode, $searchDate, 'RKPELUNASAN'); + if ($existJurnal) { + $isRegen = true; + $jurnalID = $existJurnal->jurnalID; + } + + $jurnalInfo = []; + + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); // (true) jika debug + } else { + $this->db->trans_start(); + } + + if ($isRegen) { + $this->deleteJurnal($jurnalID); + } + + $ipBranch = $this->getIpBranch($branchCode); + $url = "http://$ipBranch/one-api/keu/Acc_one/arPaymentRkPelunasan/{$searchDate}/json"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $this->db->trans_rollback(); + $this->sys_error("Gagal untuk mendapat JSON Cabang {$branchCode} di {$ipBranch}" . $raws['message']); + exit; + } + + // 2. Mapping each item + [$details, $balances, $errMap] = $this->mappingArPayRkPelunasan($raws); + + // 3. Compose jurnal info + $jurnalInfo = $this->composeJurnalInfo($branchCode, $searchDate, 'RKPELUNASAN'); + + // 4. Inject to DB + [$jurnalID, $errInsert] = $this->injectJurnal($jurnalInfo, $details); + $jurnalInfo['jurnalID'] = $jurnalID; + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Failed to insert {$jurnalInfo['jurnalTitle']} : ", $this->db); + exit; + } + + // 5. Combines Errors allow duplicate + $jurnalErr = array_merge($errMap, $errInsert); + $this->injectErrors($jurnalErr, $jurnalID); + + $this->db->trans_complete(); + + $lenRaws = count($raws); + $lenMap = count($details); + + if ($isRegen) { + $msg = "Berhasil regenerate jurnal {$jurnalInfo['jurnalTitle']}"; + } else { + $msg = "Berhasil inject jurnal {$jurnalInfo['jurnalTitle']}"; + } + + $this->sys_ok([ + 'msg' => $msg, + 'balances' => $balances, + 'jurnalErrors' => $jurnalErr, + 'jurnalInfo' => $jurnalInfo, + 'details' => $details, + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapBank($regID) + { + try { + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); + } else { + $this->db->trans_start(); + } + + $sql = "SELECT M_BranchCode, M_BranchIPAddress, M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? ORDER BY M_BranchCode ASC"; + $qry = $this->db->query($sql, [$regID]); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan cabang yang aktif", $this->db); + exit; + } + $rst = $qry->result(); + $errMap = []; + $inserted = []; + $existData = []; + + foreach ($rst as $row) { + $ipBranch = $row->M_BranchIPAddress; + $url = "http://$ipBranch/one-api/keu/Acc_one/getBanks"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $errMap[] = [ + "err_type" => "Get JSON Cabang {$ipBranch}", + "err_msg" => $raws['message'] + ]; + continue; + } + + // 2. Mapping each item + [$uniqueRows, $err, $exist] = $this->insertMapBank($raws); + $inserted = array_merge($inserted, $uniqueRows); + $errMap = array_merge($errMap, $err); + $existData = array_merge($existData, $exist); + } + + $sql = "SELECT S_RegionalName FROM s_regional WHERE S_RegionalID = ?"; + $qry = $this->db->query($sql, [$regID]); + $regName = $qry->row()->S_RegionalName; + $this->db->trans_complete(); + + $this->sys_ok([ + 'msg' => "Berhasil inject mapping bank Regional {$regName}", + 'branches' => $rst, + 'exist_data' => $existData, + 'failed_row' => $errMap, + 'total_success_row' => count($inserted), + 'inserted_rows' => $inserted + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapBankCab($branchCode) + { + try { + $isDebug = $this->sys_input['isDebug'] ? $this->sys_input['isDebug'] : 'false'; + if ($isDebug == 'true') { + $this->db->trans_start(true); + } else { + $this->db->trans_start(); + } + + $sql = "SELECT M_BranchCode, M_BranchIPAddress, M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchCode = ? ORDER BY M_BranchCode ASC"; + $qry = $this->db->query($sql, [$branchCode]); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan cabang yang aktif", $this->db); + exit; + } + $rst = $qry->row(); + $errMap = []; + $inserted = []; + $existData = []; + + + $ipBranch = $rst->M_BranchIPAddress; + $url = "http://$ipBranch/one-api/keu/Acc_one/getBanks"; + + // 1. Get JSON from cabang + $raws = json_decode($this->getJsonCabang($url)); + if ($raws['status'] == 'ERROR') { + $errMap[] = [ + "err_type" => "Get JSON Cabang {$ipBranch}", + "err_msg" => $raws['message'] + ]; + } + + // 2. Mapping each item + [$uniqueRows, $err, $exist] = $this->insertMapBank($raws); + $inserted = array_merge($inserted, $uniqueRows); + $errMap = array_merge($errMap, $err); + $existData = array_merge($existData, $exist); + + $branchName = $qry->row()->M_BranchName; + $this->db->trans_complete(); + + $this->sys_ok([ + 'msg' => "Berhasil inject mapping bank Cabang {$branchName}", + 'branches' => $rst, + 'exist_data' => $existData, + 'failed_row' => $errMap, + 'total_success_row' => count($inserted), + 'inserted_rows' => $inserted + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function injectMapNatSubGroup() + { + // Goal: Insert CoaID and CoaDesc to map_nat_subgroup from coa table based MapNatSub_PendapatanCoaAccountNo + $this->db->trans_start(); + + $sql = "SELECT MapNatSub_ID, MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON coaAccountNo = MapNatSub_PendapatanCoaAccountNo + ORDER BY MapNatSub_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + // sql for update + $sql = "UPDATE map_nat_subgroup + SET MapNatSub_PendapatanCoaID = ?, MapNatSub_PendapatanCoaDescription = ? + WHERE MapNatSub_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapNatSub_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data map_nat_subgroup", $this->db); + exit; + } + } + + // Jika tidak ada error return OK + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Gagal insert data map_nat_subgroup", $this->db); + exit; + } + + $this->db->trans_complete(); + $this->sys_ok("Berhasil insert data map_nat_subgroup"); + } + + public function injectMapBankByCoaNo() + { + $this->db->trans_start(); + // NON EDC + $sql = "SELECT MapBank_ID, MapBank_CoaAccountNo, coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_CoaAccountNo + ORDER BY MapBank_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + $sql = "UPDATE map_bank_coa + SET MapBank_CoaID = ?, MapBank_CoaDescription = ? + WHERE MapBank_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapBank_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data mapBank", $this->db); + exit; + } + } + + // EDC + $sql = "SELECT MapBank_ID, MapBank_EDC_CoaAccountNo, coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_EDC_CoaAccountNo + ORDER BY MapBank_ID ASC"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Tidak ditemukan data map_nat_subgroup", $this->db); + exit; + } + $rst = $qry->result(); + + $sql = "UPDATE map_bank_coa + SET MapBank_EDC_CoaID = ?, MapBank_EDC_CoaDescription = ? + WHERE MapBank_ID = ?"; + + foreach ($rst as $item) { + $qry = $this->db->query($sql, [$item->coaID, $item->coaDescription, $item->MapBank_ID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal insert data mapBank EDC", $this->db); + exit; + } + } + // Jika tidak ada error return OK + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db("Gagal insert data map bank", $this->db); + exit; + } + + $this->db->trans_complete(); + $this->sys_ok("Berhasil insert data map_nat_subgroup"); + } + + public function injectMapRkCabang() + { + $sql = "INSERT INTO map_rk_cabang + (Map_RkCabang_Rk_TypeID, Map_RkCabang_BranchCode, Map_RkCabang_SRegionalID, + Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription) + VALUES + ('RUJ', 'BA', 8, 674, '3160400001', 'R/K CAB. MATRAMAN - RUJUKAN'), + ('KEU', 'BA', 8, 675, '3160400002', 'R/K CAB. MATRAMAN - KEUANGAN'), + ('STOK', 'BA', 8, 677, '3160400004', 'R/K CAB. MATRAMAN - PERSEDIAAN'), + ('AKTIVA', 'BA', 8, 678, '3160400005', 'R/K CAB. MATRAMAN - AKTIVA,ASSET,PERALATAN & PERLENGKAPAN'), + ('POINT', 'BA', 8, 679, '3160400006', 'R/K CAB. MATRAMAN - POINT REWARD PELANGGAN'), + + ('RUJ', '', 8, 828, '3169200001', 'R/K REGIONAL JAKARTA - RUJUKAN'), + ('KEU', '', 8, 829, '3169200002', 'R/K REGIONAL JAKARTA - KEUANGAN'), + ('ARPAY', '', 8, 830, '3169200003', 'R/K REGIONAL JAKARTA - PELUNASAN PIUTANG'), + ('STOK', '', 8, 831, '3169200004', 'R/K REGIONAL JAKARTA - PERSEDIAAN'), + ('AKTIVA', '', 8, 832, '3169200005', 'R/K REGIONAL JAKARTA - AKTIVA,PERALATAN & PERLENGKAPAN'), + ('POINT', '', 8, 832, '3169200005', 'R/K REGIONAL JAKARTA - AKTIVA,PERALATAN & PERLENGKAPAN') + "; + } + + /* + * ------------------------* + * PRIVATE HELPER FUNCTION * + * ------------------------* + */ + + private function getIpBranch($branchCode) + { + $sql = "SELECT M_BranchName, M_BranchIPAddress + FROM m_branch + WHERE M_BranchIsActive = 'Y' AND M_BranchCode = ? LIMIT 1"; + $qry = $this->db->query($sql, [$branchCode]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Tidak ditemukan cabang dengan kode {$branchCode}. Tidak bisa membuat jurnal", $this->db); + exit; + } + $rst = $qry->row(); + $ipBranch = $rst->M_BranchIPAddress; + return $ipBranch; + } + + private function getJsonCabang($url) + { + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + )); + $resp = curl_exec($curl); + curl_close($curl); + + // Cek resp + if ($resp === false) { + $message = "Curl error: " . curl_error($curl); + $this->sys_error($message); + exit; + } + + $resp = json_decode($resp, true); + + if ($resp['status'] == 'OK') { + $data = $resp['data']; + return json_encode($data); + } else { + $message = $resp['message']; + return [ + 'status' => 'ERROR', + 'message' => $message + ]; + } + } + + /** + * Jika totalDebit != totalKredit dan selisih < Rp 500, + * maka masukkan selisih ke CoA pembulatan: CoaAccNo 1141100002 + * Masukkan sebagai debit jika debit < kredit + * Masukkan sebagai kredit jika debit > kredit + */ + private function handleRoundingDifference($balances, $details, $errMap) + { + $debit = round($balances['totalDebit'], 2); + $kredit = round($balances['totalKredit'], 2); + if ($debit != $kredit) { + // Kalau selisih < 500, masuk ke pembulatan + if (abs($debit - $kredit) < 500){ + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1141100002' AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak ditemukan mapping pembulatan CoA No 1141100002 di tabel coa." + ]; + } else { + $r = new stdClass(); + $r->coaAccNo = $qry->row()->coaAccountNo; + $r->coaID = $qry->row()->coaID; + $r->coaDescription = $qry->row()->coaDescription; + + if ($debit < $kredit) { + $r->Debit = abs($debit - $kredit); + $r->Kredit = 0; + } else { + $r->Debit = 0; + $r->Kredit = abs($debit - $kredit); + } + $details[] = $r; + + $balances['totalDebit'] += round($r->Debit, 2); + $balances['totalKredit'] += round($r->Kredit, 2); + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + } + // Kalau selisih > 500 masuk sebagai error + else { + $selisih = round(abs($debit - $kredit),2); + $lebihBesar = $debit > $kredit ? 'Debit' : 'Kredit'; + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Selisih Debit dan Kredit lebih dari Rp 500. {$lebihBesar} lebih besar dengan selisih Rp {$selisih} " + ]; + } + } + + // Rounding Total Debit Kredit and Balances + $balances['totalDebit'] = round($balances['totalDebit'], 2); + $balances['totalKredit'] = round($balances['totalKredit'], 2); + $balances['totalBalance'] = round($balances['totalBalance'], 2); + + return [$details, $balances, $errMap]; + } + + private function mappingSalesRegional($raws, $branchCode) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + foreach ($raws as $r) { + $r->Debit = round($r->Debit, 2); + $r->Kredit = round($r->Kredit, 2); + + // 1. Hanya ambil yang Bank Non EDC untuk Debit dengan CoA Bank + // ? Apakah perlu cek $r->NatBankIsEDC = 'N' ? + if ($r->M_BankAccountNo != "" && $r->M_BankAccountNo != "EDC") { + $sql = "SELECT MapBank_CoaID, MapBank_CoaAccountNo, MapBank_CoaDescription + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT('%',$r->M_BankAccountNo, '%') + AND MapBank_IsActive = 'Y' + AND MapBank_BranchCode = ? + AND MapBank_NatBankIsEDC = 'N' + ORDER BY MapBank_ID DESC LIMIT 1"; + $qry = $this->db->query($sql, [$r->BranchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank {$r->M_BankAccountNo} di Regional untuk Cabang {$r->BranchCode} yang Non-EDC tidak ditemukan. Norek: {$r->M_BankAccountNo} | Ref: {$r->Ref} || Debit: {$r->Debit} || Kredit: {$r->Kredit}" + ]; + continue; + } + + $coaID = $qry->row()->MapBank_CoaID; + $coaAccNo = $qry->row()->MapBank_CoaAccountNo; + $coaDescription = $qry->row()->MapBank_CoaDescription; + + if ($coaID == null || $coaAccNo == null || $coaID == '' || $coaAccNo == '') { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank {$r->M_BankAccountNo} di Regional untuk Cabang {$r->BranchCode} yang Non-EDC tidak ditemukan. Norek: {$r->M_BankAccountNo} | Ref: {$r->Ref} || Debit: {$r->Debit} || Kredit: {$r->Kredit}" + ]; + continue; + } + + $r->coaID = $coaID; + $r->coaAccNo = $coaAccNo; + $r->coaDescription = $coaDescription; + $details[] = $r; + + $balances['totalDebit'] += $r->Debit; + $balances['totalKredit'] += $r->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + } + + // 2. Jika ada Debit maka Insert 1 row Credit dengan CoA R/K Cabang dan Kreditnya sesuai dengan total Debit + if ($balances['totalDebit'] > 0 && count($details) > 0) { + $sql = "SELECT Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription + FROM map_rk_cabang + WHERE Map_RkCabang_Rk_TypeID = 3 + AND Map_RkCabang_BranchCode = ? AND Map_RkCabang_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$branchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping R/K Cabang-Coa (Tabel: map_rk_cabang) tidak ditemukan untuk BranchCode: {$branchCode}" + ]; + return [$details, $balances, $errMap]; + } + $kredit = $balances['totalDebit'] - $balances['totalKredit']; + $item = (object) [ + 'Ref' => 'Kredit R/K Cabang ' . $branchCode . ' di Regional', + 'Note' => 'Kredit R/K Cabang ' . $branchCode . ' di Regional', + 'coaID' => $qry->row()->Map_RkCabang_CoaID, + 'coaAccNo' => $qry->row()->Map_RkCabang_CoaAccountNo, + 'coaDescription' => $qry->row()->Map_RkCabang_CoaDescription, + 'Debit' => 0, + 'Kredit' => $kredit + ]; + + $balances['totalKredit'] += $kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + $details[] = $item; + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + return [$details, $balances, $errMap]; + } + + private function mappingSalesCabang($raws, $jurnalRegNo) + { + try { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + foreach ($raws as $raw) { + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Kredit, 2); + + // Handle Array Bank Map. Masuk Debit + if ( isset($raw->M_BankAccountNo) && $raw->M_BankAccountNo != "" && strtolower($raw->M_PaymentTypeCode) != "regonline" + ) { + // Cek jika EDC atau Non EDC dari Tabel map_bank_coa + $sql = "SELECT MapBank_NatBankIsEDC, + MapBank_EDC_CoaID, MapBank_EDC_CoaAccountNo,MapBank_EDC_CoaDescription, + MapBank_CoaID, MapBank_CoaAccountNo, MapBank_CoaDescription + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT('%',?, '%') + AND MapBank_NatBankID = ? + AND MapBank_BranchCode = ? + AND MapBank_IsActive = 'Y' + ORDER BY MapBank_ID DESC LIMIT 1"; + $qry = $this->db->query($sql, [$raw->M_BankAccountNo, $raw->Nat_BankID, $raw->BranchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank di Cabang {$raw->BranchCode} tidak ditemukan. Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + $isEdc = $qry->row()->MapBank_NatBankIsEDC; + + // Jika EDC, pakai mapping piutang EDC + if ($isEdc == 'Y' || $isEdc == 'y') { + $raw->coaID = $qry->row()->MapBank_EDC_CoaID; + $raw->coaAccNo = $qry->row()->MapBank_EDC_CoaAccountNo; + $raw->coaDescription = $qry->row()->MapBank_EDC_CoaDescription; + + // Jika salah satu dari coaID atau CoaAccNo kosong atau null maka error + if ($raw->coaID == 0 || $raw->coaID == '' || $raw->coaAccNo == null || $raw->coaAccNo == '') { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping Bank EDC di Cabang {$raw->BranchCode} tidak ditemukan. Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + $details[] = $raw; + } + // Jika Non EDC, pakai mapping R/K Regional dan bawa AddOn jurnalRegNo + else { + $sql = "SELECT Map_RkCabang_CoaID, Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription + FROM m_branch + JOIN map_rk_cabang ON Map_RkCabang_SRegionalID = M_BranchS_RegionalID + WHERE M_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 3 + AND (Map_RkCabang_BranchCode = '' OR Map_RkCabang_BranchCode IS NULL) + LIMIT 1"; + $qry = $this->db->query($sql, [$raw->BranchCode]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping Sales", + "err_msg" => "Mapping R/K Regional Keu tidak ditemukan. Cabang {$raw->BranchCode}| Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaID = $qry->row()->Map_RkCabang_CoaID; + $raw->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + $raw->coaDescription = $qry->row()->Map_RkCabang_CoaDescription; + $raw->addOns = [ + [ + 'jurnalAddOnCode' => 'NOJURNALREG', + 'jurnalAddOnValue' => $jurnalRegNo + ] + ]; + $details[] = $raw; + } + } + + // Handle regonline + else if (stripos(strtolower($raw->M_PaymentTypeCode), 'regonline') !== false) { + $raw->coaAccNo = "2140000001"; + $sql = "SELECT coaID, coaDescription FROM coa WHERE coaAccountNo = ? LIMIT 1"; + $qry = $this->db->query($sql, [$raw->coaAccNo]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "CoA ID dengan CoaNo {$raw->coaAccNo} tidak ditemukan. | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + $details[] = $raw; + } + + // Handle Cash/Tunai. Masuk Debit + else if (stripos(strtolower($raw->M_PaymentTypeCode), 'cash') !== false || stripos($raw->Ref, 'tunai') !== false) { + $raw->coaAccNo = "1110100001"; + $sql = "SELECT coaID, coaDescription FROM coa WHERE coaAccountNo = ? LIMIT 1"; + $qry = $this->db->query($sql, [$raw->coaAccNo]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "CoA ID dengan CoaNo {$raw->coaAccNo} tidak ditemukan. | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + $details[] = $raw; + } + + // Handle Voucher. Masuk Debit. Coa B. Voucher Discount + else if (stripos($raw->Ref, 'voucher')!== false) { + $raw->coaAccNo = "5210000016"; + + $sql = "SELECT coaID, coaDescription FROM coa WHERE coaAccountNo = ? LIMIT 1"; + $qry = $this->db->query($sql, [$raw->coaAccNo]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "CoA ID dengan CoaNo {$raw->coaAccNo} tidak ditemukan. | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + // Addons Debit Voucher: PAYTYPE, CMPNYID, CMPNYNAME + $raw->addOns = [ + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => 'VOUCHER' + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->F_Payment_VoucherM_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->VoucherM_CompanyName + ] + ]; + $details[] = $raw; + } + + // Handle Array Sales Nat Map Pendapatan (ada natgroup and natsubgroupID). Pasti Kredit + else if (isset($raw->NatGroupID) && isset($raw->NatSubGroupID)) { + $natGroupID = $raw->NatGroupID; + $natSubGroupID = $raw->NatSubGroupID; + // Mapping Nat SubGroup -> pendapatan + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON coaAccountNo = MapNatSub_PendapatanCoaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$natGroupID, $natSubGroupID]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$natGroupID} | NatSubGroupID: {$natSubGroupID} | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + + // Cek if kredit >= debit valid + if ($raw->Kredit >= $raw->Debit) { + $raw->Debit = 0; + $raw->addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ] + ]; + } else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Kredit Sales lebih kecil dari Debit. Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $details[] = $raw; + } + + // Handle Mapping Nat Group -> diskon. Hanya ada NatGroupID tanpa NatSubGroupID. Pasti Debit + else if (stripos($raw->Ref, 'diskon') !== false) { + $sql = "SELECT MapNatGroup_Disc_coaID, + MapNatGroup_Disc_coaAccNo, + MapNatGroup_Disc_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->NatGroupID]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Diskon tidak ditemukan. NatGroupID: {$raw->NatGroupID} | Ref: {$raw->Ref} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + $details[] = $raw; + } + + // Handle Mapping Nat Group -> retur. Masuk Debit + else if (stripos($raw->Ref, 'retur') !== false) { + $raw->Ref = substr($raw->Ref, strpos($raw->Ref, ' ') + 1); + $sql = "SELECT MapNatGroup_Retur_coaID, + MapNatGroup_Retur_coaAccNo, + MapNatGroup_Retur_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->Ref]); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Retur tidak ditemukan. Ref: {$raw->Ref}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + $details[] = $raw; + } + + // Handle Mapping round + else if (stripos($raw->Ref, 'round') !== false) { + $sql = "SELECT coaID, coaDescription FROM coa + WHERE coaAccountNo = '1141100002' AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak ditemukan mapping pembulatan CoA No 1141100002 di tabel coa. Ref: {$raw->Ref}" + ]; + continue; + } + else { + $raw->coaAccNo = "1141100002"; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + $details[] = $raw; + } + + // Update: 20250506 Pembulatan dihandle di bawah + // continue; + } + else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak bisa mapping ke COA karena belum ditentukan mapping CoA ke Jenis Ref ini. Ref: {$raw->Ref}. Debit: {$raw->Debit}. Kredit: {$raw->Kredit}" + ]; + continue; + } + $balances['totalDebit'] += $raw->Debit; + $balances['totalKredit'] += $raw->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + return [$details, $balances, $errMap]; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function mappingAr($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + // 1. Foreach sampai len-1 karena yang terakhir (len-1) adalah total + $i = 0; + $lastIdx = count($raws) - 1; + foreach ($raws as $raw) { + if ($i == $lastIdx) { + break; + } + $i++; + // Parse string to decimal then round 2 decimal + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Kredit, 2); + + // Total debit, kredit, dan balance. Di atas biar selalu diexecute walau ada continue + $balances['totalDebit'] += $raw->Debit; + $balances['totalKredit'] += $raw->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + + // 2. Kalau is_parent = 1, maka CoA pakai Piutang + if (isset($raw->is_parent) && $raw->is_parent == 1) { + // 2a. Kalau M_CompanyID 1235 (PASIEN KLINISI), pakai coaNo 1120100002 + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // 2b. Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // 2c. Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + $qry = $this->db->query($sql); + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref}" + ]; + continue; + } + // * Untuk Parent: dibuat menjadi 2 jurnal_tx + // * 1. Debit Pakai coaCompany (Piutang). rawDbt + // * 2. Kredit Pakai mapping NatSubGroup. rawCr + $rawDbt = clone $raw; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->coaDescription; + $rawDbt->coaAccNo = $qry->row()->coaAccountNo; + $rawDbt->Kredit = 0; + + $rawCr = clone $raw; + $rawCr->Debit = 0; + $natGroupID = $rawCr->NatGroupID; + $natSubGroupID = $rawCr->NatSubGroupID; + + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON MapNatSub_PendapatanCoaAccountNo = coaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$natGroupID, $natSubGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Ref: {$raw->Ref} | Error DB: {$error} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | Deskripsi: {$raw->Deskripsi}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$natGroupID} | NatSubGroupID: {$natSubGroupID} | Ref: {$raw->Ref} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | Deskripsi: {$raw->Deskripsi}" + ]; + continue; + } + $rawCr->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + + $addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + continue; // Agar tidak execute luar if else dan $raw tidak masuk ke details lagi + } + + // 3. Kalau !is_parent dan !is_diskon , maka CoA pakai mapping NatSubGroup (Product) + else if (!isset($raw->is_parent) && !isset($raw->is_diskon)) { + $sql = "SELECT MapNatSub_PendapatanCoaAccountNo, coaID, coaDescription + FROM map_nat_subgroup + JOIN coa ON MapNatSub_PendapatanCoaAccountNo = coaAccountNo + WHERE MapNatSub_NatGroupID = ? AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y' LIMIT 1"; + $qry = $this->db->query($sql, [$raw->NatGroupID, $raw->NatSubGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Failed mapping natsubgroup AR. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatSubGroup tidak ditemukan. NatGroupID: {$raw->NatGroupID} | NatSubGroupID: {$raw->NatSubGroupID} | Ref: {$raw->Ref}" + ]; + continue; + } + + $raw->coaAccNo = $qry->row()->MapNatSub_PendapatanCoaAccountNo; + $raw->coaID = $qry->row()->coaID; + $raw->coaDescription = $qry->row()->coaDescription; + + // Kalau kredit negatif, jadikan debit + if ($raw->Kredit < 0) { + $raw->Debit = abs($raw->Kredit); + $raw->Kredit = 0; + } + } + // 4. Kalau is_diskon = 1, maka CoA pakai mapping NatGroup + else if (isset($raw->is_diskon) && $raw->is_diskon == 1) { + $sql = "SELECT MapNatGroup_Disc_coaID, + MapNatGroup_Disc_coaAccNo, + MapNatGroup_Disc_coaDesc + FROM map_nat_group + WHERE MapNatGroup_NatGroupID = ? + AND MapNatGroup_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->NatGroupID]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Failed mapping diskon natgroup AR. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Mapping NatGroup Diskon tidak ditemukan. NatGroupID: {$raw->NatGroupID} | Ref: {$raw->Ref}" + ]; + continue; + } + $raw->coaAccNo = $qry->row()->MapNatGroup_Disc_coaAccNo; + $raw->coaID = $qry->row()->MapNatGroup_Disc_coaID; + $raw->coaDescription = $qry->row()->MapNatGroup_Disc_coaDesc; + + // Kalau kredit negatif, jadikan debit + if ($raw->Kredit < 0) { + $raw->Debit = abs($raw->Kredit); + $raw->Kredit = 0; + } + } else { + $errMap[] = [ + "err_type" => "Mapping", + "err_msg" => "Tidak bisa mapping ke COA karena belum ditentukan mapping CoA ke Jenis Ref ini. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + // Add addOns untuk yang selain is_parent = 1 + $addOns = [ + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + $raw->addOns = $addOns; + $details[] = $raw; + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + return [$details, $balances, $errMap]; + } + + private function mappingArPayment($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + + $i = 0; + /* + Setiap item di $raws jadi 2 jurnal_tx dan 7 addOn: + 1. Debit dari Bank + 2. Kredit ke Piutang Company + */ + foreach ($raws as $raw) { + $i++; + //! Kalau Tipe Bayar RK skip dulu karena jurnal terpisah + if ($raw->Tipe_Bayar == "RK") { + continue; + } + + $raw->Debit = round($raw->Debit, 2); + $raw->Kredit = round($raw->Debit, 2); //* Karena ini payment, maka Kredit dibuat = Debit + + // 1a. Debit dari Bank + if ($raw->IsBank) { + if ($raw->M_BankAccountNo == "") { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "No Rekening Bank tidak ditemukan. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $norek = str_replace(['-', '.'], '', $raw->M_BankAccountNo); + + $sql = "SELECT MapBank_CoaAccountNo, MapBank_CoaDescription, + MapBank_BankAccountNo, MapBank_BranchCode, + coaID, coaDescription + FROM map_bank_coa + JOIN coa ON coaAccountNo = MapBank_CoaAccountNo + WHERE MapBank_BankAccountNo = ? + AND MapBank_IsActive = 'Y' + LIMIT 1"; + $qry = $this->db->query($sql, [$norek]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping bank Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + + $rst = $qry->row(); + + if ($rst == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Mapping Bank tidak ditemukan. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawDbt = clone $raw; + $rawDbt->coaAccNo = $rst->MapBank_CoaAccountNo; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->coaDescription; + + if ($rawDbt->coaID == "" || $rawDbt->coaID == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Mapping CoA Bank tidak ditemukan. Ref: {$rawDbt->Ref} || Desc: {$rawDbt->Deskripsi} || TipeBayar: {$rawDbt->Tipe_Bayar} || Debit: {$rawDbt->Debit} || Kredit: {$rawDbt->Kredit}" + ]; + continue; + } + } + + // 1b. Debit dari Cash + if (!$raw->IsBank) { + if ($raw->Tipe_Bayar !== 'Cash') { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Belum punya mapping untuk selain Bank dan Cash. Ref: {$raw->Ref} || Desc: {$raw->Deskripsi} || TipeBayar: {$raw->Tipe_Bayar} || Debit: {$raw->Debit} || Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawDbt = clone $raw; + $rawDbt->coaAccNo = "1110100001"; + $rawDbt->coaID = 5; + $rawDbt->coaDescription = "TUNAI"; + } + + // 2. Kredit ke Piutang Company. + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // 2b. Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // 2c. Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + + $qry = $this->db->query($sql); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping AR Company Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit}" + ]; + continue; + } + + $rawCr = clone $raw; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + $rawCr->coaAccNo = $qry->row()->coaAccountNo; + + + $addOns = [ + [ + "jurnalAddOnCode" => "ARDATE", + "jurnalAddOnValue" => $raw->AR_Date + ], + [ + "jurnalAddOnCode" => "PAYTYPE", + "jurnalAddOnValue" => $raw->Tipe_Bayar + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + + $rawCr->Debit = 0; + $rawDbt->Kredit = 0; + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + + return [$details, $balances, $errMap]; + } + + private function mappingArPayRkTagihan($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + $errMap = []; + /* + Tiap item di $raws jadi 2 jurnal_tx dan 7 addOn: + 1. Debit pakai coa RK + 2. Kredit pakai coa Piutang Company + */ + foreach ($raws as $raw) { + $rawDbt = clone $raw; + $rawCr = clone $raw; + $rawDbt->Debit = round(abs($rawDbt->Total_RkAmount), 2); + $rawCr->Kredit = round(abs($rawDbt->Total_RkAmount), 2); + + //* Jika Total_RkAmount < 0 (nitip tagih) + if ($rawDbt->Total_RkAmount < 0) { + // 1. Debit pakai coa RK + $sql = "SELECT Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription, Map_RkCabang_BranchCode, coaID + FROM map_rk_cabang + JOIN coa ON Map_RkCabang_CoaAccountNo = coaAccountNo + WHERE Map_RkCabang_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 1 + AND Map_RkCabang_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$raw->BranchCode]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed query CoA RK MapBank Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK MapBank tidak ditemukan. Ref: {$raw->Ref}. Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | RK_BranchCode: {$raw->RK_BranchCode}" + ]; + continue; + } + $rawDbt->Kredit = 0; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->Map_RkCabang_CoaDesc; + $rawDbt->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + + // 2. Kredit pakai coa Piutang Company + // Kalau M_CompanyID 1235 (PASIEN DOKTER/KLINIS), pakai coaNo 1120100002 + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + // Selain itu, pakai coaNo 1120200001 PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + $qry = $this->db->query($sql); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed mapping AR Company Ar Payment. Ref: {$raw->Ref} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA AR Company tidak ditemukan. Ref: {$raw->Ref} Deskripsi: {$raw->Deskripsi} | Debit: {$raw->Debit} | Kredit: {$raw->Kredit} | RK_BranchCode: {$raw->RK_BranchCode}" + ]; + continue; + } + + $rawCr->Debit = 0; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->coaDescription; + $rawCr->coaAccNo = $qry->row()->coaAccountNo; + } else { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Total_RkAmount >= 0 tidak termasuk nitip tagih (tagihan). Ref: {$raw->Ref}" + ]; + continue; + } + + $addOns = [ + [ + "jurnalAddOnCode" => "ARDATE", + "jurnalAddOnValue" => $raw->AR_Date + ], + [ + "jurnalAddOnCode" => "PAYTYPE", + "jurnalAddOnValue" => $raw->Tipe_Bayar + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $raw->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $raw->M_OmzetTypeName + ], + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $raw->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $raw->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $raw->M_CompanyNumber + ] + ]; + + $rawDbt->addOns = $addOns; + $rawCr->addOns = $addOns; + + $details[] = $rawDbt; + $details[] = $rawCr; + + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + + return [$details, $balances, $errMap]; + } + + private function mappingArPayRkPelunasan($raws) + { + $details = []; + $balances = [ + 'totalDebit' => 0, + 'totalKredit' => 0, + 'totalBalance' => 0 + ]; + + /* --------- BRIEF: ------------ + Setiap item di $raws masing-masing menjadi 1 jurnal_tx dan berbeda AddOn + - Debit dari Client + - Coa: coa Bank + - Addon: companyid, companynum, companyname, paytypeID, paymentpusatDate + - Kredit ke R/K cabang lain + - CoA : pakai coa R/K cabang lain + - Addon: companyid, companynum, companyname, paytypeID, paymentpusatDate + - Kredit ke A/R cabang sendiri + - CoA : piutang perusahaan + - AddOn : ARdate, paytypeID, omzettypeid, omzettypename, companyid, companynum, companyname + */ + + // 1. Debit dari Client -> Mapping Bank CoA + // * Pisah foreach, agar kalau continue tidak menganggu foreach kredit yang levelnya lebih rendah + foreach ($raws as $raw) { + $rawDbt = clone $raw->Debit; + $norek = preg_replace('/[^0-9]/', '', $rawDbt->M_BankAccountNo); + $sql = "SELECT MapBank_CoaAccountNo, MapBank_CoaDescription, MapBank_BankAccountNo, MapBank_BranchCode, coaID + FROM map_bank_coa + JOIN coa ON MapBank_CoaAccountNo = coaAccountNo + WHERE MapBank_BankAccountNo = ? AND MapBank_IsActive = 'Y' AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$norek]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed query CoA RK MapBank Ar Payment. Ref: {$rawDbt->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK MapBank tidak ditemukan. Desc: {$rawDbt->Desc}" + ]; + continue; + } + $rawDbt->Debit = $rawDbt->F_BillPaymentPusatAmount; + $rawDbt->Kredit = 0; + $rawDbt->coaID = $qry->row()->coaID; + $rawDbt->coaDescription = $qry->row()->MapBank_CoaDescription; + $rawDbt->coaAccNo = $qry->row()->MapBank_CoaAccountNo; + $rawDbt->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawDbt->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawDbt->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawDbt->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawDbt->M_PaymentTypeID + ], + [ + 'jurnalAddOnCode' => 'PAYMENTPUSATDATE', + 'jurnalAddOnValue' => $rawDbt->F_BillPaymentPusatDate + ] + ]; + + $details[] = $rawDbt; + $balances['totalDebit'] += $rawDbt->Debit; + $balances['totalKredit'] += $rawDbt->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + + // 2 dan 3 untuk Kredit AR R/K cabang lain dan A/R cabang sendiri + foreach ($raws as $raw) { + $rawCabLain = $raw->AR_RK_Cabang_Lain; + $rawCabIni = $raw->AR_Cabang_Ini; + + // 2. Kredit ke R/K cabang lain -> mapping coa R/K cabang lain + // TODO: Reconfirm Map_RkCabang_Rk_TypeID = 'ARPAY' or 'RK' + foreach ($rawCabLain as &$rawCr) { + $sql = "SELECT Map_RkCabang_CoaAccountNo, Map_RkCabang_CoaDescription, Map_RkCabang_BranchCode, coaID + FROM map_rk_cabang + JOIN coa ON Map_RkCabang_CoaAccountNo = coaAccountNo + WHERE Map_RkCabang_BranchCode = ? + AND Map_RkCabang_Rk_TypeID = 1 + AND Map_RkCabang_IsActive = 'Y'"; + $qry = $this->db->query($sql, [$rawCr->RK_BranchCode]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed query mapping coa RK map_rk_cabang RK Pelunasan. Desc: {$rawCr->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK map_rk_cabang tidak ditemukan RK Pelunasan. Desc: {$rawCr->Desc}" + ]; + continue; + } + $rawCr->Debit = 0; + $rawCr->Kredit = $rawCr->F_BillIssuePusatDetailTotal; + $rawCr->coaID = $qry->row()->coaID; + $rawCr->coaDescription = $qry->row()->Map_RkCabang_CoaDesc; + $rawCr->coaAccNo = $qry->row()->Map_RkCabang_CoaAccountNo; + $rawCr->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawCr->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawCr->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawCr->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawCr->M_PaymentTypeID + ] + ]; + + $details[] = $rawCr; + + $balances['totalDebit'] += $rawCr->Debit; + $balances['totalKredit'] += $rawCr->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + unset($rawCr); + + // 3. Kredit ke A/R cabang sendiri -> mapping coa A/R cabang sendiri + foreach ($rawCabIni as &$rawCr2) { + // PASIEN DOKTER/KLINISI + if ($raw->M_CompanyID == 1235) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100002' AND coaIsActive = 'Y'"; + } + // Kalau M_CompanyID 1222 (PASIEN MANDIRI), pakai coaNo 1120100001 + else if ($raw->M_CompanyID == 1222) { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120100001' AND coaIsActive = 'Y'"; + } + //Selain itu, pakai coaNo 1120200001 9PIUTANG USAHA REKANAN) + else { + $sql = "SELECT coaID, coaDescription, coaAccountNo FROM coa + WHERE coaAccountNo = '1120200001' AND coaIsActive = 'Y'"; + } + + $qry = $this->db->query($sql); + + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "Failed query CoA RK ke A/R sendiri (PASIEN DOKTER, PASIEN MANDIRI, atau PIUTANG USAHA REKANAN). Desc: {$rawCr2->Desc} | Error DB: {$error}" + ]; + continue; + } + if ($qry->row() == null) { + $errMap[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA RK ke A/R sendiri (PASIEN DOKTER, PASIEN MANDIRI, atau PIUTANG USAHA REKANAN) tidak ditemukan. Desc: {$rawCr2->Desc}" + ]; + continue; + } + $rawCr2->Debit = 0; + $rawCr2->Kredit = $rawCr2->SumBillDetailTotal; + $rawCr2->coaID = $qry->row()->coaID; + $rawCr2->coaDescription = $qry->row()->coaDescription; + $rawCr2->coaAccNo = $qry->row()->coaAccountNo; + $rawCr2->addOns = [ + [ + 'jurnalAddOnCode' => 'CMPNYID', + 'jurnalAddOnValue' => $rawCr2->M_CompanyID + ], + [ + 'jurnalAddOnCode' => 'CMPNYNAME', + 'jurnalAddOnValue' => $rawCr2->M_CompanyName + ], + [ + 'jurnalAddOnCode' => 'CMPNYNUM', + 'jurnalAddOnValue' => $rawCr2->M_CompanyNumber + ], + [ + 'jurnalAddOnCode' => 'PAYTYPE', + 'jurnalAddOnValue' => $rawCr2->M_PaymentTypeID + ], + [ + 'jurnalAddOnCode' => 'ARDATE', + 'jurnalAddOnValue' => $rawCr2->ArDate + ], + [ + 'jurnalAddOnCode' => 'OMZTYPE', + 'jurnalAddOnValue' => $rawCr2->M_OmzetTypeID + ], + [ + 'jurnalAddOnCode' => 'OMZNAME', + 'jurnalAddOnValue' => $rawCr2->M_OmzetTypeName + ] + ]; + + $details[] = $rawCr2; + + $balances['totalDebit'] += $rawCr2->Debit; + $balances['totalKredit'] += $rawCr2->Kredit; + $balances['totalBalance'] = $balances['totalDebit'] - $balances['totalKredit']; + } + unset($rawCr2); + } + + [$details, $balances, $errMap] = $this->handleRoundingDifference($balances, $details, $errMap); + + return [$details, $balances, $errMap]; + } + + private function insertMapBank($raws) + { + $sqlCheck = "SELECT MapBank_BankAccountNo, MapBank_NatBankID, MapBank_BranchCode + FROM map_bank_coa + WHERE MapBank_BankAccountNo LIKE CONCAT ('%', ?, '%') AND MapBank_NatBankID = ? AND MapBank_BranchCode = ? + AND MapBank_IsActive = 'Y'"; + + $sql = "INSERT INTO map_bank_coa + (MapBank_BranchCode, MapBank_NatBankName, MapBank_BankAccountNo, + MapBank_NatBankID, MapBank_NatBankCode, MapBank_NatBankIsEDC, + MapBank_IsActive, MapBank_CreatedAt, MapBank_LastUpdatedAt) + VALUES (?, ?, ?, ?, ?, ?, 'Y', NOW(), NOW())"; + $errMap = []; + $seenAcc = []; + $seenNatBank = []; + $seenBranch = []; + $uniqueRows = []; + $existingRows = []; + + foreach ($raws as $raw) { + // * Check existing rows + $qryCheck = $this->db->query($sqlCheck, [ + $raw->M_BankAccountNo, + $raw->Nat_BankID, + $raw->M_BranchCode + ]); + if ($qryCheck->num_rows() > 0 || $qryCheck->row() != null) { + $existingRows[] = [ + 'BankAccountNo' => $raw->M_BankAccountNo, + 'NatBankID' => $raw->Nat_BankID, + 'BranchCode' => $raw->M_BranchCode, + ]; + continue; + } + + //* AVOID DUPLICATION * Skip jika ada row dengan norek dan natbankID yang sama + if (in_array($raw->M_BankAccountNo, $seenAcc)) { + if (in_array($raw->Nat_BankID, $seenNatBank)) { + if (in_array($raw->M_BranchCode, $seenBranch)) { + continue; + } + } + } + $seenAcc[] = $raw->M_BankAccountNo; + $seenNatBank[] = $raw->Nat_BankID; + $seenBranch[] = $raw->M_BranchCode; + $uniqueRows[] = $raw; + + $qry = $this->db->query($sql, [ + $raw->M_BranchCode, + $raw->Nat_BankName, + $raw->M_BankAccountNo, + $raw->Nat_BankID, + $raw->Nat_BankCode, + $raw->Nat_BankIsEDC + ]); + if (!$qry) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errMap[] = [ + 'err_type' => 'Inject', + 'err_msg' => "Failed Inject mapping bank. BranchCode: {$raw->_BranchCode} | BankAccountNo: {$raw->M_BankAccountNo} | NatBankID: {$raw->Nat_BankID} | Error DB: {$error}" + ]; + continue; + } + } + return [$uniqueRows, $errMap, $existingRows]; + } + + private function composeJurnalInfo($branchCode, $searchDate, $jurnalType) + { + $jurnalInfo = []; + // * Sudah pasti success karena di awal sudah ada yang mirip (tidak perlu cek eror) + $sql = "SELECT M_BranchID, M_BranchM_CompanyID, M_BranchS_RegionalID, + M_BranchName, S_RegionalName + FROM m_branch + JOIN s_regional ON M_BranchS_RegionalID = S_RegionalID + WHERE M_BranchCode = ? "; + $qry = $this->db->query($sql, [$branchCode]); + + $regID = $qry->row()->M_BranchS_RegionalID; + $regName = $qry->row()->S_RegionalName; + $branchName = $qry->row()->M_BranchName; + $jurnalInfo['S_RegionalID'] = $regID; + $jurnalInfo['M_BranchID'] = $qry->row()->M_BranchID; + $jurnalInfo['M_BranchName'] = $branchName; + $jurnalInfo['M_BranchCode'] = $branchCode; + $jurnalInfo['jurnalDate'] = $searchDate; + + $jurnalInfo['M_UserID'] = 500; //* 500 untuk autocount + + $sqlcom = "SELECT M_BranchCompanyDetailM_BranchCompanyID, M_BranchCompanyDetailM_BranchCode + FROM m_branch_companydetail + WHERE M_BranchCompanyDetailM_BranchCode = ? + AND M_BranchCompanyDetailIsActive = 'Y' LIMIT 1"; + $qrycom = $this->db->query($sqlcom, [$branchCode]); + if (!$qrycom) { + $this->sys_error_db("Tidak menemukan M_BranchCompany ID untuk branch {$branchCode}", $this->db); + exit; + } + $jurnalInfo['M_BranchCompanyID'] = $qrycom->row()->M_BranchCompanyDetailM_BranchCompanyID; + + // * Get Periode by Inserted Date + $sql = "SELECT periodeID FROM periode WHERE ? BETWEEN periodeStartDate AND periodeEndDate"; + $qry = $this->db->query($sql, [$searchDate]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Tidak menemukan periode jurnal untuk tanggal {$searchDate}", $this->db); + exit; + } + $jurnalInfo['periodeID'] = $qry->row()->periodeID; + + $sqlJurnalNo = "SELECT `fn_numbering`('J') as jurnalNo"; + + switch ($jurnalType) { + case 'SALESREG': + $jurnalInfo['M_BranchCode'] = ''; + $jurnalInfo['jurnalTitle'] = "Auto Daily Sales {$searchDate} Regional: {$regName} Cabang: {$branchName}"; + $jurnalInfo['jurnalDescription'] = "Auto Daily Sales Regional {$regName} pada {$searchDate} untuk Cabang {$branchName}"; + $jurnalInfo['jurnalTypeID'] = 7; //AUTODAILYSALES + $sqlJurnalNo = "SELECT `fn_numbering`('ACSL') as jurnalNo"; + $jurnalNoSuffix = ''; + break; + case 'SALESCAB': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily Sales {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily Sales Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 7; //AUTODAILYSALES + $jurnalInfo['jurnalNo'] = ''; //* Jurnal No Cabang akan dioverwrite dengan jurnal regional + return $jurnalInfo; + break; + case 'AR': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily AR {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily AR Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 10; //AUTODAILYAR + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'ARPAYMENT': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily AR Payment {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily AR Payment Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 11; //AUTODAILYARPAYMENT + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'RKTAGIHAN': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily RK Tagihan Terpusat {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily RK Tagihan Cabang Terpusat {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 12; //AUTODAILYRKTAGIHAN + $jurnalNoSuffix = "/{$branchCode}"; + break; + case 'RKPELUNASAN': + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Daily RK Pelunasan Terpusat {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Daily RK Pelunasan Cabang Terpusat {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalInfo['jurnalTypeID'] = 13; //AUTODAILYRKPELUNASAN + $jurnalNoSuffix = "/{$branchCode}"; + break; + + default: + $jurnalInfo['jurnalTitle'] = "{$branchCode} - Auto Jurnal {$searchDate}"; + $jurnalInfo['jurnalDescription'] = "Jurnal Auto Jurnal Cabang {$jurnalInfo['M_BranchName']} Tanggal {$searchDate}"; + $jurnalNoSuffix = "/{$branchCode}"; + break; + } + + $qry = $this->db->query($sqlJurnalNo, []); + if (!$qry) { + $this->sys_error_db("Gagal generate nomor jurnal", $this->db); + exit; + } + $rst = $qry->row(); + $jurnalInfo['jurnalNo'] = $rst->jurnalNo . $jurnalNoSuffix; + + return $jurnalInfo; + } + + private function injectJurnal($jurnalInfo, $details) + { + $sqlHeader = "INSERT INTO jurnal + (jurnalM_BranchCompanyID, JurnalS_RegionalID, jurnalM_BranchCode, + jurnalperiodeID, jurnalNo, jurnalTitle, + jurnalDescription, jurnalDate, jurnalJurnalTypeID, + jurnalCreated, jurnalM_UserID) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)"; + + $qryHead = $this->db->query($sqlHeader, [ + $jurnalInfo['M_BranchCompanyID'], + $jurnalInfo['S_RegionalID'], + $jurnalInfo['M_BranchCode'], + $jurnalInfo['periodeID'], + $jurnalInfo['jurnalNo'], + $jurnalInfo['jurnalTitle'], + $jurnalInfo['jurnalDescription'], + $jurnalInfo['jurnalDate'], + $jurnalInfo['jurnalTypeID'], + $jurnalInfo['M_UserID'] + ]); + if (!$qryHead) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed Insert Jurnal: ", $this->db); + exit; + } + + $jurnalID = $this->db->insert_id(); + $errInsert = []; + + foreach ($details as $detail) { + // Cek If coaID kosong, skip + if ($detail->coaID == "" || !isset($detail->coaID)) { + $errInsert[] = [ + 'err_type' => 'Mapping', + 'err_msg' => "CoA ID untuk {$detail->Ref} tidak ditemukan. Debit: {$detail->Debit} || Kredit: {$detail->Kredit}" + ]; + continue; + } + + [$status, $errDetail] = $this->injectDetailJurnal($detail, $jurnalID); // Child Transaction + if (!$status) { + $errInsert = array_merge($errInsert, $errDetail); + continue; + } + } + + return [$jurnalID, $errInsert]; + } + + private function injectDetailJurnal($prm, $jurnalID) + { + $coaID = $prm->coaID; + $jurnalTxDescription = $prm->coaDescription; + $jurnalTxDebit = $prm->Debit; + $jurnalTxCredit = $prm->Kredit; + $addOns = $prm->addOns; // array + $errDetail = []; + + // * Debit atau Kredit bisa masuk ke Add On (karena AR Payment Debitnya perlu addOn) + + // ? Kalau debit dan kredit kosong, apakah di skip? + // if ($jurnalTxDebit == 0 && $jurnalTxCredit == 0) { + // return; + // } + $insertTx = "INSERT INTO jurnal_tx + (jurnalTxJurnalID, jurnalTxCoaID, jurnalTxDescription, jurnalTxCredit, + jurnalTxDebit, jurnalTxIsActive, jurnalTxCreated, jurnalTxLastUpdated, jurnalTxM_UserID) + VALUES (?, ?, ?, ?, ?, 'Y', NOW(), NOW(), 500)"; + + $insertAddOn = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnIsActive, jurnalAddOnCreated, + jurnalAddOnLastUpdated, jurnalAddOnCreatedUserID) + VALUES (?, ?, ?, ?, 'Y', NOW(), NOW(), 500)"; + + $insertTxCr = $this->db->query($insertTx, [$jurnalID, $coaID, $jurnalTxDescription, $jurnalTxCredit, $jurnalTxDebit]); + if (!$insertTxCr) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errDetail[] = [ + 'err_type' => 'Insert', + 'err_msg' => "Gagal Insert Jurnal Tx. Error: $error" + ]; + return [false, $errDetail]; + } else { + $getTxId = $this->db->insert_id(); + + // Jika punya addOn + if (isset($addOns)) { + foreach ($addOns as $item) { + $addOnState = $this->db->query($insertAddOn, [$jurnalID, $getTxId, $item['jurnalAddOnCode'], $item['jurnalAddOnValue']]); + + if (!$addOnState) { + $error = json_encode($this->db->error(), JSON_PRETTY_PRINT); + $errDetail[] = [ + 'err_type' => 'Insert', + 'err_msg' => "Gagal Insert Jurnal Tx. Error: $error" + ]; + continue; + } + } + } + return [true, $errDetail]; + } + } + + private function injectErrors($jurnalErr, $jurnalID) + { + $sql = "INSERT INTO jurnal_errors + (JurnalErr_JurnalID, JurnalErr_Msg, JurnalErr_CreatedAt, JurnalErr_LastUpdatedAt) + VALUES (?, ?, NOW(), NOW())"; // NOW() is handled by MySQL, so no placeholder is needed + + foreach ($jurnalErr as $err) { + $errEncoded = json_encode($err); + $qry = $this->db->query($sql, [$jurnalID, $errEncoded]); + if (!$qry) { + $this->sys_error_db("Insert Error saja gagal. Coba dicek lagi deh", $this->db); + exit; + } + } + } + + private function getBranchCodeRegenSalesReg($jurnalNo) + { + $sql = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalNo LIKE CONCAT('%', ?, '%') + AND jurnalJurnalTypeID = 7 + AND jurnalIsActive = 'Y' ORDER BY jurnalNo DESC"; //! Harus DESC agar nomor jurnal Cabang ada di index 0 dan diquery row() langsung dapat"; + $qry = $this->db->query($sql, [$jurnalNo]); + if (!$qry) { + $this->sys_error_db("Failed to get branch code for regen sales reg", $this->db); + exit; + } + $rst = $qry->row(); + if ($rst == null || !$rst) { + return null; + } + // Ambil 2 digit terakhir dari $rst->jurnalNo + $branchCode = substr($rst->jurnalNo, -2); + return $branchCode; + } + + private function checkExistingJurnal($branchCode, $searchDate, $jurnalType, $jurnalNo = "") + { + $sql = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalM_BranchCode = ? + AND jurnalDate = ? AND jurnalJurnalTypeID = ? + AND jurnalIsActive = 'Y' ORDER BY jurnalID DESC"; + + switch ($jurnalType) { + case 'SALES': + $jurnalTypeID = 7; //AUTODAILYSALES + break; + case 'SALESCAB': + $jurnalTypeID = 7; //AUTODAILYSALES + $regenFromCab = true; + $noJurCab = $jurnalNo; + $noJurReg = substr($noJurCab, 0, -3); // $noJurReg = $noJur dengan hapus 3 digit terakhir + break; + case 'SALESREG': + $jurnalTypeID = 7; //AUTODAILYSALES + $regenFromReg = true; + $noJurReg = $jurnalNo; + $noJurCab = $jurnalNo . "/{$branchCode}"; + break; + case 'AR': + $jurnalTypeID = 10; //AUTODAILYAR + break; + case 'ARPAYMENT': + $jurnalTypeID = 11; //AUTODAILYARPAYMENT + break; + case 'RKTAGIHAN': + $jurnalTypeID = 12; //AUTODAILYRKTAGIHAN + break; + case 'RKPELUNASAN': + $jurnalTypeID = 13; //AUTODAILYRKPELUNASAN + break; + default: + break; + } + + // * Sementara khusus regen SALES karena harus 2 jurnalID + if ($regenFromCab || $regenFromReg) { + $sql_2 = "SELECT jurnalID, jurnalNo FROM jurnal + WHERE jurnalNo LIKE CONCAT(?, '%') + AND jurnalJurnalTypeID = ? + AND jurnalIsActive = 'Y' AND jurnalIsPosted = 'N' ORDER BY jurnalNo ASC"; // ASC Nomor Regional di Atas + $qry_2 = $this->db->query($sql_2, [$noJurReg, $jurnalTypeID]); // Cari dari no jurRegional agar keluar semua + if (!$qry_2) { + $this->sys_error_db("Failed to check existing jurnal", $this->db); + exit; + } + + $rst_2 = $qry_2->result(); + if (!$rst_2 || $rst_2 == null) { + return null; + } + return $rst_2; + } + + $qry = $this->db->query($sql, [$branchCode, $searchDate, $jurnalTypeID]); + if (!$qry) { + $this->sys_error_db("Failed to check existing jurnal", $this->db); + exit; + } + return $qry->row(); + } + + private function jurnalErrors($jurnalID, $type, $msg) + { + // Log jurnal error by insert it to jurnal_errors with jurnalId and Err Message + $fullmsg = [ + 'err_type' => $type, + 'err_msg' => $msg + ]; + $fullmsg = json_encode($fullmsg, JSON_PRETTY_PRINT); + + $sql = "INSERT INTO jurnal_errors + (JurnalErr_JurnalID, JurnalErr_Msg, JurnalErr_CreatedAt, JurnalErr_LastUpdatedAt) + VALUES (?, ?, NOW(), NOW())"; + $qry = $this->db->query($sql, [$jurnalID, $fullmsg]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert jurnal error", $this->db); + exit; + } + $jurnalErrID = $this->db->insert_id(); + return $jurnalErrID; + } + + private function deleteJurnal($jurnalID) + { + $userID = $this->sys_user["M_UserID"]; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa dihapus"); + exit; + } + + // 1. Update jurnal where jurnalID = ? + $this->db->set('jurnalIsActive', 'N'); + $this->db->set('jurnalLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalM_UserID', $userID); + $this->db->where('jurnalID', $jurnalID); + $this->db->update('jurnal'); + + // 2. Update jurnal_tx where jurnalTxJurnalID = ? + $this->db->set('jurnalTxIsActive', 'N'); + $this->db->set('jurnalTxLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalTxM_UserID', $userID); + $this->db->where('jurnalTxJurnalID', $jurnalID); + $this->db->update('jurnal_tx'); + + // 3. Update jurnal_addon where jurnalAddOnJurnalID = ? + $this->db->set('jurnalAddOnIsActive', 'N'); + $this->db->set('jurnalAddOnLastUpdated', 'NOW()', FALSE); + $this->db->set('jurnalAddOnLastUpdatedUserID', $userID); + $this->db->where('jurnalAddOnJurnalID', $jurnalID); + $this->db->update('jurnal_addon'); + } + + // Hard Delete (Hanya untuk debugging) + public function deleteDummyData() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $jurnalID = $prm['jurnalID']; + $userID = $this->sys_user["M_UserID"]; + + $sql = "SELECT jurnalIsPosted FROM jurnal WHERE jurnalID = ?"; + $isPosted = $this->db->query($sql, [$jurnalID])->row()->jurnalIsPosted ?? null; + if (!$isPosted) { + $this->sys_error_db("Failed to get jurnalIsPosted", $this->db); + exit; + } + if ($isPosted == 'Y') { + $this->sys_error("Jurnal sudah diposting, tidak bisa dihapus"); + exit; + } + + // Start Transaction + $this->db->trans_start(); + + // 1. Delete from jurnal where jurnalID = ? + $this->db->where('jurnalID', $jurnalID); + $this->db->delete('jurnal'); + + // 2. Delete from jurnal_tx where jurnalTxJurnalID = ? + $this->db->where('jurnalTxJurnalID', $jurnalID); + $this->db->delete('jurnal_tx'); + + // 3. Delete from jurnal_addon where jurnalAddOnJurnalID = ? + $this->db->where('jurnalAddOnJurnalID', $jurnalID); + $this->db->delete('jurnal_addon'); + + // 4. Delete from jurnal_errors where JurnalErr_JurnalID = ? + $this->db->where('JurnalErr_JurnalID', $jurnalID); + $this->db->delete('jurnal_errors'); + + // Complete Transaction + $this->db->trans_complete(); + + if ($this->db->trans_status() === FALSE) { + $this->sys_error_db('Failed to delete jurnal: ', $this->db); + exit; + } else { + $this->sys_ok("Berhasil hapus jurnal"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function injectSalesManual() + { + $jurnal = "INSERT INTO `jurnal` (`jurnalM_BranchCompanyID`, `JurnalS_RegionalID`, `jurnalM_BranchCode`, `jurnalperiodeID`, `jurnalNo`, `jurnalTitle`, `jurnalDescription`, `jurnalDate`, `jurnalIsPosted`, `jurnalJurnalTypeID`, `jurnalIsActive`, `jurnalCreated`, `jurnalLastUpdated`, `jurnalM_UserID`) VALUES (1, 8, 'BA', 4, 'autosales001', 'Media Jurnal Penjualan ', 'description', '2025-01-09', 'N', 7, 'Y',NOW(), NOW(),345)"; + + $tx = "INSERT INTO `jurnal_tx` (`jurnalTxJurnalID`, `jurnalTxCoaID`, `jurnalTxDescription`, + `jurnalTxDebit`, `jurnalTxCredit`, `jurnalTxIsActive`, `jurnalTxCreated`, + `jurnalTxLastUpdated`, `jurnalTxM_UserID`) VALUES + (96, 5, 'TUNAI', 1850000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 4393950, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 2336050, 0, 'Y', NOW(), NOW(), 345), + (96, 80, 'MANDIRI PT PRAMITA (6455)', 255000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 10827650, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 38022900, 0, 'Y', NOW(), NOW(), 345), + (96, 42, 'BNI PT PRAMITA (5688)', 5766950, 0, 'Y', NOW(), NOW(), 345), + (96, 80, 'MANDIRI PT PRAMITA (6455)', 6458400, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 420000, 0, 'Y', NOW(), NOW(), 345), + (96, 29, 'BCA PT PRAMITTA (5060)', 1512100, 0, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 4294000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 2189000, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 975000, 'Y', NOW(), NOW(), 345), + (96, 823, 'PENDAPATAN URINALIS', 0, 560000, 'Y', NOW(), NOW(), 345), + (96, 846, 'PEND. RAD. FOTO POLOS', 0, 367000, 'Y', NOW(), NOW(), 345), + (96, 856, 'PENDAPATAN LAYANAN KLINIK', 0, 236000, 'Y', NOW(), NOW(), 345), + (96, 825, 'PENDAPATAN ANALISA KLINIK RUTIN', 0, 564000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 18812000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 25948000, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 5000000, 'Y', NOW(), NOW(), 345), + (96, 823, 'PENDAPATAN URINALIS', 0, 776000, 'Y', NOW(), NOW(), 345), + (96, 846, 'PEND. RAD. FOTO POLOS', 0, 1896000, 'Y', NOW(), NOW(), 345), + (96, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 7090000, 'Y', NOW(), NOW(), 345), + (96, 848, 'PEND. RAD. FOTO KONTRAS', 0, 1748000, 'Y', NOW(), NOW(), 345), + (96, 856, 'PENDAPATAN LAYANAN KLINIK', 0, 0, 'Y', NOW(), NOW(), 345), + (96, 865, 'PEND. LAYANAN JASA MEDIS LAINNYA', 0, 103000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 840000, 'Y', NOW(), NOW(), 345), + (96, 827, 'PENDAPATAN IMMUNOLOGI', 0, 687000, 'Y', NOW(), NOW(), 345), + (96, 830, 'PENDAPATAN LAB PATHOLOGI ANATOMI', 0, 503500, 'Y', NOW(), NOW(), 345), + (96, 822, 'PENDAPATAN HEMATOLOGI', 0, 538000, 'Y', NOW(), NOW(), 345), + (96, 826, 'PENDAPATAN KIMIA KLINIK', 0, 420000, 'Y', NOW(), NOW(), 345), + (96, 828, 'PENDAPATAN MIKROBIOLOGI', 0, 1618000, 'Y', NOW(), NOW(), 345), + (96, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 1547000, 'Y', NOW(), NOW(), 345), + (96, 847, 'DISCOUNT PENDAPATAN LABORATORIUM', 4623550, 0, 'Y', NOW(), NOW(), 345), + (96, 854, 'DISC PEND. RADIODIAGNOSTIK', 243550, 0, 'Y', NOW(), NOW(), 345), + -- diskon layanan medis lainnya pakai disc layanan klinik + (96, 867, 'DISC PEND. LAYANAN KLINIK', 0, 0, 'Y', NOW(), NOW(), 345), + (96, 195, 'PEMBULATAN', 1400, 0, 'Y', NOW(), NOW(), 345), + "; + + $addOn = "INSERT INTO `jurnal_addon` (`jurnalAddOnJurnalID`, `jurnalAddOnJurnalTxID`, + `jurnalAddOnCode`, `jurnalAddOnValue`, `jurnalAddOnIsActive`, `jurnalAddOnCreated`, + `jurnalAddOnCreatedUserID`, `jurnalAddOnDeleted`, `jurnalAddOnDeletedUserID`, + `jurnalAddOnLastUpdatedUserID`, `jurnalAddOnLastUpdated`) VALUES + (96, 316,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 316,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 317,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 317,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 318,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 318,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 319,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 319,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 320,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 320,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 321,'OMZTYPE', '1', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 321,'OMZNAME', 'APS', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 322,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 322,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 323,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 323,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 324,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 324,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 325,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 325,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 326,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 326,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 327,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 327,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 328,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 328,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 329,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 329,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 330,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 330,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 331,'OMZTYPE', '2', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 331,'OMZNAME', 'Dokter', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 332,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 332,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 333,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 333,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 334,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 334,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 335,'OMZTYPE', '3', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 335,'OMZNAME', 'Perusahaan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (96, 336,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 336,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 337,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 337,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 338,'OMZTYPE', '4', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (96, 338,'OMZNAME', 'Rujukan', 'Y', NOW(), 345, NOW(), 0, 345, NOW()) + "; + } + + private function injectArManual() + { + $jurnal = "INSERT INTO `jurnal` (`jurnalM_BranchCompanyID`, `JurnalS_RegionalID`, + `jurnalM_BranchCode`, `jurnalperiodeID`, `jurnalNo`, `jurnalTitle`, `jurnalDescription`, + `jurnalDate`, `jurnalIsPosted`, `jurnalJurnalTypeID`, `jurnalIsActive`, `jurnalCreated`, + `jurnalLastUpdated`, `jurnalM_UserID`) VALUES (1, 8, 'BA', 4, 'autoAR001', + 'Media Jurnal AR', 'inject manual AR belum balance', '2025-01-09', 'N', 10, 'Y', + NOW(), NOW(),345)"; + + $jurnalID = 144; + + $tx = "INSERT INTO `jurnal_tx` (`jurnalTxJurnalID`, `jurnalTxCoaID`, `jurnalTxDescription`, + `jurnalTxDebit`, `jurnalTxCredit`, `jurnalTxIsActive`, `jurnalTxCreated`, + `jurnalTxLastUpdated`, `jurnalTxM_UserID`) VALUES + (144, 199, 'PASIEN DOKTER / KLINISI', 585600, 0, 'Y', NOW(), NOW(), 345), + (144, 847, 'PEND. RAD. PANORAMIC & DENTAL', 0, 732000, 'Y', NOW(), NOW(), 345), + (144, 854, 'DISC PEND. RADIODIAGNOSTIK', 0, -146400, 'Y', NOW(), NOW(), 345), + + (144, 595, 'HUTANG BPJS KESEHATAN', 24520000, 0, 'Y', NOW(), NOW(), 345), + (144, 823, 'PENDAPATAN URINALISIS ', 0, 10856000, 'Y', NOW(), NOW(), 345), + (144, 826, 'PENDAPATAN KIMIA KLINIK', 0, 37806000, 'Y', NOW(), NOW(), 345), + (144, 847, 'DISCOUNT PENDAPATAN LABORATORIUM', 0, -24142000, 'Y', NOW(), NOW(), 345), + + "; + + $addOn = "INSERT INTO `jurnal_addon` (`jurnalAddOnJurnalID`, `jurnalAddOnJurnalTxID`, + `jurnalAddOnCode`, `jurnalAddOnValue`, `jurnalAddOnIsActive`, `jurnalAddOnCreated`, + `jurnalAddOnCreatedUserID`, `jurnalAddOnDeleted`, `jurnalAddOnDeletedUserID`, + `jurnalAddOnLastUpdatedUserID`, `jurnalAddOnLastUpdated`) VALUES + (144, 913,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 913,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 913,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 914,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYNUM', 'PRAMITA00013', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYID', '1235', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 915,'CMPNYNAME', 'PASIEN KLINISI', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + + (144, 916,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 916,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 916,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 917,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 918,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYNUM', '0210100', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYID', '2354', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + (144, 919,'CMPNYNAME', 'BPJS CABANG JAKARTA TIMUR', 'Y', NOW(), 345, NOW(), 0, 345, NOW()), + "; + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Presentasecabang.php b/application/controllers/mockup/masterdata/accounting/Presentasecabang.php new file mode 100644 index 0000000..c5e83fa --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Presentasecabang.php @@ -0,0 +1,537 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $limit = 10; + $pages = 0; + + if ($prm['currpages'] > 0) { + $pages = ($prm['currpages'] - 1) * $limit; + } + + $total = "SELECT COUNT(*) as total FROM branch_percent WHERE BranchPercentIsActive = 'Y'"; + $qtotal = $this->db->query($total); + $rtotal = $qtotal->result_array()[0]['total']; + + $sql = "SELECT + BranchPercentID, + BranchPercentType, + BranchPercentIsActive + from branch_percent + where BranchPercentIsActive = 'Y' + limit ? offset ? + "; + $query = $this->db->query($sql, [$limit, $pages]); + if (! $query) { + $this->sys_error_db("get listing presentase cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => (int)$rtotal, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function inserttypepresentase() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "INSERT INTO `branch_percent` ( + BranchPercentType, + BranchPercentCreated, + BranchPercentCreatedUserID + ) VALUES (?, NOW(), ?)"; + + $query = $this->db->query($sql, [$typename, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("type presentase error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edittypepresentase() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_percent SET + BranchPercentType = ?, + BranchPercentLastUpdated = now(), + BranchPercentLastUpdatedUserID = ? + WHERE BranchPercentID = ?"; + + $query = $this->db->query($sql, [ + $typename, + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("update type presentase cabang", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchPercentID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletetypepresentase() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_percent SET + BranchPercentIsActive = 'N', + BranchPercentDeleted = now(), + BranchPercentDeletedUserID = ? + WHERE BranchPercentID = ?"; + + $query = $this->db->query($sql, [ + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("delete type presentase", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchPercentID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } + + function detailpresentasecabang() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $branchPercentID = $prm['presentasecabangid']; + $currPages = $prm['currpages']; + + $total = "SELECT + COUNT(DISTINCT S_RegionalID) as total + FROM branch_percent_detail + JOIN m_branch ON BranchPercentDetailM_BranchID = M_BranchID + JOIN s_regional ON BranchPercentDetailS_RegionalID = S_RegionalID + WHERE BranchPercentDetailBranchPercentID = ? AND BranchPercentDetailIsActive = 'Y' + "; + + $que_to = $this->db->query($total, array($branchPercentID)); + if (!$que_to) { + $this->sys_error_db("error get total data detail"); + exit; + } + $row_to = $que_to->result_array()[0]["total"]; + + $pages = 0; + $limit = 10; + + if ($currPages > 0) { + $pages = ($currPages - 1) * $limit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName, + GROUP_CONCAT(CONCAT(M_BranchName, ' (', BranchPercentDetailValue, '%)') ORDER BY M_BranchName SEPARATOR ', ') as DetailCabang, + GROUP_CONCAT(BranchPercentDetailID SEPARATOR ',') AS ListBranchPercentDetailID + from branch_percent_detail + join m_branch on BranchPercentDetailM_BranchID = M_BranchID + join s_regional on BranchPercentDetailS_RegionalID = S_RegionalID + where BranchPercentDetailBranchPercentID = ? and BranchPercentDetailIsActive = 'Y' + group by S_RegionalID + LIMIT ? OFFSET ?; + "; + $query = $this->db->query($sql, array($branchPercentID, $limit, $pages)); + if (!$query) { + $this->sys_error_db("get listing detail presentase cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => $row_to, + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getlistregional() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y'"; + + $query = $this->db->query($sql); + if (! $query) { + $this->sys_error_db("get listing regional"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function getregionalbranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $user_company = $this->sys_user["M_BranchCompanyID"]; + + // $sql = "SELECT + // M_BranchID, + // M_BranchCode, + // M_BranchName, + // 0 as branchValue, + // '' as accountNumber, + // '' as searchCoa + // from m_branch + // where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ?"; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + 0 as branchValue, + '' as accountNumber, + '' as searchCoa + from m_branch_company + join m_branch_companydetail on M_BranchCompanyDetailM_BranchCompanyID = M_BranchCompanyID + and M_BranchCompanyDetailIsActive = 'Y' + join m_branch on M_BranchCode = M_BranchCompanyDetailM_BranchCode and M_BranchIsActive = 'Y' + where M_BranchCompanyIsActive = 'Y' and M_BranchS_RegionalID = ? and M_BranchCompanyID = ? + "; + + $query = $this->db->query($sql, array($regionalid, $user_company)); + if (! $query) { + $this->sys_error_db("get listing regional branches"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function insertdetailprecab() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $bpid = $item['branchpercentid']; + $rgid = $item['regionalid']; + $brid = $item['branchid']; + $valu = $item['value']; + $noacc = $item['noacc']; + + $sql = "INSERT INTO `branch_percent_detail` ( + BranchPercentDetailBranchPercentID, + BranchPercentDetailS_RegionalID, + BranchPercentDetailM_BranchID, + BranchPercentDetailValue, + BranchPercentDetailAccountNumber, + BranchPercentDetailCreated, + BranchPercentDetailCreatedUserID + ) VALUES (?, ?, ?, ?, ?, NOW(), ?)"; + $query = $this->db->query($sql, [$bpid, $rgid, $brid, $valu, $noacc, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function editdetailprecab() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $detid = $item['precabdetailid']; + $value = $item['value']; + $noacc = $item['noacc']; + + $sql = "UPDATE branch_percent_detail SET + BranchPercentDetailValue = ?, + BranchPercentDetailAccountNumber = ?, + BranchPercentDetailLastUpdated = now(), + BranchPercentDetailLastUpdatedUserID = ? + WHERE BranchPercentDetailID = ?"; + + $query = $this->db->query($sql, [$value, $noacc, $userid, $detid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error update precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function getvaluedetailprecab() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $branchpercentid = $prm['branchpercentid']; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + BranchPercentDetailID, + CAST(COALESCE(BranchPercentDetailValue, 0) AS DECIMAL(10, 2)) as branchValue, + COALESCE(BranchPercentDetailAccountNumber, 0) as accountNumber, + '' as searchCoa + from m_branch + join branch_percent_detail on BranchPercentDetailM_BranchID = M_BranchID + join branch_percent on BranchPercentID = BranchPercentDetailBranchPercentID + where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ? + and BranchPercentID = ?"; + $query = $this->db->query($sql, [$regionalid, $branchpercentid]); + if (!$query) { + $this->sys_error_db("error get current value detail precab"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function deletedetailprecab() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = "(" . $prm["precabdetailid"] . ")"; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_percent_detail SET + BranchPercentDetailIsActive = 'N', + BranchPercentDetailDeleted = now(), + BranchPercentDetailDeletedUserID = ? + WHERE BranchPercentDetailID IN " . $input; + $query = $this->db->query($sql, [$userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error delete precab detail"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => $input + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function searchcoa() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid token"); + exit; + } + + $prm = $this->sys_input; + $keyword = "%" . $prm['keyword'] . "%"; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE coaIsActive = 'Y' AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 20"; + $query = $this->db->query($sql, [$keyword]); + if (!$query) { + $this->sys_error_db("Error get listing coa", $this->db); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Presentasecost.php b/application/controllers/mockup/masterdata/accounting/Presentasecost.php new file mode 100644 index 0000000..2915498 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Presentasecost.php @@ -0,0 +1,537 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $limit = 10; + $pages = 0; + + if ($prm['currpages'] > 0) { + $pages = ($prm['currpages'] - 1) * $limit; + } + + $total = "SELECT COUNT(*) as total FROM branch_cost_percent WHERE BranchCostPercentIsActive = 'Y'"; + $qtotal = $this->db->query($total); + $rtotal = $qtotal->result_array()[0]['total']; + + $sql = "SELECT + BranchCostPercentID, + BranchCostPercentType, + BranchCostPercentIsActive + from branch_cost_percent + where BranchCostPercentIsActive = 'Y' + limit ? offset ? + "; + $query = $this->db->query($sql, [$limit, $pages]); + if (! $query) { + $this->sys_error_db("get listing presentase biaya cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => (int)$rtotal, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function inserttypepresentasecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "INSERT INTO `branch_cost_percent` ( + BranchCostPercentType, + BranchCostPercentCreated, + BranchCostPercentCreatedUserID + ) VALUES (?, NOW(), ?)"; + + $query = $this->db->query($sql, [$typename, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("type presentase error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edittypepresentasecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_cost_percent SET + BranchCostPercentType = ?, + BranchCostPercentLastUpdated = now(), + BranchCostPercentLastUpdatedUserID = ? + WHERE BranchCostPercentID = ?"; + + $query = $this->db->query($sql, [ + $typename, + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("update type presentase cabang", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchCostPercentID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletetypepresentasecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_cost_percent SET + BranchCostPercentIsActive = 'N', + BranchCostPercentDeleted = now(), + BranchCostPercentDeletedUserID = ? + WHERE BranchCostPercentID = ?"; + + $query = $this->db->query($sql, [ + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("delete type presentase", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchCostPercentID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } + + function detailpresentasecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $branchCostPercentID = $prm['presentasecostid']; + $currPages = $prm['currpages']; + + $total = "SELECT + COUNT(DISTINCT S_RegionalID) as total + FROM branch_cost_percent_detail + JOIN m_branch ON BranchCostPercentDetailM_BranchID = M_BranchID + JOIN s_regional ON BranchCostPercentDetailS_RegionalID = S_RegionalID + WHERE BranchCostPercentDetailBranchCostPercentID = ? AND BranchCostPercentDetailIsActive = 'Y' + "; + + $que_to = $this->db->query($total, array($branchCostPercentID)); + if (!$que_to) { + $this->sys_error_db("error get total data detail"); + exit; + } + $row_to = $que_to->result_array()[0]["total"]; + + $pages = 0; + $limit = 10; + + if ($currPages > 0) { + $pages = ($currPages - 1) * $limit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName, + GROUP_CONCAT(CONCAT(M_BranchName, ' (', BranchCostPercentDetailValue, '%)') ORDER BY M_BranchName SEPARATOR ', ') as DetailCabang, + GROUP_CONCAT(BranchCostPercentDetailID SEPARATOR ',') AS ListBranchPercentDetailID + from branch_cost_percent_detail + join m_branch on BranchCostPercentDetailM_BranchID = M_BranchID + join s_regional on BranchCostPercentDetailS_RegionalID = S_RegionalID + where BranchCostPercentDetailBranchCostPercentID = ? and BranchCostPercentDetailIsActive = 'Y' + group by S_RegionalID + LIMIT ? OFFSET ?; + "; + $query = $this->db->query($sql, array($branchCostPercentID, $limit, $pages)); + if (!$query) { + $this->sys_error_db("get listing detail presentase cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => $row_to, + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getlistregional() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y'"; + + $query = $this->db->query($sql); + if (! $query) { + $this->sys_error_db("get listing regional"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function getregionalbranch() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $user_company = $this->sys_user["M_BranchCompanyID"]; + + // $sql = "SELECT + // M_BranchID, + // M_BranchCode, + // M_BranchName, + // 0 as branchValue, + // '' as accountNumber, + // '' as searchCoa + // from m_branch + // where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ?"; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + 0 as branchValue, + '' as accountNumber, + '' as searchCoa + from m_branch_company + join m_branch_companydetail on M_BranchCompanyDetailM_BranchCompanyID = M_BranchCompanyID + and M_BranchCompanyDetailIsActive = 'Y' + join m_branch on M_BranchCode = M_BranchCompanyDetailM_BranchCode and M_BranchIsActive = 'Y' + where M_BranchCompanyIsActive = 'Y' and M_BranchS_RegionalID = ? and M_BranchCompanyID = ? + "; + + $query = $this->db->query($sql, array($regionalid, $user_company)); + if (! $query) { + $this->sys_error_db("get listing regional branches"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function insertdetailprecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $bpid = $item['branchcostpercentid']; + $rgid = $item['regionalid']; + $brid = $item['branchid']; + $valu = $item['value']; + $noacc = $item['noacc']; + + $sql = "INSERT INTO `branch_cost_percent_detail` ( + BranchCostPercentDetailBranchCostPercentID, + BranchCostPercentDetailS_RegionalID, + BranchCostPercentDetailM_BranchID, + BranchCostPercentDetailValue, + BranchCostPercentDetailAccountNumber, + BranchCostPercentDetailCreated, + BranchCostPercentDetailCreatedUserID + ) VALUES (?, ?, ?, ?, ?, NOW(), ?)"; + $query = $this->db->query($sql, [$bpid, $rgid, $brid, $valu, $noacc, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function editdetailprecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $detid = $item['precabdetailid']; + $value = $item['value']; + $noacc = $item['noacc']; + + $sql = "UPDATE branch_cost_percent_detail SET + BranchCostPercentDetailValue = ?, + BranchCostPercentDetailAccountNumber = ?, + BranchCostPercentDetailLastUpdated = now(), + BranchCostPercentDetailLastUpdatedUserID = ? + WHERE BranchCostPercentDetailID = ?"; + + $query = $this->db->query($sql, [$value, $noacc, $userid, $detid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error update precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function getvaluedetailprecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $branchcostpercentid = $prm['branchcostpercentid']; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + BranchCostPercentDetailID, + CAST(COALESCE(BranchCostPercentDetailValue, 0) AS DECIMAL(10, 2)) as branchValue, + COALESCE(BranchCostPercentDetailAccountNumber, 0) as accountNumber, + '' as searchCoa + from m_branch + join branch_cost_percent_detail on BranchCostPercentDetailM_BranchID = M_BranchID + join branch_cost_percent on BranchCostPercentID = BranchCostPercentDetailBranchCostPercentID + where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ? + and BranchCostPercentID = ?"; + $query = $this->db->query($sql, [$regionalid, $branchcostpercentid]); + if (!$query) { + $this->sys_error_db("error get current value detail precab"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function deletedetailprecost() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = "(" . $prm["precabdetailid"] . ")"; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_cost_percent_detail SET + BranchCostPercentDetailIsActive = 'N', + BranchCostPercentDetailDeleted = now(), + BranchCostPercentDetailDeletedUserID = ? + WHERE BranchCostPercentDetailID IN " . $input; + $query = $this->db->query($sql, [$userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error delete precab detail"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => $input + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function searchcoa() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid token"); + exit; + } + + $prm = $this->sys_input; + $keyword = "%" . $prm['keyword'] . "%"; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE coaIsActive = 'Y' AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 20"; + $query = $this->db->query($sql, [$keyword]); + if (!$query) { + $this->sys_error_db("Error get listing coa", $this->db); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Presentasefacabang.php b/application/controllers/mockup/masterdata/accounting/Presentasefacabang.php new file mode 100644 index 0000000..72ce3df --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Presentasefacabang.php @@ -0,0 +1,529 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $limit = 10; + $pages = 0; + + if ($prm['currpages'] > 0) { + $pages = ($prm['currpages'] - 1) * $limit; + } + + $total = "SELECT COUNT(*) as total FROM branch_fa_percent WHERE BranchFaPercentIsActive = 'Y'"; + $qtotal = $this->db->query($total); + $rtotal = $qtotal->result_array()[0]['total']; + + $sql = "SELECT + BranchFaPercentID, + BranchFaPercentType, + BranchFaPercentIsActive + from branch_fa_percent + where BranchFaPercentIsActive = 'Y' + limit ? offset ? + "; + $query = $this->db->query($sql, [$limit, $pages]); + if (! $query) { + $this->sys_error_db("get listing presentase cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => (int)$rtotal, + "records" => $rows + ); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function inserttypepresentase() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "INSERT INTO `branch_fa_percent` ( + BranchFaPercentType, + BranchFaPercentCreated, + BranchFaPercentCreatedUserID + ) VALUES (?, NOW(), ?)"; + + $query = $this->db->query($sql, [$typename, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("type presentase error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => 0 + ); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edittypepresentase() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $typename = $prm['typename']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_fa_percent SET + BranchFaPercentType = ?, + BranchFaPercentLastUpdated = now(), + BranchFaPercentLastUpdatedUserID = ? + WHERE BranchFaPercentID = ?"; + + $query = $this->db->query($sql, [ + $typename, + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("update type presentase cabang", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchFaPercentID" => $typeid)); + $this->sys_ok($result); + + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletetypepresentase() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $typeid = $prm['typeid']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_fa_percent SET + BranchFaPercentIsActive = 'N', + BranchFaPercentDeleted = now(), + BranchFaPercentDeletedUserID = ? + WHERE BranchFaPercentID = ?"; + + $query = $this->db->query($sql, [ + $userid, + $typeid + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("delete type presentase", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array("total" => 1, "records" => array("BranchFaPercentID" => $typeid)); + $this->sys_ok($result); + } catch (Exception $exc) { + $msg = $exc->getMessage(); + $this->sys_error($msg); + } + } + + function detailpresentasecabang() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $branchPercentID = $prm['presentasecabangid']; + $currPages = $prm['currpages']; + + $total = "SELECT + COUNT(DISTINCT S_RegionalID) as total + FROM branch_fa_percent_detail + JOIN m_branch ON BranchFaPercentDetailM_BranchID = M_BranchID + JOIN s_regional ON BranchFaPercentDetailS_RegionalID = S_RegionalID + WHERE BranchFaPercentDetailBranchFaPercentID = ? AND BranchFaPercentDetailIsActive = 'Y' + "; + + $que_to = $this->db->query($total, array($branchPercentID)); + if (!$que_to) { + $this->sys_error_db("error get total data detail"); + exit; + } + $row_to = $que_to->result_array()[0]["total"]; + + $pages = 0; + $limit = 10; + + if ($currPages > 0) { + $pages = ($currPages - 1) * $limit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName, + GROUP_CONCAT(CONCAT(M_BranchName, ' (', BranchFaPercentDetailValue, '%)') ORDER BY M_BranchName SEPARATOR ', ') as DetailCabang, + GROUP_CONCAT(BranchFaPercentDetailID SEPARATOR ',') AS ListBranchFaPercentDetailID + from branch_fa_percent_detail + join m_branch on BranchFaPercentDetailM_BranchID = M_BranchID + join s_regional on BranchFaPercentDetailS_RegionalID = S_RegionalID + where BranchFaPercentDetailBranchFaPercentID = ? and BranchFaPercentDetailIsActive = 'Y' + group by S_RegionalID + LIMIT ? OFFSET ?; + "; + $query = $this->db->query($sql, array($branchPercentID, $limit, $pages)); + if (!$query) { + $this->sys_error_db("get listing detail presentase cabang"); + exit; + } + $rows = $query->result_array(); + + $result = array( + "total" => $row_to, + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getlistregional() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y'"; + + $query = $this->db->query($sql); + if (! $query) { + $this->sys_error_db("get listing regional"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function getregionalbranch() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $user_company = $this->sys_user["M_BranchCompanyID"]; + + // $sql = "SELECT + // M_BranchID, + // M_BranchCode, + // M_BranchName, + // 0 as branchValue, + // '' as accountNumber, + // '' as searchCoa + // from m_branch + // where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ?"; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + 0 as branchValue, + '' as accountNumber, + '' as searchCoa + from m_branch_company + join m_branch_companydetail on M_BranchCompanyDetailM_BranchCompanyID = M_BranchCompanyID + and M_BranchCompanyDetailIsActive = 'Y' + join m_branch on M_BranchCode = M_BranchCompanyDetailM_BranchCode and M_BranchIsActive = 'Y' + where M_BranchCompanyIsActive = 'Y' and M_BranchS_RegionalID = ? and M_BranchCompanyID = ? + "; + + $query = $this->db->query($sql, array($regionalid, $user_company)); + if (! $query) { + $this->sys_error_db("get listing regional branches"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $mssg = $exc->getMessage(); + $this->sys_error($mssg); + } + } + + function insertdetailprecab() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $bpid = $item['branchpercentid']; + $rgid = $item['regionalid']; + $brid = $item['branchid']; + $valu = $item['value']; + $noacc = $item['noacc']; + + $sql = "INSERT INTO `branch_fa_percent_detail` ( + BranchFaPercentDetailBranchFaPercentID, + BranchFaPercentDetailS_RegionalID, + BranchFaPercentDetailM_BranchID, + BranchFaPercentDetailValue, + BranchFaPercentDetailAccountNumber, + BranchFaPercentDetailCreated, + BranchFaPercentDetailCreatedUserID + ) VALUES (?, ?, ?, ?, ?, NOW(), ?)"; + $query = $this->db->query($sql, [$bpid, $rgid, $brid, $valu, $noacc, $userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error insert precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function editdetailprecab() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = $prm["branchvalue"]; + $userid = $this->sys_user["M_UserID"]; + + foreach ($input as $item) { + $detid = $item['precabdetailid']; + $value = $item['value']; + $noacc = $item['noacc']; + + $sql = "UPDATE branch_fa_percent_detail SET + BranchFaPercentDetailValue = ?, + BranchFaPercentDetailAccountNumber = ?, + BranchFaPercentDetailLastUpdated = now(), + BranchFaPercentDetailLastUpdatedUserID = ? + WHERE BranchFaPercentDetailID = ?"; + + $query = $this->db->query($sql, [$value, $noacc, $userid, $detid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error update precab detail"); + exit; + } + } + + $this->db->trans_commit(); + $result = array( + "total" => sizeof($input), + "records" => 0 + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function getvaluedetailprecab() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $regionalid = $prm['regionalid']; + $branchpercentid = $prm['branchpercentid']; + + $sql = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName, + BranchFaPercentDetailID, + CAST(COALESCE(BranchFaPercentDetailValue, 0) AS DECIMAL(10, 2)) as branchValue, + COALESCE(BranchFaPercentDetailAccountNumber, 0) as accountNumber, + '' as searchCoa + from m_branch + join branch_fa_percent_detail on BranchFaPercentDetailM_BranchID = M_BranchID + join branch_fa_percent on BranchFaPercentID = BranchFaPercentDetailBranchFaPercentID + where M_BranchIsActive = 'Y' and M_BranchS_RegionalID = ? + and BranchFaPercentID = ?"; + $query = $this->db->query($sql, [$regionalid, $branchpercentid]); + if (!$query) { + $this->sys_error_db("error get current value detail precab"); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function deletedetailprecab() { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $input = "(" . $prm["precabdetailid"] . ")"; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE branch_fa_percent_detail SET + BranchFaPercentDetailIsActive = 'N', + BranchFaPercentDetailDeleted = now(), + BranchFaPercentDetailDeletedUserID = ? + WHERE BranchFaPercentDetailID IN " . $input; + $query = $this->db->query($sql, [$userid]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("error delete precab detail"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => $input + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } + + function searchcoa() { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid token"); + exit; + } + + $prm = $this->sys_input; + $keyword = "%" . $prm['keyword'] . "%"; + + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' - ' ,coaDescription) as display + FROM coa + WHERE coaIsActive = 'Y' AND coaIsInput = 'Y' + AND (CONCAT(coaAccountNo, ' - ' ,coaDescription) LIKE ?) + LIMIT 20"; + $query = $this->db->query($sql, [$keyword]); + if (!$query) { + $this->sys_error_db("Error get listing coa", $this->db); + exit; + } + $rows = $query->result_array(); + $result = array( + "total" => sizeof($rows), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $ex) { + $msg = $ex->getMessage(); + $this->sys_error($msg); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Presetjurnal.http b/application/controllers/mockup/masterdata/accounting/Presetjurnal.http new file mode 100644 index 0000000..2ece9d4 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Presetjurnal.http @@ -0,0 +1,16 @@ +POST https://{{host}}/mockup/masterdata/accounting/presetjurnal/getPeriode +Content-Type: "application/json" + +{ + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJNX1VzZXJJRCI6IjMiLCJNX1VzZXJVc2VybmFtZSI6ImFkbWluICIsIk1fVXNlckdyb3VwRGFzaGJvYXJkIjoidGVzdFwvdnVleFwvb25lLWZvLXJlZ2lzdHJhdGlvbi12MzFcLyIsIk1fVXNlckRlZmF1bHRUX1NhbXBsZVN0YXRpb25JRCI6IjAiLCJNX1N0YWZmTmFtZSI6IkFETUlOIiwiaXNfY291cmllciI6Ik4iLCJ0aW1lX2F1dG9sb2dvdXQiOiIxMjAiLCJpcCI6IjE0OS4xMTMuOTUuMTUzIiwiYWdlbnQiOiJNb3ppbGxhXC81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXRcLzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZVwvMTI4LjAuMC4wIFNhZmFyaVwvNTM3LjM2IEVkZ1wvMTI4LjAuMC4wIiwidmVyc2lvbiI6InYyIiwibGFzdC1sb2dpbiI6IjIwMjQtMDktMDIgMTE6MzY6MDgiLCJNX1NhdGVsbGl0ZUlEIjowfQ.38owLzgSjtoley0Vz9W9silF4vfp7hrJEQqytYHf8P0" +} + +### +POST https://{{host}}/mockup/masterdata/accounting/presetjurnal/searchDetail +Content-Type: "application/json" + +{ + "page": 3, + "jurnal": {"id":3}, + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJNX1VzZXJJRCI6IjMiLCJNX1VzZXJVc2VybmFtZSI6ImFkbWluICIsIk1fVXNlckdyb3VwRGFzaGJvYXJkIjoidGVzdFwvdnVleFwvb25lLWZvLXJlZ2lzdHJhdGlvbi12MzFcLyIsIk1fVXNlckRlZmF1bHRUX1NhbXBsZVN0YXRpb25JRCI6IjAiLCJNX1N0YWZmTmFtZSI6IkFETUlOIiwiaXNfY291cmllciI6Ik4iLCJ0aW1lX2F1dG9sb2dvdXQiOiIxMjAiLCJpcCI6IjE0OS4xMTMuOTUuMTUzIiwiYWdlbnQiOiJNb3ppbGxhXC81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXRcLzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZVwvMTI4LjAuMC4wIFNhZmFyaVwvNTM3LjM2IEVkZ1wvMTI4LjAuMC4wIiwidmVyc2lvbiI6InYyIiwibGFzdC1sb2dpbiI6IjIwMjQtMDktMDIgMTE6MzY6MDgiLCJNX1NhdGVsbGl0ZUlEIjowfQ.38owLzgSjtoley0Vz9W9silF4vfp7hrJEQqytYHf8P0" +} \ No newline at end of file diff --git a/application/controllers/mockup/masterdata/accounting/Presetjurnal.php b/application/controllers/mockup/masterdata/accounting/Presetjurnal.php new file mode 100644 index 0000000..d5958d0 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Presetjurnal.php @@ -0,0 +1,866 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function getPeriode() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $sql = "SELECT + periodeID AS id, + periodeName as name, + CONCAT(DATE_FORMAT(periodeStartDate, '%d-%m-%Y'), ' - ',DATE_FORMAT(periodeEndDate, '%d-%m-%Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $rst = $qry->result_array(); + // $data = array( + // array("id" => "1", "name" => "Periode Januari", "periode" => '01-01-2024 - 31-01-2024'), + // array("id" => "2", "name" => "Periode Februari", "periode" => '01-02-2024 - 31-02-2024'), + // array("id" => "3", "name" => "Periode Maret", "periode" => '01-03-2024 - 31-03-2024'), + // ); + $this->sys_ok($rst); + } + function getBranch() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $sql = "SELECT + M_BranchID branchID, + M_BranchCode branchCode, + M_BranchName branchName + FROM m_branch WHERE M_BranchIsActive = 'Y'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("get branch", $this->db); + exit; + } + $rst = $qry->result_array(); + + $this->sys_ok($rst); + } + function addJurnal() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $sql = "SELECT fn_numbering('PJ') as number"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("get numbering", $this->db); + exit; + } + $numbering = $qry->result_array()[0]['number']; + $sql = "INSERT INTO t_presetjurnal( + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalType, + jurnalCreated, + jurnalM_UserID) + VALUES (?,?,?,?,?,NOW(),?)"; + $qry = $this->db->query($sql, [ + $prm['branch'], + $prm['periode'], + $numbering, + $prm['name'], + $prm['type'], + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error insert preset jurnal header", $this->db); + exit; + } + + $this->sys_ok($numbering); + } + function editJurnal() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE t_presetjurnal SET + jurnalM_BranchCode = ?, + jurnalperiodeID = ?, + jurnalTitle = ?, + jurnalType = ?, + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ? + "; + $qry = $this->db->query($sql, [ + $prm['branch'], + $prm['periode'], + $prm['name'], + $prm['type'], + $userid, + $prm['id'], + ]); + if (!$qry) { + $this->sys_error_db("Error update preset jurnal header", $this->db); + exit; + } + + $this->sys_ok('OK'); + } + function deleteJurnal() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $sql = "UPDATE t_presetjurnal SET + jurnalIsActive = 'N', + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ? + "; + $qry = $this->db->query($sql, [ + $userid, + $prm['id'], + ]); + if (!$qry) { + $this->sys_error_db("Error delete jurnal header", $this->db); + exit; + } + $sql = "UPDATE t_presetjurnaldetail SET + jurnalTxIsActive = 'N', + jurnalTxLastUpdated = NOW(), + jurnalTxM_UserID = ? + WHERE jurnalTxJurnalID = ? + "; + $qry = $this->db->query($sql, [ + $userid, + $prm['id'], + ]); + if (!$qry) { + $this->sys_error_db("Error delete jurnal header", $this->db); + exit; + } + + $this->sys_ok('OK'); + } + function searchHeader() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + $periode = $prm["periode"]; + $ROW_PER_PAGE = 5; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sql = "SELECT + COUNT(jurnalID) as total + FROM t_presetjurnal + JOIN periode + ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + WHERE (jurnalNo LIKE ? OR jurnalTitle LIKE ?) + AND jurnalperiodeID = ? + AND jurnalIsActive = 'Y'"; + $qry = $this->db->query($sql, [ + $search, + $search, + $periode + + ]); + if (!$qry) { + $this->sys_error_db("Error get total", $this->db); + exit; + } + $total = $qry->result_array()[0]['total']; + $sql = "SELECT + jurnalID id, + jurnalM_BranchCode as branch, + jurnalperiodeID periode, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d/%m/%Y'), ' - ',DATE_FORMAT(periodeEndDate, '%d/%m/%Y')) as periodeDate, + M_BranchName branchName, + jurnalNo number, + jurnalTitle name, + jurnalType as type, + CASE + WHEN jurnalStatus = 0 THEN 'NEW' + WHEN jurnalStatus <> 0 THEN 'POST' + END as status + FROM t_presetjurnal + JOIN periode + ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + JOIN m_branch + ON jurnalM_BranchCode = M_BranchCode + AND M_BranchIsActive = 'Y' + WHERE (jurnalNo LIKE ? OR jurnalTitle LIKE ?) + AND jurnalperiodeID = ? + AND jurnalIsActive = 'Y' + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $search, + $search, + $periode, + $ROW_PER_PAGE, + $start_offset + ]); + if (!$qry) { + $this->sys_error_db("Error get total", $this->db); + exit; + } + $rst = array( + "total" => ceil($total / $ROW_PER_PAGE), + "records" => $qry->result_array() + ); + $this->sys_ok($rst); + } + function cek() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $sql = "SELECT COUNT(*) as total FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + exit; + } + $rst = $qry->result_array()[0]['total']; + $this->sys_ok($rst); + } + function save() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $jurnal = $prm['jurnal']; + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT COUNT(*) as total FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $total = $qry->result_array()[0]['total']; + if (intval($total) > 0) { + $sql = "DELETE FROM t_presetjurnaldetail WHERE jurnalTxJurnalID = ?"; + $qry = $this->db->query($sql, [$jurnal['id']]); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + $this->db->trans_rollback(); + exit; + } + } + + for ($i = 0; $i < count($data); $i++) { + $cekData = $data[$i]; + if (!array_key_exists('Number', $cekData)) { + $this->sys_error("Kolom Number tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Keterangan', $cekData)) { + $this->sys_error("Kolom Keterangan tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Debit', $cekData)) { + $this->sys_error("Kolom Debit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Kredit', $cekData)) { + $this->sys_error("Kolom Kredit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (floatval($cekData['Debit']) > 0 && floatval($cekData['Kredit']) > 0) { + $this->sys_error("Jumlah debit dan credit keduanya lebih besar dari 0"); + $this->db->trans_rollback(); + exit; + } + $sql = "SELECT coaID FROM coa + WHERE coaAccountNo = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$cekData['Number']]); + if (!$qry) { + $this->sys_error_db("cek coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->result_array(); + if (count($cek) == 0) { + $this->sys_error_db("{$cekData['Number']} tidak ada di coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $data[$i]['coaID'] = $cek[0]['coaID']; + } + + for ($i = 0; $i < count($data); $i++) { + $dataCoa = $data[$i]; + $debit = $dataCoa['Debit']; + $credit = $dataCoa['Kredit']; + $type = 'DB'; + if (floatval($dataCoa['Kredit']) > 0) { + $type = 'CR'; + } + + $sql = "INSERT INTO t_presetjurnaldetail( + jurnalTxJurnalID, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxCreated, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,NOW(),?)"; + $qry = $this->db->query($sql, [ + $jurnal['id'], + $dataCoa['coaID'], + $dataCoa['Keterangan'], + $debit, + $credit, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error insert beginning balance", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->sys_ok("OK"); + $this->db->trans_commit(); + } + function addData() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $jurnal = $prm['jurnal']; + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT COUNT(*) as total FROM t_beginningbalance"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $total = $qry->result_array()[0]['total']; + // if (intval($total) > 0) { + // $sql = "DELETE FROM t_presetjurnaldetail"; + // $qry = $this->db->query($sql, []); + // if (!$qry) { + // $this->sys_error_db("Error truncate", $this->db); + // $this->db->trans_rollback(); + // exit; + // } + // } + + for ($i = 0; $i < count($data); $i++) { + $cekData = $data[$i]; + if (!array_key_exists('Number', $cekData)) { + $this->sys_error("Pilih coa terlebih dahulu"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Keterangan', $cekData)) { + $this->sys_error("Kolom Keterangan tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (trim($cekData['Keterangan']) == '') { + $this->sys_error("Keterangan tidak boleh kosong"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Debit', $cekData)) { + $this->sys_error("Kolom Debit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (!array_key_exists('Kredit', $cekData)) { + $this->sys_error("Kolom Kredit tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + if (floatval($cekData['Debit']) > 0 && floatval($cekData['Kredit']) > 0) { + $this->sys_error("Jumlah debit dan credit keduanya lebih besar dari 0"); + $this->db->trans_rollback(); + exit; + } + $sql = "SELECT coaID FROM coa + WHERE coaAccountNo = ? + AND coaIsInput = 'Y' + AND coaIsActive = 'Y'"; + $qry = $this->db->query($sql, [$cekData['Number']]); + if (!$qry) { + $this->sys_error_db("cek coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->result_array(); + if (count($cek) == 0) { + $this->sys_error_db("{$cekData['Number']} tidak ada di coa", $this->db); + $this->db->trans_rollback(); + exit; + } + $data[$i]['coaID'] = $cek[0]['coaID']; + } + + for ($i = 0; $i < count($data); $i++) { + $dataCoa = $data[$i]; + $debit = $dataCoa['Debit']; + $credit = $dataCoa['Kredit']; + $type = 'DB'; + if (floatval($dataCoa['Kredit']) > 0) { + $type = 'CR'; + } + + $sql = "INSERT INTO t_presetjurnaldetail( + jurnalTxJurnalID, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxCreated, + jurnalTxM_UserID) + VALUES(?,?,?,?,?,NOW(),?)"; + $qry = $this->db->query($sql, [ + $jurnal['id'], + $dataCoa['coaID'], + $dataCoa['Keterangan'], + $debit, + $credit, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error insert beginning balance", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->sys_ok("OK"); + $this->db->trans_commit(); + } + + + function searchDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + $jurnal = $prm["jurnal"]; + $ROW_PER_PAGE = 20; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sql = "SELECT + count(jurnalTxID) as total + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + WHERE (coaAccountNo LIKE ? OR junalTxDescription LIKE ?) + AND jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ?"; + $qry = $this->db->query($sql, [ + $search, + $search, + $jurnal['id'] + ]); + if (!$qry) { + $this->sys_error_db("Error get total", $this->db); + exit; + } + $total = $qry->result_array()[0]['total']; + $sql = "SELECT + jurnalTxID id, + coaAccountNo number, + jurnalTxCoaID coaid, + CONCAT(coaAccountNo, ' ' ,coaDescription) as searchCoa, + coaDescription, + junalTxDescription keterangan, + jurnalTxDebit, + jurnalTxCredit, + CASE + WHEN jurnalTxDebit <> 0 AND jurnalTxCredit = 0 THEN jurnalTxDebit + WHEN jurnalTxCredit <> 0 AND jurnalTxDebit = 0 THEN jurnalTxCredit + WHEN jurnalTxCredit = 0 AND jurnalTxDebit = 0 THEN jurnalTxDebit + ELSE jurnalTxDebit + END as value, + CASE + WHEN jurnalTxDebit <> 0 AND jurnalTxCredit = 0 THEN 'DB' + WHEN jurnalTxCredit <> 0 AND jurnalTxDebit = 0 THEN 'CR' + WHEN jurnalTxCredit = 0 AND jurnalTxDebit = 0 THEN 'DB' + ELSE 'ERROR' + END as type + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + WHERE (coaAccountNo LIKE ? OR junalTxDescription LIKE ?) + AND jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $search, $jurnal['id'], $ROW_PER_PAGE, $start_offset]); + if (!$qry) { + $this->sys_error_db("search detail", $this->db); + exit; + } + $data = $qry->result_array(); + $totalDebit = 0; + $totalCredit = 0; + $totalBalance = 0; + $status = 'N'; + + $sql = "SELECT + IFNULL(SUM(jurnalTxDebit), 0) as debit, + IFNULL(SUM(jurnalTxCredit), 0) as credit + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + AND jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + "; + $qry = $this->db->query($sql, [$jurnal['id'],]); + if (!$qry) { + $this->sys_error_db("Error sql count balance", $this->db); + exit; + } + $totalSum = $qry->row_array(); + $totalDebit = $totalSum['debit']; + $totalCredit = $totalSum['credit']; + + // for ($i = 0; $i < count($data); $i++) { + // $dataCek = $data[$i]; + // if ($dataCek['type'] == 'DB') { + // $totalDebit = $totalDebit + floatval($dataCek['value']); + // } + // if ($dataCek['type'] == 'CR') { + // $totalCredit = $totalCredit + floatval($dataCek['value']); + // } + // } + $totalBalance = $totalDebit - $totalCredit; + $periode = array(); + + + $rst = array( + 'data' => $data, + "total" => ceil($total / $ROW_PER_PAGE), + 'summary' => array( + 'debit' => $totalDebit, + 'credit' => $totalCredit, + 'balance' => $totalBalance + ) + ); + $this->sys_ok($rst); + } + function updateData() + { + // $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $data = $prm['data']; + $coa = $prm['coa']; + $userid = $this->sys_user["M_UserID"]; + $debit = 0; + $credit = 0; + $type = $data['type']; + if ($type == 'DB') { + $debit = $data['value']; + $credit = 0; + } + if ($type == 'CR') { + $credit = $data['value']; + $debit = 0; + } + + $sql = "UPDATE t_presetjurnaldetail + SET + jurnalTxCoaID = ?, + jurnalTxDebit = ?, + jurnalTxCredit = ?, + junalTxDescription = ?, + jurnalTxM_UserID = ? + WHERE jurnalTxID = ?"; + $qry = $this->db->query($sql, [$coa['coaID'], $debit, $credit, $data['keterangan'], $userid, $data['id']]); + if (!$qry) { + $this->sys_error_db("Error update preset jurnal", $this->db); + exit; + } + $retval = array( + "debit" => $debit, + "type" => $type, + "credit" => $credit, + "last_qry" => $this->db->last_query() + ); + $this->sys_ok($retval); + } + function postData() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + // $this->db->trans_commit(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT + COUNT(jurnalTxCoaID) as total + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + AND jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + "; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error sql count balance", $this->db); + exit; + } + $totalData = $qry->row_array()['total']; + if (intval($totalData) == 0) { + $this->sys_error_db("Belum memiliki jurnal detail", $this->db); + exit; + } + $sql = "SELECT + IFNULL(SUM(jurnalTxDebit), 0) as debit, + IFNULL(SUM(jurnalTxCredit), 0) as credit + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + AND jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ? + "; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error sql count balance", $this->db); + exit; + } + $totalSum = $qry->row_array(); + $totalDebit = $totalSum['debit']; + $totalCredit = $totalSum['credit']; + if ((floatval($totalDebit) - floatval($totalCredit)) != 0) { + $this->sys_error_db(" GAGAL, Jurnal tidak balance !", $this->db); + exit; + } + + + $sql = "INSERT INTO jurnal + (jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDate, + jurnalType, + jurnalM_UserID) + SELECT + jurnalM_BranchCode, + jurnalperiodeID, + fn_numbering('J'), + jurnalTitle, + NOW(), + jurnalType, + {$userid} + FROM t_presetjurnal + WHERE jurnalID = ? + "; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Insert jurnal", $this->db); + $this->db->trans_rollback(); + exit; + } + $insertedID = $this->db->insert_id(); + $sql = "UPDATE t_presetjurnal SET + jurnalStatus = ?, + jurnalLastUpdated = NOW(), + jurnalM_UserID = ? + WHERE jurnalID = ? + "; + $qry = $this->db->query($sql, [ + $insertedID, + $userid, + $id + ]); + if (!$qry) { + $this->sys_error_db("Error update preset jurnal header", $this->db); + $this->db->trans_rollback(); + + exit; + } + + $sql = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID) + SELECT + {$insertedID}, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + {$userid} + FROM t_presetjurnaldetail + JOIN coa + ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + AND coaIsInput = 'Y' + WHERE jurnalTxIsActive = 'Y' + AND jurnalTxJurnalID = ?"; + $qry = $this->db->query($sql, [ + $id + ]); + if (!$qry) { + $this->sys_error_db("Error update preset jurnal detail", $this->db); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok('OK'); + } + function delete() + { + $this->db->trans_begin(); + // $this->db->trans_rollback(); + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $sql = "DELETE FROM t_presetjurnaldetail WHERE jurnalTxID = ?"; + $qry = $this->db->query($sql, [$prm['id']]); + if (!$qry) { + $this->sys_error_db("Error delete", $this->db); + $this->db->trans_rollback(); + exit; + } + $this->db->trans_commit(); + $this->sys_ok('OK'); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $jurnal = $prm['jurnal']; + $sql = "SELECT + coaID, + jurnalTxID , + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, ' ' ,coaDescription) as display + FROM coa + LEFT JOIN t_presetjurnaldetail + ON coaID = jurnalTxCoaID + AND jurnalTxJurnalID = ? + WHERE + coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND (coaAccountNo LIKE ? OR coaDescription LIKE ? OR CONCAT(coaAccountNo, ' ' ,coaDescription) LIKE ? ) + "; + // AND jurnalTxID IS NULL + $qry = $this->db->query($sql, [$jurnal['id'], $search, $search, $search]); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Recrusivetemplate.php b/application/controllers/mockup/masterdata/accounting/Recrusivetemplate.php new file mode 100644 index 0000000..c813d08 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Recrusivetemplate.php @@ -0,0 +1,246 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + function searchCoa() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + $sql = "SELECT + coaID as id, + coaAccountNo as number, + coaDescription as keterangan, + CONCAT(coaAccountNo, '-' ,coaDescription) as display + FROM coa + WHERE + coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND (CONCAT(coaAccountNo, '-' ,coaDescription) LIKE ?) + "; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error truncate", $this->db); + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function insertTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + $sql = "SELECT fn_numbering('RJT') as number + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get number", $this->db); + exit; + } + $number = $qry->row_array()['number']; + $sql = "INSERT INTO t_recrusivejurnaltemplate( + T_RecrusiveJurnalTemplateNumber, + T_RecrusiveJurnalTemplateStartDate, + T_RecrusiveJurnalTemplateEndDate, + T_RecrusiveJurnalTemplateTenor, + T_RecrusiveJurnalTemplatePrePaid, + T_RecrusiveJurnalTemplateCreditCoaID, + T_RecrusiveJurnalTemplateDebetCoaID, + T_RecrusiveJurnalTemplateMonthly, + T_RecrusiveJurnalTemplateCreatedUserID, + T_RecrusiveJurnalTemplateCreated + ) + VALUES(?, + ?,?,?,?,?,?,?,?,NOW() + )"; + $qry = $this->db->query($sql, [ + $number, + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $userid + ]); + if (!$qry) { + $this->sys_error_db("Error Insert Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success tambah data"); + } + function updateTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + $startDate = $prm['startDate']; + $id = $prm['id']; + $endDate = $prm['endDate']; + $tenor = $prm['tenor']; + $prePaid = $prm['prePaid']; + $kredit = $prm['kredit']; + $debet = $prm['debet']; + $bulanan = $prm['bulanan']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateStartDate = ?, + T_RecrusiveJurnalTemplateEndDate = ?, + T_RecrusiveJurnalTemplateTenor = ?, + T_RecrusiveJurnalTemplatePrePaid = ?, + T_RecrusiveJurnalTemplateCreditCoaID = ?, + T_RecrusiveJurnalTemplateDebetCoaID = ?, + T_RecrusiveJurnalTemplateMonthly = ?, + T_RecrusiveJurnalTemplateLastUpdatedUserID = '{$userid}', + T_RecrusiveJurnalTemplateLastUpdated = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $startDate, + $endDate, + $tenor, + $prePaid, + $kredit, + $debet, + $bulanan, + $id + ]); + if (!$qry) { + $this->sys_error_db("Error Update Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success update data"); + } + function deleteTemplate() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + + $id = $prm['id']; + + $sql = "UPDATE t_recrusivejurnaltemplate SET + T_RecrusiveJurnalTemplateIsActive = 'N', + T_RecrusiveJurnalTemplateDeletedUserID = '{$userid}', + T_RecrusiveJurnalTemplateDeleted = NOW() + WHERE T_RecrusiveJurnalTemplateID = ?"; + $qry = $this->db->query($sql, [ + $id + ]); + if (!$qry) { + $this->sys_error_db("Error delete Recrusive Jurnal Template", $this->db); + exit; + } + $this->sys_ok("Success delete data"); + } + function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + + $ROW_PER_PAGE = 5; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sql = "SELECT + COUNT(T_RecrusiveJurnalTemplateID) as total + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + "; + $qry = $this->db->query($sql, [ + $search, + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $total = $qry->row_array()['total']; + $sql = "SELECT + T_RecrusiveJurnalTemplateID as id, + c.coaID as creditCoaID, + CONCAT(c.coaAccountNo, '-' ,c.coaDescription) as creditName, + d.coaID as debitCoaID, + CONCAT(d.coaAccountNo, '-' ,d.coaDescription) as debitName, + T_RecrusiveJurnalTemplateNumber as number, + T_RecrusiveJurnalTemplatePrePaid as prePaid, + DATE_FORMAT(T_RecrusiveJurnalTemplateStartDate , '%d-%m-%Y') as startDate, + T_RecrusiveJurnalTemplateStartDate as startDateVal, + DATE_FORMAT(T_RecrusiveJurnalTemplateEndDate, '%d-%m-%Y') as endDate, + T_RecrusiveJurnalTemplateEndDate as endDateVal, + T_RecrusiveJurnalTemplateTenor as tenor, + T_RecrusiveJurnalTemplateMonthly as bulanan + FROM t_recrusivejurnaltemplate + JOIN coa c + ON T_RecrusiveJurnalTemplateCreditCoaID = c.coaID + JOIN coa d + ON T_RecrusiveJurnalTemplateDebetCoaID = d.coaID + WHERE T_RecrusiveJurnalTemplateNumber LIKE ? + AND T_RecrusiveJurnalTemplateIsActive = 'Y' + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $search, + $ROW_PER_PAGE, + $start_offset + ]); + if (!$qry) { + $this->sys_error_db("Error search", $this->db); + exit; + } + $rst = array( + "total" => ceil($total / $ROW_PER_PAGE), + "records" => $qry->result_array() + ); + $this->sys_ok($rst); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Reverse.php b/application/controllers/mockup/masterdata/accounting/Reverse.php new file mode 100644 index 0000000..71ed3f9 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Reverse.php @@ -0,0 +1,333 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search = ""; + $number_limit = 10; + $tot_count = 0; + + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $sql = "SELECT + periodeID AS id, + periodeYear, + periodeMonth, + CONCAT(periodeYear, ' - ',periodeMonth) as yearandmonth, + periodeName, + CONCAT(DATE_FORMAT(periodeStartDate, '%d %M %Y'), ' - ', DATE_FORMAT(periodeEndDate, '%d %M %Y')) as periode + FROM periode + WHERE periodeIsActive = 'Y' + AND periodeIsClosed = 'N' + ORDER BY periodeMonth DESC + "; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("select period", $this->db); + exit; + } + $rst = $qry->result_array(); + $this->sys_ok($rst); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function search() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $periodeid = $prm["periodeid"]; + $journalno = $prm["journalno"]; + // $prm['current_page'] = isset($prm['current_page']) ? $prm['current_page'] : 1; + + if (intval($periodeid) == 0) { + $this->sys_error("Periode belum dipilih, silahkan dipilih dulu."); + $this->db->trans_rollback(); + exit; + } + + $sql_where = "WHERE jurnalIsActive = 'Y'"; + $sql_param = array(); + if ($periodeid != "") { + if ($sql_where != "") { + $sql_where .= " AND "; + } + $sql_where .= " jurnalperiodeID = ?"; + $sql_param[] = $periodeid; + } + if ($journalno != "") { + if ($sql_where != "") { + $sql_where .= " AND "; + } + $sql_where .= " jurnalNo LIKE ? "; + $sql_param[] = "%$journalno%"; + } + + $sql = "SELECT + jurnalID, + jurnalM_BranchCode, + jurnalNo, + jurnalTitle, + DATE_FORMAT(jurnalDate, '%d-%m-%Y') as jurnalDate, + jurnalType, + jurnalTxID, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + periodeID, + periodeYear, + periodeMonth, + periodeName, + periodeStartDate, + periodeEndDate, + periodeIsClosed, + CASE + WHEN jurnalTxDebit <> 0 AND jurnalTxCredit = 0 THEN jurnalTxDebit + WHEN jurnalTxCredit <> 0 AND jurnalTxDebit = 0 THEN jurnalTxCredit + WHEN jurnalTxCredit = 0 AND jurnalTxDebit = 0 THEN jurnalTxDebit + ELSE jurnalTxDebit + END as value, + CASE + WHEN jurnalTxDebit <> 0 AND jurnalTxCredit = 0 THEN 'DB' + WHEN jurnalTxCredit <> 0 AND jurnalTxDebit = 0 THEN 'CR' + WHEN jurnalTxCredit = 0 AND jurnalTxDebit = 0 THEN 'DB' + ELSE 'ERROR' + END as type, + jurnalArID, + jurnalArJurnalTxID, + jurnalArM_CompanyID, + jurnalArRefNo, + jurnalArM_CompanyCode, + jurnalArM_CompanyName + FROM jurnal + JOIN jurnal_tx ON jurnalID = jurnalTxJurnalID + AND jurnalTxIsActive = 'Y' + LEFT JOIN jurnal_ar ON jurnalTxID = jurnalArJurnalTxID + AND jurnalArIsActive = 'Y' + JOIN coa ON jurnalTxCoaID = coaID + AND coaIsActive = 'Y' + JOIN periode ON jurnalperiodeID = periodeID + AND periodeIsActive = 'Y' + $sql_where"; + $qry = $this->db->query($sql, $sql_param); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("select jurnal error", $this->db); + exit; + } + + // $sql_count = "SELECT + // jurnalID, + // IFNULL(SUM(jurnalTxDebit),0) as debit, + // IFNULL(SUM(jurnalTxCredit),0) as credit + // FROM jurnal + // JOIN jurnal_tx ON jurnalID = jurnalTxJurnalID + // AND jurnalTxIsActive = 'Y' + // LEFT JOIN jurnal_ar ON jurnalTxID = jurnalArJurnalTxID + // AND jurnalArIsActive = 'Y' + // JOIN coa ON jurnalTxCoaID = coaID + // AND coaIsActive = 'Y' + // JOIN periode ON jurnalperiodeID = periodeID + // AND periodeIsActive = 'Y' + // $sql_where"; + // $qry_count = $this->db->query($sql_count, $sql_param); + // if ($qry_count) { + // $sumtotal = $qry_count->row_array(); + // } else { + // $this->sys_error_db("select sum jurnal error", $this->db); + // exit; + // } + // $totalDebit = $sumtotal['debit']; + // $totalCredit = $sumtotal['credit']; + // $totalBalance = 0; + + + // $totalBalance = $totalDebit - $totalCredit; + // $arrTotal = array('debit' => $totalDebit, 'credit' => $totalCredit, 'balance' => $totalBalance); + + + // $jurnalNumbers = []; + // $description = []; + // if ($rows) { + // $coaAccountNoCheck = ""; + + // foreach ($rows as $key => $value) { + + // if ($journalno != "") { + + // if (!in_array($value['jurnalNo'], $jurnalNumbers)) { + // $jurnalNumbers[] = $value['jurnalNo']; + // } + + // if ($coaAccountNoCheck != $value['coaAccountNo']) { + // $description[] = $value['junalTxDescription']; + // $coaAccountNoCheck = $value['coaAccountNo']; + // } + // } + // } + // } + + // $selectjournal = array('jurnalnumber' => $jurnalNumbers, 'description' => $description); + + $result = array("records" => $rows, "sql" => $this->db->last_query()); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function numbering($jurnalno) + { + $numbers = 'R' . '-' . $jurnalno; + return $numbers; + } + + function savereverse() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $reverse = $prm['reversejournal']; + // print_r($reverse[0]); + // exit; + + $sqlj = "INSERT INTO jurnal( + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDate, + jurnalType, + jurnalM_UserID) + SELECT + jurnalM_BranchCode, + jurnalperiodeID, + '{$reverse[0]['jurnalNo']}', + '{$reverse[0]['jurnalTitle']}', + NOW(), + jurnalType, + {$userid} + FROM jurnal + WHERE jurnalID = {$reverse[0]['jurnalID']}"; + $qryj = $this->db->query($sqlj); + if (!$qryj) { + $this->sys_error_db("Insert jurnal", $this->db); + $this->db->trans_rollback(); + exit; + } + + $insertedID = $this->db->insert_id(); + + foreach ($reverse as $k => $v) { + // print_r($v[0]); + // exit; + + $sql_tx = "INSERT INTO jurnal_tx( + jurnalTxJurnalID, + jurnalTxCoaID, + junalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxCreated, + jurnalTxM_UserID) VALUES(?,?,?,?,?,NOW(),?)"; + $qry_tx = $this->db->query($sql_tx, [ + $insertedID, + $v['jurnalTxCoaID'], + $v['junalTxDescription'], + $v['jurnalTxDebit'], + $v['jurnalTxCredit'], + $userid + ]); + if (!$qry_tx) { + $this->sys_error_db("Insert jurnal tx", $this->db); + $this->db->trans_rollback(); + exit; + } + $insertedtxID = $this->db->insert_id(); + + if ($v['jurnalType'] == 'AR') { + $sql_ar = "INSERT INTO jurnal_ar( + jurnalArJurnalTxID, + jurnalArM_CompanyID, + jurnalArRefNo, + jurnalArM_CompanyCode, + jurnalArM_CompanyName, + jurnalArCreated, + jurnalArM_UserID + ) VALUES(?,?,?,?,?,NOW(),?)"; + $qry_ar = $this->db->query($sql_ar, [ + $insertedtxID, + $v['jurnalArM_CompanyID'], + $v['jurnalArRefNo'], + $v['jurnalArM_CompanyCode'], + $v['jurnalArM_CompanyName'], + $userid + ]); + if (!$qry_ar) { + $this->sys_error_db("Insert jurnal ar", $this->db); + $this->db->trans_rollback(); + exit; + } + } + } + + $this->db->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Supplier.php b/application/controllers/mockup/masterdata/accounting/Supplier.php new file mode 100644 index 0000000..fb0939f --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Supplier.php @@ -0,0 +1,1003 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_count = "SELECT count(*) as total + FROM supplier + WHERE SupplierIsActive = 'Y' + AND (SupplierCode LIKE ? OR SupplierName LIKE ?)"; + $qry_count = $this->db->query($sql_count, [$search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier count error", $this->db); + exit; + } + + $sql = "SELECT SupplierID, + SupplierCode, + SupplierName, + SupplierTermOfPayment, + SupplierIsPpn, + SupplierIsPph, + SupplierPpnPct, + SupplierPphPct, + SupplierAddress, + SupplierPhone, + SupplierAdminName as SupplierPIC, + SupplierAdminEmail as SupplierPICEmail, + SupplierAdminPhone as SupplierPICPhone, + SupplierAdminHp as SupplierPICHp + FROM supplier + WHERE SupplierIsActive = 'Y' + AND (SupplierCode LIKE ? OR SupplierName LIKE ?) + ORDER BY SupplierID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier list error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchdetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + // Get supplier ID from parameters + if (!isset($prm['supplier_id'])) { + $this->sys_error("Supplier ID is required"); + exit; + } + $supplier_id = $prm['supplier_id']; + + // Handle search parameter + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + // Pagination setup + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + // Count total records + $sql_count = "SELECT COUNT(*) as total + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceIsActive = 'Y' + AND sp.SupplierPriceSupplierID = ? + AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?)"; + + $qry_count = $this->db->query($sql_count, [$supplier_id, $search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price count error", $this->db); + exit; + } + + // Get detailed records + $sql = "SELECT + sp.SupplierPriceID, + sp.SupplierPriceSupplierID, + mi.M_ItemID, + mi.M_ItemCode, + mi.M_ItemDesc, + iu.ItemUnitID, + iu.ItemUnitCode, + iu.ItemUnitName, + sp.SupplierPricePrice, + sp.SupplierPriceCreated, + sp.SupplierPriceLastUpdated, + sp.SupplierPriceMinQty, + sp.SupplierPriceMinInclusive, + sp.SupplierPriceMaxQty, + sp.SupplierPriceMaxInclusive, + sp.SupplierPriceFlagQty + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceIsActive = 'Y' + AND sp.SupplierPriceSupplierID = ? + AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?) + ORDER BY sp.SupplierPriceID DESC + LIMIT ? OFFSET ?"; + + $qry = $this->db->query($sql, [$supplier_id, $search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price list error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") { + $this->sys_error("Supplier name is required"); + exit; + } + + $nameSupplier = ""; + if (isset($prm['nameSupplier'])) { + $nameSupplier = trim($prm['nameSupplier']); + } + // $isPpn = ""; + // if (isset($prm['isPpn'])) { + // $isPpn = trim($prm['isPpn']); + // } + // $isPph = ""; + // if (isset($prm['isPph'])) { + // $isPph = trim($prm['isPph']); + // } + // $PpnPercent = ""; + // if (isset($prm['PpnPercent'])) { + // $PpnPercent = trim($prm['PpnPercent']); + // } + // $PphPercent = ""; + // if (isset($prm['PphPercent'])) { + // $PphPercent = trim($prm['PphPercent']); + // } + $SupplierAddress = ""; + if (isset($prm['SupplierAddress'])) { + $SupplierAddress = trim($prm['SupplierAddress']); + } + $SupplierPhone = ""; + if (isset($prm['SupplierPhone'])) { + $SupplierPhone = trim($prm['SupplierPhone']); + } + $SupplierPIC = ""; + if (isset($prm['SupplierPIC'])) { + $SupplierPIC = trim($prm['SupplierPIC']); + } + $SupplierPICEmail = ""; + if (isset($prm['SupplierPICEmail'])) { + $SupplierPICEmail = trim($prm['SupplierPICEmail']); + } + $SupplierPICPhone = ""; + if (isset($prm['SupplierPICPhone'])) { + $SupplierPICPhone = trim($prm['SupplierPICPhone']); + } + $SupplierPICHp = ""; + if (isset($prm['SupplierPICHp'])) { + $SupplierPICHp = trim($prm['SupplierPICHp']); + } + + $suppliertop = 0; + if (isset($prm['SupplierTOP'])) { + $suppliertop = intval($prm['SupplierTOP']); + } + + $codeSql = "SELECT `fn_numbering`('S') as codeSp"; + $exec = $this->db->query($codeSql, []); + $codeSupplier = ""; + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("generate code error", $this->db); + exit; + } else { + $codeSupplier = $exec->result_array()[0]["codeSp"]; + } + + // Check for existing supplier with same name + $sql_check = "SELECT COUNT(*) as total FROM supplier + WHERE SupplierName = ? AND SupplierIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$nameSupplier]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama supplier sudah ada"); + exit; + } + + $sql = "INSERT INTO supplier( + SupplierCode, + SupplierName, + -- SupplierIsPpn, + -- SupplierIsPph, + -- SupplierPpnPct, + -- SupplierPphPct, + SupplierTermOfPayment, + SupplierAddress, + SupplierPhone, + SupplierAdminName, + SupplierAdminEmail, + SupplierAdminPhone, + SupplierAdminHp, + SupplierIsActive, + SupplierCreatedUserID, + SupplierCreated + ) VALUES(?,?,?,?,?,?,?,?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $codeSupplier, + $nameSupplier, + $suppliertop, + $SupplierAddress, + $SupplierPhone, + $SupplierPIC, + $SupplierPICEmail, + $SupplierPICPhone, + $SupplierPICHp, + // $isPpn, + // $isPph, + // $PpnPercent, + // $PphPercent, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM supplier WHERE SupplierCode = '{$codeSupplier}' AND SupplierIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function update() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") { + $this->sys_error("Supplier name is required"); + exit; + } + + $nameSupplier = ""; + if (isset($prm['nameSupplier'])) { + $nameSupplier = trim($prm['nameSupplier']); + } + $SupplierAddress = ""; + if (isset($prm['SupplierAddress'])) { + $SupplierAddress = trim($prm['SupplierAddress']); + } + + $suppliertop = 0; + if (isset($prm['SupplierAddress'])) { + $suppliertop = intval($prm['SupplierTOP']); + } + + $SupplierPhone = ""; + if (isset($prm['SupplierPhone'])) { + $SupplierPhone = trim($prm['SupplierPhone']); + } + $SupplierPIC = ""; + if (isset($prm['SupplierPIC'])) { + $SupplierPIC = trim($prm['SupplierPIC']); + } + $SupplierPICEmail = ""; + if (isset($prm['SupplierPICEmail'])) { + $SupplierPICEmail = trim($prm['SupplierPICEmail']); + } + $SupplierPICPhone = ""; + if (isset($prm['SupplierPICPhone'])) { + $SupplierPICPhone = trim($prm['SupplierPICPhone']); + } + $SupplierPICHp = ""; + if (isset($prm['SupplierPICHp'])) { + $SupplierPICHp = trim($prm['SupplierPICHp']); + } + // $isPpn = ""; + // if (isset($prm['isPpn'])) { + // $isPpn = trim($prm['isPpn']); + // } + // $isPph = ""; + // if (isset($prm['isPph'])) { + // $isPph = trim($prm['isPph']); + // } + // $PpnPercent = ""; + // if (isset($prm['PpnPercent'])) { + // $PpnPercent = trim($prm['PpnPercent']); + // } + // $PphPercent = ""; + // if (isset($prm['PphPercent'])) { + // $PphPercent = trim($prm['PphPercent']); + // } + $supplier_id = ""; + if (isset($prm['supplier_id'])) { + $supplier_id = trim($prm['supplier_id']); + } + + $sql = "UPDATE supplier SET + SupplierName = ?, + SupplierAddress = ?, + SupplierTermOfPayment = ?, + SupplierPhone = ?, + SupplierAdminName = ?, + SupplierAdminEmail = ?, + SupplierAdminPhone = ?, + SupplierAdminHp = ?, + SupplierLastUpdatedUserID = ?, + SupplierLastUpdated = NOW() + WHERE SupplierID = ?"; + $qry = $this->db->query($sql, [ + $nameSupplier, + $SupplierAddress, + $suppliertop, + $SupplierPhone, + $SupplierPIC, + $SupplierPICEmail, + $SupplierPICPhone, + $SupplierPICHp, + $userId, + $supplier_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier update error" . $this->db->last_query(), $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM supplier WHERE SupplierID = {$supplier_id} AND SupplierIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletesupplier() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $supplier_id = ""; + if (isset($prm['supplier_id'])) { + $supplier_id = trim($prm['supplier_id']); + } + + $sql = "UPDATE supplier SET + SupplierIsActive = 'N', + SupplierDeletedUserID = ?, + SupplierDeleted = NOW() + WHERE SupplierID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $supplier_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier update error", $this->db); + exit; + } + + $sql_price = "UPDATE supplier_price SET + SupplierPriceIsActive = 'N', + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceSupplierID = ?"; + $qry_price = $this->db->query($sql_price, [ + $userId, + $supplier_id + ]); + + if (!$qry_price) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price update error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $this->sys_ok(array( + "total" => 1, + "records" => array("xId" => $prm["supplier_id"]) + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchItem() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $payload = $this->sys_input; + + $search = ""; + if (isset($payload["search"])) { + $search = trim($payload["search"]); + if ($search != "") { + $search = "%" . $payload["search"] . "%"; + } else { + $search = "%%"; + } + } + + $number_limit = 10; + $sql = "SELECT + M_ItemID, + M_ItemCode, + IF(M_ItemDesc = '', '-', M_ItemDesc) AS M_ItemDesc + FROM m_item + WHERE (M_ItemCode LIKE ? OR M_ItemDesc LIKE ?) + ORDER BY M_ItemDesc ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($search, $search, $number_limit)); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select item error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUnit() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $itemID = $prm["itemID"]; + + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitIsActive, + ItemUnitUserID + FROM itemunit + JOIN itemunitmap ON ItemUnitMapItemUnitID = ItemUnitID + AND ItemUnitMapM_ItemID = {$itemID} + AND ItemUnitMapIsActive = 'Y' + AND ItemUnitMapIsPurchase = 'Y' + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE '%$search%' + ORDER BY ItemUnitName ASC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("item unit list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + $supplierMinInclusive = 'Y'; + $supplierMinQty = 0; + $supplierMaxInclusive = 'Y'; + $supplierMaxQty = 0; + + $type = $prm['type']; + + if ($type == "R") { + if (intval($prm['min_value']) == 0 || intval($prm['max_value']) == 0) { + $this->sys_error("Qty rentang harus diisi"); + exit; + } + + $supplierMinInclusive = $prm['min_inclusive'] == true ? 'Y' : 'N'; + $supplierMinQty = $prm['min_value']; + $supplierMaxInclusive = $prm['max_inclusive'] == true ? 'Y' : 'N'; + $supplierMaxQty = $prm['max_value']; + } + + // Ambil semua data aktif untuk kombinasi supplier + item + unit + $sql_check = "SELECT SupplierPriceFlagQty, SupplierPriceMinQty, SupplierPriceMaxQty + FROM supplier_price + WHERE SupplierPriceSupplierID = ? + AND SupplierPriceM_ItemID = ? + AND SupplierPriceItemUnitID = ? + AND SupplierPriceIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id]); + if (!$qry_check) { + $this->sys_error_db("Gagal select supplier price", $this->db); + exit; + } + $rows = $qry_check->result_array(); + + // Cek tipe existing + $hasTakTerhingga = false; + $hasRentang = false; + + foreach ($rows as $r) { + if ($r['SupplierPriceFlagQty'] == 'T') $hasTakTerhingga = true; + if ($r['SupplierPriceFlagQty'] == 'R') $hasRentang = true; + } + + // --- VALIDASI FLAG T --- + if ($type == 'T' && ($hasTakTerhingga || $hasRentang)) { + $this->sys_error("Tidak bisa menambahkan tipe TAK TERHINGGA. Sudah ada data RENTANG atau TAK TERHINGGA untuk item dan unit ini."); + exit; + } + + if ($type == 'R' && $hasTakTerhingga) { + $this->sys_error("Tidak bisa menambahkan tipe RENTANG. Sudah ada data TAK TERHINGGA untuk item dan unit ini."); + exit; + } + + // --- VALIDASI RENTANG (OVERLAP) --- + if ($type == 'R') { + $minQty = (int) $prm['min_value']; // ambil dari input user + $maxQty = (int) $prm['max_value']; + + if ($maxQty <= $minQty) { + $this->sys_error("Max Qty harus lebih besar dari Min Qty."); + exit; + } + + foreach ($rows as $r) { + if ($r['SupplierPriceFlagQty'] == 'R') { + $existMin = (int) $r['SupplierPriceMinQty']; + $existMax = (int) $r['SupplierPriceMaxQty']; + + // Cek overlap (tumpang tindih) + if ( + ($minQty >= $existMin && $minQty <= $existMax) || // min masuk rentang lama + ($maxQty >= $existMin && $maxQty <= $existMax) || // max masuk rentang lama + ($minQty <= $existMin && $maxQty >= $existMax) // mencakup seluruh rentang lama + ) { + $this->sys_error("Rentang Qty " . $minQty . " - " . $maxQty . " tumpang tindih dengan rentang yang sudah ada (" . $existMin . "-" . $existMax . ")."); + exit; + } + } + } + } + + // Jika lolos semua validasi, lanjut INSERT + $sql = "INSERT INTO supplier_price( + SupplierPriceSupplierID, + SupplierPriceM_ItemID, + SupplierPriceItemUnitID, + SupplierPricePrice, + SupplierPriceMinQty, + SupplierPriceMinInclusive, + SupplierPriceMaxQty, + SupplierPriceMaxInclusive, + SupplierPriceFlagQty, + SupplierPriceIsActive, + SupplierPriceUserID, + SupplierPriceCreated + ) VALUES(?,?,?,?,?,?,?,?,?,'Y',?,NOW())"; + + $qry = $this->db->query($sql, [ + $supplier_id, + $item_id, + $unit_id, + $price, + $supplierMinQty, + $supplierMinInclusive, + $supplierMaxQty, + $supplierMaxInclusive, + $type, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceID = LAST_INSERT_ID()"; + $records = $this->db->query($newInsert)->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function updateprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_price_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $supplier_price_id = trim($prm['supplier_price_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + $supplierMinInclusive = 'Y'; + $supplierMinQty = 0; + $supplierMaxInclusive = 'Y'; + $supplierMaxQty = 0; + + $type = $prm['type']; + + if ($type == "R") { + if (intval($prm['min_value']) == 0 || intval($prm['max_value']) == 0) { + $this->sys_error("Qty rentang harus diisi"); + exit; + } + + $supplierMinInclusive = $prm['min_inclusive'] == true ? 'Y' : 'N'; + $supplierMinQty = $prm['min_value']; + $supplierMaxInclusive = $prm['max_inclusive'] == true ? 'Y' : 'N'; + $supplierMaxQty = $prm['max_value']; + } + + // Check for existing supplier price with type flag qty + // $sql_check = "SELECT COUNT(*) as total + // FROM supplier_price + // WHERE SupplierPriceSupplierID = ? + // AND SupplierPriceM_ItemID = ? + // AND SupplierPriceItemUnitID = ? + // AND SupplierPriceIsActive = 'Y' + // AND SupplierPriceFlagQty = ? + // AND SupplierPriceID != ?"; + // $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id, $type, $supplier_price_id]); + // echo $this->db->last_query(); + // exit; + // if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + // $this->sys_error("Price for this item and unit already exists"); + // exit; + // } + + // Ambil semua data aktif untuk kombinasi supplier + item + unit + $sql_check = "SELECT SupplierPriceFlagQty, SupplierPriceMinQty, SupplierPriceMaxQty + FROM supplier_price + WHERE SupplierPriceSupplierID = ? + AND SupplierPriceM_ItemID = ? + AND SupplierPriceItemUnitID = ? + AND SupplierPriceIsActive = 'Y' + AND SupplierPriceID != ?"; + $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id, $supplier_price_id]); + if (!$qry_check) { + $this->sys_error_db("Gagal select supplier price", $this->db); + exit; + } + $rows = $qry_check->result_array(); + + // Cek tipe existing + $hasTakTerhingga = false; + $hasRentang = false; + + foreach ($rows as $r) { + if ($r['SupplierPriceFlagQty'] == 'T') $hasTakTerhingga = true; + if ($r['SupplierPriceFlagQty'] == 'R') $hasRentang = true; + } + + // --- VALIDASI FLAG T --- + if ($type == 'T' && ($hasTakTerhingga || $hasRentang)) { + $this->sys_error("Tidak bisa menambahkan tipe TAK TERHINGGA. Sudah ada data RENTANG atau TAK TERHINGGA untuk item dan unit ini."); + exit; + } + + if ($type == 'R' && $hasTakTerhingga) { + $this->sys_error("Tidak bisa menambahkan tipe RENTANG. Sudah ada data TAK TERHINGGA untuk item dan unit ini."); + exit; + } + + // --- VALIDASI RENTANG (OVERLAP) --- + if ($type == 'R') { + $minQty = (int) $prm['min_value']; // ambil dari input user + $maxQty = (int) $prm['max_value']; + + if ($maxQty <= $minQty) { + $this->sys_error("Max Qty harus lebih besar dari Min Qty."); + exit; + } + + foreach ($rows as $r) { + if ($r['SupplierPriceFlagQty'] == 'R') { + $existMin = (int) $r['SupplierPriceMinQty']; + $existMax = (int) $r['SupplierPriceMaxQty']; + + // Cek overlap (tumpang tindih) + if ( + ($minQty >= $existMin && $minQty <= $existMax) || // min masuk rentang lama + ($maxQty >= $existMin && $maxQty <= $existMax) || // max masuk rentang lama + ($minQty <= $existMin && $maxQty >= $existMax) // mencakup seluruh rentang lama + ) { + $this->sys_error("Rentang Qty " . $minQty . " - " . $maxQty . " tumpang tindih dengan rentang yang sudah ada (" . $existMin . "-" . $existMax . ")."); + exit; + } + } + } + } + + $sql = "UPDATE supplier_price SET + SupplierPriceM_ItemID = ?, + SupplierPriceItemUnitID = ?, + SupplierPricePrice = ?, + SupplierPriceMinQty = ?, + SupplierPriceMinInclusive = ?, + SupplierPriceMaxQty = ?, + SupplierPriceMaxInclusive = ?, + SupplierPriceFlagQty = ?, + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceID = ?"; + + $qry = $this->db->query($sql, [ + $item_id, + $unit_id, + $price, + $supplierMinQty, + $supplierMinInclusive, + $supplierMaxQty, + $supplierMaxInclusive, + $type, + $userId, + $supplier_price_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceID = {$supplier_price_id}"; + $records = $this->db->query($newInsert)->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_price_id'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $supplier_price_id = trim($prm['supplier_price_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + $sql = "UPDATE supplier_price SET + SupplierPriceIsActive = 'N', + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceID = ?"; + + $qry = $this->db->query($sql, [ + $userId, + $supplier_price_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok(array( + "total" => 1, + "qry" => $this->db->last_query() + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Supplier_bckp.php b/application/controllers/mockup/masterdata/accounting/Supplier_bckp.php new file mode 100644 index 0000000..77220b2 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Supplier_bckp.php @@ -0,0 +1,737 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + $sql_count = "SELECT count(*) as total + FROM supplier + WHERE SupplierIsActive = 'Y' + AND (SupplierCode LIKE ? OR SupplierName LIKE ?)"; + $qry_count = $this->db->query($sql_count, [$search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier count error", $this->db); + exit; + } + + $sql = "SELECT SupplierID, + SupplierCode, + SupplierName, + SupplierIsPpn, + SupplierIsPph, + SupplierPpnPct, + SupplierPphPct + FROM supplier + WHERE SupplierIsActive = 'Y' + AND (SupplierCode LIKE ? OR SupplierName LIKE ?) + ORDER BY SupplierID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier list error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchdetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + // Get supplier ID from parameters + if (!isset($prm['supplier_id'])) { + $this->sys_error("Supplier ID is required"); + exit; + } + $supplier_id = $prm['supplier_id']; + + // Handle search parameter + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + // Pagination setup + $number_limit = 20; + $number_offset = 0; + if ($prm['current_page'] > 0) { + $number_offset = ($prm['current_page'] - 1) * $number_limit; + } + + // Count total records + $sql_count = "SELECT COUNT(*) as total + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceIsActive = 'Y' + AND sp.SupplierPriceSupplierID = ? + AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?)"; + + $qry_count = $this->db->query($sql_count, [$supplier_id, $search, $search]); + $tot_count = 0; + $tot_page = 0; + if ($qry_count) { + $tot_count = $qry_count->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price count error", $this->db); + exit; + } + + // Get detailed records + $sql = "SELECT + sp.SupplierPriceID, + sp.SupplierPriceSupplierID, + mi.M_ItemID, + mi.M_ItemCode, + mi.M_ItemDesc, + iu.ItemUnitID, + iu.ItemUnitCode, + iu.ItemUnitName, + sp.SupplierPricePrice, + sp.SupplierPriceCreated, + sp.SupplierPriceLastUpdated + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + LEFT JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceIsActive = 'Y' + AND sp.SupplierPriceSupplierID = ? + AND (mi.M_ItemCode LIKE ? OR mi.M_ItemDesc LIKE ?) + ORDER BY sp.SupplierPriceID DESC + LIMIT ? OFFSET ?"; + + $qry = $this->db->query($sql, [$supplier_id, $search, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price list error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows, + "sql" => $this->db->last_query() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") { + $this->sys_error("Supplier name is required"); + exit; + } + + $nameSupplier = ""; + if (isset($prm['nameSupplier'])) { + $nameSupplier = trim($prm['nameSupplier']); + } + $isPpn = ""; + if (isset($prm['isPpn'])) { + $isPpn = trim($prm['isPpn']); + } + $isPph = ""; + if (isset($prm['isPph'])) { + $isPph = trim($prm['isPph']); + } + $PpnPercent = ""; + if (isset($prm['PpnPercent'])) { + $PpnPercent = trim($prm['PpnPercent']); + } + $PphPercent = ""; + if (isset($prm['PphPercent'])) { + $PphPercent = trim($prm['PphPercent']); + } + + $codeSql = "SELECT `fn_numbering`('S') as codeSp"; + $exec = $this->db->query($codeSql, []); + $codeSupplier = ""; + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("generate code error", $this->db); + exit; + } else { + $codeSupplier = $exec->result_array()[0]["codeSp"]; + } + + // Check for existing supplier with same name + $sql_check = "SELECT COUNT(*) as total FROM supplier + WHERE SupplierName = ? AND SupplierIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$nameSupplier]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Nama supplier sudah ada"); + exit; + } + + $sql = "INSERT INTO supplier( + SupplierCode, + SupplierName, + SupplierIsPpn, + SupplierIsPph, + SupplierPpnPct, + SupplierPphPct, + SupplierIsActive, + SupplierCreatedUserID, + SupplierCreated + ) VALUES(?,?,?,?,?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $codeSupplier, + $nameSupplier, + $isPpn, + $isPph, + $PpnPercent, + $PphPercent, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM supplier WHERE SupplierCode = '{$codeSupplier}' AND SupplierIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function update() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['nameSupplier']) || trim($prm['nameSupplier']) == "") { + $this->sys_error("Supplier name is required"); + exit; + } + + $nameSupplier = ""; + if (isset($prm['nameSupplier'])) { + $nameSupplier = trim($prm['nameSupplier']); + } + $isPpn = ""; + if (isset($prm['isPpn'])) { + $isPpn = trim($prm['isPpn']); + } + $isPph = ""; + if (isset($prm['isPph'])) { + $isPph = trim($prm['isPph']); + } + $PpnPercent = ""; + if (isset($prm['PpnPercent'])) { + $PpnPercent = trim($prm['PpnPercent']); + } + $PphPercent = ""; + if (isset($prm['PphPercent'])) { + $PphPercent = trim($prm['PphPercent']); + } + $supplier_id = ""; + if (isset($prm['supplier_id'])) { + $supplier_id = trim($prm['supplier_id']); + } + + $sql = "UPDATE supplier SET + SupplierName = ?, + SupplierIsPpn = ?, + SupplierIsPph = ?, + SupplierPpnPct = ?, + SupplierPphPct = ?, + SupplierLastUpdatedUserID = ?, + SupplierLastUpdated = NOW() + WHERE SupplierID = ?"; + $qry = $this->db->query($sql, [ + $nameSupplier, + $isPpn, + $isPph, + $PpnPercent, + $PphPercent, + $userId, + $supplier_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier update error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT * FROM supplier WHERE SupplierID = {$supplier_id} AND SupplierIsActive = 'Y'"; + $records = $this->db->query($newInsert, [])->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deletesupplier() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $supplier_id = ""; + if (isset($prm['supplier_id'])) { + $supplier_id = trim($prm['supplier_id']); + } + + $sql = "UPDATE supplier SET + SupplierIsActive = 'N', + SupplierDeletedUserID = ?, + SupplierDeleted = NOW() + WHERE SupplierID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $supplier_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier update error", $this->db); + exit; + } + + $sql_price = "UPDATE supplier_price SET + SupplierPriceIsActive = 'N', + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceSupplierID = ?"; + $qry_price = $this->db->query($sql_price, [ + $userId, + $supplier_id + ]); + + if (!$qry_price) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price update error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $this->sys_ok(array( + "total" => 1, + "records" => array("xId" => $prm["supplier_id"]) + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchItem() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $payload = $this->sys_input; + + $search = ""; + if (isset($payload["search"])) { + $search = trim($payload["search"]); + if ($search != "") { + $search = "%" . $payload["search"] . "%"; + } else { + $search = "%%"; + } + } + + $number_limit = 10; + $sql = "SELECT + M_ItemID, + M_ItemCode, + IF(M_ItemDesc = '', '-', M_ItemDesc) AS M_ItemDesc + FROM m_item + WHERE (M_ItemCode LIKE ? OR M_ItemDesc LIKE ?) + ORDER BY M_ItemDesc ASC + LIMIT ?"; + $qry = $this->db->query($sql, array($search, $search, $number_limit)); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select item error", $this->db); + exit; + } + + $result = array( + "records" => $rows, + "total_filter" => sizeof($rows) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUnit() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $itemID = $prm["itemID"]; + + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitIsActive, + ItemUnitUserID + FROM itemunit + JOIN itemunitmap ON ItemUnitMapItemUnitID = ItemUnitID + AND ItemUnitMapM_ItemID = {$itemID} + AND ItemUnitMapIsActive = 'Y' + AND ItemUnitMapIsPurchase = 'Y' + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE '%$search%' + ORDER BY ItemUnitName ASC"; + + $query = $this->db->query($sql); + + if (!$query) { + $this->sys_error_db("item unit list", $this->db); + exit; + } + + $rows = $query->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + // Check for existing supplier price with same item and unit + $sql_check = "SELECT COUNT(*) as total + FROM supplier_price + WHERE SupplierPriceSupplierID = ? + AND SupplierPriceM_ItemID = ? + AND SupplierPriceItemUnitID = ? + AND SupplierPriceIsActive = 'Y'"; + $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Price for this item and unit already exists"); + exit; + } + + $sql = "INSERT INTO supplier_price( + SupplierPriceSupplierID, + SupplierPriceM_ItemID, + SupplierPriceItemUnitID, + SupplierPricePrice, + SupplierPriceIsActive, + SupplierPriceUserID, + SupplierPriceCreated + ) VALUES(?,?,?,?,'Y',?,NOW())"; + + $qry = $this->db->query($sql, [ + $supplier_id, + $item_id, + $unit_id, + $price, + $userId + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceID = LAST_INSERT_ID()"; + $records = $this->db->query($newInsert)->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function updateprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_price_id']) || !isset($prm['item_id']) || !isset($prm['unit_id']) || !isset($prm['price'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $supplier_price_id = trim($prm['supplier_price_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + // Check for existing supplier price with same item and unit + $sql_check = "SELECT COUNT(*) as total + FROM supplier_price + WHERE SupplierPriceSupplierID = ? + AND SupplierPriceM_ItemID = ? + AND SupplierPriceItemUnitID = ? + AND SupplierPriceIsActive = 'Y' + AND SupplierPriceID != ?"; + $qry_check = $this->db->query($sql_check, [$supplier_id, $item_id, $unit_id, $supplier_price_id]); + + if ($qry_check && $qry_check->result_array()[0]['total'] > 0) { + $this->sys_error("Price for this item and unit already exists"); + exit; + } + + $sql = "UPDATE supplier_price SET + SupplierPriceM_ItemID = ?, + SupplierPriceItemUnitID = ?, + SupplierPricePrice = ?, + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceID = ?"; + + $qry = $this->db->query($sql, [ + $item_id, + $unit_id, + $price, + $userId, + $supplier_price_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price insert error", $this->db); + exit; + } + + $this->db->trans_commit(); + + $newInsert = "SELECT sp.*, mi.M_ItemCode, mi.M_ItemDesc, iu.ItemUnitCode, iu.ItemUnitName + FROM supplier_price sp + JOIN m_item mi ON sp.SupplierPriceM_ItemID = mi.M_ItemID + JOIN itemunit iu ON sp.SupplierPriceItemUnitID = iu.ItemUnitID + WHERE sp.SupplierPriceID = {$supplier_price_id}"; + $records = $this->db->query($newInsert)->result_array(); + + $this->sys_ok(array( + "total" => 1, + "records" => $records + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteprice() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Validate required parameters + if (!isset($prm['supplier_price_id'])) { + $this->sys_error("All fields are required"); + exit; + } + + $supplier_id = trim($prm['supplier_id']); + $supplier_price_id = trim($prm['supplier_price_id']); + $item_id = trim($prm['item_id']); + $unit_id = trim($prm['unit_id']); + $price = trim($prm['price']); + + $sql = "UPDATE supplier_price SET + SupplierPriceIsActive = 'N', + SupplierPriceUserID = ?, + SupplierPriceLastUpdated = NOW() + WHERE SupplierPriceID = ?"; + + $qry = $this->db->query($sql, [ + $userId, + $supplier_price_id + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("supplier price delete error", $this->db); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok(array( + "total" => 1, + "qry" => $this->db->last_query() + )); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Unitconvert.php b/application/controllers/mockup/masterdata/accounting/Unitconvert.php new file mode 100644 index 0000000..cede521 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/Unitconvert.php @@ -0,0 +1,526 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } else + + $prm = $this->sys_input; + + $search = ""; + if (isset($prm["search"])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = "%" . $prm["search"] . "%"; + } else { + $search = "%%"; + } + } + + $sortBy = $prm["sortBy"]; + $sortStatus = $prm["sortStatus"]; + if ($sortBy) { + $q_sort = "ORDER BY " . $sortBy . " " . $sortStatus; + } + + $number_offset = 0; + $number_limit = 10; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sql_filter = "SELECT COUNT(*) as total + FROM ( + SELECT DISTINCT + UnitConvertID AS id + FROM unitconvert + JOIN itemunit AS fromitemunit ON UnitConvertFromItemUnitID = fromitemunit.ItemUnitID + JOIN itemunit AS toitemunit ON UnitConvertToItemUnitID = toitemunit.ItemUnitID + WHERE + ( fromitemunit.ItemUnitName LIKE ? OR toitemunit.ItemUnitName LIKE ? ) AND UnitConvertIsActive = 'Y' + ) x"; + + $qry_filter = $this->db->query($sql_filter, [$search, $search]); + + $tot_count = 0; + $tot_page = 0; + if ($qry_filter) { + $tot_count = $qry_filter->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("itemunitconvert count error", $this->db); + exit; + } + + $sql = "SELECT DISTINCT + UnitConvertID AS id, + fromitemunit.ItemUnitID AS FromItemUnitID, + fromitemunit.ItemUnitName AS FromItemUnitName, + toitemunit.ItemUnitID AS ToItemUnitID, + toitemunit.ItemUnitName AS ToItemUnitName, + UnitConvertAmount AS Amount + FROM unitconvert + JOIN itemunit AS fromitemunit ON UnitConvertFromItemUnitID = fromitemunit.ItemUnitID + + JOIN itemunit AS toitemunit ON UnitConvertToItemUnitID = toitemunit.ItemUnitID + WHERE + ( fromitemunit.ItemUnitName LIKE ? OR toitemunit.ItemUnitName LIKE ? ) AND UnitConvertIsActive = 'Y' + $q_sort + LIMIT ? offset ?"; + + $qry = $this->db->query($sql, array($search, $search, $number_limit, $number_offset)); + //echo $this->db->last_query(); + // print_r($rows = $qry->result_array()); + if ($qry) { + $rows = $qry->result_array(); + } else { + //echo $this->db->last_query(); + $this->sys_error_db("Itemunitconvert select error", $this->db); + exit; + } + + $result = array( + "total_page" => $tot_page, + "total_filter" => $tot_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchitemx() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT DISTINCT ItemID as id_item, + ItemName as name_item + FROM item + JOIN itemunitmap ON ItemID = itemUnitMapItemID + WHERE ItemIsActive = 'Y'"; + + $query = $this->db->query($sql); + + $rows = $query->result_array(); + if (!$query) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"] + ); + $this->sys_error_db($error); + exit; + } + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // konversi awal + function fromitemunit() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $sql = "SELECT ItemUnitID as id, + ItemUnitName as name + FROM itemunit + WHERE + ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE CONCAT('%',?,'%')"; + + $qry = $this->db->query($sql, array($prm['search'])); + //echo $this->db->last_query(); + if (!$qry) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"] + ); + $this->sys_error_db($error); + exit; + } + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // konversi akhir + function toitemunit() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $id = ""; + + $sql = "SELECT ItemUnitID as id, + ItemUnitName as name + FROM itemunit + AND ItemUnitIsActive = 'Y'"; + + $qry = $this->db->query($sql, array($id)); + if (!$qry) { + $this->db->trans_rollback(); + $error = array( + "message" => $this->db->error()["message"] + ); + $this->sys_error_db($error); + exit; + } + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function save() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + // convert + $id_item = 0; + $id_fromitemunit = 0; + $id_toitemunit = 0; + $amount = 0; + + if (isset($prm['id_fromitemunit'])) { + $id_fromitemunit = trim($prm['id_fromitemunit']); + } + + if (isset($prm['id_toitemunit'])) { + $id_toitemunit = trim($prm['id_toitemunit']); + } + + if (isset($prm['amount'])) { + $amount = trim($prm['amount']); + } + + // sql insert + $sql = "INSERT INTO unitconvert( + UnitConvertFromItemUnitID, + UnitConvertToItemUnitID, + UnitConvertAmount, + UnitConvertCreated, + UnitConvertLAstUpdated, + UnitConvertUserID) + VALUES ( ?, ?, ?, NOW(), NOW(), ?)"; + + $qry = $this->db->query($sql, [ + $id_fromitemunit, + $id_toitemunit, + $amount, + $userid + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Itemunitconvert insert", $this->db); + exit; + } + + $insert_id = $this->db->insert_id(); + + $sql_json_before = "SELECT * + FROM unitconvert + WHERE UnitConvertIsActive = 'Y' + AND UnitConvertID = ?"; + + $qry_json_before = $this->db->query($sql_json_before, [ + $insert_id + ]); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunitconvert select json", $this->db); + exit; + } + + $data_by_id = $qry_json_before->row(); + + $json_after_log = json_encode($data_by_id); + + $sql_insert_log = "INSERT INTO acc_one_log.unitconvert_log( + UnitConvertLogStatus, + UnitConvertLogUnitConvertID, + UnitConvertLogJSONBefore, + UnitConvertLogJSONAfter, + UnitConvertLogUserID, + UnitConvertLogCreated + ) VALUES('ADD',?,NULL,?,?,NOW())"; + + $qry_insert_log = $this->db->query($sql_insert_log, [ + $insert_id, + $json_after_log, + $userid + ]); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log error", $this->db); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function edit() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $id = $prm["id"]; + + $sql_data = "UPDATE unitconvert + SET UnitConvertFromItemUnitID = ?, + UnitConvertToItemUnitID = ?, + UnitConvertAmount = ?, + UnitConvertLAstUpdated = NOW(), + UnitConvertUserID = ? + WHERE UnitConvertID = ?"; + + $qry_data = $this->db->query($sql_data, [ + $prm["id_fromitemunit"], + $prm["id_toitemunit"], + $prm["amount"], + $userid, + $id + ]); + + if (!$qry_data) { + $this->db->trans_rollback(); + $this->sys_error_db("Itemunitconvert update", $this->db); + exit; + } + + // json before + $sql_json_before = "SELECT * + FROM unitconvert + WHERE UnitConvertIsActive = 'Y' + AND UnitConvertID = ?"; + + $qry_json_before = $this->db->query($sql_json_before, [ + $id + ]); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunitconvert select json before, $this->db"); + exit; + } + + $data_before_by_id = $qry_json_before->row(); + + $json_before = json_encode($data_before_by_id); + + // json after + $sql_json_after = "SELECT * + FROM unitconvert + WHERE UnitConvertIsActive = 'Y' + AND UnitConvertID = ?"; + + $qry_json_after = $this->db->query($sql_json_after, [ + $id + ]); + + if (!$qry_json_after) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunitconvert select json after, $this->db"); + exit; + } + + $data_after_by_id = $qry_json_after->row(); + + $json_after = json_encode($data_after_by_id); + + $sql_insert_log = "INSERT INTO acc_one_log.unitconvert_log( + UnitConvertLogStatus, + UnitConvertLogUnitConvertID, + UnitConvertLogJSONBefore, + UnitConvertLogJSONAfter, + UnitConvertLogUserID, + UnitConvertLogCreated + ) VALUES('EDIT',?,?,?,?,NOW())"; + + $qry_insert_log = $this->db->query($sql_insert_log, [ + $id, + $json_before, + $json_after, + $userid + ]); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("update log error, $this->db"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function delete() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $id = $prm["id"]; + + $sql_data = "UPDATE unitconvert + SET UnitConvertIsActive = 'N', + UnitConvertLAstUpdated = NOW(), + UnitConvertUserID = ? + WHERE UnitConvertID = ?"; + + $qry_data = $this->db->query($sql_data, [ + $userid, + $id + ]); + + if (!$qry_data) { + $this->db->trans_commit(); + $this->sys_error_db("itemunitconvert delete", $this->db); + exit; + } + + // json before + $sql_json_before = "SELECT * + FROM unitconvert + WHERE UnitConvertID = ?"; + + $qry_json_before = $this->db->query($sql_json_before, [ + $id + ]); + + if (!$qry_json_before) { + $this->db->trans_rollback(); + $this->sys_error_db("itemunitconvert select json, $this->db"); + exit; + } + + $data_before_by_id = $qry_json_before->row(); + + $json_before = json_encode($data_before_by_id); + + $sql_insert_log = "INSERT INTO acc_one_log.unitconvert_log( + UnitConvertLogStatus, + UnitConvertLogUnitConvertID, + UnitConvertLogJSONBefore, + UnitConvertLogJSONAfter, + UnitConvertLogUserID, + UnitConvertLogCreated + ) VALUES('DELETE',?,NULL,?,?,NOW())"; + + $qry_insert_log = $this->db->query($sql_insert_log, [ + $id, + $json_before, + $userid + ]); + + if (!$qry_insert_log) { + $this->db->trans_rollback(); + $this->sys_error_db("delete log error, $this->db"); + exit; + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "records" => array("xid" => 0) + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/accounting/md-rochecklist/Rochecklist.php b/application/controllers/mockup/masterdata/accounting/md-rochecklist/Rochecklist.php new file mode 100644 index 0000000..48c3385 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/md-rochecklist/Rochecklist.php @@ -0,0 +1,680 @@ +isLogin) { + $this->sys_error("Invalid Token"); + } + $sql = "SELECT + itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get item category", $this->db); + exit; + } + // print_r($this->db->last_query()); + $data = $qry->result_array(); + $this->sys_ok($data); + } + public function getItemGroup() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $sql = "SELECT + Nat_GroupID, + Nat_GroupName + FROM nat_group + WHERE Nat_GroupIsActive = 'Y';"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get item group", $this->db); + exit; + } + // print_r($this->db->last_query()); + $group = $qry->result_array(); + $sql = "SELECT Nat_SubGroupID, + Nat_SubGroupNat_GroupID, + Nat_SubGroupName + FROM nat_subgroup + WHERE Nat_SubGroupIsActive = 'Y';"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error get item sub group", $this->db); + exit; + } + // print_r($this->db->last_query()); + $subgGroup = $qry->result_array(); + $this->sys_ok([ + 'group' => $group, + 'subGroup' => $subgGroup + ]); + } + public function search() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $search = '%' . $prm['search'] . '%'; + + $page = $prm["page"]; + $type = $prm["type"]; + + $ROW_PER_PAGE = 15; + $start_offset = 0; + // print_r($prm); + + if (isset($prm["page"])) { + if ( + is_numeric($prm["page"]) && $prm["page"] > 0 + ) { + $start_offset = ($page - 1) * $ROW_PER_PAGE; + } + } + $sqlType = ''; + if ($type == 'G') { + $sqlType = "AND RoChecklistType = 'G"; + } + if ($type == 'C') { + $sqlType = "AND RoChecklistType = 'C"; + } + if ($type == 'P') { + $sqlType = "AND RoChecklistType = 'P"; + } + + $sql = "SELECT COUNT(*) as total + FROM ro_checklist + WHERE RoChecklistIsActive = 'Y' + AND RoChecklistName LIKE ? + {$sqlType}"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("Error get total", $this->db); + exit; + } + // print_r($this->db->last_query()); + $total = $qry->row_array()['total']; + $sql = "SELECT * + FROM ro_checklist + WHERE RoChecklistIsActive = 'Y' + AND RoChecklistName LIKE ? + {$sqlType} + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$search, $ROW_PER_PAGE, $start_offset]); + if (!$qry) { + $this->sys_error_db("Error get total", $this->db); + exit; + } + // print_r($this->db->last_query()); + $rst = array( + "total" => ceil($total / $ROW_PER_PAGE), + "records" => $qry->result_array() + ); + $this->sys_ok($rst); + } + + public function add() + { + // $this->db->trans_commit(); + // $this->db->trans_rollback(); + $this->db->trans_begin(); + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $search = '%' . $prm['search'] . '%'; + $page = $prm["page"]; + $type = $prm["type"]; + $detail = $prm["detail"]; + + if (!in_array($type, ['G', 'C', 'P'])) { + $this->sys_error("Type tidak sesuai"); + exit; + } + + $sql = "INSERT INTO ro_checklist ( + RoChecklistName, + RoChecklistType, + RoChecklistTypeCreatedUserID + ) VALUES ( + ?, + ?, + ? + );"; + $qry = $this->db->query($sql, [$prm['name'], $type, $userId]); + if (!$qry) { + $this->sys_error_db("Error add ", $this->db); + print_r($this->db->last_query()); + $this->db->trans_rollback(); + exit; + } + $checklistID = $this->db->insert_id(); + if ($type == 'C') { + $sqlInsert = ''; + $arrCategory = []; + foreach ($detail as $key => $value) { + $sqlInsert = "{$sqlInsert} ({$checklistID}, {$value['itemCategoryID']}, {$userId})"; + if (($key + 1) != count($detail)) { + $sqlInsert = "{$sqlInsert},"; + } + + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapItemCategoryID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$checklistID, $value['itemCategoryID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + if (!empty($cek) || in_array($value['itemCategoryID'], $arrCategory)) { + $this->sys_error_db("{$value['itemCategoryName']} sudah pernah di pilih ", $this->db); + $this->db->trans_rollback(); + exit; + } + $arrCategory[] = $value['itemCategoryID']; + } + + $sql = "INSERT INTO ro_checklist_map ( + RoChecklistMapRoChecklistID, + RoChecklistMapItemCategoryID, + RoChecklistMapCreatedUserID + ) VALUES {$sqlInsert};"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error add detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + } + if ($type == 'P') { + $sqlInsert = ''; + $arrSubGroup = []; + foreach ($detail as $key => $value) { + + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapNat_GroupID = ? + AND RoChecklistMapNat_SubGroupID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$checklistID, $value['Nat_SubGroupNat_GroupID'], $value['Nat_SubGroupID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + // echo empty($cek); + // echo $value['Nat_SubGroupID']; + // echo "\n"; + // print_r($arrSubGroup); + // echo "\n"; + // echo in_array($value['Nat_SubGroupID'], $arrSubGroup); + if (!empty($cek) || in_array($value['Nat_SubGroupID'], $arrSubGroup)) { + $this->sys_error_db("{$value['Nat_SubGroupName']} sudah pernah di pilih", $this->db); + $this->db->trans_rollback(); + exit; + } + $arrSubGroup[] = $value['Nat_SubGroupID']; + $sqlInsert = "{$sqlInsert} ({$checklistID}, {$value['Nat_SubGroupNat_GroupID']}, {$value['Nat_SubGroupID']},{$userId})"; + if (($key + 1) != count($detail)) { + $sqlInsert = "{$sqlInsert},"; + } + } + $sql = "INSERT INTO ro_checklist_map ( + RoChecklistMapRoChecklistID, + RoChecklistMapNat_GroupID, + RoChecklistMapNat_SubGroupID, + RoChecklistMapCreatedUserID + ) VALUES {$sqlInsert};"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error add detail mapping product", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->db->trans_commit(); + $this->sys_ok('Success'); + } + + public function addItem() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + + $id = $prm["id"]; + $type = $prm["type"]; + $detail = $prm["detail"]; + if ($type == 'C') { + $sqlInsert = ''; + $arrCategory = []; + foreach ($detail as $key => $value) { + $sqlInsert = "{$sqlInsert} ({$id}, {$value['itemCategoryID']}, {$userId})"; + if (($key + 1) != count($detail)) { + $sqlInsert = "{$sqlInsert},"; + } + + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapItemCategoryID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$id, $value['itemCategoryID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + if (!empty($cek) || in_array($value['itemCategoryID'], $arrCategory)) { + $this->sys_error_db("{$value['itemCategoryName']} sudah pernah di pilih ", $this->db); + $this->db->trans_rollback(); + exit; + } + $arrCategory[] = $value['itemCategoryID']; + } + + $sql = "INSERT INTO ro_checklist_map ( + RoChecklistMapRoChecklistID, + RoChecklistMapItemCategoryID, + RoChecklistMapCreatedUserID + ) VALUES {$sqlInsert};"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error add detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + } + if ($type == 'P') { + $sqlInsert = ''; + $arrSubGroup = []; + foreach ($detail as $key => $value) { + + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapNat_GroupID = ? + AND RoChecklistMapNat_SubGroupID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$id, $value['Nat_SubGroupNat_GroupID'], $value['Nat_SubGroupID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + if (!empty($cek) || in_array($value['Nat_SubGroupID'], $arrSubGroup)) { + $this->sys_error_db("{$value['Nat_SubGroupName']} sudah pernah di pilih", $this->db); + $this->db->trans_rollback(); + exit; + } + $arrSubGroup[] = $value['Nat_SubGroupID']; + $sqlInsert = "{$sqlInsert} ({$id}, {$value['Nat_SubGroupNat_GroupID']}, {$value['Nat_SubGroupID']},{$userId})"; + if (($key + 1) != count($detail)) { + $sqlInsert = "{$sqlInsert},"; + } + } + $sql = "INSERT INTO ro_checklist_map ( + RoChecklistMapRoChecklistID, + RoChecklistMapNat_GroupID, + RoChecklistMapNat_SubGroupID, + RoChecklistMapCreatedUserID + ) VALUES {$sqlInsert};"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("Error add detail mapping product", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->sys_ok('Success'); + } + + public function getDetail() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + + $id = $prm["id"]; + $sql = "SELECT * + FROM ro_checklist + WHERE RoChecklistIsActive = 'Y' + AND RoChecklistID = ? + LIMIT 1"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get checklist", $this->db); + exit; + } + $data = $qry->row_array(); + $retval = []; + if ($data['RoChecklistType'] == 'C') { + $sql = "SELECT + RoChecklistMapID, + RoChecklistMapRoChecklistID, + RoChecklistMapItemCategoryID itemCategoryID, + itemCategoryName + FROM + ro_checklist_map + JOIN + ro_checklist + ON RoChecklistMapRoChecklistID = RoChecklistID + JOIN item_category + ON RoChecklistMapItemCategoryID = itemCategoryID + WHERE + RoChecklistMapRoChecklistID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get checklist detail category", $this->db); + exit; + } + $retval = $qry->result_array(); + } + if ($data['RoChecklistType'] == 'P') { + $sql = "SELECT + RoChecklistMapID, + RoChecklistMapRoChecklistID, + Nat_GroupID, + Nat_GroupName, + Nat_SubGroupID, + Nat_SubGroupName + FROM + ro_checklist_map + JOIN + ro_checklist + ON RoChecklistMapRoChecklistID = RoChecklistID + JOIN nat_group + ON RoChecklistMapNat_GroupID = Nat_GroupID + JOIN nat_subgroup + ON RoChecklistMapNat_SubGroupID= Nat_SubGroupID + WHERE + RoChecklistMapRoChecklistID = ? + AND RoChecklistMapIsActive = 'Y';"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get checklist detail category", $this->db); + exit; + } + $retval = $qry->result_array(); + } + $this->sys_ok($retval); + } + public function updateMapping() + { + $this->db->trans_begin(); + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $id = $prm["id"]; + $type = $prm["type"]; + $detail = $prm["detail"]; + + if (!in_array($type, ['G', 'C', 'P'])) { + $this->sys_error("Type tidak sesuai"); + exit; + } + if ($type == 'C') { + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapItemCategoryID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$id, $detail['itemCategoryID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + if (!empty($cek)) { + $this->sys_error_db("{$detail['itemCategoryName']} sudah pernah di pilih ", $this->db); + $this->db->trans_rollback(); + exit; + } + + $sql = "UPDATE ro_checklist_map SET + RoChecklistMapItemCategoryID = ?, + RoChecklistMapLastUpdatedUserID = ? + WHERE RoChecklistMapID = ? + "; + $qry = $this->db->query($sql, [$detail['itemCategoryID'], $userId, $detail['RoChecklistMapID']]); + if (!$qry) { + $this->sys_error_db("Error add detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + } + if ($type == 'P') { + $sqlCek = "SELECT * FROM ro_checklist_map + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapNat_GroupID = ? + AND RoChecklistMapNat_SubGroupID = ? + AND RoChecklistMapIsActive = 'Y'"; + $qry = $this->db->query($sqlCek, [$id, $detail['Nat_SubGroupNat_GroupID'], $detail['Nat_SubGroupID']]); + if (!$qry) { + $this->sys_error_db("Error cek detail mapping category", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + // echo $this->db->last_query(); + // print_r($cek); + // echo ($cek); + // exit; + if (!empty($cek)) { + $this->sys_error_db("{$detail['Nat_SubGroupName']} sudah pernah di pilih", $this->db); + $this->db->trans_rollback(); + exit; + } + + $sql = "UPDATE ro_checklist_map SET + RoChecklistMapNat_GroupID = ?, + RoChecklistMapNat_SubGroupID = ?, + RoChecklistMapLastUpdatedUserID = ? + WHERE RoChecklistMapID = ? + "; + $qry = $this->db->query($sql, [$detail['Nat_SubGroupNat_GroupID'], $detail['Nat_SubGroupID'], $userId, $detail['RoChecklistMapID']]); + if (!$qry) { + $this->sys_error_db("Error add detail mapping product", $this->db); + $this->db->trans_rollback(); + exit; + } + } + $this->db->trans_commit(); + $this->sys_ok('Success'); + } + public function updateName() + { + $this->db->trans_begin(); + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $id = $prm["id"]; + // $type = $prm["type"]; + $name = $prm["name"]; + + + $sqlCek = "UPDATE ro_checklist SET + RoChecklistName = ?, + RoChecklistTypeLastUpdatedUserID = ? + WHERE RoChecklistID = ?"; + $qry = $this->db->query($sqlCek, [$name, $userId, $id]); + if (!$qry) { + $this->sys_error_db("Error update name", $this->db); + $this->db->trans_rollback(); + exit; + } + + + $this->db->trans_commit(); + $this->sys_ok('Success'); + } + public function updateType() + { + $this->db->trans_begin(); + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $id = $prm["id"]; + // $type = $prm["type"]; + $type = $prm["type"]; + if (!in_array($type, ['G', 'C', 'P'])) { + $this->sys_error("Type tidak sesuai"); + exit; + } + + $sqlCek = "SELECT * FROM ro_checklist WHERE RoChecklistID = ?"; + $qry = $this->db->query($sqlCek, [$id]); + if (!$qry) { + $this->sys_error_db("Error cek", $this->db); + $this->db->trans_rollback(); + exit; + } + $cek = $qry->row_array(); + if ($cek['RoChecklistType'] == $type) { + $this->sys_error_db("tipe tidak berubah", $this->db); + $this->db->trans_rollback(); + exit; + } + + + + $sql = "UPDATE ro_checklist SET + RoChecklistType = ?, + RoChecklistTypeLastUpdatedUserID = ? + WHERE RoChecklistID = ?"; + $qry = $this->db->query($sql, [$type, $userId, $id]); + if (!$qry) { + $this->sys_error_db("Error update name", $this->db); + $this->db->trans_rollback(); + exit; + } + + $sql = "UPDATE ro_checklist_map SET + RoChecklistMapIsActive = 'N', + RoChecklistMapDeletedUserID = ?, + RoChecklistMapDeleted = NOW() + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapIsActive = 'Y' + + "; + $qry = $this->db->query($sql, [$userId, $id]); + if (!$qry) { + $this->sys_error_db("Error detail detail mapping", $this->db); + $this->db->trans_rollback(); + exit; + } + + + $this->db->trans_commit(); + $this->sys_ok('Success'); + } + public function delete() + { + $this->db->trans_begin(); + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $id = $prm["id"]; + // $type = $prm["type"]; + + + + $sqlCek = "UPDATE ro_checklist SET + RoChecklistIsActive = 'N', + RoChecklistTypeDeleted = NOW(), + RoChecklistTypeDeletedUserID = ? + WHERE RoChecklistID = ?"; + $qry = $this->db->query($sqlCek, [$userId, $id]); + if (!$qry) { + $this->sys_error_db("Error update name", $this->db); + $this->db->trans_rollback(); + exit; + } + + $sql = "UPDATE ro_checklist_map SET + RoChecklistMapIsActive = 'N', + RoChecklistMapDeletedUserID = ?, + RoChecklistMapDeleted = NOW() + WHERE RoChecklistMapRoChecklistID = ? + AND RoChecklistMapIsActive = 'Y' + + "; + $qry = $this->db->query($sql, [$userId, $id]); + if (!$qry) { + $this->sys_error_db("Error detail detail mapping", $this->db); + $this->db->trans_rollback(); + exit; + } + + + $this->db->trans_commit(); + $this->sys_ok('Success'); + } + public function deleteItem() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $prm = $this->sys_input; + $user = $this->sys_user; + $userId = $this->sys_user["M_UserID"]; + $id = $prm["id"]; + $sql = "UPDATE ro_checklist_map SET + RoChecklistMapIsActive = 'N', + RoChecklistMapDeletedUserID = ?, + RoChecklistMapDeleted = NOW() + WHERE RoChecklistMapID = ? + + "; + $qry = $this->db->query($sql, [$userId, $id]); + if (!$qry) { + $this->sys_error_db("Error detail detail mapping", $this->db); + $this->db->trans_rollback(); + exit; + } + $this->sys_ok('Success'); + } +} diff --git a/application/controllers/mockup/masterdata/accounting/mediajurnalauto.http b/application/controllers/mockup/masterdata/accounting/mediajurnalauto.http new file mode 100644 index 0000000..7d784f6 --- /dev/null +++ b/application/controllers/mockup/masterdata/accounting/mediajurnalauto.http @@ -0,0 +1,127 @@ +@token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJNX1VzZXJJRCI6IjM0NSIsIk1fVXNlclVzZXJuYW1lIjoiY29iYWJyYW5jaCIsIk1fVXNlckdyb3VwRGFzaGJvYXJkIjoib25lLXVpXC90ZXN0XC92dWV4XC9hY2Mtb25lLW1kLWNvYVwvIiwiTV9Vc2VyRGVmYXVsdFRfU2FtcGxlU3RhdGlvbklEIjoiMCIsIk1fU3RhZmZOYW1lIjoiQURNSU4iLCJpc19jb3VyaWVyIjoiTiIsInRpbWVfYXV0b2xvZ291dCI6IjEyMCIsIk1fVXNlckxvY2F0aW9uSUQiOiIyIiwiTV9Vc2VyTG9jYXRpb25GbGFnIjoiQiIsIlNfUmVnaW9uYWxOYW1lIjoiU3VyYWJheWEgUmF5YSIsIlNfUmVnaW9uYWxJRCI6IjYiLCJNX0JyYW5jaE5hbWUiOiJQcmFtaXRhIE5nYWdlbCBKYXlhIiwiTV9CcmFuY2hJRCI6IjEzIiwibG9naW5MZXZlbCI6ImJyYW5jaCIsIk1fQnJhbmNoQ29tcGFueUlEIjoiMSIsIk1fQnJhbmNoQ29tcGFueU5hbWUiOiJQVCBQUkFNSVRBIiwiaXAiOiIxNDkuMTEzLjExOS4yNDYiLCJhZ2VudCI6Ik1vemlsbGFcLzUuMCAoV2luZG93cyBOVCAxMC4wOyBXaW42NDsgeDY0KSBBcHBsZVdlYktpdFwvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lXC8xMzEuMC4wLjAgU2FmYXJpXC81MzcuMzYgRWRnXC8xMzEuMC4wLjAiLCJ2ZXJzaW9uIjoidjIiLCJsYXN0LWxvZ2luIjoiMjAyNS0wMS0wOCAxODowOTozNSIsIk1fU2F0ZWxsaXRlSUQiOjB9.0D4KFzCL2VY3R_vM9b6o2wupRu-KjATCRVUL7S89wtc" + +@host = https://accone.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto +# @host = https://accone-prod.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto + +### LIST OF Endpoints +### {{ host }}//insertSales/{branchCode}/{date} +### {{ host }}//insertAr/{branchCode}/{date} +### {{ host }}//insertArPayment/{branchCode}/{date} +### {{ host }}//insertRkTagihan/{branchCode}/{date} +### {{ host }}//insertRkPelunasan/{branchCode}/{date} + + +### +GET https://accone.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto/index + +### AUTO JURNAL PENJUALAN +GET {{host}}/insertSales/LE/2025-05-13?isregen=1&jurnalno=ACSL/202505/0311/LE + +{ + "isDebug": true +} + +### REGEN AUTO JURNAL PENJUALAN +GET {{host}}/insertSales/LD/2025-05-21?isregen=1&jurnalno=ACSL/202505/0234 + +{ + "isDebug": false +} + +### AUTO JURNAL AR +GET {{host}}/insertAr/LE/2025-04-12 + +{ + "isDebug": false +} + +### AUTO JURNAL AR PAYMENT +GET {{host}}/insertArPayment/LE/2025-04-12 + +{ + "isDebug": false +} + +### AUTO JURNAL RK TAGIHAN +GET {{host}}/insertRkTagihan/LE/2025-04-12 + +{ + "isDebug": false +} + +### AUTO JURNAL RK PELUNASAN +GET {{host}}/insertRkPelunasan/LB/2025-05-15/1/1527 + +{ + "isDebug": false +} + +### DELETE DUMMY DATA +POST {{ host }}/deleteDummyData + +{ + "jurnalID": "389", + "token": {{ token }} +} + +### * Inject Map Bank per Cabang +### @param = branchCode +GET {{ host }}/injectMapBankCab/LE + +### * Inject Map Bank per Regional +### @param = regionalID +GET {{ host }}/injectMapBank/6 + + +### +## *UNTUK CEK API DI CABANG +### +### +GET http://devone.aplikasi.web.id/one-api/keu/Acc_one/getBanks + +### +GET http://ngagel/one-api/keu/Acc_one/sales/2025-12-01/json + +### +GET http://jemur/one-api/keu/Acc_one/sales/2025-05-21/json + +### +GET http://ngagel/one-api/keu/Acc_one/getBanks + +### sales +GET http://192.168.250.241/one-api/keu/Acc_one/sales/2025-01-03/json/ + +### ar +GET http://aditya/one-api/keu/Acc_one/ar/2025-05-13/json/ + +### ar payment +GET http://192.168.250.181/one-api/keu/Acc_one/arPayment/2025-01-02/json/ + +### TAGIHAN +GET http://192.168.250.181/one-api/keu/Acc_one/arPaymentRkTagihan/2025-01-10/json/ + +### PELUNASAN +GET http://192.168.250.182/one-api/keu/Acc_one/arPaymentRkPelunasan/2025-01-10/ + + +### ---------------------------- +### KEBONJERUK +GET http://192.168.250.182/one-api/keu/Acc_one/arPaymentRkPelunasan/2025-01-02/ + +### +GET http://192.168.250.182/one-api/keu/acc_one/arPayment/2025-01-02/json/ + + + + +### REGENERATE +GET https://accone.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto/insertSales/BA/2025-01-11/1/157 + +### +GET https://accone.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto/insertAr/BA/2025-01-09/1/157 + +### +GET https://accone.aplikasi.web.id/one-api/mockup/masterdata/accounting/Mediajurnalauto/insertArPayment/BA/2025-01-06/1/246 + +### +GET {{ host }}/testExc \ No newline at end of file diff --git a/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris_bckup-260506.php b/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris_bckup-260506.php new file mode 100644 index 0000000..1a1a21e --- /dev/null +++ b/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris_bckup-260506.php @@ -0,0 +1,3225 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $payload = $this->sys_input; + $search = $payload['search'] . '%'; + + $sql = "SELECT + SupplierID, + SupplierCode, + SupplierName + FROM supplier + WHERE SupplierIsActive = 'Y' + AND SupplierName LIKE ? + ORDER BY SupplierName ASC "; + $que = $this->db->query($sql, [$search]); + if (!$que) { + $this->sys_error_db("[Error] query listing supplier");; + exit; + } + + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getRuangan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $search = $payload['search'] . '%'; + + $sql = "SELECT M_RuanganID, + M_RuanganM_BranchID, + M_RuanganName, + M_RuanganCode + FROM m_ruangan + WHERE M_RuanganIsActive = 'Y' + AND M_RuanganM_BranchID = ? + AND M_RuanganName LIKE ? + ORDER BY M_RuanganName ASC"; + $qry = $this->db->query($sql, [$user['M_BranchID'], $search]); + + if (!$qry) { + $this->sys_error_db("[Error] query listing ruangan");; + exit; + } + + $data = $qry->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getPurchaseOrder() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $payload = $this->sys_input; + $user = $this->sys_user; + + $const_params = [ + $user['M_BranchID'] ?? 0, + $user['S_RegionalID'], + $payload['SupplierID'], + $payload['search'] . '%' + ]; + + $placeholders = '?'; + $list_includeID = ["0"]; + $localPO_deleted = $payload['localPO_deleted']; + if (sizeof($localPO_deleted) > 0) { + $placeholders = implode(", ", array_fill(0, count($localPO_deleted), '?')); + $list_includeID = $payload['localPO_deleted']; + } + + $params = array_merge($list_includeID, $const_params); + + $sql = "SELECT + GROUP_CONCAT(DISTINCT PurchaseOrderDetailWarehouseID) AS arrWarehouse, + purchase_order.* + FROM purchase_order + JOIN purchase_order_detail ON PurchaseOrderID = PurchaseOrderDetailPurchaseOrderID + AND PurchaseOrderDetailIsActive = 'Y' + AND + ((SELECT IFNULL(SUM(PoItemReceiveQty - PoItemReceiveQtyReceived), 0) + FROM po_item_receive + WHERE PoItemReceivePurchaseOrderID = PurchaseOrderID) > 0) + OR + (SELECT PoItemReceiveID + FROM po_item_receive + WHERE PoItemReceivePurchaseOrderID = PurchaseOrderID + AND PoItemReceiveID IN ({$placeholders})) + JOIN warehouse ON PurchaseOrderDetailWarehouseID = WarehouseID + AND WarehouseM_BranchID = ? + WHERE WarehouseS_RegionalID = ? + AND PurchaseOrderSupplierID = ? + AND PurchaseOrderStatus = 'Approved' + AND PurchaseOrderItemCategoryID = 2 + AND PurchaseOrderNumber LIKE ? + AND PurchaseOrderIsActive = 'Y' + GROUP BY PurchaseOrderID + ORDER BY PurchaseOrderID DESC LIMIT 50"; + $que = $this->db->query($sql, $params); + if (!$que) { + $this->sys_error_db("[Error] query purhcase order"); + exit; + } + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getWarehouse() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $user = $this->sys_user; + $whtype = ($user['M_UserLocationFlag'] == 'R') ? 'R' : 'B'; + + $sql = "SELECT + WarehouseID, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + WarehouseType, + WarehouseIsDefault, + WarehouseS_RegionalID, + WarehouseM_BranchID, + S_RegionalID, + S_RegionalName + FROM warehouse + JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID AND M_BranchIsActive = 'Y' + WHERE WarehouseS_RegionalID = ? + AND WarehouseIsActive = 'Y' AND WarehouseIsTransit = 'N' + AND WarehouseType = ? AND WarehouseM_BranchID = ? + ORDER BY WarehouseName ASC"; + $que = $this->db->query($sql, [ + $user['S_RegionalID'], + $whtype, + $user['M_BranchID'] + ]); + if (!$que) { + $this->sys_error_db("[Error] get list warehouse"); + exit; + } + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItem() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $POID = $param['POID']; + $warehouseID = $param['WarehouseID']; + + $sql = "SELECT + CONCAT(PoItemReceiveID,',','-') as keyID, + PoItemReceiveID, + PurchaseOrderNumber, + PurchaseOrderShippingCost, + PurchaseOrderShippingCostStatus, + PoItemReceivePurchaseOrderID, + PoItemReceivePurchaseOrderSummaryID, + PoItemReceivePurchaseOrderDetailID, + WarehouseID, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitName, + M_ItemItem_CategoryID, + PoItemReceiveQty as originalQty, + PoItemReceiveQtyReceived as receivedQty, + 0 as qty, + PoItemReceiveQty - PurchaseOrderSummaryQtyReceived AS qtyRest, + PoItemReceivePrice, + 'N' as alreadySave + FROM po_item_receive + JOIN purchase_order ON PoItemReceivePurchaseOrderID = PurchaseOrderID + AND PurchaseOrderIsActive = 'Y' + AND PoItemReceiveIsActive = 'Y' + -- AND (PoItemReceiveQty - PoItemReceiveQtyReceived) > 0 + JOIN purchase_order_summary ON PurchaseOrderSummaryID = PoItemReceivePurchaseOrderSummaryID + JOIN warehouse ON PoItemReceiveWarehouseID = WarehouseID + AND WarehouseIsActive = 'Y' + JOIN m_item ON PoItemReceiveItemID = M_ItemID + JOIN itemunit ON PoItemReceiveItemUnitID= ItemUnitID + JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID + LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID + WHERE PurchaseOrderID = ? AND WarehouseID = ?"; + $que = $this->db->query($sql, [$POID, $warehouseID]); + if (!$que) { + $this->sys_error_db("[Error] ger item PO");; + exit; + } + $data = $que->result_array(); + foreach ($data as $key => $value) { + $data[$key]['batchlist'] = []; + } + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemUpdate() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $ROID = $param['ROID']; + + $sql = "SELECT + ReceiveOrderPoDetailID, + CONCAT(ReceiveOrderPoDetailPoItemReceiveID,',',ReceiveOrderPoDetailID) AS keyID, + ReceiveOrderPoDetailPoItemReceiveID AS PoItemReceiveID, + PurchaseOrderNumber, + PurchaseOrderShippingCost, + PurchaseOrderShippingCostStatus, + ReceiveOrderPoDetailPurchaseOrderID AS PoItemReceivePurchaseOrderID, + ReceiveOrderPoDetailPurchaseOrderSummaryID AS PoItemReceivePurchaseOrderSummaryID, + ReceiveOrderPoDetailPurchaseOrderDetailID AS PoItemReceivePurchaseOrderDetailID, + WarehouseID, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + M_RuanganID, + M_RuanganName, + M_RuanganCode, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitName, + M_ItemItem_CategoryID, + PoItemReceiveQty AS originalQty, + PoItemReceiveQtyReceived AS receivedQty, + ReceiveOrderPoDetailQty AS qty, + ReceiveOrderPoDetailQty AS tmpQty, + PoItemReceiveQty - PurchaseOrderSummaryQtyReceived AS qtyRest, + ReceiveOrderPoDetailQty, + PoItemReceivePrice, + 'Y' AS alreadySave, + ReceiveOrderPoDetailBatchNo AS batchNo, + ReceiveOrderPoDetailEd AS itemEd, + ReceiveOrderPoDetailBatchList + FROM receive_order_po_detail + JOIN receive_order_po ON ReceiveOrderPoDetailReceiveOrderPoID = ReceiveOrderPoID + JOIN purchase_order ON ReceiveOrderPoDetailPurchaseOrderID = PurchaseOrderID + JOIN po_item_receive ON ReceiveOrderPoDetailPoItemReceiveID = PoItemReceiveID + JOIN purchase_order_summary ON PurchaseOrderSummaryID = PoItemReceivePurchaseOrderSummaryID + JOIN warehouse ON ReceiveOrderPoWarehouseID = WarehouseID + JOIN m_item ON ReceiveOrderPoItemID = M_ItemID + JOIN itemunit ON ReceiveOrderPoItemUnitID = ItemUnitID + JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID + LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID + LEFT JOIN m_ruangan ON M_RuanganM_BranchID = M_BranchID + WHERE ReceiveOrderPoDetailIsActive = 'Y' + AND ReceiveOrderPoDetailReceiveOrderPoID = ? + ORDER BY ReceiveOrderPoDetailID ASC"; + $que = $this->db->query($sql, [$ROID]); + if (!$que) { + $this->sys_error_db("[Error] get item untuk update"); + exit; + } + + $data = $que->result_array(); + + foreach ($data as $key => $item) { + $jsonstr = $item['ReceiveOrderPoDetailBatchList']; + $batchlist = []; + + if (!empty($jsonstr)) { + $decode = json_decode($jsonstr); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batchlist = $decode; + } else { + $this->sys_error("[Error] decode json batch list item received"); + exit; + } + $data[$key]['batchlist'] = $batchlist; + unset($data[$key]['ReceiveOrderPoDetailBatchList']); + } + } + + $detailID = array_column($data, 'ReceiveOrderPoDetailID'); + $placeholders = implode(", ", array_fill(0, count($detailID), '?')); + + $sqlInspeksi = "SELECT + ReceiveOrderPoInspeksiID, + ReceiveOrderPoInspeksiReceiveOrderPoDetailID, + ReceiveOrderPoInspeksiQtyPesan AS qty_po, + ReceiveOrderPoInspeksiQtyActual AS qty_ro, + ReceiveOrderPoInspeksiPricePesan AS price_po, + ReceiveOrderPoInspeksiPriceActual AS price_ro, + ReceiveOrderPoInspeksiDatePesan AS date_po, + ReceiveOrderPoInspeksiDateActual AS date_ro, + ReceiveOrderPoInspeksiExpireDate AS expire_date, + ReceiveOrderPoInspeksiKeadaanKemasan AS condt_kemasan, + ReceiveOrderPoInspeksiKeadaanKemasanNote AS catatan_kemasan, + ReceiveOrderPoInspeksiKondisiPengiriman AS condt_pengiriman, + ReceiveOrderPoInspeksiKondisiPengirimanNote AS catatan_kirim, + ReceiveOrderPoInspeksiSimpulan AS summary, + ReceiveOrderPoInspeksiCatatan AS catatan, + ReceiveOrderPoInspeksiStaffPenerimaID AS pemeriksa, + ReceiveOrderPoInspeksiPengirim AS pengirim + FROM receive_order_po_inspeksi + WHERE ReceiveOrderPoInspeksiIsActive = 'Y' + AND ReceiveOrderPoInspeksiReceiveOrderPoDetailID IN ({$placeholders})"; + $queInspeksi = $this->db->query($sqlInspeksi, $detailID); + if (!$queInspeksi) { + $this->sys_error_db("[Error] get item inspeksi data"); + exit; + } + $list_inspeksi = $queInspeksi->result_array(); + + $lookup_map = []; + foreach ($list_inspeksi as $inspeksi) { + $RODetailID = $inspeksi['ReceiveOrderPoInspeksiReceiveOrderPoDetailID']; + $lookup_map[$RODetailID] = $inspeksi; + } + + $sql_barcode = "SELECT T_BarcodeBarangID, + T_BarcodeBarangReceiveOrderPoDetailID, + T_BarcodeBarangM_ItemID + FROM t_barcode_barang + WHERE T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangReceiveOrderPoDetailID IN ($placeholders)"; + $qry_barcode = $this->db->query($sql_barcode, $detailID); + if (!$qry_barcode) { + $this->sys_error_db("[Error] get item barcode data"); + exit; + } + $list_barcode = $qry_barcode->result_array(); + + $lookup_map_barcode = []; + foreach ($list_barcode as $barcode) { + $RODetailID = $barcode['T_BarcodeBarangReceiveOrderPoDetailID']; + $lookup_map_barcode[$RODetailID][] = $barcode; + } + + $result = []; + foreach ($data as $rodetail) { + $rodetailID = $rodetail['ReceiveOrderPoDetailID']; + + // gabung inspeksi + if (isset($lookup_map[$rodetailID])) { + $rodetail['inspeksi_item'] = $lookup_map[$rodetailID]; + } + + // gabung barcode + if (isset($lookup_map_barcode[$rodetailID])) { + $rodetail['barcode_item'] = $lookup_map_barcode[$rodetailID]; + } + + $result[] = $rodetail; + } + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchRO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + $search = $param['search'] . '%'; + $startdate = $param['startdate']; + $enddate = $param['enddate']; + $regID = $user['S_RegionalID']; + $brnCD = $user['M_BranchCode'] . '%'; + + $page = 0; + $limit = 15; + if ($param['page'] > 0) { + $page = ($param['page'] - 1) * $limit; + } + + $sql = "SELECT + ReceiveOrderPoNumber, + ReceiveOrderPoID, + ReceiveOrderPoSupplierID, + ReceiveOrderPoIDate, + ReceiveOrderShippingCostAmount, + ReceiveOrderPoNote, + ReceiveOrderPoRefNumber, + ReceiveOrderPoDONumber, + ReceiveOrderPoIsHandover, + SupplierID, + SupplierName, + WarehouseID, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + M_RuanganID, + M_RuanganName, + M_RuanganCode, + ReceiveOrderPoConfirmed, + DATE_FORMAT(ReceiveOrderPoConfirmedDate, '%d-%m-%Y %H:%i') AS ReceiveOrderPoConfirmedDate, + M_UserUsername AS ReceiveOrderPoConfirmedUserName + FROM receive_order_po + JOIN warehouse ON ReceiveOrderPoWarehouseID = WarehouseID + JOIN supplier ON ReceiveOrderPoSupplierID = SupplierID + JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID + AND M_BranchIsActive = 'Y' + LEFT JOIN m_user ON ReceiveOrderPoConfirmedUserID = M_UserID + LEFT JOIN m_ruangan ON M_RuanganM_BranchID = M_BranchID + WHERE ReceiveOrderPoIsActive = 'Y' + AND (ReceiveOrderPoNumber LIKE ? OR ReceiveOrderPoDONumber LIKE ?) + AND ReceiveOrderPoIDate BETWEEN DATE(?) AND DATE(?) + AND ReceiveOrderPoS_RegionalID = ? + AND ReceiveOrderPoM_BranchCode LIKE ? + AND ReceiveOrderPoID NOT IN ( + SELECT DISTINCT ReceiveOrderPoDetailReceiveOrderPoID + FROM receive_order_po_detail + JOIN purchase_order ON ReceiveOrderPoDetailPurchaseOrderID = PurchaseOrderID + WHERE PurchaseOrderItemCategoryID IN (1, 4) + AND ReceiveOrderPoDetailIsActive = 'Y' + ) + ORDER BY ReceiveOrderPoID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $quetotal = $this->db->query($sqltotal, [$search, $search, $startdate, $enddate, $regID, $brnCD]); + if (!$quetotal) { + $this->sys_error_db("[Error] get total data RO"); + exit; + } + $total = $quetotal->row_array()['total']; + + $sqldata = $sql . " LIMIT ? OFFSET ?"; + $quedata = $this->db->query($sqldata, [ + $search, + $search, + $startdate, + $enddate, + $regID, + $brnCD, + $limit, + $page + ]); + if (!$quedata) { + $this->sys_error_db("[Error] get list data RO"); + exit; + } + + $records = $quedata->result_array(); + foreach ($records as $key => $value) { + $sql = "SELECT ReceiveOrderPoDocumentID, + ReceiveOrderPoDocumentDate, + ReceiveOrderPoDocumentFile + FROM receive_order_po_document + WHERE ReceiveOrderPoDocumentIsActive = 'Y' + AND ReceiveOrderPoDocumentReceiveOrderPoID = ?"; + $qry = $this->db->query($sql, [$value['ReceiveOrderPoID']]); + if (!$qry) { + $this->sys_error_db("[Error] get document RO"); + exit; + } + + $rowsdata = $qry->result_array(); + if (count($rowsdata) > 0) { + $records[$key]['hasDocuments'] = true; + $records[$key]['documents'] = $rowsdata; + } else { + $records[$key]['hasDocuments'] = false; + $records[$key]['documents'] = []; + } + } + + $result = array( + "records" => $records, + "total" => ceil($total / $limit) + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemDataInspeksi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $RODetailID = $param['RODetailID']; + + $sql = "SELECT + ReceiveOrderPoInspeksiID, + ReceiveOrderPoInspeksiReceiveOrderPoDetailID, + ReceiveOrderPoInspeksiQtyPesan, + ReceiveOrderPoInspeksiQtyActual, + ReceiveOrderPoInspeksiPricePesan, + ReceiveOrderPoInspeksiPriceActual, + ReceiveOrderPoInspeksiDatePesan, + ReceiveOrderPoInspeksiDateActual, + ReceiveOrderPoInspeksiExpireDate, + ReceiveOrderPoInspeksiKeadaanKemasan, + ReceiveOrderPoInspeksiKondisiPengiriman, + ReceiveOrderPoInspeksiSimpulan, + ReceiveOrderPoInspeksiCatatan, + ReceiveOrderPoInspeksiStaffPenerima, + ReceiveOrderPoInspeksiStaffPengirim + FROM receive_order_po_inspeksi + WHERE ReceiveOrderPoInspeksiIsActive = 'Y' + AND ReceiveOrderPoInspeksiReceiveOrderPoDetailID = ?"; + $que = $this->db->query($sql, [$RODetailID]); + if (!$que) { + $this->sys_error_db("[Error] get data inspeksi item"); + exit; + } + $data = $que->row_array(); + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getListStaff() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid token"); + exit; + } + + $user = $this->sys_user; + $param = $this->sys_input; + + // $sql = "SELECT DISTINCT + // u.M_UserID, + // u.M_UserUsername + // FROM receive_order_po ro + // JOIN receive_order_po_detail rod + // ON rod.ReceiveOrderPoDetailReceiveOrderPoID = ro.ReceiveOrderPoID + // AND rod.ReceiveOrderPoDetailIsActive = 'Y' + // JOIN purchase_order_detail pod + // ON pod.PurchaseOrderDetailID = rod.ReceiveOrderPoDetailPurchaseOrderDetailID + // AND pod.PurchaseOrderDetailIsActive = 'Y' + // JOIN purchase_request pr + // ON pr.PurchaseRequestID = pod.PurchaseOrderDetailPurchaseRequestID + // AND pr.PurchaseRequestIsActive = 'Y' + // JOIN m_user u + // ON u.M_UserID = pr.PurchaseRequestRequestedBy + // AND u.M_UserIsActive = 'Y' + // WHERE + // ro.ReceiveOrderPoID = ? + // AND ro.ReceiveOrderPoIsActive = 'Y'"; + // $que = $this->db->query($sql, [$param['ROID']]); + // + + $sql = "SELECT + M_UserID, + M_UserUsername + FROM m_user + WHERE M_UserM_BranchID = ? + AND M_UserS_RegionalID = ? + AND M_UserIsActive = 'Y' + ORDER BY M_UserUsername"; + $que = $this->db->query($sql, [$user['M_BranchID'], $user['S_RegionalID']]); + if (!$que) { + $this->sys_error_db("[Error] get staff"); + exit; + } + $data = $que->result_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function generateNoLogistik($user, $typeLogistik): string + { + $areaid = ($user['loginLevel'] == 'regional') ? $user['S_RegionalID'] : $user['M_BranchID']; + $areatype = ($user['loginLevel'] == 'regional') ? 'R' : 'B'; + + $sqlusrdivisi = "SELECT M_UserDivisionDivisionID FROM m_userdivision + WHERE M_UserDivisionM_UserID = ? AND M_UserDivisionIsActive = 'Y'"; + $queusrdivisi = $this->db->query($sqlusrdivisi, [$user['M_UserID']]); + if (!$queusrdivisi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get user divisi"); + exit; + } + + $usrdivisiID = $queusrdivisi->row_array()['M_UserDivisionDivisionID']; + if (!isset($usrdivisiID)) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] user divisi id null"); + exit; + } + + $sqlnum = "SELECT `fn_penomoran`(?, ?, ?, ?, ?, ?) AS numpd;"; + $quenum = $this->db->query($sqlnum, [$typeLogistik, $usrdivisiID, $areatype, $areaid, 'SM', 'Y']); + if (!$quenum) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] generate number PI"); + exit; + } + + $numPL = $quenum->row_array()['numpd']; + if (!isset($numPL)) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] number PI null"); + exit; + } + + return $numPL; + } + + private function generateNoBarcode($user, $lokasiID, $typeBarcode, $itemid) + { + $branchid = ($user['loginLevel'] == 'branch') ? $user['M_BranchID'] : 0; + + if ($user['loginlevel'] == 'regional') { + $this->db->trans_rollback(); + $this->sys_error('Tidak bisa generare No Barcode, anda login sebagai regional'); + exit; + } + + // -- numtype = tipe numbering + // -- itemid = id item inventaris/asset + // -- branchid = id cabang + // -- ruanganid = id ruangan di cabang + + $sqlnum = "SELECT `fn_num_nonpersediaan`(?, ?, ?, ?) AS numpd;"; + $quenum = $this->db->query($sqlnum, [$typeBarcode, $itemid, $branchid, $lokasiID]); + + if (!$quenum) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] generate number Barcode"); + exit; + } + + $numPL = $quenum->row_array()['numpd']; + if (!isset($numPL)) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] number Barcode null"); + exit; + } + + return $numPL; + } + + private function getPOItemReceived($id) + { + $sql = "SELECT * FROM po_item_receive + JOIN warehouse ON PoItemReceiveWarehouseID= WarehouseID + JOIN itemunit ON PoItemReceiveItemUnitID = ItemUnitID + WHERE PoItemReceiveID = ?"; + $que = $this->db->query($sql, [$id]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] getDataPoItemReceive");; + exit; + } + return $que->row_array(); + } + + private function getDataROPO($id) + { + $sql = "SELECT * FROM receive_order_po WHERE ReceiveOrderPoID = ?"; + $que = $this->db->query($sql, [$id]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] getDataReceiveOrderPO ");; + exit; + } + $ROheader = $que->row_array(); + + $sqldetail = "SELECT * FROM receive_order_po_detail + WHERE ReceiveOrderPoDetailReceiveOrderPoID = ? AND ReceiveOrderPoDetailIsActive = 'Y'"; + $quedetail = $this->db->query($sqldetail, [$id]); + if (!$quedetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] getDataReceiveOrderPO detail");; + exit; + } + $ROdetail = $quedetail->result_array(); + $ROheader['details'] = $ROdetail; + return $ROheader; + } + + ## MUTATION ## + + function saveRO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # generate nomor purchase invoice # + $numGR = $this->generateNoLogistik($user, 'GR'); + + # insert table ro # + $sqlInsRO = "INSERT INTO receive_order_po ( + ReceiveOrderPoNumber, + ReceiveOrderPoSupplierID, + ReceiveOrderPoIDate, + ReceiveOrderPoWarehouseID, + ReceiveOrderPoM_BranchCode, + ReceiveOrderPoS_RegionalID, + ReceiveOrderShippingCostAmount, + ReceiveOrderShippingCostIsPaid, + ReceiveOrderPoNote, + ReceiveOrderPoRefNumber, + ReceiveOrderPoDONumber, + ReceiveOrderPoCreatedUserID + ) VALUE (?,?,?,?,?,?,?,?,?,?,?,?)"; + $queInsRO = $this->db->query($sqlInsRO, [ + $numGR, + $param['supplierID'], + $param['date'], + $param['warehouseID'], + $user['M_BranchCode'], + $user['S_RegionalID'], + $param['shippingCost'], + $param['shippingIsPaid'], + $param['note'], + $param['refNumber'], + $param['refNumber'], + $user['M_UserID'] + ]); + if (!$queInsRO) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table receive order po"); + exit; + } + $roID = $this->db->insert_id(); + + # inset to table ro detail # + $logDesc = []; + foreach ($param['detail'] as $key => $obj) { + $sqlRcvdItem = "SELECT * FROM po_item_receive WHERE PoItemReceiveID = ?"; + $queRcvdItem = $this->db->query($sqlRcvdItem, [$obj['PoItemReceiveID']]); + if (!$queRcvdItem) { + $this->db->trans_rollback(); + $this->sys_error_db("Error cek data item po_item_receive"); + exit; + } + $cekReceived = $queRcvdItem->row_array(); + + # cek item received # + if ($cekReceived['PoItemReceiveIsActive'] == 'N') { + $this->db->trans_rollback(); + $this->sys_error("[Error] Item {$obj['M_ItemDesc']} sudah diterima"); + exit; + } + + if ($cekReceived['PoItemReceiveQtyReceived'] == $cekReceived['PoItemReceiveQty']) { + $this->db->trans_rollback(); + $this->sys_error("[Error] Item {$obj['M_ItemDesc']} sudah diterima semuanya"); + exit; + } + + if (intval($obj['qty']) > intval($cekReceived['PoItemReceiveQty'])) { + $this->db->trans_rollback(); + $this->sys_error("Jumlah item {$obj['M_ItemDesc']} yang tersedia sudah berubah silahkan ulangi pilih item"); + exit; + } + + $jsonBatch = "[]"; + if (isset($obj['batchlist']) && is_array($obj['batchlist'])) { + $batchlist = $obj['batchlist']; + if (sizeof($batchlist) > 0) { + $json = json_encode($batchlist); + if ($json === false) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] encode json batch number"); + exit; + } else { + $jsonBatch = $json; + } + } + } + + $sqlInsRODetail = "INSERT INTO receive_order_po_detail ( + ReceiveOrderPoDetailReceiveOrderPoID, + ReceiveOrderPoDetailPurchaseOrderID, + ReceiveOrderPoDetailPurchaseOrderSummaryID, + ReceiveOrderPoDetailPurchaseOrderDetailID, + ReceiveOrderPoDetailPoItemReceiveID, + ReceiveOrderPoDetailQty, + ReceiveOrderPoDetailPrice, + ReceiveOrderPoDetailTotal, + ReceiveOrderPoDetailCreatedUserID, + ReceiveOrderPoItemID, + ReceiveOrderPoItemUnitID, + ReceiveOrderPoDetailBatchNo, + ReceiveOrderPoDetailEd, + ReceiveOrderPoDetailBatchList + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $queInsRODetail = $this->db->query($sqlInsRODetail, [ + $roID, + $obj['PoItemReceivePurchaseOrderID'], + $obj['PoItemReceivePurchaseOrderSummaryID'], + $obj['PoItemReceivePurchaseOrderDetailID'], + $obj['PoItemReceiveID'], + $obj['qty'], + $obj['PoItemReceivePrice'], + (doubleval($obj['PoItemReceivePrice']) * intval($obj['qty'])), + $user['M_UserID'], + $obj['M_ItemID'], + $obj['ItemUnitID'], + $obj['batchNo'], + $obj['itemEd'], + $jsonBatch + ]); + if (!$queInsRODetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] receive order detail"); + exit; + } + + $logDesc[] = "- ADD {$obj['M_ItemDesc']} {$obj['qty']} {$obj['ItemUnitName']} nomor batch {$obj['WarehouseName']}"; + + $RODetailID = $this->db->insert_id(); + + if (intval($obj['qty']) > 0) { + $qty = intval($obj['qty']); + for ($i = 0; $i < $qty; $i++) { + # generate nomor barcode # + $noBarcode = $this->generateNoBarcode($user, $param['lokasiID'], 'BNP', $obj['M_ItemID']); + + # INSERT INTO t_barcode_barang # + $sqlInsertBarcode = "INSERT INTO t_barcode_barang( + T_BarcodeBarangReceiveOrderPoID, + T_BarcodeBarangReceiveOrderPoDetailID, + T_BarcodeBarangRefType, + T_BarcodeBarangM_ItemID, + T_BarcodeBarangItemUnitID, + T_BarcodeBarangNumber, + T_BarcodeBarangM_RuanganID, + T_BarcodeBarangM_BranchID, + T_BarcodeBarangIsActive, + T_BarcodeBarangUserID, + T_BarcodeBarangCreated) VALUES(?,?,'PO',?,?,?,?,?,'Y',?,NOW())"; + $qryInsertBarcode = $this->db->query($sqlInsertBarcode, array( + $roID, + $RODetailID, + $obj['M_ItemID'], + $obj['ItemUnitID'], + $noBarcode, + $param['lokasiID'], + $user['M_BranchID'], + $user['M_UserID'] + )); + if (!$qryInsertBarcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert data barcode item"); + exit; + } + } + } + + # INSERT INTO receive_order_po_inspeksi # + $inspeksi = $obj['inspeksi_item']; + $sqlInspeksi = "INSERT INTO receive_order_po_inspeksi ( + ReceiveOrderPoInspeksiReceiveOrderPoDetailID, + ReceiveOrderPoInspeksiQtyPesan, + ReceiveOrderPoInspeksiQtyActual, + ReceiveOrderPoInspeksiPricePesan, + ReceiveOrderPoInspeksiPriceActual, + ReceiveOrderPoInspeksiDatePesan, + ReceiveOrderPoInspeksiDateActual, + ReceiveOrderPoInspeksiKeadaanKemasan, + ReceiveOrderPoInspeksiKeadaanKemasanNote, + ReceiveOrderPoInspeksiKondisiPengiriman, + ReceiveOrderPoInspeksiKondisiPengirimanNote, + ReceiveOrderPoInspeksiSimpulan, + ReceiveOrderPoInspeksiCatatan, + ReceiveOrderPoInspeksiStaffPenerimaID, + ReceiveOrderPoInspeksiPengirim, + ReceiveOrderPoInspeksiUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $queInspeksi = $this->db->query($sqlInspeksi, [ + $RODetailID, + $inspeksi['qty_po'], + $inspeksi['qty_ro'], + $inspeksi['price_po'], + $inspeksi['price_ro'], + $inspeksi['date_po'], + $inspeksi['date_ro'], + $inspeksi['condt_kemasan'], + $inspeksi['catatan_kemasan'], + $inspeksi['condt_pengiriman'], + $inspeksi['catatan_kirim'], + $inspeksi['summary'], + $inspeksi['catatan'], + $inspeksi['pemeriksa'], + $inspeksi['pengirim'], + $user['M_UserID'] + ]); + if (!$queInspeksi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert data inspeksi item"); + exit; + } + + # po item received && log item change # + $jsonBefore = $this->getPOItemReceived($obj['PoItemReceiveID']); + $sqlupd = "UPDATE po_item_receive SET + PoItemReceiveQtyReceived = ?, + PoItemReceiveUpdatedUserID = ? + WHERE PoItemReceiveID = ?"; + $queupd = $this->db->query($sqlupd, [ + (intval($cekReceived['PoItemReceiveQtyReceived']) + intval($obj['qty'])), + $user['M_UserID'], + $obj['PoItemReceiveID'] + ]); + if (!$queupd) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update item receive"); + exit; + } + + $jsonAfter = $this->getPOItemReceived($obj['PoItemReceiveID']); + $desc = "Diterima {$obj['M_ItemDesc']} sejumlah {$obj['qty']} {$obj['ItemUnitName']} di RO nomor {$numGR} *RO belum di konfirmasi"; + $this->insertLogPoItemReceive( + $obj['PoItemReceiveID'], + 'UPDATE', + $roID, + $jsonBefore, + $jsonAfter, + $user['M_UserID'], + $desc + ); + } + + $dataROAfter = $this->getDataROPO($roID); + $this->insertLogReceiveOrderPo($roID, 'ADD', '', $dataROAfter, $user['M_UserID'], implode("\n", $logDesc)); + $this->insertUserActivty($roID, 'RO', 'ADD', $user['M_UserID'], implode("\n", $logDesc)); + + $this->db->trans_commit(); + $this->sys_ok("Berhasil terima barang dengan nomor {$numGR}"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditRO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sql_ro = "UPDATE receive_order_po SET + ReceiveOrderPoNumber = ?, + ReceiveOrderPoSupplierID = ?, + ReceiveOrderPoIDate = ?, + ReceiveOrderPoWarehouseID = ?, + ReceiveOrderPoM_BranchCode = ?, + ReceiveOrderPoS_RegionalID = ?, + ReceiveOrderShippingCostAmount = ?, + ReceiveOrderShippingCostIsPaid = ?, + ReceiveOrderPoNote = ?, + ReceiveOrderPoRefNumber = ?, + ReceiveOrderPoDONumber = ? + WHERE ReceiveOrderPoID = ?"; + $que_ro = $this->db->query($sql_ro, [ + $param['numGR'], + $param['supplierID'], + $param['date'], + $param['warehouseID'], + $user['M_BranchCode'], + $user['S_RegionalID'], + $param['shippingCost'], + $param['shippingIsPaid'], + $param['note'], + $param['refNumber'], + $param['refNumber'], + $param['ReceiveOrderID'] + ]); + if (!$que_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table receive order po"); + exit; + } + + # CHECK IF DETAIL ALREADY IN TABLE RECEIVE # + $sql_check_ro = "SELECT ReceiveOrderPoDetailID, ReceiveOrderPoDetailPoItemReceiveID + FROM receive_order_po_detail + WHERE ReceiveOrderPoDetailReceiveOrderPoID = ? + AND ReceiveOrderPoDetailIsActive = 'Y'"; + $que_check_ro = $this->db->query($sql_check_ro, [$param['ReceiveOrderID']]); + if (!$que_check_ro) { + $this->db->trans_rollback(); + $this->sys_error("[Error] get list ro detail id"); + exit; + } + $list_detailID = $que_check_ro->result_array(); + $master_detailID = array_column($list_detailID, 'ReceiveOrderPoDetailID'); + $input_detailID = array_column($param['detail'], 'ReceiveOrderPoDetailID'); + + $update = []; + $insert = []; + $delete = []; + + foreach ($param['detail'] as $key => $obj) { + if (empty($obj['ReceiveOrderPoDetailID'])) { + $insert[] = $obj; + continue; + } + if (in_array($obj['ReceiveOrderPoDetailID'], $master_detailID)) { + $update[] = $obj; + } + } + + foreach ($list_detailID as $key => $obj) { + if (!in_array($obj['ReceiveOrderPoDetailID'], $input_detailID)) { + $delete[] = $obj; + } + } + + # UPDATE # + foreach ($update as $key => $obj) { + # cek item received # + $sqlRcvdItem = "SELECT * FROM po_item_receive WHERE PoItemReceiveID = ?"; + $queRcvdItem = $this->db->query($sqlRcvdItem, [$obj['PoItemReceiveID']]); + if (!$queRcvdItem) { + $this->db->trans_rollback(); + $this->sys_error_db("Error cek data item po_item_receive"); + exit; + } + $cekReceived = $queRcvdItem->row_array(); + if ($cekReceived['PoItemReceiveIsActive'] == 'N') { + $this->db->trans_rollback(); + $this->sys_error("[Error] Item {$obj['M_ItemDesc']} tidak aktif"); + exit; + } + + if (intval($obj['qty']) > intval($cekReceived['PoItemReceiveQty'])) { + $this->db->trans_rollback(); + $this->sys_error("Jumlah item {$obj['M_ItemDesc']} yang tersedia sudah berubah silahkan ulangi pilih item"); + exit; + } + + # UPDATE po item receive # + $sql_up_po_receive = "UPDATE po_item_receive + JOIN receive_order_po_detail ON ReceiveOrderPoDetailPoItemReceiveID = PoItemReceiveID + AND ReceiveOrderPoDetailID = ? + SET + PoItemReceiveQtyReceived = (PoItemReceiveQtyReceived - ReceiveOrderPoDetailQty) + ?, + PoItemReceiveUpdatedUserID = ? + WHERE PoItemReceiveID = ?"; + $que_up_po_receive = $this->db->query($sql_up_po_receive, [ + $obj['ReceiveOrderPoDetailID'], + $obj['qty'], + $user['M_UserID'], + $obj['PoItemReceiveID'] + ]); + if (!$que_up_po_receive) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update receive order detail"); + exit; + } + + # UPDATE receive detail po # + $jsonBatch = "[]"; + if (isset($obj['batchlist']) && is_array($obj['batchlist'])) { + $batchlist = $obj['batchlist']; + if (sizeof($batchlist) > 0) { + $json = json_encode($batchlist); + if ($json === false) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] encode json batch number"); + exit; + } else { + $jsonBatch = $json; + } + } + } + + $sql_update_detail = "UPDATE receive_order_po_detail SET + ReceiveOrderPoDetailReceiveOrderPoID = ?, + ReceiveOrderPoDetailPurchaseOrderID = ?, + ReceiveOrderPoDetailPurchaseOrderSummaryID = ?, + ReceiveOrderPoDetailPurchaseOrderDetailID = ?, + ReceiveOrderPoDetailPoItemReceiveID = ?, + ReceiveOrderPoDetailQty = ?, + ReceiveOrderPoDetailPrice = ?, + ReceiveOrderPoDetailTotal = ?, + ReceiveOrderPoItemID = ?, + ReceiveOrderPoItemUnitID = ?, + ReceiveOrderPoDetailBatchNo = ?, + ReceiveOrderPoDetailEd = ?, + ReceiveOrderPoDetailBatchList = ? + WHERE ReceiveOrderPoDetailID = ?"; + $que_update_detail = $this->db->query($sql_update_detail, [ + $param['ReceiveOrderID'], + $obj['PoItemReceivePurchaseOrderID'], + $obj['PoItemReceivePurchaseOrderSummaryID'], + $obj['PoItemReceivePurchaseOrderDetailID'], + $obj['PoItemReceiveID'], + $obj['qty'], + $obj['PoItemReceivePrice'], + (doubleval($obj['PoItemReceivePrice']) * intval($obj['qty'])), + $obj['M_ItemID'], + $obj['ItemUnitID'], + $obj['batchNo'], + $obj['itemEd'], + $jsonBatch, + $obj['ReceiveOrderPoDetailID'] + ]); + if (!$que_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update receive order detail"); + exit; + } + + + if (intval($obj['qty']) > 0) { + $qty = intval($obj['qty']); + for ($i = 0; $i < $qty; $i++) { + + # INSERT INTO t_barcode_barang # + $barcode_item = $obj['barcode_item']; + + foreach ($barcode_item as $key => $barcode) { + # generate nomor barcode # + $noBarcode = $this->generateNoBarcode($user, $param['lokasiID'], 'BNP', $obj['M_ItemID']); + + $sqlInsertBarcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangReceiveOrderPoID = ?, + T_BarcodeBarangReceiveOrderPoDetailID = ?, + T_BarcodeBarangRefType = 'PO', + T_BarcodeBarangM_ItemID = ?, + T_BarcodeBarangItemUnitID = ?, + T_BarcodeBarangNumber = ?, + T_BarcodeBarangM_RuanganID = ?, + T_BarcodeBarangM_BranchID = ?, + T_BarcodeBarangIsActive = 'Y', + T_BarcodeBarangUserID = ?, + T_BarcodeBarangLastUpdated = NOW() + WHERE T_BarcodeBarangID = ?"; + $qryInsertBarcode = $this->db->query($sqlInsertBarcode, array( + $param['ReceiveOrderID'], + $obj['ReceiveOrderPoDetailID'], + $obj['M_ItemID'], + $obj['ItemUnitID'], + $noBarcode, + $param['lokasiID'], + $user['M_BranchID'], + $user['M_UserID'], + $barcode['T_BarcodeBarangID'] + )); + if (!$qryInsertBarcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update data barcode item", $this->db); + exit; + } + } + } + } + + # update form inspeksi item # + $inspeksi = $obj['inspeksi_item']; + $sql_inspeksi = "UPDATE receive_order_po_inspeksi SET + ReceiveOrderPoInspeksiQtyPesan = ?, + ReceiveOrderPoInspeksiQtyActual = ?, + ReceiveOrderPoInspeksiPricePesan = ?, + ReceiveOrderPoInspeksiPriceActual = ?, + ReceiveOrderPoInspeksiDatePesan = ?, + ReceiveOrderPoInspeksiDateActual = ?, + ReceiveOrderPoInspeksiKeadaanKemasan = ?, + ReceiveOrderPoInspeksiKeadaanKemasanNote = ?, + ReceiveOrderPoInspeksiKondisiPengiriman = ?, + ReceiveOrderPoInspeksiKondisiPengirimanNote = ?, + ReceiveOrderPoInspeksiSimpulan = ?, + ReceiveOrderPoInspeksiCatatan = ?, + ReceiveOrderPoInspeksiStaffPenerimaID = ?, + ReceiveOrderPoInspeksiPengirim = ? + WHERE ReceiveOrderPoInspeksiID = ?"; + $que_inspeksi = $this->db->query($sql_inspeksi, [ + $inspeksi['qty_po'], + $inspeksi['qty_ro'], + $inspeksi['price_po'], + $inspeksi['price_ro'], + $inspeksi['date_po'], + $inspeksi['date_ro'], + $inspeksi['condt_kemasan'], + $inspeksi['catatan_kemasan'], + $inspeksi['condt_pengiriman'], + $inspeksi['catatan_kirim'], + $inspeksi['summary'], + $inspeksi['catatan'], + $inspeksi['pemeriksa'], + $inspeksi['pemeriksa'], + $inspeksi['ReceiveOrderPoInspeksiID'] + ]); + if (!$que_inspeksi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update form inspeksi"); + exit; + } + } + + # INSERT # + foreach ($insert as $key => $obj) { + # cek item received # + $sqlRcvdItem = "SELECT * FROM po_item_receive WHERE PoItemReceiveID = ?"; + $queRcvdItem = $this->db->query($sqlRcvdItem, [$obj['PoItemReceiveID']]); + if (!$queRcvdItem) { + $this->db->trans_rollback(); + $this->sys_error_db("Error cek data item po_item_receive"); + exit; + } + $cekReceived = $queRcvdItem->row_array(); + if ($cekReceived['PoItemReceiveIsActive'] == 'N') { + $this->db->trans_rollback(); + $this->sys_error("[Error] Item {$obj['M_ItemDesc']} tidak aktif"); + exit; + } + + if (intval($obj['qty']) > intval($cekReceived['PoItemReceiveQty'])) { + $this->db->trans_rollback(); + $this->sys_error("Jumlah item {$obj['M_ItemDesc']} yang tersedia sudah berubah silahkan ulangi pilih item"); + exit; + } + + # UPDATE po item receive # + $sql_up_po_receive = "UPDATE po_item_receive SET + PoItemReceiveQtyReceived = ?, + PoItemReceiveUpdatedUserID = ? + WHERE PoItemReceiveID = ?"; + $que_up_po_receive = $this->db->query($sql_up_po_receive, [ + (intval($cekReceived['PoItemReceiveQtyReceived']) + intval($obj['qty'])), + $user['M_UserID'], + $obj['PoItemReceiveID'] + ]); + if (!$que_up_po_receive) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update receive order detail"); + exit; + } + + $jsonBatch = "[]"; + if (isset($obj['batchlist']) && is_array($obj['batchlist'])) { + $batchlist = $obj['batchlist']; + if (sizeof($batchlist) > 0) { + $json = json_encode($batchlist); + if ($json === false) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] encode json batch number"); + exit; + } else { + $jsonBatch = $json; + } + } + } + + # RE-INSERT ITEM DETAIL # + $sql_insert_rodetail = "INSERT INTO receive_order_po_detail ( + ReceiveOrderPoDetailReceiveOrderPoID, + ReceiveOrderPoDetailPurchaseOrderID, + ReceiveOrderPoDetailPurchaseOrderSummaryID, + ReceiveOrderPoDetailPurchaseOrderDetailID, + ReceiveOrderPoDetailPoItemReceiveID, + ReceiveOrderPoDetailQty, + ReceiveOrderPoDetailPrice, + ReceiveOrderPoDetailTotal, + ReceiveOrderPoDetailCreatedUserID, + ReceiveOrderPoItemID, + ReceiveOrderPoItemUnitID, + ReceiveOrderPoDetailBatchNo, + ReceiveOrderPoDetailEd, + ReceiveOrderPoDetailBatchList + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $que_insert_rodetail = $this->db->query($sql_insert_rodetail, [ + $param['ReceiveOrderID'], + $obj['PoItemReceivePurchaseOrderID'], + $obj['PoItemReceivePurchaseOrderSummaryID'], + $obj['PoItemReceivePurchaseOrderDetailID'], + $obj['PoItemReceiveID'], + $obj['qty'], + $obj['PoItemReceivePrice'], + (doubleval($obj['PoItemReceivePrice']) * intval($obj['qty'])), + $user['M_UserID'], + $obj['M_ItemID'], + $obj['ItemUnitID'], + $obj['batchNo'], + $obj['itemEd'], + $jsonBatch + ]); + if (!$que_insert_rodetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert receive order detail"); + exit; + } + $ro_detail_ID = $this->db->insert_id(); + + if (intval($obj['qty']) > 0) { + $qty = intval($obj['qty']); + for ($i = 0; $i < $qty; $i++) { + # generate nomor barcode # + $noBarcode = $this->generateNoBarcode($user, $param['lokasiID'], 'BNP', $obj['M_ItemID']); + + # INSERT INTO t_barcode_barang # + $sqlInsertBarcode = "INSERT INTO t_barcode_barang( + T_BarcodeBarangReceiveOrderPoID, + T_BarcodeBarangReceiveOrderPoDetailID, + T_BarcodeBarangRefType, + T_BarcodeBarangM_ItemID, + T_BarcodeBarangItemUnitID, + T_BarcodeBarangNumber, + T_BarcodeBarangM_RuanganID, + T_BarcodeBarangM_BranchID, + T_BarcodeBarangIsActive, + T_BarcodeBarangUserID, + T_BarcodeBarangCreated) VALUES(?,?,'PO',?,?,?,?,?,'Y',?,NOW())"; + $qryInsertBarcode = $this->db->query($sqlInsertBarcode, array( + $param['ReceiveOrderID'], + $ro_detail_ID, + $obj['M_ItemID'], + $obj['ItemUnitID'], + $noBarcode, + $param['lokasiID'], + $user['M_BranchID'], + $user['M_UserID'] + )); + if (!$qryInsertBarcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert data barcode item"); + exit; + } + } + } + + # INSERT form inspeksi item # + $inspekitem = $obj['inspeksi_item']; + $sql_insert_inspeksi = " INSERT INTO receive_order_po_inspeksi ( + ReceiveOrderPoInspeksiReceiveOrderPoDetailID, + ReceiveOrderPoInspeksiQtyPesan, + ReceiveOrderPoInspeksiQtyActual, + ReceiveOrderPoInspeksiPricePesan, + ReceiveOrderPoInspeksiPriceActual, + ReceiveOrderPoInspeksiDatePesan, + ReceiveOrderPoInspeksiDateActual, + ReceiveOrderPoInspeksiKeadaanKemasan, + ReceiveOrderPoInspeksiKeadaanKemasanNote, + ReceiveOrderPoInspeksiKondisiPengiriman, + ReceiveOrderPoInspeksiKondisiPengirimanNote, + ReceiveOrderPoInspeksiSimpulan, + ReceiveOrderPoInspeksiCatatan, + ReceiveOrderPoInspeksiStaffPenerimaID, + ReceiveOrderPoInspeksiPengirim, + ReceiveOrderPoInspeksiUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $que_insert_inspeksi = $this->db->query($sql_insert_inspeksi, [ + $ro_detail_ID, + $inspekitem['qty_po'], + $inspekitem['qty_ro'], + $inspekitem['price_po'], + $inspekitem['price_ro'], + $inspekitem['date_po'], + $inspekitem['date_ro'], + $inspekitem['condt_kemasan'], + $inspekitem['catatan_kemasan'], + $inspekitem['condt_pengiriman'], + $inspekitem['catatan_kirim'], + $inspekitem['summary'], + $inspekitem['catatan'], + $inspekitem['pemeriksa'], + $inspekitem['pengirim'], + $user['M_UserID'] + ]); + if (!$que_insert_inspeksi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert hasil form inspeksi"); + exit; + } + } + + # DELETE # + if (count($delete) > 0) { + $deleted_id = array_column($delete, 'ReceiveOrderPoDetailID'); + $placeholders = implode(', ', array_fill(0, count($deleted_id), '?')); + + $deleted_poid = array_column($delete, 'ReceiveOrderPoDetailPoItemReceiveID'); + $placeholders_po = implode(', ', array_fill(0, count($deleted_poid), '?')); + + # UPDATE po item receive # + $del_param = array_merge(array($user['M_UserID']), $deleted_poid, $deleted_id); + + $sql_up_po_receive = "UPDATE po_item_receive + JOIN receive_order_po_detail ON ReceiveOrderPoDetailPoItemReceiveID = PoItemReceiveID + SET PoItemReceiveQtyReceived = (PoItemReceiveQtyReceived - ReceiveOrderPoDetailQty), + PoItemReceiveUpdatedUserID = ? + WHERE PoItemReceiveID IN ($placeholders) + AND ReceiveOrderPoDetailID IN ($placeholders_po)"; + $que_up_po_receive = $this->db->query($sql_up_po_receive, $del_param); + if (!$que_up_po_receive) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update receive po item"); + exit; + } + + # UPDATE receive order po detail # + $upd_param = array_merge(array($user['M_UserID']), $deleted_id); + $sql_update_detail = "UPDATE receive_order_po_detail SET + ReceiveOrderPoDetailIsActive = 'N', + ReceiveOrderPoDetailDeleted = NOW(), + ReceiveOrderPoDetailDeletedUserID = ? + WHERE ReceiveOrderPoDetailID IN ($placeholders)"; + $que_update_detail = $this->db->query($sql_update_detail, $upd_param); + if (!$que_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status receive order detail"); + exit; + } + + # update status table form inspeksi # + $deleted_inspeksi = array_map(function ($item) { + if (isset($item['inspeksi_item']['ReceiveOrderPoInspeksiID'])) { + return $item['inspeksi_item']['ReceiveOrderPoInspeksiID']; + } + return null; + }, $delete); + $placeholders_inspeksi = implode(', ', array_fill(0, count($deleted_inspeksi), '?')); + $delinspeksi_param = array_merge($user['M_UserID'], $deleted_inspeksi); + + $sql_inspeksi_status = "UPDATE receive_order_po_inspeksi SET + ReceiveOrderPoInspeksiIsActive = 'N', + ReceiveOrderPoInspeksiUserID = ?, + ReceiveOrderPoInspeksiDeleted = NOW() + WHERE ReceiveOrderPoInspeksiID IN ($placeholders_inspeksi)"; + $que_inspeksi_status = $this->db->query($sql_inspeksi_status, $delinspeksi_param); + if (!$que_inspeksi_status) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status form receive item"); + exit; + } + + # update status barcode barang # + $sql_barcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangIsActive = 'N', + T_BarcodeBarangUserID = ?, + T_BarcodeBarangLastUpdated = NOW() + WHERE T_BarcodeBarangReceiveOrderPoDetailID IN ($placeholders)"; + $qry_barcode = $this->db->query($sql_barcode, $upd_param); + if (!$qry_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status barcode barang", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("Success"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function confirmRO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + $ROID = $param['ROID']; + + # GET DATA RO # + $json_ro_before = $this->getDataROPO($ROID); + $sql_ro = "SELECT + receive_order_po.*, + DATE_FORMAT(ReceiveOrderPoIDate, '%d-%m-%Y') AS formatedDate, + CASE + WHEN WarehouseType = 'B' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' + THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + WarehouseID + FROM receive_order_po + JOIN warehouse ON ReceiveOrderPoWarehouseID = WarehouseID + JOIN s_regional ON WarehouseS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON WarehouseM_BranchID = M_BranchID + AND M_BranchIsActive = 'Y' + WHERE ReceiveOrderPoID = ?"; + $que_ro = $this->db->query($sql_ro, [$ROID]); + if (!$que_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get data RO"); + exit; + } + $data_ro = $que_ro->row_array(); + if ($data_ro['ReceiveOrderPoConfirmed'] == 'Y') { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] item dari RO{$data_ro['ReceiveOrderPoNumber']} sudah pernah di konfirmasi"); + exit; + } + + $sql_detail_ro = "SELECT + receive_order_po_detail.*, + PurchaseOrderID, + PurchaseOrderNumber, + PurchaseOrderTaxPercentPph, + PurchaseOrderTaxPercentPpn, + PurchaseOrderSummaryDiscountAmount as DiscountPerItem, + PurchaseOrderSummaryQty as QtyAllPO, + PurchaseOrderSummaryTotal as TotalAllPO, + PurchaseOrderDiscountPercent AS DiscPOPercent, + PurchaseOrderDiscountAmount AS DiscPORupiah + FROM receive_order_po_detail + JOIN purchase_order ON ReceiveOrderPoDetailPurchaseOrderID = PurchaseOrderID + JOIN purchase_order_summary ON ReceiveOrderPoDetailPurchaseOrderSummaryID = PurchaseOrderSummaryID + AND PurchaseOrderSummaryIsActive = 'Y' + WHERE ReceiveOrderPoDetailReceiveOrderPoID = ? + AND ReceiveOrderPoDetailIsActive='Y' + GROUP BY ReceiveOrderPoDetailID"; + $que_detail_ro = $this->db->query($sql_detail_ro, [$ROID]); + if (!$que_detail_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get detail data ro"); + exit; + } + $data_detail_ro = $que_detail_ro->result_array(); + + # UPDATE STATUS RO # + $sql_update_ro = "UPDATE receive_order_po SET + ReceiveOrderPoConfirmed = 'Y', + ReceiveOrderPoConfirmedDate = NOW(), + ReceiveOrderPoConfirmedUserID = ? + WHERE ReceiveOrderPoID = ?"; + $que_update_ro = $this->db->query($sql_update_ro, [$user['M_UserID'], $ROID]); + if (!$que_update_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get update status ro"); + exit; + } + + # PREPARE DATA FOR JURNAL # + $sql_jrnl_num = "SELECT `fn_numbering`('J') AS numbering"; + $que_jrnl_num = $this->db->query($sql_jrnl_num, []); + if (!$que_jrnl_num) { + $this->sys_error_db("[Error] generate jurnal number"); + $this->db->trans_rollback(); + exit; + } + $jurnal_number = $que_jrnl_num->row_array()['numbering']; + + $sql_periode = "SELECT periodeID FROM periode + WHERE DATE(NOW()) BETWEEN periodeStartDate AND periodeEndDate + AND periodeIsActive= 'Y' AND periodeIsClosed = 'N'"; + $que_periode = $this->db->query($sql_periode, []); + if (!$que_periode) { + $this->sys_error_db("[Error] get periode", $this->db); + $this->db->trans_rollback(); + exit; + } + if ($que_periode->num_rows() === 0) { + $this->sys_error_db("[Error] waktu periode tidak ditemukan", $this->db); + $this->db->trans_rollback(); + exit; + } + $jurnal_periode = $que_periode->row_array()['periodeID']; + + $sql_jrnl_type = "SELECT JurnalTypeID FROM jurnal_type WHERE JurnalTypeCode = ? AND JurnalTypeIsActive = 'Y'"; + $que_jrnl_type = $this->db->query($sql_jrnl_type, ['AUTOGOODRECEIVE']); + if (!$que_jrnl_type) { + $this->sys_error_db("[Error] get jurnal type", $this->db); + $this->db->trans_rollback(); + exit; + } + if ($que_jrnl_type->num_rows() === 0) { + $this->sys_error_db("[Error] tipe jurnal tidak ditemukan", $this->db); + $this->db->trans_rollback(); + exit; + } + $jurnal_type = $que_jrnl_type->row_array()['JurnalTypeID']; + + $list_po_in_ro = array_column($data_detail_ro, 'PurchaseOrderNumber'); + $str_po = implode(', ', array_unique($list_po_in_ro)); + + $jurnal_title = "Jurnal Penerimaan Barang Dari PO {$str_po} Tanggal {$data_ro['formatedDate']}"; + $jurnal_desc = $jurnal_title . " Dengan Nomor DO {$data_ro['ReceiveOrderPoDONumber']} Di {$data_ro['WarehouseName']}"; + + # INSERT JURNAL HEADER # + $sql_head_jurnal = "INSERT INTO jurnal ( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalM_UserID + ) VALUES (?,?,?,?,?,?,?,NOW(),?,?)"; + $que_head_jurnal = $this->db->query($sql_head_jurnal, [ + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + $user['M_BranchCode'], + $jurnal_periode, + $jurnal_number, + $jurnal_title, + $jurnal_desc, + $jurnal_type, + $user['M_UserID'] + ]); + if (!$que_head_jurnal) { + $this->sys_error_db("[Error] insert header jurnal", $this->db); + $this->db->trans_rollback(); + exit; + } + $jurnal_ID = $this->db->insert_id(); + + $total_debet = 0.00; + $total_discount_item = 0.00; + $total_discount_po = 0.00; + $each_desc = []; + + foreach ($data_detail_ro as $key => $detail) { + # UPDATE PO Summary # + $sql_posummary = "UPDATE purchase_order_summary SET + PurchaseOrderSummaryQtyReceived = PurchaseOrderSummaryQtyReceived + ? + WHERE PurchaseOrderSummaryIsActive = 'Y' + AND PurchaseOrderSummaryID = ?"; + $que_posummary = $this->db->query($sql_posummary, [ + intval($detail['ReceiveOrderPoDetailQty']), + $detail['ReceiveOrderPoDetailPurchaseOrderSummaryID'] + ]); + if (!$que_posummary) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update qty received po summary"); + exit; + } + + $sql_cek_item = "SELECT * FROM m_item WHERE M_ItemID = ?"; + $que_cek_item = $this->db->query($sql_cek_item, [$detail['ReceiveOrderPoItemID']]); + if (!$que_cek_item) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] cek item received"); + exit; + } + $item_cek = $que_cek_item->row_array(); + if (empty($item_cek['M_ItemItem_CategoryID'])) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] kategori item {$item_cek['M_ItemDesc']} tidak ditemukan pada PO + {$detail['PurchaseOrderNumber']}"); + exit; + } + + # INSERT JURNAL TX # + if (intval($item_cek['M_ItemItem_CategoryID']) == 2) { + if (empty($item_cek['M_ItemNat_SubGroupID'])) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] subgroup item {$item_cek['M_ItemDesc']} tidak ditemukan pada PO + {$detail['PurchaseOrderNumber']}"); + exit; + } + + $sql_item_group = "SELECT * FROM map_nat_subgroup + WHERE MapNatSub_NatGroupID = ? + AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y'"; + $que_item_group = $this->db->query($sql_item_group, [ + $item_cek['M_ItemNat_GroupID'], + $item_cek['M_ItemNat_SubGroupID'] + ]); + if (!$que_item_group) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get item group/subgroup"); + exit; + } + $item_group = $que_item_group->row_array(); + if ( + empty($item_group['MapNatSub_BiayaCoaID']) || + empty($item_group['MapNatSub_BiayaCoaAccountNo']) || + empty($item_group['MapNatSub_BiayaCoaDescription']) + ) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] Account inventory item {$item_cek['M_ItemDesc']} tidak ditemukan"); + exit; + } + + $debet = doubleval($detail['ReceiveOrderPoDetailTotal']); + $total_debet = round($total_debet + $debet, 2); + + # INSERT JURNAL TX DEBET # + $sql_tx_jurnal = "INSERT INTO jurnal_tx ( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID + ) VALUES (?,?,?,?,?,?)"; + $que_tx_jurnal = $this->db->query($sql_tx_jurnal, [ + $jurnal_ID, + $item_group['MapNatSub_BiayaCoaID'], + $item_group['MapNatSub_BiayaCoaDescription'], + $debet, + 0, + $user['M_UserID'] + ]); + if (!$que_tx_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] failed insert jurnal tx {$item_cek['M_ItemDesc']} + PO {$detail['PurchaseOrderNumber']}"); + exit; + } + $juranl_tx_ID = $this->db->insert_id(); + $each_desc[] = "- Add detail Jurnal debet {$item_cek['M_ItemDesc']} + {$item_group['MapNatSub_BiayaCoaDescription']} sejumlah {$this->formatRupiah($debet)}"; + + # INSERT JURNAL ADDON # + $sql_addon_jurnal = "INSERT INTO jurnal_addon ( + jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnM_ItemID, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID + ) VALUES (?,?,'PONUMB',?,?,NOW(),?)"; + $que_addon_jurnal = $this->db->query($sql_addon_jurnal, [ + $jurnal_ID, + $juranl_tx_ID, + $detail['PurchaseOrderNumber'], + $detail['ReceiveOrderPoItemID'], + $user['M_UserID'] + ]); + if (!$que_addon_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] failed insert jurnal addon {$item_cek['M_ItemDesc']} + PO {$detail['PurchaseOrderNumber']}"); + exit; + } + + # INSERT JURNAL TX KREDIT DISKON # + $sql_po = "SELECT + SUM(subquery.PurchaseOrderSummaryQty) as totalAllQtyPO, + SUM(subquery.PurchaseOrderSummaryTotal) as totalAllPricePO + FROM ( + SELECT + PurchaseOrderSummaryQty, + PurchaseOrderSummaryTotal + FROM receive_order_po_detail + JOIN purchase_order_summary ON PurchaseOrderSummaryPurchaseOrderID = ReceiveOrderPoDetailPurchaseOrderID + AND PurchaseOrderSummaryIsActive = 'Y' + WHERE ReceiveOrderPoDetailReceiveOrderPoID = ? + GROUP BY PurchaseOrderSummaryID + ) as subquery"; + $que_po = $this->db->query($sql_po, [$ROID]); + if (!$que_po) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get detail total qty and price of item po"); + exit; + } + $data_po = $que_po->row_array(); + + // calc diskon per item + $diskon = round(intval($detail['ReceiveOrderPoDetailQty'] * doubleval($detail['DiscountPerItem'])), 2); + $total_discount_item = round($total_discount_item + $diskon, 2); + + // calc diskon prorata PO untuk item + $diskon_po = doubleval($detail['DiscPORupiah']); + if (doubleval($detail['DiscPOPercent']) != 0.00) { + $diskon_po = doubleval($data_po['totalAllPricePO']) * doubleval($detail['DiscPOPercent']) / 100; + } + $diskon_prorata_po = $diskon_po * (doubleval($detail['TotalAllPO'])) / doubleval($data_po['totalAllPricePO']); + $diskon_prorata_item = round((intval($detail['ReceiveOrderPoDetailQty']) / intval($detail['QtyAllPO'])) * $diskon_prorata_po, 2); + + $total_discount_po = round($total_discount_po + $diskon_prorata_item, 2); + $input_diskon = [$diskon, $diskon_prorata_item]; + + // get account coa diskon + $sql_coa_disc = "SELECT * FROM coa WHERE coaAccountNo = ? LIMIT 1"; + $que_coa_disc = $this->db->query($sql_coa_disc, ['2190100001']); + if (!$que_coa_disc) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get account diskon"); + exit; + } + $coa_diskon = $que_coa_disc->row_array(); + + foreach ($input_diskon as $kkey => $value) { + if (doubleval($value) === 0.00) { + continue; + } + $que_tx_jurnal = $this->db->query($sql_tx_jurnal, [ + $jurnal_ID, + $coa_diskon['coaID'], + $coa_diskon['coaDescription'], + 0, + $value, + $user['M_UserID'] + ]); + if (!$que_tx_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] failed insert jurnal tx diskon + item {$item_cek['M_ItemDesc']} PO {$detail['PurchaseOrderNumber']}"); + exit; + } + $juranl_txdisc_ID = $this->db->insert_id(); + $que_addon_jurnal = $this->db->query($sql_addon_jurnal, [ + $jurnal_ID, + $juranl_txdisc_ID, + $detail['PurchaseOrderNumber'], + $user['M_UserID'] + ]); + if (!$que_addon_jurnal) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] failed insert jurnal addon diskon + item {$item_cek['M_ItemDesc']} PO {$detail['PurchaseOrderNumber']}"); + exit; + } + } + + // save diskon prorata + $sql_save_diskon = "UPDATE receive_order_po_detail SET + ReceiveOrderPoDetailDiskonPoProrata = ? + WHERE ReceiveOrderPoDetailID = ?"; + $que_save_diskon = $this->db->query($sql_save_diskon, [ + $diskon_prorata_item, + $detail['ReceiveOrderPoDetailID'] + ]); + if (!$que_save_diskon) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] save diskon prorata + item {$item_cek['M_ItemDesc']} PO {$detail['PurchaseOrderNumber']}"); + exit; + } + } else { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] BE Jurnal tipe selain Inventory tidak ada"); + exit; + } + + # HANDLE STOCK UPDATE # + // decode batchlist item diterima + $json_batch_item = $detail['ReceiveOrderPoDetailBatchList']; + $batch_list = []; + if (!empty($json_batch_item)) { + $decode = json_decode($json_batch_item, true); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batch_list = $decode; + } else { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] decode json for batches number"); + exit; + } + } + + // update stock based on batch + foreach ($batch_list as $key => $batch) { + $sql_cek_stock = "SELECT * + FROM stock s + JOIN m_item i ON s.StockItemID = i.M_ItemID + WHERE s.StockItemID = ? + AND s.StockItemUnitID = ? + AND s.StockWarehouseID = ? + AND i.M_ItemItem_CategoryID = ?"; + $que_cek_stock = $this->db->query($sql_cek_stock, [ + $detail['ReceiveOrderPoItemID'], + $detail['ReceiveOrderPoItemUnitID'], + $data_ro['WarehouseID'], + $batch['item_category'] + ]); + if (!$que_cek_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] check stock exist or not"); + exit; + } + $stock_exist = $que_cek_stock->row_array(); + $stock_ID = $stock_exist['StockID']; + $stock_qty_ori = intval($stock_exist['StockQty']); + $stock_price = doubleval($stock_exist['StockItemPrice']); + $stock_qty_end = 0; + + if (!empty($stock_exist)) { + // calc new prive average + $stock_qty_end = $stock_qty_ori + intval($batch['qty']); + $all_price = ($stock_qty_ori * $stock_price) + (intval($batch['qty']) * doubleval($detail['ReceiveOrderPoDetailPrice'])); + $avg_prive = round($all_price / $stock_qty_end, 2); + + $sql_update_stock = "UPDATE stock SET + StockItemPrice = ?, + StockQty = ?, + StockLastUpdated = NOW(), + StockUserID = ? + WHERE StockID = ?"; + $que_update_stock = $this->db->query($sql_update_stock, [ + $avg_prive, + $stock_qty_end, + $user['M_UserID'], + $stock_ID + ]); + if (!$que_update_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert update stock"); + exit; + } + + // insert stockid barcode barang + $sql_update_barcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangStockID = ? + WHERE T_BarcodeBarangReceiveOrderPoDetailID = ?"; + $qry_update_barcode = $this->db->query($sql_update_barcode, [ + $stock_ID, + $detail['ReceiveOrderPoDetailID'] + ]); + if (!$qry_update_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update barcode stockID", $this->db); + exit; + } + } else { + $sql_insert_stock = "INSERT INTO stock ( + StockWarehouseAlmariID, + StockWarehouseRackID, + StockWarehouseID, + StockStockNumber, + StockItemID, + StockItemUnitID, + StockItemPrice, + StockQty, + StockLastUpdated, + StockUserID + ) VALUES (0,0,?,fn_numbering('SN'),?,?,?,?,NOW(),?)"; + $que_insert_stock = $this->db->query($sql_insert_stock, [ + $data_ro['WarehouseID'], + $detail['ReceiveOrderPoItemID'], + $detail['ReceiveOrderPoItemUnitID'], + $detail['ReceiveOrderPoDetailPrice'], + $batch['qty'], + $user['M_UserID'] + ]); + if (!$que_insert_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert new batch stock"); + exit; + } + + $stockID = $this->db->insert_id(); + $stock_qty_ori = 0; + $stock_qty_end = intval($batch['qty']); + + // insert stockid barcode barang + $sql_update_barcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangStockID = ? + WHERE T_BarcodeBarangReceiveOrderPoDetailID = ?"; + $qry_update_barcode = $this->db->query($sql_update_barcode, [ + $stockID, + $detail['ReceiveOrderPoDetailID'] + ]); + if (!$qry_update_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update barcode stockID", $this->db); + exit; + } + } + + // insert stock card + $sql_stock_card = "INSERT INTO stockcard ( + StockCardWarehouseID, + StockCardDatetime, + StockCardItemID, + StockCardItemUnitID, + StockCardReffID, + StockCardStatus, + StockCardBefore, + StockCardIn, + StockCardOut, + StockCardAfter, + StockCardUserID + ) VALUES (?, NOW(), ?, ?, ?, 'PRV', ?, ?, 0, ?, ?)"; + $que_stock_card = $this->db->query($sql_stock_card, [ + $data_ro['WarehouseID'], + $detail['ReceiveOrderPoItemID'], + $detail['ReceiveOrderPoItemUnitID'], + $stock_ID, + $stock_qty_ori, + $batch['qty'], + $stock_qty_end, + $user['M_UserID'] + ]); + if (!$que_stock_card) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert stock card"); + exit; + } + + // insert stock log + $sql_stock = "SELECT * FROM stock WHERE StockID = ?"; + $que_stock = $this->db->query($sql_stock, [$stock_ID]); + if (!$que_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest stock"); + exit; + } + $stock_latest = $que_stock->row_array(); + + $sql_stock_log = "INSERT INTO stocklog ( + StockLogWarehouseID, + StockLogDateTime, + StockLogItemID, + StockLogItemUnitID, + StockLogStockNumber, + StockLogReffID, + StockLogStatus, + StockLogQty, + StockLogUserID + ) VALUES (?, NOW(), ?, ?, ?, ?, 'PRV', ?, ?)"; + $que_stock_log = $this->db->query($sql_stock_log, [ + $data_ro['WarehouseID'], + $detail['ReceiveOrderPoItemID'], + $detail['ReceiveOrderPoItemUnitID'], + $stock_latest['StockStockNumber'], + $stock_ID, + $batch['qty'], + $user['M_UserID'] + ]); + if (!$que_stock_log) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get latest stock"); + exit; + } + } + } + + # insert shipping cost ke jurnal # + $ship_cost = round(doubleval($data_ro['ReceiveOrderShippingCostAmount']), 2); + if ($ship_cost > 0.00) { + $sql_tx_ship = "INSERT INTO jurnal_tx ( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID + ) SELECT ?, coaID, coaDescription, ?, 0, ? + FROM coa WHERE coaAccountNo = '5320700001' LIMIT 1"; + $que_tx_ship = $this->db->query($sql_tx_ship, [$jurnal_ID, $ship_cost, $user['M_UserID']]); + if (!$que_tx_ship) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal tx shipping cost"); + exit; + } + } + + // insert jurnal tx for GRNI + $total_grni = round($total_debet - ($total_discount_item + $total_discount_po), 2) + $ship_cost; + $sql_grni = "INSERT INTO jurnal_tx ( + jurnalTxJurnalID, + jurnalTxCoaID, + jurnalTxDescription, + jurnalTxDebit, + jurnalTxCredit, + jurnalTxM_UserID + ) SELECT ?, coaID, coaDescription, 0, ?, ? + FROM coa WHERE coaAccountNo = '2110100030' LIMIT 1"; + $que_grni = $this->db->query($sql_grni, [$jurnal_ID, $total_grni, $user['M_UserID']]); + if (!$que_grni) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal tx GRNI"); + exit; + } + $grni_jurnal_id = $this->db->insert_id(); + + $sql_addon_grni = "INSERT INTO jurnal_addon ( + jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID + ) VALUES (?,?,'RONUMB',?,NOW(),?)"; + $que_addon_grni = $this->db->query($sql_addon_grni, [ + $jurnal_ID, + $grni_jurnal_id, + $data_ro['ReceiveOrderPoNumber'], + $user['M_UserID'] + ]); + if (!$que_addon_grni) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert jurnal addon GRNI"); + exit; + } + + # insert into shipping table # + $sql_rec_ship = "INSERT INTO receive_order_po_shipping ( + ReceiveOrderPoShippingPurchaseOrderID, + ReceiveOrderPoShippingReceiveOrderPoID, + ReceiveOrderPoShippingAmount, + ReceiveOrderPoShippingStatus, + ReceiveOrderPoShippingIsActive, + ReceiveOrderPoShippingCreatedUserID + ) SELECT + PurchaseOrderID, + {$ROID}, + PurchaseOrderShippingCost, + PurchaseOrderShippingCostStatus, + 'Y', + {$user['M_UserID']} + FROM purchase_order + WHERE PurchaseOrderID IN ( + SELECT DISTINCT ReceiveOrderPoDetailPurchaseOrderID + FROM receive_order_po + JOIN receive_order_po_detail ON ReceiveOrderPoDetailReceiveOrderPoID = ReceiveOrderPoID + WHERE ReceiveOrderPoID = {$user['M_UserID']} + ) + AND PurchaseOrderShippingCost IS NOT NULL + AND PurchaseOrderShippingCost > 0"; + $que_rec_ship = $this->db->query($sql_rec_ship, []); + if (!$que_rec_ship) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table shipping cost"); + exit; + } + + # LOG # + $desc = "Konfirmasi penerimaan barang {$data_ro['ReceiveOrderPoNumber']} Tanggal {$data_ro['formatedDate']} + di {$data_ro['WarehouseName']} yang meliputi beberapa item dari PO {$str_po}"; + $log_desc = $desc . "\n" . implode("\n", $each_desc); + + $json_ro_after = $this->getDataROPO($ROID); + $this->insertLogReceiveOrderPo($ROID, 'CONFIRM', $json_ro_before, $json_ro_after, $user['M_UserID'], $log_desc); + $this->insertUserActivty($ROID, 'RO', 'CONFIRM', $user['M_UserID'], $log_desc); + + # GENERATE PURCHASE INVOICE # + $this->generatePurchaseInvoice($user, $ROID, $total_grni, $total_discount_po, $ship_cost); + + $this->db->trans_commit(); + $this->sys_ok("[Success] Berhasil konfirmasi terima barang"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteRO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $ROID = $param['ROID']; + + # data before fo logging # + $json_ro_before = $this->getDataROPO($ROID); + + # update status header RO # + $sql = "UPDATE receive_order_po SET + ReceiveOrderPoIsActive = 'N', + ReceiveOrderPoDeleted = NOW(), + ReceiveOrderPoDeletedUserID = ? + WHERE ReceiveOrderPoID = ?"; + $que = $this->db->query($sql, [$user['M_UserID'], $ROID]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] delete receive oder"); + exit; + } + + $sql_detail = "SELECT * FROM receive_order_po_detail + WHERE ReceiveOrderPoDetailReceiveOrderPoID = ? + AND ReceiveOrderPoDetailIsActive = 'Y'"; + $que_detail = $this->db->query($sql_detail, [$ROID]); + if (!$que_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get detail RO "); + exit; + } + $details = $que_detail->result_array(); + + # update status detail RO # + foreach ($details as $key => $detail) { + # update receive detail po # + $sql_update_detail = "UPDATE receive_order_po_detail SET + ReceiveOrderPoDetailIsActive = 'N', + ReceiveOrderPoDetailDeletedUserID = ?, + ReceiveOrderPoDetailDeleted = NOW() + WHERE ReceiveOrderPoDetailID = ?"; + $que_update_detail = $this->db->query($sql_update_detail, [ + $user['M_UserID'], + $detail['ReceiveOrderPoDetailID'] + ]); + if (!$que_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status detail RO"); + exit; + } + + # update status form inspeksi # + $sql_inspeksi = "UPDATE receive_order_po_inspeksi SET + ReceiveOrderPoInspeksiIsActive = 'N' + WHERE ReceiveOrderPoInspeksiReceiveOrderPoDetailID = ? "; + $que_inspeksi = $this->db->query($sql_inspeksi, [$detail['ReceiveOrderPoDetailID']]); + if (!$que_inspeksi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status form inspeksi"); + exit; + } + + # update status barcode barang # + $sql_barcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangIsActive = 'N', + T_BarcodeBarangUserID = ?, + T_BarcodeBarangLastUpdated = NOW() + WHERE T_BarcodeBarangReceiveOrderPoDetailID = ?"; + $qry_barcode = $this->db->query($sql_barcode, [ + $user['M_UserID'], + $detail['ReceiveOrderPoDetailID'] + ]); + if (!$qry_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status barcode barang", $this->db); + exit; + } + + # update po item receive # + $json_po_before = $this->getPOItemReceived($detail['ReceiveOrderPoDetailPoItemReceiveID']); + $sql_upd_po_received = "UPDATE po_item_receive + JOIN receive_order_po_detail ON PoItemReceiveID = ReceiveOrderPoDetailPoItemReceiveID + AND ReceiveOrderPoDetailReceiveOrderPoID = ? + AND ReceiveOrderPoDetailID = ? + SET PoItemReceiveQtyReceived = PoItemReceiveQtyReceived - ReceiveOrderPoDetailQty, + PoItemReceiveUpdatedUserID = ? + WHERE PoItemReceiveID = ?"; + $que_upd_po_received = $this->db->query($sql_upd_po_received, [ + $ROID, + $detail['ReceiveOrderPoDetailID'], + $user['M_UserID'], + $detail['ReceiveOrderPoDetailPoItemReceiveID'] + ]); + if (!$que_upd_po_received) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update qty PO item received"); + exit; + } + $json_po_after = $this->getPOItemReceived($detail['ReceiveOrderPoDetailPoItemReceiveID']); + $descItem = "Dihapus {$detail['M_ItemDesc']} sejumlah {$detail['ReceiveOrderPoDetailQty']} + {$detail['ItemUnitName']} di RO nomor {$json_ro_before['ReceiveOrderPoNumber']} + *RO belum di konfirmasi"; + + # log # + $this->insertLogPoItemReceive( + $detail['ReceiveOrderPoDetailPoItemReceiveID'], + 'UPDATE', + $ROID, + $json_po_before, + $json_po_after, + $user['M_UserID'], + $descItem + ); + } + + $json_ro_after = $this->getDataROPO($ROID); + $this->insertLogReceiveOrderPo( + $ROID, + 'DELETE', + $json_ro_before, + $json_ro_after, + $user['M_UserID'], + "Update data RO ID: {$ROID}" + ); + + $this->insertUserActivty($ROID, 'RO', 'DELETE', $user['M_UserID'], "Update data RO ID: {$ROID}"); + + $this->db->trans_commit(); + $this->sys_ok("[Success]"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveInspeksi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $user = $this->sys_user; + + # Prepare Data # + $inspeksi = $param['form_inspeksi']; + $ROdetailID = $param['ROdetailID']; + + # Insert Query # + $this->db->trans_begin(); + + $sql_insert = "INSERT INTO receive_order_po_inspeksi ( + ReceiveOrderPoInspeksiReceiveOrderPoDetailID, + ReceiveOrderPoInspeksiQtyPesan, + ReceiveOrderPoInspeksiQtyActual, + ReceiveOrderPoInspeksiPricePesan, + ReceiveOrderPoInspeksiPriceActual, + ReceiveOrderPoInspeksiDatePesan, + ReceiveOrderPoInspeksiDateActual, + ReceiveOrderPoInspeksiExpireDate, + ReceiveOrderPoInspeksiKeadaanKemasan, + ReceiveOrderPoInspeksiKondisiPengiriman, + ReceiveOrderPoInspeksiSimpulan, + ReceiveOrderPoInspeksiCatatan, + ReceiveOrderPoInspeksiStaffPenerima, + ReceiveOrderPoInspeksiStaffPengirim, + ReceiveOrderPoInspeksiUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $que_insert = $this->db->query($sql_insert, [ + $ROdetailID, + $inspeksi['qty_po'], + $inspeksi['qty_ro'], + $inspeksi['price_po'], + $inspeksi['price_ro'], + $inspeksi['date_po'], + $inspeksi['date_ro'], + $inspeksi['expire_date'], + $inspeksi['condt_kemasan'], + $inspeksi['condt_pengiriman'], + $inspeksi['summary'], + $inspeksi['catatan'], + $inspeksi['pemeriksa'], + $inspeksi['pengirim'], + $user['M_UserID'] + ]); + if (!$que_insert) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table receiec order po inspeksi"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] save inspeksi item"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function generateItemPO() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $param = $this->sys_input; + $userid = $this->sys_user; + $POID = $param['id']; + + if (!isset($POID)) { + $this->sys_error("Missing required parameters"); + exit; + } + + $this->db->trans_begin(); + + $sql_po = "SELECT * FROM purchase_order WHERE PurchaseOrderID = ?"; + $que_po = $this->db->query($sql_po, [$POID]); + if (!$que_po) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get data PO"); + exit; + } + $data_po = $que_po->row_array(); + + if ($data_po['PurchaseOrderStatus'] != 'Approved') { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] status PO belum Approved"); + exit; + } + + $data_detail = []; + + if (strtolower($data_po['PurchaseOrderWarehouseType']) == 'single') { + $sql_POdetail = "SELECT + IFNULL(pir.PoItemReceiveID, 0) as receivedID, + IFNULL(pir.PoItemReceiveQtyReceived, 0) as qtyReceived, + pos.PurchaseOrderSummaryID as orderSummaryID, + pos.PurchaseOrderSummaryItemID as itemID, + pos.PurchaseOrderSummaryItemUnitID as itemUnitID, + pos.PurchaseOrderSummaryQty as qty, + pos.PurchaseOrderSummaryPrice as price, + m_itemDesc as itemName, + ItemUnitName as itemUnitName, + PurchaseOrderDetailID + FROM purchase_order_summary pos + JOIN purchase_order_detail ON PurchaseOrderDetailPurchaseOrderID = pos.PurchaseOrderSummaryPurchaseOrderID + AND PurchaseOrderSummaryItemID = PurchaseOrderDetailItemID + AND PurchaseOrderSummaryItemUnitID = PurchaseOrderDetailItemUnitID + JOIN m_item ON pos.PurchaseOrderSummaryItemID = M_ItemID + JOIN itemunit ON pos.PurchaseOrderSummaryItemUnitID = ItemUnitID + LEFT JOIN po_item_receive pir ON pos.PurchaseOrderSummaryPurchaseOrderID = pir.PoItemReceivePurchaseOrderID + AND pos.PurchaseOrderSummaryItemID = pir.PoItemReceiveItemID + WHERE pos.PurchaseOrderSummaryPurchaseOrderID = ? + AND pos.PurchaseOrderSummaryIsActive = 'Y' + AND IFNULL(pir.PoItemReceiveQtyReceived, 0) = 0"; + $que_POdetail = $this->db->query($sql_POdetail, [$POID]); + if (!$que_POdetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get data detail PO"); + exit; + } + $data_detail = $que_POdetail->result_array(); + + foreach ($data_detail as $key => $obj) { + if (intval($obj['PoItemReceiveID']) == 0) { + $sql_ins = "INSERT INTO po_item_receive ( + PoItemReceivePurchaseOrderID, + PoItemReceivePurchaseOrderSummaryID, + PoItemReceivePurchaseOrderDetailID, + PoItemReceiveWarehouseID, + PoItemReceiveItemID, + PoItemReceiveItemUnitID, + PoItemReceiveQty, + PoItemReceiveQtyReceived, + PoItemReceiveIsActive, + PoItemReceiveCreated, + PoItemReceiveCreatedUserID, + PoItemReceivePrice + ) VALUES (?,?,?,?,?,?,?,0,'Y',NOW(),?,?)"; + $que_ins = $this->db->query($sql_ins, [ + $POID, + $obj['orderSummaryID'], + $obj['PurchaseOrderDetailID'], + $data_po['PurchaseOrderWarehouseID'], + $obj['itemID'], + $obj['itemUnitID'], + $obj['qty'], + $userid, + $obj['price'] + ]); + if (!$que_ins) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert po item receive"); + exit; + } + $insertedID = $this->db->insert_id(); + + $desc = "ADD {$obj['itemName']} {$obj['qty']} {$obj['itemUnitName']} {$data_po['WarehouseName']}"; + $jsonAfter = $this->getPOItemReceived($insertedID); + $this->insertLogPoItemReceive($insertedID, 'ADD', 0, '', $jsonAfter, $userid, $desc); + } else { + $jsonBefore = $this->getPOItemReceived($obj['PoItemReceiveID']); + $sql_upd = "UPDATE po_item_receive SET + PoItemReceiveQty = ?, + PoItemReceiveIsActive = 'Y', + PoItemReceiveUpdate = NOW(), + PoItemReceiveUpdatedUserID = ?, + PoItemReceiveWarehouseID = ?, + PoItemReceiveItemUnitID = ?, + PoItemReceivePrice = ? + WHERE PoItemReceiveID = ?"; + $que_upd = $this->db->query($sql_upd, [ + $obj['qty'], + $userid, + $data_po['PurchaseOrderWarehouseID'], + $obj['itemUnitID'], + $obj['price'], + $obj['receivedID'] + ]); + if (!$que_upd) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update po item receive"); + exit; + } + + $jsonAfter = $this->getPOItemReceived($obj['PoItemReceiveID']); + $desc = "UPDATE {$obj['itemName']} {$obj['qty']} {$obj['itemUnitName']} {$data_po['WarehouseName']}"; + $this->insertLogPoItemReceive($obj['PoItemReceiveID'], 'UPDATE', 0, $jsonBefore, $jsonAfter, $userid, $desc); + } + } + } + + if (strtolower($data_po['PurchaseOrderWarehouseType']) == 'multiple') { + $sql_det = "SELECT + IFNULL(PoItemReceiveID, 0) as cekID, + IFNULL(PoItemReceiveQtyReceived, 0) as qtyCek, + pod.PurchaseOrderDetailPurchaseSummaryID as summaryID, + pod.PurchaseOrderDetailID as poDetailID, + pod.PurchaseOrderDetailWarehouseID as warehouseID, + WarehouseName, + pod.PurchaseOrderDetailItemID as itemID, + M_ItemDesc as itemName, + pos.PurchaseOrderSummaryItemUnitID as itemUnitID, + ItemUnitName as itemUnitName, + ConvertQuantityToPurchasedItemUnit( + pod.PurchaseOrderDetailItemID, + pod.PurchaseOrderDetailItemUnitID, + pod.PurchaseOrderDetailQty + ) as poQty, + pos.PurchaseOrderSummaryPrice as price + FROM purchase_order_detail pod + JOIN purchase_order_summary pos ON pod.PurchaseOrderDetailPurchaseSummaryID = pos.PurchaseOrderSummaryID + JOIN m_item ON pod.PurchaseOrderDetailItemID = M_ItemID + JOIN itemunit ON pos.PurchaseOrderSummaryItemUnitID = ItemUnitID + JOIN warehouse ON pod.PurchaseOrderDetailWarehouseID = WarehouseID + LEFT JOIN po_item_receive p ON p.PoItemReceiveItemID = pod.PurchaseOrderDetailItemID + AND p.PoItemReceivePurchaseOrderID = ? + AND p.PoItemReceivePurchaseOrderSummaryID = pos.PurchaseOrderSummaryID + AND p.PoItemReceivePurchaseOrderDetailID = pod.PurchaseOrderDetailID + WHERE pod.PurchaseOrderDetailPurchaseOrderID = ? + AND IFNULL(PoItemReceiveQtyReceived, 0) = 0 + AND pod.PurchaseOrderDetailIsActive = 'Y'"; + $que_det = $this->db->query($sql_det, [$POID, $POID]); + if (!$que_det) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get item"); + exit; + } + $data_detail = $que_det->result_array(); + + foreach ($data_detail as $key => $obj) { + if (intval($obj['cekID']) == 0) { + $sql_ins = "INSERT INTO po_item_receive ( + PoItemReceivePurchaseOrderID, + PoItemReceivePurchaseOrderSummaryID, + PoItemReceivePurchaseOrderDetailID, + PoItemReceiveWarehouseID, + PoItemReceiveItemID, + PoItemReceiveItemUnitID, + PoItemReceiveQty, + PoItemReceiveQtyReceived, + PoItemReceiveIsActive, + PoItemReceiveCreated, + PoItemReceiveCreatedUserID, + PoItemReceivePrice + ) VALUES (?,?,?,?,?,?,?,0,'Y',NOW(),?,?)"; + $que_ins = $this->db->query($sql_ins, [ + $POID, + $obj['summaryID'], + $obj['poDetailID'], + $obj['warehouseID'], + $obj['itemID'], + $obj['itemUnitID'], + $obj['poQty'], + $userid, + $obj['price'] + ]); + if (!$que_ins) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert po item receive multiple wh"); + exit; + } + $insertedID = $this->db->insert_id(); + + $desc = "ADD {$obj['itemName']} {$obj['poQty']} {$obj['itemUnitName']} {$obj['WarehouseName']}"; + $jsonAfter = $this->getPOItemReceived($insertedID); + $this->insertLogPoItemReceive($insertedID, 'ADD', 0, '', $jsonAfter, $userid, $desc); + } else { + $jsonBefore = $this->getPOItemReceived($obj['cekID']); + + $sql_upd = "UPDATE po_item_receive SET + PoItemReceiveQty = ?, + PoItemReceiveIsActive = 'Y', + PoItemReceiveUpdate = NOW(), + PoItemReceiveUpdatedUserID = ?, + PoItemReceiveWarehouseID = ?, + PoItemReceiveItemUnitID = ?, + PoItemReceivePrice = ? + WHERE PoItemReceiveID = ?"; + $que_upd = $this->db->query($sql_upd, [ + $obj['poQty'], + $userid, + $obj['warehouseID'], + $obj['itemUnitID'], + $obj['price'], + $obj['cekID'] + ]); + if (!$que_upd) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update po item receive multiple wh"); + exit; + } + + $desc = "ADD {$obj['itemName']} {$obj['poQty']} {$obj['itemUnitName']} {$obj['WarehouseName']}"; + $jsonAfter = $this->getPOItemReceived($obj['cekID']); + $this->insertLogPoItemReceive($obj['cekID'], 'UPDATE', 0, $jsonBefore, $jsonAfter, $userid, $desc); + } + } + } + + $this->db->trans_commit(); + $this->sys_ok([ + 'header' => $data_po, + 'detail' => $data_detail + ]); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveHandover() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + # Ambil data PurchaseRequestID # + $sql_get_prid = "SELECT DISTINCT + pod.PurchaseOrderDetailPurchaseRequestID AS PurchaseRequestID + FROM receive_order_po_detail ropd + JOIN purchase_order_detail pod + ON pod.PurchaseOrderDetailID = ropd.ReceiveOrderPoDetailPurchaseOrderDetailID + WHERE ropd.ReceiveOrderPoDetailReceiveOrderPoID = ? + AND pod.PurchaseOrderDetailPurchaseRequestID IS NOT NULL"; + $que_get_prid = $this->db->query($sql_get_prid, [$param['receiveOrderPoID']]); + if (!$que_get_prid) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get PurchaseRequestID from RO Detail"); + exit; + } + $data_prid = $que_get_prid->row_array(); + + # insert handover # + $sql_insert_handover = "INSERT INTO asset_handover( + AssetHandoverPurchaseRequestID, + AssetHandoverReceiveOrderPoID, + AssetHandoverDate, + AssetHandoverM_RuanganID, + AssetHandoverToUserID, + AssetHandoverIsActive, + AssetHandoverCreated, + AssetHandoverUserID) VALUES(?,?,NOW(),?,?,'Y',NOW(),?)"; + $qry_insert_handover = $this->db->query($sql_insert_handover, [ + $data_prid['PurchaseRequestID'], + $param['receiveOrderPoID'], + $param['ruanganID'], + $param['staffID'], + $user['M_UserID'] + ]); + if (!$qry_insert_handover) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert asset handover"); + exit; + } + + $handoverID = $this->db->insert_id(); + + # ambil data barcode # + $sql_get_barcode = "SELECT + ropd.ReceiveOrderPoDetailID, + ropd.ReceiveOrderPoItemID AS M_ItemID, + bb.T_BarcodeBarangID + FROM receive_order_po_detail ropd + JOIN t_barcode_barang bb + ON bb.T_BarcodeBarangReceiveOrderPoDetailID = ropd.ReceiveOrderPoDetailID + AND bb.T_BarcodeBarangIsActive = 'Y' + WHERE ropd.ReceiveOrderPoDetailReceiveOrderPoID = ?"; + $que_get_barcode = $this->db->query($sql_get_barcode, [$param['receiveOrderPoID']]); + if (!$que_get_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get barcode barang from RO Detail"); + exit; + } + + $barcodes = $que_get_barcode->result_array(); + + # insert handover detail # + foreach ($barcodes as $key => $value) { + $sql_insert_handover_detail = "INSERT INTO asset_handover_detail( + AssetHandoverDetailAssetHandoverID, + AssetHandoverDetailT_BarcodeBarangID, + AssetHandoverDetailM_ItemID, + AssetHandoverDetailIsActive, + AssetHandoverDetailCreated, + AssetHandoverDetailUserID) VALUES(?,?,?,'Y',NOW(),?)"; + $que_insert_handover_detail = $this->db->query($sql_insert_handover_detail, [ + $handoverID, + $value['T_BarcodeBarangID'], + $value['M_ItemID'], + $user['M_UserID'] + ]); + if (!$que_insert_handover_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert asset handover detail"); + exit; + } + } + + # update status handover di receive order po # + $sql_update_ro = "UPDATE receive_order_po SET + ReceiveOrderPoIsHandover = 'Y', + ReceiveOrderPoLastUpdated = NOW(), + ReceiveOrderPoLastUpdatedUserID = ? + WHERE ReceiveOrderPoID = ?"; + $que_update_ro = $this->db->query($sql_update_ro, [ + $user['M_UserID'], + $param['receiveOrderPoID'] + ]); + if (!$que_update_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status handover di RO"); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] Berhasil menyimpan data serah terima barang"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveFiles() + { + try { + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + + $path = "/home/one/project/accone/one-media/order-inventaris/"; + $year = date('Y'); + $targetpath = $path . $year . "/"; + + if (!is_dir($targetpath)) { + mkdir($targetpath, 0755, true); + } + + $config['upload_path'] = $targetpath; + $config['allowed_types'] = 'jpg|jpeg|png'; + $config['max_size'] = '10000'; + $count = count($_FILES['files']['name']); + $this->load->library('upload', $config); + + $error = []; + for ($i = 0; $i < $count; $i++) { + if (!empty($_FILES['files']['name'][$i])) { + $_FILES['file']['name'] = $_FILES['files']['name'][$i]; + $_FILES['file']['type'] = $_FILES['files']['type'][$i]; + $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i]; + $_FILES['file']['error'] = $_FILES['files']['error'][$i]; + $_FILES['file']['size'] = $_FILES['files']['size'][$i]; + + $ext = pathinfo($_FILES['name'][$i], PATHINFO_EXTENSION); + $random_str = bin2hex(random_bytes(4)); + $new_filename = 'IVT' . $random_str . '_' . $param['receiveOrderPoNumber'] . $ext; + $config['file_name'] = $new_filename; + + $this->upload->initialize($config); + + if ($this->upload->do_upload('file')) { + $uploadData = $this->upload->data(); + $filename = $uploadData['file_name']; + + $sql_insert_file = "INSERT INTO receive_order_po_document ( + ReceiveOrderPoDocumentReceiveOrderPoID, + ReceiveOrderPoDocumentDate, + ReceiveOrderPoDocumentFile, + ReceiveOrderPoDocumentIsActive, + ReceiveOrderPoDocumentCreated, + ReceiveOrderPoDocumentUserID + ) VALUES(?,NOW(),?,'Y',NOW(),?)"; + $que_insert_file = $this->db->query($sql_insert_file, [ + $param['receiveOrderPoID'], + $filename, + $param['userId'] + ]); + if (!$que_insert_file) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert receive order po files"); + exit; + } + } else { + $this->db->trans_rollback(); + $error[] = $this->upload->display_errors(); + $this->sys_error("[Error] " . $error); + exit; + } + } + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] Berhasil upload file"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBarcodes() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $param = $this->sys_input; + $user = $this->sys_user; + + $sql = "SELECT + T_BarcodeBarangID as id, + T_BarcodeBarangNumber, + M_ItemDesc, + M_BranchName, + M_RuanganName, + 'N' as chex + FROM t_barcode_barang + JOIN m_item ON M_ItemID = T_BarcodeBarangM_ItemID + JOIN m_branch ON M_BranchID = T_BarcodeBarangM_BranchID + LEFT JOIN m_ruangan ON M_RuanganID = T_BarcodeBarangM_RuanganID + WHERE T_BarcodeBarangReceiveOrderPoID = ? + AND T_BarcodeBarangIsActive = 'Y' + ORDER BY T_BarcodeBarangID"; + $que = $this->db->query($sql, [$param['ROID']]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get barcodes"); + exit; + } + + $barcodes = $que->result_array(); + if ($barcodes) { + foreach ($barcodes as $k => $v) { + if ($v['chex'] == 'N') + $barcodes[$k]['chex'] = false; + else + $barcodes[$k]['chex'] = true; + } + } + $this->db->trans_commit(); + $this->sys_ok($barcodes); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function insertJurnalPerItem($user, $detail_ro) {} + + private function generatePurchaseInvoice($user, $ROID, $grni, $discpo, $shipping) + { + + # generate nomor purchase invoice # + $numPI = $this->generateNoLogistik($user, 'PI'); + + # prepare data # + $sql_data_ro = "SELECT * FROM receive_order_po WHERE ReceiveOrderPoID = ?"; + $que_data_ro = $this->db->query($sql_data_ro, [$ROID]); + if (!$que_data_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get data RO to generate PI"); + exit; + } + $data_ro = $que_data_ro->row_array(); + + $sql_detail_ro = "SELECT + receive_order_po_detail.*, + M_ItemDesc, + PurchaseOrderSummaryDiscountType AS DiscountType, + PurchaseOrderSummaryDiscountRupiah AS DiscountRupiah, + PurchaseOrderSummaryDiscountPercent AS DiscountPercent, + PurchaseOrderSummaryDiscountAmount as DiscountPerItem + FROM receive_order_po_detail + JOIN m_item ON M_ItemID = ReceiveOrderPoItemID AND M_ItemIsActive = 'Y' + JOIN purchase_order_summary ON ReceiveOrderPoDetailPurchaseOrderSummaryID = PurchaseOrderSummaryID + WHERE ReceiveOrderPoDetailIsActive = 'Y' + AND ReceiveOrderPoDetailReceiveOrderPoID = ?"; + $que_detail_ro = $this->db->query($sql_detail_ro, [$ROID]); + if (!$que_detail_ro) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get data detail RO to generate PI"); + exit; + } + $detail_ro = $que_detail_ro->result_array(); + + $due_date = new DateTime($data_ro['ReceiveOrderPoIDate']); + $due_date->add(new DateInterval('P30D')); + $due_date = $due_date->format('Y-m-d'); + + $subtotal = round(($grni - $shipping) + $discpo, 2); + + # insert header purchase invoice # + $sql_insert_PI = "INSERT INTO supplier_invoice ( + SupplierInvoiceNumber, + SupplierInvoiceReceiveOrderPoID, + SupplierInvoiceDate, + SupplierInvoiceDueDate, + SupplierInvoiceSupplierID, + SupplierInvoiceRefNumber, + SupplierInvoiceDeliveryOrderNumber, + SupplierInvoiceSubTotal, + SupplierInvoiceDiscountPercent, + SupplierInvoiceDiscountAmount, + SupplierInvoiceTaxPercentPph, + SupplierInvoiceTaxAmountPph, + SupplierInvoiceTaxPercentPpn, + SupplierInvoiceTaxAmountPpn, + SupplierInvoiceShippingCost, + SupplierInvoiceGrandTotal, + SupplierInvoiceUnpaid, + SupplierInvoiceNote, + SupplierInvoiceReceiveDate, + SupplierInvoiceReceivedBy, + SupplierInvoiceCreatedUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?)"; + $que_insert_PI = $this->db->query($sql_insert_PI, [ + $numPI, + $data_ro['ReceiveOrderPoID'], + $data_ro['ReceiveOrderPoIDate'], + $due_date, + $data_ro['ReceiveOrderPoSupplierID'], + $data_ro['ReceiveOrderPoRefNumber'], + $data_ro['ReceiveOrderPoDONumber'], + $subtotal, + 0.00, + $discpo, + 0.00, + 0.00, + 0.00, + 0.00, + $shipping, + $grni, + $grni, + $data_ro['ReceiveOrderPoNote'], + $user['M_UserID'], + $user['M_UserID'] + ]); + if (!$que_insert_PI) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert header purchase invoice"); + exit; + } + $Pinvoice_ID = $this->db->insert_id(); + + # insert detail purchase invoice # + $sql_insert_detailPI = "INSERT INTO supplier_invoice_detail ( + SupplierInvoiceDetailSupplierInvoiceID, + SupplierInvoiceDetailPurchaseOrderID, + SupplierInvoiceDetailPurchaseOrderSummaryID, + SupplierInvoiceDetailReceiveOrderPoID, + SupplierInvoiceDetailReceiveOrderPoDetailID, + SupplierInvoiceDetailItemID, + SupplierInvoiceDetailItemUnitID, + SupplierInvoiceDetailDescription, + SupplierInvoiceDetailQty, + SupplierInvoiceDetailPrice, + SupplierInvoiceDetailDiscountPercent, + SupplierInvoiceDetailDiscountDiscountRupiah, + SupplierInvoiceDetailDiscountDiscountType, + SupplierInvoiceDetailDiscountPoProrata, + SupplierInvoiceDetailDiscountAmount, + SupplierInvoiceDetailTotal, + SupplierInvoiceDetailUnpaid, + SupplierInvoiceDetailCreatedUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + foreach ($detail_ro as $key => $item) { + $itemprice = doubleval($item['ReceiveOrderPoDetailPrice']) - doubleval($item['DiscountPerItem']); + $total_price = round($itemprice * intval($item['ReceiveOrderPoDetailQty']), 2); + + $que_insert_itemPI = $this->db->query($sql_insert_detailPI, [ + $Pinvoice_ID, + $item['ReceiveOrderPoDetailPurchaseOrderID'], + $item['ReceiveOrderPoDetailPurchaseOrderSummaryID'], + $item['ReceiveOrderPoDetailReceiveOrderPoID'], + $item['ReceiveOrderPoDetailID'], + $item['ReceiveOrderPoItemID'], + $item['ReceiveOrderPoItemUnitID'], + $item['M_ItemDesc'], + $item['ReceiveOrderPoDetailQty'], + $item['ReceiveOrderPoDetailPrice'], + $item['DiscountPercent'], + $item['DiscountRupiah'], + $item['DiscountType'], + $item['ReceiveOrderPoDetailDiskonPoProrata'], + $item['DiscountPerItem'], + $total_price, + $total_price, + $user['M_UserID'] + ]); + if (!$que_insert_itemPI) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert header purchase invoice"); + exit; + } + } + + # insert log activity # + $this->insertUserActivty($Pinvoice_ID, 'INV', 'CREATE', $user['M_UserID'], ''); + } + + private function insertLogReceiveOrderPo($id, $type, $dataBefore, $dataAfter, $userID, $desc = '') + { + $sql = "INSERT INTO acc_one_log.receive_order_po_log ( + ReceiveOrderPoLogReceiveOrderPoID, + ReceiveOrderPoLogType, + ReceiveOrderPoLogDesc, + ReceiveOrderPoLogJsonBefore, + ReceiveOrderPoLogJsonAfter, + ReceiveOrderPoLogUserID, + ReceiveOrderPoLogCreated + ) VALUES (?, ?, ?, ?, ?, ?, NOW())"; + $que = $this->db->query($sql, [ + $id, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$que) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] inserting log into insert LogReceiveOrderPo"); + exit; + } + } + + private function insertLogPoItemReceive($id, $type, $roID, $dataBefore, $dataAfter, $userID, $desc = '') + { + $sql = "INSERT INTO acc_one_log.po_item_receive_log ( + PoItemReceiveLogPoItemReceiveID, + PoItemReceiveLogReceiveOrderPoID, + PoItemReceiveLogType, + PoItemReceiveLogDesc, + PoItemReceiveLogJsonBefore, + PoItemReceiveLogJsonAfter, + PoItemReceiveLogUserID, + PoItemReceiveLogCreated + ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"; + $que = $this->db->query($sql, [ + $id, + $roID, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$que) { + $this->sys_error_db("[Error] inserting log po item receive"); + $this->db->trans_rollback(); + exit; + } + } + + private function insertUserActivty($id, $typePL, $status, $userID, $desc = '') + { + $sql = "INSERT INTO user_activity ( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityUserID, + UserActivityCreated + ) VALUES (?, ?, ?, ?, ?, NOW())"; + $que = $this->db->query($sql, [$typePL, $status, $desc, $id, $userID]); + if (!$que) { + $this->sys_error_db("[Error] inserting user activity"); + $this->db->trans_rollback(); + exit; + } + } + + private function formatRupiah($data) + { + $data = str_replace(',', '.', $data); + if (!is_numeric($data)) { + return 'Input tidak valid'; + } + + $data = (float)$data; + $data = round($data, 2); + + if (fmod($data, 1) == 0.0) { + $formatted = number_format($data, 0, ',', '.'); + } else { + $formatted = number_format($data, 2, ',', '.'); + } + return 'Rp ' . $formatted; + } + + function template() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +}