From 5ecf65a82079150fe83acc49de37d007e3133b9c Mon Sep 17 00:00:00 2001 From: sasadib Date: Mon, 6 Jul 2026 16:44:35 +0700 Subject: [PATCH] add api file from used in s_menu fe accone --- application/controllers/fixedasset/Item.php | 831 +++++ .../fixedasset/Journalfixedassetv2.php | 1055 ++++++ .../controllers/itemdivision/Itemdivision.php | 365 ++ .../mockup/approvalall/Approvalallrequest.php | 665 ++++ .../mockup/approvalall/Tasklist.php | 83 + .../controllers/mockup/itemout/Itemoutv3.php | 3044 +++++++++++++++++ .../mockup/itemout/Itemusagev3.php | 1272 +++++++ .../mockup/itemout/RequestItemOut.php | 2231 ++++++++++++ .../mockup/masterdata/Expedition.php | 712 ++++ .../mockup/masterdata/Priviledge.php | 241 ++ .../controllers/mockup/masterdata/Staffv2.php | 722 ++++ .../masterdata/accounting/Journalcashv2.php | 6 +- .../accounting/Journalgoodreceive.php | 13 + .../mockup/masterdata/accounting/Ruangan.php | 76 +- .../mockup/mutasi/HandoverMutasi.php | 1579 +++++++++ .../mockup/mutasi/ReceiveMutasi.php | 1006 ++++++ .../mockup/mutasi/Requestmutasi.php | 1401 ++++++++ .../mockup/mutasi/RequestmutasiApproved.php | 1420 ++++++++ .../Nonpersediaanapproved.php | 715 ++++ .../Purchaserequestkacab.php | 701 ++++ .../ReceiveItemPoInventaris.php | 53 +- .../supplierpaymentapprovedv3/Billv2.php | 264 ++ .../mockup/supplierpaymentfailed/Bill.php | 769 +++++ .../mockup/supplierpaymentfailed/Payment.php | 1024 ++++++ .../mockup/supplierpaymentv4/Bill.php | 257 ++ .../mockup/supplierpaymentv4/Payment.php | 982 ++++++ .../mockup/usergroup/Usergroupv6.php | 1014 ++++++ .../v1/report-usergroup/Usergroup.php | 650 ++++ .../controllers/v1/report-v9/Lookup.php | 43 + application/controllers/v1/report-v9/Main.php | 185 + 30 files changed, 23347 insertions(+), 32 deletions(-) create mode 100644 application/controllers/fixedasset/Item.php create mode 100644 application/controllers/fixedasset/Journalfixedassetv2.php create mode 100644 application/controllers/itemdivision/Itemdivision.php create mode 100644 application/controllers/mockup/approvalall/Approvalallrequest.php create mode 100644 application/controllers/mockup/approvalall/Tasklist.php create mode 100644 application/controllers/mockup/itemout/Itemoutv3.php create mode 100644 application/controllers/mockup/itemout/Itemusagev3.php create mode 100644 application/controllers/mockup/itemout/RequestItemOut.php create mode 100644 application/controllers/mockup/masterdata/Expedition.php create mode 100755 application/controllers/mockup/masterdata/Priviledge.php create mode 100644 application/controllers/mockup/masterdata/Staffv2.php create mode 100644 application/controllers/mockup/mutasi/HandoverMutasi.php create mode 100644 application/controllers/mockup/mutasi/ReceiveMutasi.php create mode 100644 application/controllers/mockup/mutasi/Requestmutasi.php create mode 100644 application/controllers/mockup/mutasi/RequestmutasiApproved.php create mode 100644 application/controllers/mockup/nonpersediaanapproved/Nonpersediaanapproved.php create mode 100644 application/controllers/mockup/purchaserequestkacab/Purchaserequestkacab.php create mode 100644 application/controllers/mockup/supplierpaymentapprovedv3/Billv2.php create mode 100644 application/controllers/mockup/supplierpaymentfailed/Bill.php create mode 100644 application/controllers/mockup/supplierpaymentfailed/Payment.php create mode 100644 application/controllers/mockup/supplierpaymentv4/Bill.php create mode 100644 application/controllers/mockup/supplierpaymentv4/Payment.php create mode 100644 application/controllers/mockup/usergroup/Usergroupv6.php create mode 100644 application/controllers/v1/report-usergroup/Usergroup.php create mode 100644 application/controllers/v1/report-v9/Lookup.php create mode 100644 application/controllers/v1/report-v9/Main.php diff --git a/application/controllers/fixedasset/Item.php b/application/controllers/fixedasset/Item.php new file mode 100644 index 0000000..796e726 --- /dev/null +++ b/application/controllers/fixedasset/Item.php @@ -0,0 +1,831 @@ +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%" : "%%"; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + + /* if (isset($branchCode)) { + $join_branch = " JOIN m_branch ON M_BranchCode = '{$branchCode}' + JOIN s_regional ON S_RegionalID = '{$regionalID}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'"; + }else{ + $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}' + LEFT JOIN m_branch ON M_BranchS_RegionalID = '{$regionalID}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'"; + } */ + $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}' + LEFT JOIN m_branch ON M_BranchS_RegionalID = '{$regionalID}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'"; + $number_limit = 10; + $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0; + + $sql = "SELECT + f.Fa_ItemID, + IFNULL(f.Fa_ItemDate, '') AS Fa_ItemDate, + IFNULL(f.Fa_ItemNumber, '') AS Fa_ItemNumber, + IFNULL(f.Fa_ItemType, '') AS Fa_ItemType, + IFNULL(f.Fa_ItemNote, '') AS Fa_ItemNote, + IFNULL(f.Fa_ItemM_DepartmentID, 0) AS Fa_ItemM_DepartmentID, + IFNULL(f.Fa_ItemBranchFaPercentID, 0) AS Fa_ItemBranchFaPercentID, + IFNULL(f.Fa_ItemM_ItemID, 0) AS Fa_ItemM_ItemID, + IFNULL(f.Fa_ItemQty, 0) AS Fa_ItemQty, + IFNULL(f.Fa_ItemPurchaseDate, '') AS Fa_ItemPurchaseDate, + IFNULL(f.Fa_ItemPurchasePrice, 0.00) AS Fa_ItemPurchasePrice, + IFNULL(f.Fa_ItemAcquisitionPrice, 0.00) AS Fa_ItemAcquisitionPrice, + IFNULL(f.Fa_ItemNetBookValue, 0.00) AS Fa_ItemNetBookValue, + IFNULL(f.Fa_ItemDeprePerMonth, 0.00) AS Fa_ItemDeprePerMonth, + IFNULL(f.Fa_ItemFa_ClassCoaID, 0) AS Fa_ItemFa_ClassCoaID, + IFNULL(f.Fa_ItemFa_ClassAccumDepreCoaID, 0) AS Fa_ItemFa_ClassAccumDepreCoaID, + IFNULL(f.Fa_ItemFa_ClassDepreCoaID, 0) AS Fa_ItemFa_ClassDepreCoaID, + IFNULL(f.Fa_ItemAcquisitionCoaID, 0) AS Fa_ItemAcquisitionCoaID, + IFNULL(f.Fa_ItemCurrentValue, 0.00) AS Fa_ItemCurrentValue, + IFNULL(f.Fa_ItemAccumDepre, 0.00) AS Fa_ItemAccumDepre, + IFNULL(f.Fa_ItemStatus, '') AS Fa_ItemStatus, + IFNULL(f.Fa_ItemUserID, 0) AS Fa_ItemUserID, + IFNULL(f.Fa_ItemCreated, CURRENT_TIMESTAMP) AS Fa_ItemCreated, + IFNULL(f.Fa_ItemLastUpdated, CURRENT_TIMESTAMP) AS Fa_ItemLastUpdated, + Fa_ItemInventarisNumber, + + M_ItemID, + M_ItemCode, + M_ItemDesc, + M_ItemItem_CategoryID, + M_ItemInventoryCode, + M_ItemNat_GroupID, + M_ItemNat_SubGroupID, + M_ItemFa_ClassID, + Fa_ClassID, + Fa_ClassName, + Fa_ClassFlagType, + Fa_ClassCoaID, + Fa_ClassCoaAccountNo, + Fa_ClassCoaDesc, + Fa_ClassDepreCorp, + Fa_ClassDepreGov, + Fa_ClassAccumDepreCoaID, + Fa_ClassAccumDepreCoaAccountNo, + Fa_ClassAccumDepreCoaDesc, + Fa_ClassDepreCoaID, + Fa_ClassAccumNote, + M_ItemM_InventarisGolID, + M_ItemPurchaseUOM, + M_ItemBaseUOM, + M_ItemItem_UnitID, + Fa_ClassAgeAsset, + -- Data dari tabel coa untuk Class CoA + IFNULL(c_class.coaID, 0) AS ClassCoaID, + IFNULL(c_class.coaAccountNo, '') AS ClassCoaAccountNo, + IFNULL(c_class.coaDescription, '') AS ClassCoaDescription, + + -- Data dari tabel coa untuk Accumulated Depreciation CoA + IFNULL(c_accum.coaID, 0) AS AccumDepreCoaID, + IFNULL(c_accum.coaAccountNo, '') AS AccumDepreCoaAccountNo, + IFNULL(c_accum.coaDescription, '') AS AccumDepreCoaDescription, + + -- Data dari tabel coa untuk Depre + IFNULL(c_depre.coaID, 0) AS DepreCoaID, + IFNULL(c_depre.coaAccountNo, '') AS DepreCoaAccountNo, + IFNULL(c_depre.coaDescription, '') AS DepreCoaDescription, + + M_DepartmentID, + M_DepartmentCode, + M_DepartmentName, + + IFNULL(c_acquisition.coaID, 0) AS AcquisitionCoaID, + IFNULL(c_acquisition.coaAccountNo, '') AS AcquisitionCoaAccountNo, + IFNULL(c_acquisition.coaDescription, '') AS AcquisitionCoaDescription, + + M_BranchID, + M_BranchS_RegionalID, + M_BranchCode, + M_BranchName, + S_RegionalID, + S_RegionalName, + BranchFaPercentID, + BranchFaPercentType + + + + + FROM fa_item f + LEFT JOIN m_item ON M_ItemID = Fa_ItemM_ItemID + LEFT JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID + LEFT JOIN m_department ON M_DepartmentID = Fa_ItemM_DepartmentID + LEFT JOIN branch_fa_percent ON BranchFaPercentID = Fa_ItemBranchFaPercentID + LEFT JOIN coa c_class + ON f.Fa_ItemFa_ClassCoaID = c_class.coaID + LEFT JOIN coa c_accum + ON f.Fa_ItemFa_ClassAccumDepreCoaID = c_accum.coaID + LEFT JOIN coa c_depre + ON f.Fa_ItemFa_ClassDepreCoaID = c_depre.coaID + LEFT JOIN coa c_acquisition + ON f.Fa_ItemAcquisitionCoaID = c_acquisition.coaID + $join_branch + WHERE f.Fa_ItemIsActive = 'Y' + $filter_branch + AND ( + f.Fa_ItemName LIKE CONCAT('%', '$search', '%') + OR f.Fa_ItemNumber LIKE CONCAT('%', '$search', '%') + ) + GROUP BY f.Fa_ItemID + ORDER BY f.Fa_ItemID DESC"; + //echo $this->db_onedev->last_query(); + + $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 fa_item 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 fa_item 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()); + } +} + + // ac getAcAccumDepre + function getAcAccumDepre() + { + $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 + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaSpecialAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + coaCreated, + coaLastUpdated, + coaIsActive, + coaLevel + FROM coa + WHERE coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND + ( + coaDescription LIKE '$where_search_desc' + OR coaAccountNo 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); + } + } + + // ac getAcCoa + function getAcCoa() + { + $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 + coaID, + coaAccountNo, + coaDescription, + coaSubDescription, + coaAccountType, + coaSpecialAccountType, + coaIsInput, + coaReportSchedule, + coaCurrencyCode, + coaCashFlowCategory, + coaCreated, + coaLastUpdated, + coaIsActive, + coaLevel + FROM coa + WHERE coaIsInput = 'Y' + AND coaIsActive = 'Y' + AND + ( + coaDescription LIKE '$where_search_desc' + OR coaAccountNo 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 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_ItemFa_ClassID, + Fa_ClassID, + Fa_ClassName, + Fa_ClassFlagType, + Fa_ClassCoaID, + Fa_ClassCoaAccountNo, + Fa_ClassCoaDesc, + Fa_ClassDepreCorp, + Fa_ClassDepreGov, + Fa_ClassAccumDepreCoaID, + Fa_ClassAccumDepreCoaAccountNo, + Fa_ClassAccumDepreCoaDesc, + Fa_ClassDepreCoaID, + coaID, + coaAccountNo, + coaDescription, + Fa_ClassAccumNote, + M_ItemM_InventarisGolID, + M_ItemPurchaseUOM, + M_ItemBaseUOM, + M_ItemItem_UnitID, + Fa_ClassAgeAsset + FROM m_item + JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID + LEFT JOIN coa ON coaID = Fa_ClassDepreCoaID + WHERE M_ItemIsActive = 'Y' + AND M_ItemItem_CategoryID = '3' + 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 getDepartment() + { + $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 * + FROM m_department + WHERE M_DepartmentIsActive = 'Y' + AND + ( + M_DepartmentName LIKE '$where_search_desc' + OR M_DepartmentCode 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 getPresentase() + { + $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 * + FROM branch_fa_percent + WHERE BranchFaPercentIsActive = 'Y' + AND + ( + BranchFaPercentType LIKE '$where_search_desc' + + )"; + + // 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); + } + } + + // 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']; + + $pdSql = "SELECT `fn_numbering`('FAI') AS FAI"; + $exec = $this->db->query($pdSql, []); + $pd = ""; + $dateNow = date('Y-m-d'); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("payment voucher insert error", $this->db); + exit; + } else { + $pd = $exec->result_array()[0]["FAI"]; + } + + // Extract input parameters + $Fa_ItemNote = $prm['Fa_ItemNote']; + $Fa_ItemM_DepartmentID = isset($prm['Fa_ItemM_DepartmentID']) ? $prm['Fa_ItemM_DepartmentID'] : 0; + $Fa_ItemBranchFaPercentID = isset($prm['Fa_ItemBranchFaPercentID']) ? $prm['Fa_ItemBranchFaPercentID'] : 0; + $Fa_ItemM_ItemID = isset($prm['Fa_ItemM_ItemID']) ? $prm['Fa_ItemM_ItemID'] : 0; + $Fa_ItemQty = isset($prm['Fa_ItemQty']) ? $prm['Fa_ItemQty'] : 0; + $Fa_ItemPurchasePrice = isset($prm['Fa_ItemPurchasePrice']) ? $prm['Fa_ItemPurchasePrice'] : 0.00; + $Fa_ItemAcquisitionPrice = isset($prm['Fa_ItemAcquisitionPrice']) ? $prm['Fa_ItemAcquisitionPrice'] : 0.00; + $Fa_ItemNetBookValue = isset($prm['Fa_ItemNetBookValue']) ? $prm['Fa_ItemNetBookValue'] : 0.00; + $Fa_ItemDeprePerMonth = isset($prm['Fa_ItemDeprePerMonth']) ? $prm['Fa_ItemDeprePerMonth'] : 0.00; + $Fa_ItemFa_ClassCoaID = isset($prm['Fa_ItemFa_ClassCoaID']) ? $prm['Fa_ItemFa_ClassCoaID'] : 0; + $Fa_ItemFa_ClassAccumDepreCoaID = isset($prm['Fa_ItemFa_ClassAccumDepreCoaID']) ? $prm['Fa_ItemFa_ClassAccumDepreCoaID'] : 0; + $Fa_ItemFa_ClassDepreCoaID = isset($prm['Fa_ItemFa_ClassDepreCoaID']) ? $prm['Fa_ItemFa_ClassDepreCoaID'] : 0; + $Fa_ItemAcquisitionCoaID = isset($prm['Fa_ItemAcquisitionCoaID']) ? $prm['Fa_ItemAcquisitionCoaID'] : 0; + $Fa_ItemCurrentValue = isset($prm['Fa_ItemCurrentValue']) ? $prm['Fa_ItemCurrentValue'] : 0.00; + $Fa_ItemAccumDepre = isset($prm['Fa_ItemAccumDepre']) ? $prm['Fa_ItemAccumDepre'] : 0.00; + $Fa_ItemStatus = isset($prm['Fa_ItemStatus']) ? $prm['Fa_ItemStatus'] : 'Draft'; + $Fa_ItemInventarisNumber = isset($prm['Fa_ItemInventarisNumber']) ? $prm['Fa_ItemInventarisNumber'] : ''; + $Fa_ItemS_RegionalID = isset($prm['Fa_ItemS_RegionalID']) ? $prm['Fa_ItemS_RegionalID'] : 0; + $Fa_ItemM_BranchCode = isset($prm['Fa_ItemM_BranchCode']) ? $prm['Fa_ItemM_BranchCode'] : ''; + + // Construct SQL query + $sql = "INSERT INTO fa_item ( + Fa_ItemS_RegionalID, + Fa_ItemM_BranchCode, + Fa_ItemDate, + Fa_ItemNumber, + Fa_ItemType, + Fa_ItemNote, + Fa_ItemM_DepartmentID, + Fa_ItemBranchFaPercentID, + Fa_ItemM_ItemID, + Fa_ItemQty, + Fa_ItemPurchaseDate, + Fa_ItemPurchasePrice, + Fa_ItemAcquisitionPrice, + Fa_ItemNetBookValue, + Fa_ItemDeprePerMonth, + Fa_ItemFa_ClassCoaID, + Fa_ItemFa_ClassAccumDepreCoaID, + Fa_ItemFa_ClassDepreCoaID, + Fa_ItemAcquisitionCoaID, + Fa_ItemCurrentValue, + Fa_ItemAccumDepre, + Fa_ItemInventarisNumber, + Fa_ItemStatus, + Fa_ItemUserID, + Fa_ItemCreated, + Fa_ItemLastUpdated + ) VALUES ( + '$Fa_ItemS_RegionalID', + '$Fa_ItemM_BranchCode', + now(), + '$pd', + 'ACCOUNT', + '$Fa_ItemNote', + '$Fa_ItemM_DepartmentID', + '$Fa_ItemBranchFaPercentID', + '$Fa_ItemM_ItemID', + '$Fa_ItemQty', + now(), + '$Fa_ItemPurchasePrice', + '$Fa_ItemAcquisitionPrice', + '$Fa_ItemNetBookValue', + '$Fa_ItemDeprePerMonth', + '$Fa_ItemFa_ClassCoaID', + '$Fa_ItemFa_ClassAccumDepreCoaID', + '$Fa_ItemFa_ClassDepreCoaID', + '$Fa_ItemAcquisitionCoaID', + '$Fa_ItemCurrentValue', + '$Fa_ItemAccumDepre', + '$Fa_ItemInventarisNumber', + '$Fa_ItemStatus', + '$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; + } + + // fa_item + $Fa_ItemID = isset($prm['Fa_ItemID']) ? $prm['Fa_ItemID'] : 0; + + $sql_m = "SELECT * FROM fa_item where Fa_ItemID = '$Fa_ItemID'"; + + $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 + $Fa_ItemCoaID = isset($prm['Fa_ItemCoaID']) ? $prm['Fa_ItemCoaID'] : 0; + $sql_u = "SELECT * FROM coa where coaID = '$Fa_ItemCoaID' + 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 + $Fa_ItemAccumDepreCoaID = $prm['Fa_ItemAccumDepreCoaID']; + $sql_h = "SELECT * FROM coa where coaID = '$Fa_ItemAccumDepreCoaID' + 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_fa_item" => $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']; + + $Fa_ItemID = $prm['Fa_ItemID']; + $Fa_ItemNote = $prm['Fa_ItemNote']; + $Fa_ItemM_DepartmentID = isset($prm['Fa_ItemM_DepartmentID']) ? $prm['Fa_ItemM_DepartmentID'] : 0; + $Fa_ItemBranchFaPercentID = isset($prm['Fa_ItemBranchFaPercentID']) ? $prm['Fa_ItemBranchFaPercentID'] : 0; + $Fa_ItemM_ItemID = isset($prm['Fa_ItemM_ItemID']) ? $prm['Fa_ItemM_ItemID'] : 0; + $Fa_ItemQty = isset($prm['Fa_ItemQty']) ? $prm['Fa_ItemQty'] : 0; + $Fa_ItemPurchasePrice = isset($prm['Fa_ItemPurchasePrice']) ? $prm['Fa_ItemPurchasePrice'] : 0.00; + $Fa_ItemAcquisitionPrice = isset($prm['Fa_ItemAcquisitionPrice']) ? $prm['Fa_ItemAcquisitionPrice'] : 0.00; + $Fa_ItemNetBookValue = isset($prm['Fa_ItemNetBookValue']) ? $prm['Fa_ItemNetBookValue'] : 0.00; + $Fa_ItemDeprePerMonth = isset($prm['Fa_ItemDeprePerMonth']) ? $prm['Fa_ItemDeprePerMonth'] : 0.00; + $Fa_ItemFa_ClassCoaID = isset($prm['Fa_ItemFa_ClassCoaID']) ? $prm['Fa_ItemFa_ClassCoaID'] : 0; + $Fa_ItemFa_ClassAccumDepreCoaID = isset($prm['Fa_ItemFa_ClassAccumDepreCoaID']) ? $prm['Fa_ItemFa_ClassAccumDepreCoaID'] : 0; + $Fa_ItemFa_ClassDepreCoaID = isset($prm['Fa_ItemFa_ClassDepreCoaID']) ? $prm['Fa_ItemFa_ClassDepreCoaID'] : 0; + $Fa_ItemAcquisitionCoaID = isset($prm['Fa_ItemAcquisitionCoaID']) ? $prm['Fa_ItemAcquisitionCoaID'] : 0; + $Fa_ItemCurrentValue = isset($prm['Fa_ItemCurrentValue']) ? $prm['Fa_ItemCurrentValue'] : 0.00; + $Fa_ItemAccumDepre = isset($prm['Fa_ItemAccumDepre']) ? $prm['Fa_ItemAccumDepre'] : 0.00; + $Fa_ItemStatus = isset($prm['Fa_ItemStatus']) ? $prm['Fa_ItemStatus'] : 'Draft'; + $Fa_ItemInventarisNumber = isset($prm['Fa_ItemInventarisNumber']) ? $prm['Fa_ItemInventarisNumber'] : ''; + $Fa_ItemS_RegionalID = isset($prm['Fa_ItemS_RegionalID']) ? $prm['Fa_ItemS_RegionalID'] : 0; + $Fa_ItemM_BranchCode = isset($prm['Fa_ItemM_BranchCode']) ? $prm['Fa_ItemM_BranchCode'] : ''; + + $sql = "UPDATE fa_item SET + Fa_ItemNote = '{$Fa_ItemNote}', + Fa_ItemM_DepartmentID = '{$Fa_ItemM_DepartmentID}', + Fa_ItemBranchFaPercentID = '{$Fa_ItemBranchFaPercentID}', + Fa_ItemM_ItemID = '{$Fa_ItemM_ItemID}', + Fa_ItemQty = '{$Fa_ItemQty}', + Fa_ItemAcquisitionPrice = '{$Fa_ItemAcquisitionPrice}', + Fa_ItemNetBookValue = '{$Fa_ItemNetBookValue}', + Fa_ItemDeprePerMonth = '{$Fa_ItemDeprePerMonth}', + Fa_ItemFa_ClassCoaID = '{$Fa_ItemFa_ClassCoaID}', + Fa_ItemFa_ClassAccumDepreCoaID = '{$Fa_ItemFa_ClassAccumDepreCoaID}', + Fa_ItemFa_ClassDepreCoaID = '{$Fa_ItemFa_ClassDepreCoaID}', + Fa_ItemAcquisitionCoaID = '{$Fa_ItemAcquisitionCoaID}', + Fa_ItemCurrentValue = '{$Fa_ItemCurrentValue}', + Fa_ItemAccumDepre = '{$Fa_ItemAccumDepre}', + Fa_ItemInventarisNumber = '{$Fa_ItemInventarisNumber}', + Fa_ItemUserID = '{$userid}', + Fa_ItemLastUpdated = now(), + Fa_ItemS_RegionalID = '{$Fa_ItemS_RegionalID}', + Fa_ItemM_BranchCode = '{$Fa_ItemM_BranchCode}' + WHERE Fa_ItemID = '$Fa_ItemID' + "; + + + // 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']; + + $Fa_ItemID = $prm['Fa_ItemID']; + + + $sql = "UPDATE fa_item + SET + Fa_ItemIsActive = 'N', + Fa_ItemLastUpdated = now(), + Fa_ItemUserID = '$userid' + WHERE Fa_ItemID = '$Fa_ItemID'"; + + $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/fixedasset/Journalfixedassetv2.php b/application/controllers/fixedasset/Journalfixedassetv2.php new file mode 100644 index 0000000..9af525e --- /dev/null +++ b/application/controllers/fixedasset/Journalfixedassetv2.php @@ -0,0 +1,1055 @@ +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"]; + + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + + /* if (isset($branchCode)) { + $join_branch = " JOIN m_branch ON M_BranchCode = '{$branchCode}' + JOIN s_regional ON S_RegionalID = '{$regionalID}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}' AND Fa_ItemM_BranchCode = '{$branchCode}'"; + }else{ + $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}' + LEFT JOIN m_branch ON M_BranchS_RegionalID = '{$regionalID}' AND Fa_ItemM_BranchCode = '{$branchCode}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'"; + } + */ + $join_branch = " JOIN s_regional ON S_RegionalID = '{$regionalID}'"; + $filter_branch = " AND Fa_ItemS_RegionalID = '{$regionalID}'"; + + $sql_confirm = "SELECT COUNT(*) as total + FROM (SELECT periodeID + FROM periode + WHERE periodeEndDate < ( + SELECT periodeStartDate + FROM periode + WHERE periodeID = '{$periodeid}') + ORDER BY periodeEndDate DESC + LIMIT 1) a + JOIN fa_item_detail ON Fa_ItemDetailperiodeID = a.periodeID AND Fa_ItemDetailIsActive = 'Y' + "; + $qry_confirm = $this->db->query($sql_confirm); + //echo $this->db->last_query(); + if ($qry_confirm) { + $totalConfirm = $qry_confirm->result_array()[0]["total"]; + if ($totalConfirm == 0){ + $hide = 'Y'; + } else { + $hide = 'N'; + } + } + + $sql = "SELECT +'{$hide}' as ishide, +Fa_ItemID, +Fa_ItemNote, +Fa_ItemNumber CodeFixedAsset, +M_ItemDesc NameFixedAsset, +Fa_ItemAcquisitionPrice AcquisitionPrice, +Fa_ItemDeprePerMonth, +CASE + WHEN Fa_ItemDate BETWEEN periodeStartDate AND periodeEndDate THEN 1 + ELSE 0 + END AS pMonth, +IFNULL(Fa_ClassDepreCorp,0) DepreRateFixedAsset, +IFNULL(Fa_ClassDepreGov,0) DepreGovPercent, +0 depresiasi, +0 akumulasi, +0 nilai_saat_ini, +0 depresiasi_text, +0 akumulasi_text, +0 nilai_saat_ini_text, +Fa_ItemNetBookValue BookValue, +0 BookValue_text, +'' as ErrStatus, +'' as ErrMsg, +'' as detailtx, +Fa_ItemDetailID, +IFNULL(Fa_ItemDetailIsConfirm,'N') as Fa_ItemIsConfirm, +DATE_FORMAT(Fa_ItemDate, '%c') month_fa, +0 AcquisitionPrice_text, +1 total_month, +Fa_ItemBranchFaPercentID, +'' branchlists +FROM fa_item +JOIN m_item ON M_ItemID = Fa_ItemM_ItemID +JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID +LEFT JOIN fa_item_detail ON Fa_ItemDetailFa_ItemID = Fa_ItemID AND Fa_ItemDetailIsActive = 'Y' AND Fa_ItemDetailperiodeID = $periodeid +JOIN periode ON periodeID = $periodeid AND periodeIsActive = 'Y' +$join_branch +WHERE Fa_ItemIsActive = 'Y' +$filter_branch +AND (date(Fa_ItemDate) <= periodeStartDate OR date(Fa_ItemDate) <= periodeEndDate) +ORDER BY Fa_ItemID DESC"; + + + $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 = "SELECT periodeYear, periodeMonth FROM periode WHERE periodeID = ?"; + $date_now = $this->db->query($sql, [$periodeid])->row(); + + $month = $date_now->periodeMonth; + if($month == 1){ + $year = $date_now->periodeYear - 1; + $month_before = 12 ; + }else{ + $year = $date_now->periodeYear; + $month_before = $month - 1 ; + } + + $sql = "SELECT periodeID FROM periode WHERE periodeYear = '{$year}' AND periodeMonth = '{$month_before}'"; + $periode_before = $this->db->query($sql)->row()->periodeID; + + $total_month = $month - $value['month_fa'] + 1; + $rows[$key]["total_month"] = $total_month; + + $sql = "SELECT Fa_ItemDetailFa_ItemID, + Fa_ItemDetailperiodeID, + Fa_ItemDetailDepre, + Fa_ItemDetailAccum, + Fa_ItemDetailCurrentValue, + Fa_ItemDetailCurrentValue as Fa_ItemDetailBookValue + FROM fa_item_detail + JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID + WHERE Fa_ItemDetailFa_ItemID = {$value['Fa_ItemID']} AND + Fa_ItemDetailperiodeID = $periode_before + AND Fa_ItemDetailIsActive = 'Y'"; + $fa_detail = $this->db->query($sql)->row(); + + + $depre_amount = $value['Fa_ItemDeprePerMonth']; + $rows[$key]["depresiasi"] = $depre_amount; + $rows[$key]["depresiasi_text"] = number_format($depre_amount, 0, ',', '.'); + $sum_depre_before = $depre_amount; + + $akumulasi = $total_month * $sum_depre_before; + $rows[$key]["akumulasi"] = $akumulasi; + $rows[$key]["akumulasi_text"] = number_format($akumulasi, 0, ',', '.'); + $nilai_saat_ini = $value['AcquisitionPrice'] - $akumulasi; + $rows[$key]["nilai_saat_ini"] = $nilai_saat_ini; + $rows[$key]["nilai_saat_ini_text"] = number_format($nilai_saat_ini, 0, ',', '.'); + $rows[$key]["AcquisitionPrice_text"] = number_format($value['AcquisitionPrice'], 0, ',', '.'); + + if (isset($fa_detail->Fa_ItemDetailBookValue)){ + $Fa_ItemDetailBookValue = $fa_detail->Fa_ItemDetailBookValue; + $rows[$key]["BookValue"] = $Fa_ItemDetailBookValue; + $rows[$key]["BookValue_text"] = number_format($Fa_ItemDetailBookValue, 0, ',', '.'); + }else{ + $Fa_ItemDetailBookValue = $nilai_saat_ini + $depre_amount; + $rows[$key]["BookValue"] = $Fa_ItemDetailBookValue; + $rows[$key]["BookValue_text"] = number_format($Fa_ItemDetailBookValue, 0, ',', '.'); + } + $rows[$key]['branchlists'] = $this->getdetail($value['Fa_ItemBranchFaPercentID'],$depre_amount); + + } + + $result = array( + 'total' => $totalPage, + 'totalfilter' => $totalCount, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function getdetail($Fa_ItemBranchFaPercentID,$depre_amount) + { + $sql = "SELECT BranchFaPercentDetailID, + BranchFaPercentDetailBranchFaPercentID, + BranchFaPercentDetailS_RegionalID, + BranchFaPercentDetailAccountNumber, + BranchFaPercentDetailM_BranchID, + BranchFaPercentDetailValue, + coaID, + coaAccountNo, + coaDescription, + M_BranchName, + (BranchFaPercentDetailValue / 100) * $depre_amount as totaldepre, + 0 totaldepretext + FROM branch_fa_percent + JOIN branch_fa_percent_detail ON BranchFaPercentID = BranchFaPercentDetailBranchFaPercentID AND BranchFaPercentIsActive = 'Y' + AND BranchFaPercentDetailIsActive = 'Y' + AND BranchFaPercentDetailBranchFaPercentID = ? + JOIN coa + ON BranchFaPercentDetailAccountNumber = coaAccountNo + AND coaIsActive = 'Y' + JOIN m_branch + ON M_BranchID = BranchFaPercentDetailM_BranchID + "; + $query = $this->db->query($sql, [$Fa_ItemBranchFaPercentID]); + if ($query) { + $rows = $query->result_array(); + if($rows){ + foreach ($rows as $key => $value) { + $rows[$key]["totaldepretext"] = number_format($value['totaldepre'], 0, ',', '.'); + } + } + return $rows; + + } else { + $this->sys_error_db("get branchlist", $this->db_onedev); + exit; + } + + } + function addConfirm() +{ + $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']; + + $periodeid = $prm['periodeid']; + + foreach ($prm['details'] as $k => $v) { + // Pastikan hanya proses yang belum dikonfirmasi + if ($v['Fa_ItemIsConfirm'] == 'N') { + // Masukkan data ke fa_item_detail + $query = "INSERT INTO fa_item_detail + (Fa_ItemDetailFa_ItemID, + Fa_ItemDetailperiodeID, + Fa_ItemDetailBookValue, + Fa_ItemDetailDeprePerMonth, + Fa_ItemDetailDepre, + Fa_ItemDetailAccum, + Fa_ItemDetailCurrentValue, + Fa_ItemDetailIsConfirm, + Fa_ItemDetailConfirmDate, + Fa_ItemDetailConfirmUserID) + VALUES(?,?,?,?,?,?,?,?,now(),?)"; + $qry = $this->db_onedev->query($query, array( + $v['Fa_ItemID'], + $periodeid, + $v['BookValue'], + $v['Fa_ItemDeprePerMonth'], + $v['depresiasi'], + $v['akumulasi'], + $v['nilai_saat_ini'], + 'Y', + $userid + )); + $last_qry = $this->db_onedev->last_query(); + 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; + } + $last_id = $this->db_onedev->insert_id(); + + // Insert jurnal pembelian + $newData = []; + $sqlData = "SELECT fa_item.*, + fa_item_detail.*, + M_BranchID, + M_BranchCode, + M_BranchName, + M_BranchS_RegionalID, + M_BranchCompanyID, + M_BranchCompanyName, + CONCAT('Jurnal Pembelian Fix Asset ', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription, + '{$periodeid}' periodeid, + CONCAT('Jurnal Pembelian Fix Asset ', DATE_FORMAT(now(), '%d-%m-%Y'), ' cabang ',M_BranchName) title, + 21 typeid, + '' detailjurnal, + ca.coaDescription as CoaBiayaDepresiasi, + cb.coaDescription as CoaAkumulasiDepresiasi, + Fa_ClassAccumDepreCostCoaID, + Fa_ItemFa_ClassAccumDepreCoaID, + bd.coaID as CoaBeliDebetID, + bd.coaDescription as CoaBeliDebetName, + bc.coaID as CoaBeliCreditID, + bc.coaDescription as CoaBeliCreditName + FROM fa_item_detail + JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID + JOIN m_item ON M_ItemID = Fa_ItemM_ItemID + JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID + LEFT JOIN m_branch ON M_BranchCode = Fa_ItemM_BranchCode + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ca ON ca.coaID = Fa_ClassAccumDepreCostCoaID + JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID + LEFT JOIN coa bd ON bd.coaID = Fa_ItemFa_ClassCoaID + LEFT JOIN coa bc ON bc.coaID = Fa_ItemAcquisitionCoaID + WHERE Fa_ItemDetailID = {$last_id} AND Fa_ItemDetailIsActive = 'Y'"; + $qryData = $this->db_onedev->query($sqlData); + $last_qry = $this->db_onedev->last_query(); + if (!$qryData) { + $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; + } + $newData = $qryData->result_array(); + + if ($newData) { + foreach ($newData as $k_jurnal => $v_jurnal) { + $branchid = $v_jurnal["M_BranchID"]; + $branchcompanyid = $v_jurnal["M_BranchCompanyID"]; + $date = date('Y-m-d'); + $description = $v_jurnal["xdescription"]; + $regionalid = $v_jurnal["M_BranchS_RegionalID"]; + $title = $v_jurnal["title"]; + $typeid = $v_jurnal["typeid"]; + $pvno = $v_jurnal["Fa_ItemNumber"]; + $detailjurnal = $this->db_onedev->query("SELECT {$v_jurnal["CoaBeliDebetID"]} coaid, + '{$v_jurnal["CoaBeliDebetName"]}' xdescription, + {$v_jurnal["Fa_ItemDetailBookValue"]} debit, + 0 credit + UNION + SELECT + {$v_jurnal["CoaBeliCreditID"]} coaid, + '{$v_jurnal["CoaBeliCreditName"]}' xdescription, + 0 debit, + {$v_jurnal["Fa_ItemDetailBookValue"]} credit")->result_array(); + $this->savejurnalbeli($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid); + } + } + + // Loop untuk branchlists + // Data branchlists sudah ada di $v dari hasil fungsi search() + foreach ($v['branchlists'] as $key => $value) { + $branchlistid = $value["BranchFaPercentDetailM_BranchID"]; + $querybranchlist = "INSERT INTO fa_item_branch + (Fa_ItemBranchFa_ItemID, + Fa_ItemBranchFa_ItemDetailID, + Fa_ItemBranchM_BranchID, + Fa_ItemBranchperiodeID, + Fa_ItemBranchDeprePerMonth, + Fa_ItemBranchIsConfirm, + Fa_ItemBranchConfirmDate, + Fa_ItemBranchConfirmUserID, + Fa_ItemBranchUserID) + VALUES(?,?,?,?,?,?,now(),?,?)"; + $qrybranchlist = $this->db_onedev->query($querybranchlist, array( + $v['Fa_ItemID'], + $last_id, + $branchlistid, + $periodeid, + $value['totaldepre'], + 'Y', + $userid, + $userid + )); + $last_qry = $this->db_onedev->last_query(); + + if (!$qrybranchlist) { + $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; + } + $last_branchid = $this->db_onedev->insert_id(); + + // Jurnal untuk branch regional + $sqlDatabranchlist = "SELECT fa_item.*, + fa_item_detail.*, + fa_item_branch.*, + M_BranchID, + M_BranchCode, + M_BranchName, + M_BranchS_RegionalID, + M_BranchCompanyID, + M_BranchCompanyName, + CONCAT('Jurnal Depresiasi Fix Asset Cabang', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription, + '{$periodeid}' periodeid, + CONCAT('Jurnal Depresiasi Fix Asset Cabang', DATE_FORMAT(now(), '%d-%m-%Y'), ' cabang ', M_BranchName) title, + 21 typeid, + '' detailjurnal, + cb.coaID as CoaDebetID, + cb.coaDescription as CoaDebetName, + ca.coaID as CoaCreditID, + ca.coaDescription as CoaCreditName + FROM fa_item_branch + JOIN fa_item_detail ON Fa_ItemDetailID = Fa_ItemBranchFa_ItemDetailID AND Fa_ItemBranchIsActive = 'Y' + JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID + JOIN m_item ON M_ItemID = Fa_ItemM_ItemID + JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID + LEFT JOIN m_branch ON M_BranchID = Fa_ItemBranchM_BranchID + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN branch_fa_percent ON BranchFaPercentID = Fa_ItemBranchFaPercentID + JOIN branch_fa_percent_detail ON BranchFaPercentDetailBranchFaPercentID = BranchFaPercentID AND BranchFaPercentDetailM_BranchID = Fa_ItemBranchM_BranchID AND BranchFaPercentDetailIsActive = 'Y' + JOIN coa ca ON ca.coaAccountNo = BranchFaPercentDetailAccountNumber + JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID + WHERE Fa_ItemBranchFa_ItemDetailID = {$last_id} AND Fa_ItemBranchIsActive = 'Y' AND Fa_ItemBranchID = {$last_branchid}"; + + $qryDatabranchlist = $this->db_onedev->query($sqlDatabranchlist); + $last_qry = $this->db_onedev->last_query(); + + if (!$qryDatabranchlist) { + $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; + } + $newDatabranchlist = $qryDatabranchlist->result_array(); + + if ($newDatabranchlist) { + foreach ($newDatabranchlist as $key_jurnal_regional => $value_jurnal_regional) { + $branchid = $value_jurnal_regional["M_BranchID"]; + $branchcompanyid = $value_jurnal_regional["M_BranchCompanyID"]; + $date = date('Y-m-d'); + $description = $value_jurnal_regional["xdescription"]; + $regionalid = $value_jurnal_regional["M_BranchS_RegionalID"]; + $title = $value_jurnal_regional["title"]; + $typeid = $value_jurnal_regional["typeid"]; + $pvno = $value_jurnal_regional["Fa_ItemNumber"]; + $creditid = $value_jurnal_regional["CoaCreditID"]; + $creditname = $value_jurnal_regional["CoaCreditName"]; + $credittotal = $value_jurnal_regional["Fa_ItemDetailDeprePerMonth"]; + + $detailjurnal = $this->db_onedev->query("SELECT {$value_jurnal_regional["CoaDebetID"]} coaid, + '{$value_jurnal_regional["CoaDebetName"]}' xdescription, + {$value_jurnal_regional["Fa_ItemBranchDeprePerMonth"]} debit, + 0 credit + + UNION SELECT {$value_jurnal_regional["CoaCreditID"]} coaid, + '{$value_jurnal_regional["CoaCreditName"]}' xdescription, + 0 debit, + {$value_jurnal_regional["Fa_ItemBranchDeprePerMonth"]} credit + ")->result_array(); + + + $this->savejurnalbranch($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid, $creditid, $creditname, $credittotal); + } + } + } + $newDataRegional = []; + $sqlDataRegional = "SELECT fa_item.*, + fa_item_detail.*, + M_BranchID, + M_BranchCode, + M_BranchName, + M_BranchS_RegionalID, + M_BranchCompanyID, + M_BranchCompanyName, + CONCAT('Jurnal Depresiasi Fix Asset Regional', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription, + '{$periodeid}' periodeid, + CONCAT('Jurnal Depresiasi Fix Asset Regional', DATE_FORMAT(now(), '%d-%m-%Y'), ' ',S_RegionalName) title, + 21 typeid, + '' detailjurnal, + ca.coaDescription as CoaBiayaDepresiasi, + cb.coaDescription as CoaAkumulasiDepresiasi, + Fa_ClassAccumDepreCostCoaID, + Fa_ItemFa_ClassAccumDepreCoaID, + bd.coaID as CoaDebetID, + bd.coaDescription as CoaDebetName, + cb.coaID as CoaCreditID, + cb.coaDescription as CoaCreditName + FROM fa_item_detail + JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID + JOIN m_item ON M_ItemID = Fa_ItemM_ItemID + JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID + LEFT JOIN m_branch ON M_BranchCode = Fa_ItemM_BranchCode + LEFT JOIN s_regional ON S_RegionalID = M_BranchS_RegionalID + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ca ON ca.coaID = Fa_ClassAccumDepreCostCoaID + JOIN coa cb ON cb.coaID = Fa_ItemFa_ClassAccumDepreCoaID + LEFT JOIN coa bd ON bd.coaID = Fa_ItemFa_ClassCoaID + LEFT JOIN coa bc ON bc.coaID = Fa_ItemAcquisitionCoaID + WHERE Fa_ItemDetailID = {$last_id} AND Fa_ItemDetailIsActive = 'Y'"; + $qryDataRegional = $this->db_onedev->query($sqlDataRegional); + $last_qry = $this->db_onedev->last_query(); + if (!$qryDataRegional) { + $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; + } + $newDataRegional = $qryDataRegional->result_array(); + + if ($newDataRegional) { + foreach ($newDataRegional as $k_jurnal => $v_jurnal) { + $branchid = $v_jurnal["M_BranchID"]; + $branchcompanyid = $v_jurnal["M_BranchCompanyID"]; + $date = date('Y-m-d'); + $description = $v_jurnal["xdescription"]; + $regionalid = $v_jurnal["M_BranchS_RegionalID"]; + $title = $v_jurnal["title"]; + $typeid = $v_jurnal["typeid"]; + $pvno = $v_jurnal["Fa_ItemNumber"]; + $detailjurnal = $this->db_onedev->query("SELECT coaID coaid, + coaDescription xdescription, + Fa_ItemBranchDeprePerMonth debit, + 0 credit + FROM fa_item_branch + JOIN fa_item_detail ON Fa_ItemDetailID = Fa_ItemBranchFa_ItemDetailID AND Fa_ItemBranchIsActive = 'Y' + JOIN fa_item ON Fa_ItemID = Fa_ItemDetailFa_ItemID + JOIN branch_fa_percent ON BranchFaPercentID = Fa_ItemBranchFaPercentID + JOIN branch_fa_percent_detail ON BranchFaPercentDetailBranchFaPercentID = BranchFaPercentID AND BranchFaPercentDetailM_BranchID = Fa_ItemBranchM_BranchID AND BranchFaPercentDetailIsActive = 'Y' + JOIN coa ON coaAccountNo = BranchFaPercentDetailAccountNumber + WHERE Fa_ItemBranchFa_ItemDetailID = {$last_id} AND Fa_ItemBranchIsActive = 'Y' + UNION ALL + SELECT + {$v_jurnal["CoaCreditID"]} coaid, + '{$v_jurnal["CoaCreditName"]}' xdescription, + 0 debit, + {$v_jurnal["Fa_ItemDetailDeprePerMonth"]} credit")->result_array(); + $this->savejurnalregional($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid); + } + } + + } + } + + $this->db_onedev->trans_commit(); + $result = array("total" => 1); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } +} + function savejurnalbeli($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid) + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $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, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalIsActive, + jurnalCreated, + jurnalM_UserID + ) VALUES(?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)"; + $qry = $this->db->query($sql, array( + $branchcompanyid, + $regionalid, + $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["xdescription"], + $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; + } + + $tx_id = $this->db->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'JFA', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db->query($sql, array( + $last_id, + $tx_id, + $pvno, + $userid, + $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; + } + } + + + $this->db->trans_commit(); + // $result = array("total" => 1); + // $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function savejurnalregional($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid) + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $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, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalIsActive, + jurnalCreated, + jurnalM_UserID + ) VALUES(?,?,?,`fn_numbering`('J'),?,?,?,?,'Y',NOW(),?)"; + $qry = $this->db->query($sql, array( + $branchcompanyid, + $regionalid, + $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["xdescription"], + $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; + } + + $tx_id = $this->db->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'JFA', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db->query($sql, array( + $last_id, + $tx_id, + $pvno, + $userid, + $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; + } + } + + + $this->db->trans_commit(); + // $result = array("total" => 1); + // $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function savejurnalbranch($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid,$creditid,$creditname,$credittotal) + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $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["xdescription"], + $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; + } + + $tx_id = $this->db->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'JFA', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db->query($sql, array( + $last_id, + $tx_id, + $pvno, + $userid, + $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; + } + } + + + $this->db->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/itemdivision/Itemdivision.php b/application/controllers/itemdivision/Itemdivision.php new file mode 100644 index 0000000..46cb40a --- /dev/null +++ b/application/controllers/itemdivision/Itemdivision.php @@ -0,0 +1,365 @@ +db_onedev = $this->load->database("onedev", true); + } + + // search item + function search_item() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $search_item = isset($prm['search_item']) ? trim($prm['search_item']) : ''; + + $where_search = '%'.$search_item.'%'; + $itemCategoryID = isset($prm['itemCategoryID']) ? (int) $prm['itemCategoryID'] : (int) 0; + + $where_item_category_id = ($itemCategoryID > 0) ? "AND itemCategoryID = '$itemCategoryID'" : ""; + // $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * 20 : 0; + // $number_limit = 2; + $number_limit = 10; + $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0; + + $sql = "SELECT + M_ItemID, + IFNULL(itemCategoryName, '') AS itemCategoryName, + IFNULL(M_ItemCode, '') AS M_ItemCode, + IFNULL(M_ItemDesc, '') AS M_ItemDesc + from m_item + join item_category + ON M_ItemItem_CategoryID = itemCategoryID + AND itemCategoryIsActive = 'Y' + WHERE M_ItemIsActive = 'Y' + $where_item_category_id + AND ( + M_ItemDesc LIKE '$where_search' + OR M_ItemCode LIKE '$where_search' + ) + ORDER BY M_ItemID ASC"; + + $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_item count error", $this->db_onedev);; + exit; + } + + $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset"; + + $qry = $this->db_onedev->query($sql_select); + + if(!$qry){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("select m_item error", $this->db_onedev); + exit; + } + + $rows = $qry->result_array(); + + $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()); + } + } + + // dropdown item_category + function dropdown_item_category() + { + $prm = $this->sys_input; + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT + itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y' + ORDER BY itemCategoryID ASC"; + + // echo $sql; + // die(); + $qry = $this->db_onedev->query($sql, array()); + + if (!$qry) { + // $this->db->trans_rollback(); + $this->sys_error_db("Error get dropdown item_category"); + exit; + } + + $rows = $qry->result_array(); + if(count($rows) > 0){ + $response = [ + "records" => $rows, + "sql" => $this->db_onedev->last_query() + ]; + + $this->sys_ok($response); + } else { + $rows[] = [ + "M_ItemID" => 0, + "itemCategoryName" => "Item Tidak Ada", + "M_ItemCode" => "", + "M_ItemDesc" => "" + ]; + + $response = [ + "records" => $rows, + "sql" => $this->db_onedev->last_query() + ]; + + $this->sys_ok($response); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // item division list + function item_division_list() + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $M_ItemID = isset($prm['M_ItemID']) ? (int) $prm['M_ItemID'] : (int) 0; + + $where_item_id = ($M_ItemID > 0) ? "AND M_ItemDivisionM_ItemID = '$M_ItemID'" : ""; + // $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * 20 : 0; + // $number_limit = 2; + $number_limit = 10; + $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0; + + $sql = "SELECT + IFNULL(M_ItemDivisionID, 0) AS M_ItemDivisionID, + IFNULL(M_ItemDivisionM_ItemID, 0) AS M_ItemDivisionM_ItemID, + DivisionName, + IFNULL(DivisionID, 0) AS DivisionID, + CASE + WHEN M_ItemDivisionIsActive = 'Y' + THEN 1 + ELSE 0 + END as IsChecked + from division + left join m_itemdivision + ON DivisionID = M_ItemDivisionID + $where_item_id + where DivisionIsActive = 'Y' + ORDER BY DivisionID asc"; + + $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_itemdivision count error", $this->db_onedev);; + exit; + } + + // $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset"; + $sql_select = $sql; + + $qry = $this->db_onedev->query($sql_select); + + if(!$qry){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("select m_itemdivision error", $this->db_onedev); + exit; + } + + $rows = $qry->result_array(); + + $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()); + } + } + + // update m_itemdivision + function update_item_division() + { + try { + // Cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $prm = $this->sys_input; + + $userid = $this->sys_user["M_UserID"]; + $M_ItemDivisionID = isset($prm['M_ItemDivisionID']) ? $prm['M_ItemDivisionID'] : []; + $M_ItemID = isset($prm['M_ItemID']) ? (int) $prm['M_ItemID'] : (int) 0; + $where_item_id = ($M_ItemID > 0) ? "AND M_ItemDivisionM_ItemID = '$M_ItemID'" : ""; + + // $sql_u = ""; + + // var_dump($M_ItemDivisionID); + + if(count($M_ItemDivisionID) > 0){ + foreach ($M_ItemDivisionID as $row) { + $id = $row['M_ItemDivisionID']; + + $M_ItemDivisionDivisionID = $row['DivisionID']; + // $M_ItemDivisionM_ItemID = $row['M_ItemDivisionM_ItemID']; + + $flag = ($row['IsChecked'] === "1") ? "Y" : "N"; + + // check data jika ada update jika tidak ada insert + $sql_c = "SELECT * + FROM m_itemdivision + WHERE M_ItemDivisionID = '$id'"; + + $qry_c = $this->db_onedev->query($sql_c); + if(!$qry_c){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("query check data m_itemdivision", $this->db_onedev); + exit; + } + + $rc = $qry_c->result_array(); + if(count($rc) > 0) { + // update + $sql_u = "UPDATE m_itemdivision SET + M_ItemDivisionIsActive = '$flag', + M_ItemDivisionLastUpdatedUserID = '$userid', + M_ItemDivisionLastUpdated = NOW() + WHERE M_ItemDivisionID = '$id'"; + + // echo $sql_u; + $query_u = $this->db_onedev->query($sql_u); + if(!$query_u){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("query m_itemdivision update", $this->db_onedev); + exit; + } + } else{ + // insert + $sql_i = "INSERT INTO m_itemdivision ( + M_ItemDivisionM_ItemID, + M_ItemDivisionDivisionID, + M_ItemDivisionIsActive, + M_ItemDivisionCreated, + M_ItemDivisionCreatedUserID + ) VALUES ( + '$M_ItemID', + '$M_ItemDivisionDivisionID', + 'Y', + NOW(), + $userid + )"; + + $query_i = $this->db_onedev->query($sql_i); + if(!$query_i){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("query m_itemdivision insert", $this->db_onedev); + exit; + } + } + } + } + + $number_limit = 10; + $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0; + + $sql = "SELECT + IFNULL(M_ItemDivisionID, 0) AS M_ItemDivisionID, + IFNULL(M_ItemDivisionM_ItemID, 0) AS M_ItemDivisionM_ItemID, + DivisionName, + IFNULL(DivisionID, 0) AS DivisionID, + CASE + WHEN M_ItemDivisionIsActive = 'Y' + THEN 1 + ELSE 0 + END as IsChecked + from division + left join m_itemdivision + ON DivisionID = M_ItemDivisionID + $where_item_id + where DivisionIsActive = 'Y' + ORDER BY DivisionID asc"; + + $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_itemdivision count error", $this->db_onedev);; + exit; + } + + $sql_select = $sql; + $qry = $this->db_onedev->query($sql_select); + + if(!$qry){ + $this->db_onedev->trans_rollback(); + $this->sys_error_db("select m_itemdivision error", $this->db_onedev); + exit; + } + + $this->db_onedev->trans_commit(); + $rows = $qry->result_array(); + + $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()); + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/approvalall/Approvalallrequest.php b/application/controllers/mockup/approvalall/Approvalallrequest.php new file mode 100644 index 0000000..3c531b2 --- /dev/null +++ b/application/controllers/mockup/approvalall/Approvalallrequest.php @@ -0,0 +1,665 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + + public function listApprove() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $sql = "SELECT S_MenuID, + S_MenuName as menuname, + S_MenuName as name, + S_MenuRegional, + S_MenuUrl, + S_MenuIcon, + S_MenuParentS_MenuID, + S_MenuLevel, + S_MenuIsParent, + S_MenuOrder, + S_MenuIsActive + + FROM s_menu + WHERE S_MenuID IN (31, 69, 82)"; + $qry = $this->db->query($sql); + if (!$qry) { + $this->sys_error_db("Error get list menu"); + exit; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } + + public function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $userID = $user['M_UserID']; + $approveLevelID = $user['M_UserM_ApproveLevelID']; + $loginType = $user['M_UserLocationFlag']; + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?;"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } + + $totalStart = $approvalLevel[0]['M_ApproveLevelStartTotal']; + $totalEnd = $approvalLevel[0]['M_ApproveLevelEndTotal']; + + $params = [$regionalID, $regionalID]; + + if ($approveLevelID == '1') { + // manager -> verifikator + $sqlSupplierPayment = " AND SupplierPaymentIsVerif = 'N' AND SupplierPaymentStatus != 'Verif' "; + $sqlStockRequest = " AND (PurchaseRequestVerifiedBy = 0 OR PurchaseRequestVerifiedBy IS NULL) "; + $sqlPurchaseOrder = " AND PurchaseOrderApprovedManagerUserID = 0"; + $sqlRIO = " AND RequestItemOutVerifiedUserID = 0"; + } else if ($approveLevelID == '2') { + // kacab / regional -> approver + $sqlSupplierPayment = " AND SupplierPaymentIsApproved = 'N' AND SupplierPaymentStatus = 'Verif'"; + $sqlStockRequest = " AND PurchaseRequestApprovedBy IS NULL"; + $sqlPurchaseOrder = " AND PurchaseOrderApprovedUserID IS NULL"; + $sqlRIO = " AND RequestItemOutVerifiedUserID != 0"; + } + $sqlSelect = "SELECT + COUNT(*) total, + GROUP_CONCAT(PurchaseRequestNumber SEPARATOR ', ') AS number, + MIN(PurchaseRequestDate) AS date, + PurchaseRequestStatus as status, + 'STOCK REQUEST (P)' as type, + 'p' as flag + FROM purchase_request + WHERE PurchaseRequestIsActive = 'Y' + AND PurchaseRequestStatus = 'Pending' + AND PurchaseRequestItemCategoryID = 1 + AND PurchaseRequestS_RegionalID = ? + $sqlBranch + $sqlStockRequest + + UNION + + SELECT + COUNT(*) total, + GROUP_CONCAT(PurchaseRequestNumber SEPARATOR ', ') AS number, + MIN(PurchaseRequestDate) AS date, + PurchaseRequestStatus as status, + 'PURCHASE REQUEST (NP)' as type, + 'np' as flag + FROM purchase_request + WHERE PurchaseRequestIsActive = 'Y' + AND PurchaseRequestStatus = 'Pending' + AND PurchaseRequestItemCategoryID <> 1 + AND PurchaseRequestS_RegionalID = ? + $sqlBranch + $sqlStockRequest + + UNION + + SELECT COUNT(*) as total, + GROUP_CONCAT(PurchaseOrderNumber SEPARATOR ', ') AS number, + MIN(PurchaseOrderDate) AS date, + PurchaseOrderStatus as status, + 'PURCHASE ORDER' as type, + 'po' as flag + FROM purchase_order + WHERE PurchaseOrderIsActive = 'Y' + AND PurchaseOrderStatus = 'Pending' + $sqlPurchaseOrder + + UNION + + SELECT COUNT(*) as total, + GROUP_CONCAT(PurchaseRequestDirectNumber SEPARATOR ', ') as number, + MIN(PurchaseRequestDirectDate) as date, + PurchaseRequestDirectStatus as status, + 'PURCHASE REQUEST DIRECT' as type, + 'prd' as flag + FROM purchase_request_direct + WHERE PurchaseRequestDirectStatus = 'Pending' + AND PurchaseRequestDirectTotalEstimation BETWEEN $totalStart AND $totalEnd + AND PurchaseRequestDirectIsActive = 'Y' + + UNION + + SELECT COUNT(*) as total, + GROUP_CONCAT(PaymentVoucherNumber SEPARATOR ', ') as number, + MIN(DATE(PaymentVoucherDate)) as date, + PaymentVoucherStatus as status, + 'KASIR (REALISASI)' as type, + 'r' as flag + FROM payment_voucher + WHERE PaymentVoucherIsActive = 'Y' + AND PaymentVoucherStatus = 'Paid' + + UNION + + SELECT + COUNT(*) as total, + GROUP_CONCAT(SupplierInvoiceNumber SEPARATOR ', ') as number, + MIN(DATE(SupplierInvoiceDraftPaymentDate)) as date, + SupplierPaymentStatus as status, + 'PAYMENT APPROVED' as type, + 'pa' as flag + FROM supplier_payment + LEFT JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID + WHERE SupplierPaymentIsActive = 'Y' + $sqlSupplierPayment + + UNION + + SELECT COUNT(*) as total, + GROUP_CONCAT(RequestItemOutNumber SEPARATOR ', ') as number, + MIN(DATE(RequestItemOutDate)) as date, + IF(RequestItemOutStatus = 'Send Request' , 'SendRequest', '') as status, + 'REQUEST PENGELUARAN BARANG' as type, + 'rio' as flag + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutStatus = 'Send Request' + $sqlRIO + "; + + $qry_end = $this->db->query($sqlSelect, $params); + if ($qry_end) { + $rows = $qry_end->result_array(); + } else { + $this->sys_error_db("Error searching"); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $result = array( + 'records' => $rows, + "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + public function searchold() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $date = $prm['date']; + $status = $prm['status']; + $page = $prm['page']; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?;"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } + + $params = [$search, $search, $regionalID, $search]; + + // $sql = "SELECT + // PurchaseRequestID prID, + // DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') prDate, + // PurchaseRequestNumber prNumber, + // PurchaseRequestRefNumber prRefNumber, + // PurchaseRequestNote prNote, + // PurchaseRequestTotal prTotal, + // PurchaseRequestItemCategoryID prItemType, + // ItemCategoryName prItemTypeName, + // PurchaseRequestStatus prStatus, + // DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') prApprovedDate, + // a.M_userUserName prApprovedBy, + // b.M_UserID prRequestedByID, + // b.M_userUserName prRequestedBy, + // b.M_UserM_BranchID prRequestedByFromBranch, + // S_RegionalName prRegionalName, + // M_BranchName prBranchName, + // IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') prItemName + // FROM purchase_request + // JOIN s_regional + // ON PurchaseRequestS_RegionalID = S_RegionalID + // AND S_RegionalIsActive = 'Y' + // JOIN item_category + // ON PurchaseRequestItemCategoryID = ItemCategoryID + // AND ItemCategoryIsActive = 'Y' + // JOIN m_user b + // ON PurchaseRequestRequestedBy = b.M_UserID + // AND b.M_UserIsActive = 'Y' + // LEFT JOIN m_user a + // ON PurchaseRequestApprovedBy = a.M_UserID + // AND a.M_UserIsActive = 'Y' + // LEFT JOIN + // m_branch + // ON PurchaseRequestM_BranchCode = M_BranchCode + // WHERE PurchaseRequestIsActive = 'Y' + // AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + // AND PurchaseRequestS_RegionalID = ? + // AND PurchaseRequestStatus = 'Pending' + // $sqlBranch + // ORDER BY prDate,prNumber + // DESC + // LIMIT ? OFFSET ?"; + + $sqlSelect = "SELECT + PurchaseRequestID AS ID, + 'PR' AS SourceType, + DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') AS Date, + PurchaseRequestNumber AS Number, + PurchaseRequestRefNumber AS RefNumber, + PurchaseRequestNote AS Note, + PurchaseRequestTotal AS Total, + PurchaseRequestItemCategoryID AS ItemCategoryID, + ItemCategoryName AS ItemCategoryName, + PurchaseRequestStatus AS Status, + DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') AS ApprovedDate, + a.M_userUserName AS ApprovedBy, + b.M_UserID AS RequestedByID, + b.M_userUserName AS RequestedBy, + b.M_UserM_BranchID AS RequestedByFromBranch, + S_RegionalName AS RegionalName, + M_BranchName AS BranchName, + IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') AS ItemName, + NULL AS DiscountType, + NULL AS DiscountAmount, + NULL AS TaxAmount, + NULL AS SupplierCode, + NULL AS SupplierName, + NULL AS WarehouseCode, + NULL AS WarehouseName, + NULL AS DisplayDate + FROM purchase_request + JOIN s_regional ON PurchaseRequestS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + JOIN item_category ON PurchaseRequestItemCategoryID = ItemCategoryID AND ItemCategoryIsActive = 'Y' + JOIN m_user b ON PurchaseRequestRequestedBy = b.M_UserID AND b.M_UserIsActive = 'Y' + LEFT JOIN m_user a ON PurchaseRequestApprovedBy = a.M_UserID AND a.M_UserIsActive = 'Y' + LEFT JOIN m_branch ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' + AND PurchaseRequestStatus = 'Pending' + $sqlBranch + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ?) + AND PurchaseRequestS_RegionalID = ? + + UNION + ( + SELECT + PurchaseOrderID AS ID, + 'PO' AS SourceType, + DATE_FORMAT(PurchaseOrderDate, '%d-%m-%Y') AS Date, + PurchaseOrderNumber AS Number, + NULL AS RefNumber, + PurchaseOrderNote AS Note, + 0 AS Total, + itemCategoryID AS ItemCategoryID, + itemCategoryName AS ItemCategoryName, + PurchaseOrderStatus AS Status, + NULL AS ApprovedDate, + NULL AS ApprovedBy, + NULL AS RequestedByID, + NULL AS RequestedBy, + NULL AS RequestedByFromBranch, + S_RegionalName AS RegionalName, + M_BranchName AS BranchName, + NULL AS ItemName, + CASE + WHEN PurchaseOrderDiscountPercent = 0 THEN 'Absolute' + WHEN PurchaseOrderDiscountAmount = 0 THEN 'Percentage' + ELSE '' + END AS DiscountType, + CASE + WHEN PurchaseOrderDiscountPercent <> 0 THEN (PurchaseOrderDiscountPercent / 100) * PurchaseOrderSubTotal + WHEN PurchaseOrderDiscountAmount <> 0 THEN PurchaseOrderDiscountAmount + ELSE 0 + END AS DiscountAmount, + PurchaseOrderTaxAmountPph + PurchaseOrderTaxAmountPpn AS TaxAmount, + SupplierCode, + SupplierName, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END AS WarehouseName, + DATE_FORMAT(PurchaseOrderDate, '%d %M %Y') AS DisplayDate + FROM purchase_order + LEFT JOIN item_category ON PurchaseOrderItemCategoryID = itemCategoryID + LEFT JOIN supplier ON SupplierID = PurchaseOrderSupplierID + LEFT JOIN warehouse ON WarehouseID = PurchaseOrderWarehouseID + LEFT JOIN s_regional ON S_RegionalID = WarehouseS_RegionalID + LEFT JOIN m_branch ON M_BranchID = WarehouseM_BranchID + WHERE PurchaseOrderIsActive = 'Y' + AND PurchaseOrderStatus = 'Pending' + AND PurchaseOrderNumber LIKE ? + )"; + + $sqlTotal = "SELECT COUNT(*) AS total FROM ($sqlSelect) AS x"; + $qry = $this->db->query($sqlTotal, $params); + + $number_limit = 20; + $number_offset = 0; + if ($page > 0) { + $number_offset = ($prm['page'] - 1) * $number_limit; + } + + $totalCount = 0; + $totalPage = 0; + if ($qry) { + $totalCount = $qry->row_array()["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("Error searching count"); + exit; + } + + $sql_painated = $sqlSelect . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry_end = $this->db->query($sql_painated, $params_paginated); + if ($qry_end) { + $rows = $qry_end->result_array(); + } else { + $this->sys_error_db("Error searching"); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $result = array( + 'total' => $totalPage, + 'records' => $rows, + // "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + + public function search_x() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $date = $prm['date']; + $status = $prm['status']; + $page = $prm['page']; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?;"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } + + $params = [$search, $search, $regionalID, $search]; + + $sql = "SELECT + PurchaseRequestID prID, + DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') prDate, + PurchaseRequestNumber prNumber, + PurchaseRequestRefNumber prRefNumber, + PurchaseRequestNote prNote, + PurchaseRequestTotal prTotal, + PurchaseRequestItemCategoryID prItemType, + ItemCategoryName prItemTypeName, + PurchaseRequestStatus prStatus, + DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') prApprovedDate, + a.M_userUserName prApprovedBy, + b.M_UserID prRequestedByID, + b.M_userUserName prRequestedBy, + b.M_UserM_BranchID prRequestedByFromBranch, + S_RegionalName prRegionalName, + M_BranchName prBranchName, + IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') prItemName + FROM purchase_request + JOIN s_regional + ON PurchaseRequestS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + JOIN item_category + ON PurchaseRequestItemCategoryID = ItemCategoryID + AND ItemCategoryIsActive = 'Y' + JOIN m_user b + ON PurchaseRequestRequestedBy = b.M_UserID + AND b.M_UserIsActive = 'Y' + LEFT JOIN m_user a + ON PurchaseRequestApprovedBy = a.M_UserID + AND a.M_UserIsActive = 'Y' + LEFT JOIN + m_branch + ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + AND PurchaseRequestS_RegionalID = ? + AND PurchaseRequestStatus = 'Pending' + $sqlBranch + ORDER BY prDate,prNumber + DESC + LIMIT ? OFFSET ?"; + + $sqlSelect = "(SELECT + PurchaseRequestID AS ID, + 'PR' AS SourceType, + DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') AS Date, + PurchaseRequestNumber AS Number, + PurchaseRequestRefNumber AS RefNumber, + PurchaseRequestNote AS Note, + PurchaseRequestTotal AS Total, + PurchaseRequestItemCategoryID AS ItemCategoryID, + ItemCategoryName AS ItemCategoryName, + PurchaseRequestStatus AS Status, + DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') AS ApprovedDate, + a.M_userUserName AS ApprovedBy, + b.M_UserID AS RequestedByID, + b.M_userUserName AS RequestedBy, + b.M_UserM_BranchID AS RequestedByFromBranch, + S_RegionalName AS RegionalName, + M_BranchName AS BranchName, + IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') AS ItemName, + NULL AS DiscountType, + NULL AS DiscountAmount, + NULL AS TaxAmount, + NULL AS SupplierCode, + NULL AS SupplierName, + NULL AS WarehouseCode, + NULL AS WarehouseName, + NULL AS DisplayDate + FROM purchase_request + JOIN s_regional ON PurchaseRequestS_RegionalID = S_RegionalID AND S_RegionalIsActive = 'Y' + JOIN item_category ON PurchaseRequestItemCategoryID = ItemCategoryID AND ItemCategoryIsActive = 'Y' + JOIN m_user b ON PurchaseRequestRequestedBy = b.M_UserID AND b.M_UserIsActive = 'Y' + LEFT JOIN m_user a ON PurchaseRequestApprovedBy = a.M_UserID AND a.M_UserIsActive = 'Y' + LEFT JOIN m_branch ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' + AND PurchaseRequestStatus = 'Pending' + $sqlBranch + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ?) + AND PurchaseRequestS_RegionalID = ? + ) + UNION + ( + SELECT + PurchaseOrderID AS ID, + 'PO' AS SourceType, + DATE_FORMAT(PurchaseOrderDate, '%d-%m-%Y') AS Date, + PurchaseOrderNumber AS Number, + NULL AS RefNumber, + PurchaseOrderNote AS Note, + 0 AS Total, + itemCategoryID AS ItemCategoryID, + itemCategoryName AS ItemCategoryName, + PurchaseOrderStatus AS Status, + NULL AS ApprovedDate, + NULL AS ApprovedBy, + NULL AS RequestedByID, + NULL AS RequestedBy, + NULL AS RequestedByFromBranch, + S_RegionalName AS RegionalName, + M_BranchName AS BranchName, + NULL AS ItemName, + CASE + WHEN PurchaseOrderDiscountPercent = 0 THEN 'Absolute' + WHEN PurchaseOrderDiscountAmount = 0 THEN 'Percentage' + ELSE '' + END AS DiscountType, + CASE + WHEN PurchaseOrderDiscountPercent <> 0 THEN (PurchaseOrderDiscountPercent / 100) * PurchaseOrderSubTotal + WHEN PurchaseOrderDiscountAmount <> 0 THEN PurchaseOrderDiscountAmount + ELSE 0 + END AS DiscountAmount, + PurchaseOrderTaxAmountPph + PurchaseOrderTaxAmountPpn AS TaxAmount, + SupplierCode, + SupplierName, + WarehouseCode, + CASE + WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END AS WarehouseName, + DATE_FORMAT(PurchaseOrderDate, '%d %M %Y') AS DisplayDate + FROM purchase_order + LEFT JOIN item_category ON PurchaseOrderItemCategoryID = itemCategoryID + LEFT JOIN supplier ON SupplierID = PurchaseOrderSupplierID + LEFT JOIN warehouse ON WarehouseID = PurchaseOrderWarehouseID + LEFT JOIN s_regional ON S_RegionalID = WarehouseS_RegionalID + LEFT JOIN m_branch ON M_BranchID = WarehouseM_BranchID + WHERE PurchaseOrderIsActive = 'Y' + AND PurchaseOrderStatus = 'Pending' + AND PurchaseOrderNumber LIKE ? + ) + ORDER BY Date DESC"; + + $sqlTotal = "SELECT COUNT(*) AS total FROM ($sqlSelect) AS x"; + $qry = $this->db->query($sqlTotal, $params); + + $number_limit = 20; + $number_offset = 0; + if ($page > 0) { + $number_offset = ($prm['page'] - 1) * $number_limit; + } + + $totalCount = 0; + $totalPage = 0; + if ($qry) { + $totalCount = $qry->row_array()["total"]; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("Error searching count"); + exit; + } + + $sql_painated = $sqlSelect . " LIMIT ? OFFSET ?"; + $params_paginated = array_merge($params, [$number_limit, $number_offset]); + + $qry_end = $this->db->query($sql_painated, $params_paginated); + if ($qry_end) { + $rows = $qry_end->result_array(); + } else { + $this->sys_error_db("Error searching"); + exit; + } + + echo $this->db->last_query(); + exit; + + $result = array( + 'total' => $totalPage, + 'records' => $rows, + // "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } +} diff --git a/application/controllers/mockup/approvalall/Tasklist.php b/application/controllers/mockup/approvalall/Tasklist.php new file mode 100644 index 0000000..8ca3bf1 --- /dev/null +++ b/application/controllers/mockup/approvalall/Tasklist.php @@ -0,0 +1,83 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + + public function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $userID = $user['M_UserID']; + $loginType = $user['M_UserLocationFlag']; + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + + $params = [$regionalID, $regionalID, $regionalID]; + $sqlSelect = "SELECT COUNT(*) as total, + GROUP_CONCAT(PaymentVoucherNumber SEPARATOR ', ') as number, + MIN(DATE(PaymentVoucherDate)) as date, + PaymentVoucherStatus as status, + 'PAID PR' as type, + 'p' as flag + FROM payment_voucher + WHERE PaymentVoucherIsActive = 'Y' + AND PaymentVoucherStatus = 'Draft' + + UNION + + SELECT count(*) as total, + GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as number, + MIN(DATE(SupplierInvoiceDraftPaymentDate)) as date, + SupplierPaymentIsConfirm as status, + 'PAYMENT CASHIER' as type, + 'pc' as flag + FROM supplier_invoice + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + LEFT JOIN supplier_payment ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID AND SupplierPaymentIsActive = 'Y' + LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID + JOIN purchase_order ON PurchaseOrderID = SupplierInvoicePurchaseOrderID + WHERE SupplierInvoiceIsActive = 'Y' + AND SupplierPaymentIsApproved = 'Y' + AND SupplierPaymentIsVerif = 'Y' + AND SupplierPaymentIsConfirm = 'N' + "; + + $qry_end = $this->db->query($sqlSelect, []); + if ($qry_end) { + $rows = $qry_end->result_array(); + } else { + $this->sys_error_db("Error searching"); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $result = array( + 'records' => $rows, + // "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } +} diff --git a/application/controllers/mockup/itemout/Itemoutv3.php b/application/controllers/mockup/itemout/Itemoutv3.php new file mode 100644 index 0000000..e6a39cb --- /dev/null +++ b/application/controllers/mockup/itemout/Itemoutv3.php @@ -0,0 +1,3044 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $date = isset($prm["date"]) ? $prm["date"] : ""; + if ($date == "" || $date == null) { + $this->sys_error("Invalid Date Use"); + exit; + } + $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : ""; + if ($warehouseID == "" || $warehouseID == null) { + $this->sys_error("Warehouse masih kosong"); + exit; + } + $note = ""; + if (isset($prm["note"])) { + $note = trim($prm["note"]); + } + $divisionID = isset($prm["divisionID"]) ? $prm["divisionID"] : ""; + if ($divisionID == "" || $divisionID == null) { + $this->sys_error("Division masih kosong"); + exit; + } + $items = isset($prm["items"]) ? $prm["items"] : []; + if (count($items) == 0) { + $this->sys_error("Items cannot be empty"); + exit; + } + + + $sqlnum = "SELECT `fn_numbering`('IO') as IOnumber"; + $qrynum = $this->db->query($sqlnum, []); + $IOnumber = $qrynum->row()->IOnumber; + + $sqlIO = "INSERT INTO t_item_out ( + T_ItemOutDate, + T_ItemOutNumber, + T_ItemOutWarehouseID, + T_ItemOutNote, + T_ItemOutDivisionID, + T_ItemOutStatus, + T_ItemOutIsActive, + T_ItemOutUserID, + T_ItemOutCreated, + T_ItemOutLastUpdated) VALUES(?,?,?,?,?,'Draft','Y',?,NOW(),NOW())"; + $qryIO = $this->db->query($sqlIO, [ + $date, + $IOnumber, + $warehouseID, + $note, + $divisionID, + $userId + ]); + if (!$qryIO) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed to insert data table item out", $this->db); + } + + $ioId = $this->db->insert_id(); + + // Kelompokkan item berdasarkan rioID + $grouped = []; + foreach ($items as $item) { + $grouped[$item['rioID']][] = $item; + } + + foreach ($grouped as $rioID => $itemGroup) { + $statusHeader = 'Completed'; + + foreach ($itemGroup as $item) { + $receiveQty = intval($item['rioDReceiveQty']); + + // encode json list batch number + $jsonBatchNo = "[]"; + if (isset($item['ItemRequest']) && is_array($item['ItemRequest'])) { + $batches = $item['ItemRequest']; + if (sizeof($batches) > 0) { + $jsonResult = json_encode($batches); + if ($jsonResult === false) { + throw new Exception("[Error] Failed to encode json batch number"); + } else { + $jsonBatchNo = $jsonResult; + } + } + } + + // transaksi insert item out detail + $sql = "INSERT INTO t_item_out_detail( + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailRequestItemOutID, + T_ItemOutDetailRequestItemOutDetailID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailItemBatchNo, + T_ItemOutDetailQty, + T_ItemOutDetailCreated, + T_ItemOutDetailUserID) VALUES(?, ?, ?, ?, ?, ?, ?, NOW(), ?)"; + $qry = $this->db->query($sql, [ + $ioId, + $item["rioID"], + $item["rioDID"], + $item["itemID"], + $item["unitID"], + $jsonBatchNo, + $receiveQty, + $userId + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("failed to insert data table item out detail", $this->db); + exit; + } + + $isPartial = intval($receiveQty) < intval($item['rioDQty']); + $detailStatus = $isPartial ? 'Partial' : 'Completed'; + + if ($isPartial) { + $statusHeader = 'Partial'; // Jika ada satu saja partial, status header ikut partial + } + + // Update request item out detail + $sqlDetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = ?, + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailID = ?"; + $queryDetail = $this->db->query($sqlDetail, [ + $detailStatus, + $userId, + $item['rioDID'] + ]); + if (!$queryDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update detail RIO", $this->db); + exit; + } + } + + $sqlHeader = "UPDATE request_item_out SET + RequestItemOutStatus = ?, + RequestItemOutUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $queryHeader = $this->db->query($sqlHeader, [ + $statusHeader, + $userId, + $rioID + ]); + + if (!$queryHeader) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update header RIO", $this->db); + exit; + } + + + $userdesc = "Transaksi item out dengan kode " . $IOnumber . " telah di buat"; + $this->insertUserActivityIo($ioId, $userId, "DRAFT", $userdesc); + // Insert user activity (log) + $this->insertUserActivityRio($rioID, $userId, $statusHeader); + } + + + // transaksi pengurangan stockqty + foreach ($items as $key => $item) { + // array stock request per batch + foreach ($item["ItemRequest"] as $k => $v) { + // update stock + $stockupd = "UPDATE stock + SET StockQty = StockQty - ? + WHERE StockID = ? + AND StockWarehouseID = ?"; + $stockupd = $this->db->query($stockupd, [ + intval($v["QtyReq"]), + $v["StockID"], + $v["WarehouseID"] + ]); + if (!$stockupd) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update stock qty item out", $this->db); + exit; + } + + $receiveQty = intval($v['QtyReq']); + $currentQty = intval($v['StockQty']); + $remainingQty = max(0, $currentQty - $receiveQty); + + // insert stockcard + $sqlcard = "INSERT INTO stockcard ( + StockCardWarehouseID, + StockCardDatetime, + StockCardItemID, + StockCardItemUnitID, + StockCardBatchNo, + StockCardED, + StockCardReffID, + StockCardStatus, + StockCardBefore, + StockCardIn, + StockCardOut, + StockCardAfter, + StockCardUserID + ) VALUES (?, NOW(), ?, ?, ?, ?, ?, 'IO', ?, 0, ?, ?, ?)"; + $qrycard = $this->db->query($sqlcard, array( + $v["WarehouseID"], + $v["StockItemID"], + $v["StockItemUnitID"], + $v["StockBatchNo"], + $v["StockED"], + $v["StockID"], + $currentQty, + $receiveQty, + $remainingQty, + $userId + )); + if (!$qrycard) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert stock card", $this->db); + exit; + } + + // insert into stocklog + $sqllog = "INSERT INTO stocklog ( + StockLogWarehouseID, + StockLogDateTime, + StockLogItemID, + StockLogItemUnitID, + StockLogStockNumber, + StockLogBatchNo, + StockLogED, + StockLogReffID, + StockLogStatus, + StockLogQty, + StockLogUserID + ) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?)"; + $qrylog = $this->db->query($sqllog, [ + $v["WarehouseID"], + $v["StockItemID"], + $v["StockItemUnitID"], + $v["StockStockNumber"], + $v["StockBatchNo"], + $v["StockED"], + $v["StockID"], + 'IO', + $receiveQty, + $userId, + ]); + if (!$qrylog) { + $this->db->trans_rollback(); + $this->sys_error_db("Error insert stocklog", $this->db); + exit; + } + } + } + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "affected_rows" => $this->db->affected_rows() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getItemOuts() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + $this->db->trans_begin(); + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $ioID = isset($prm["ioID"]) ? $prm["ioID"] : ""; + if ($ioID == "" || $ioID == null) { + $this->sys_error("Invalid item out ID"); + exit; + } + $sql = "SELECT + T_ItemOutDetailID, + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailRequestItemOutID, + T_ItemOutDetailRequestItemOutDetailID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailItemBatchNo, + T_ItemOutDetailQty, + T_ItemOutID, + T_ItemOutDate, + T_ItemOutNumber, + T_ItemOutNote, + RequestItemOutDetailID, + RequestItemOutDetailReceiveQty, + RequestItemOutDetailQty, + IFNULL(RequestItemOutDetailQty, 0) - IFNULL(T_ItemOutDetailQty, 0) as remainingRequestQty, + M_ItemID, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + CASE + WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', M_BranchName) + WHEN WarehouseType = 'R' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', S_RegionalName) + ELSE '' + END WarehouseName, + WarehouseID, + StockID, + StockWarehouseID, + StockWarehouseAlmariID, + StockWarehouseRackID, + StockStockNumber, + StockItemID, + StockItemUnitID, + StockItemPrice, + StockBatchNo, + StockED, + StockLastUpdated, + StockUserID, + SUM(stock.StockQty) AS StockQty + FROM t_item_out_detail + JOIN t_item_out ON T_ItemOutDetailT_ItemOutID = T_ItemOutID + AND T_ItemOutIsActive = 'Y' + JOIN warehouse ON T_ItemOutWarehouseID = WarehouseID + JOIN request_item_out_detail ON T_ItemOutDetailRequestItemOutDetailID = RequestItemOutDetailID + AND RequestItemOutDetailIsActive = 'Y' + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON T_ItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN stock ON StockItemID = T_ItemOutDetailM_ItemID + AND StockItemUnitID = T_ItemOutDetailItemUnitID + AND StockWarehouseID = T_ItemOutWarehouseID + 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 T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + GROUP BY T_ItemOutDetailID + ORDER BY T_ItemOutDetailID DESC"; + $qry = $this->db->query($sql, [$ioID]); + if (!$qry) { + $this->sys_error_db("ERROR, get detail item out data", $this->db); + exit; + } + $rows = $qry->result_array(); + + foreach ($rows as $key => $value) { + $jsonStr = $value['T_ItemOutDetailItemBatchNo']; + $batches = []; + + if (!empty($jsonStr)) { + $decode = json_decode($jsonStr); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batches = $decode; + } else { + $this->sys_error_db("[Error] decode json for batches number"); + exit; + } + } + $rows[$key]['ItemRequest'] = $batches; + unset($rows[$key]['T_ItemOutDetailItemBatchNo']); + } + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function confirmIO() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $ioID = isset($prm["ioID"]) ? $prm["ioID"] : ""; + if ($ioID == "" || $ioID == null) { + $this->sys_error("Item out ID not found"); + exit; + } + + $sql_update = "UPDATE t_item_out SET + T_ItemOutIsConfirmDate = NOW(), + T_ItemOutIsConfirm = 'Y', + T_ItemOutUserID = ?, + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qry_update = $this->db->query($sql_update, [$userId, $ioID]); + if (!$qry_update) { + $this->db->trans_rollback(); + $this->sys_error_db("Gagal konfirmasi", $this->db); + exit; + } + + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$ioID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di konfirmasi"; + $this->insertUserActivityIo($ioID, $userId, "CONFIRM", $userdesc); + $this->db->trans_commit(); + $result = array( + "total" => 1, + "affected_rows" => $this->db->affected_rows() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function approveIO() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $ioID = isset($prm["ioID"]) ? $prm["ioID"] : ""; + if ($ioID == "" || $ioID == null) { + $this->sys_error("Item out ID not found"); + exit; + } + + $sqlApp = "UPDATE t_item_out SET + T_ItemOutApproveDate = NOW(), + T_ItemOutApproveID = ? + WHERE T_ItemOutID = ?"; + $qryApp = $this->db->query($sqlApp, [ + $userId, + $ioID + ]); + if (!$qryApp) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update approve failed", $this->db); + exit; + } + + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$ioID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di approve"; + $this->insertUserActivityIo($ioID, $userId, "Approve", $userdesc); + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "affected_rows" => $this->db->affected_rows() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function processIO() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $ioID = isset($prm["ioID"]) ? $prm["ioID"] : ""; + if ($ioID == "" || $ioID == null) { + $this->sys_error("Item out ID not found"); + exit; + } + $items = isset($prm["items"]) ? $prm["items"] : []; + if (count($items) == 0) { + $this->sys_error("Items cannot be empty"); + exit; + } + + $sqlApp = "UPDATE t_item_out SET + T_ItemOutStatus = 'Process', + T_ItemOutReceiveUserID = ?, + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qryApp = $this->db->query($sqlApp, [ + $userId, + $ioID + ]); + if (!$qryApp) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update Process failed", $this->db); + exit; + } + + foreach ($items as $key => $item) { + + $sqlQty = "UPDATE request_item_out_detail SET + RequestItemOutDetailQty = RequestItemOutDetailQty - ?, + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailID = ?"; + $qryQty = $this->db->query($sqlQty, [ + intval($item["T_ItemOutDetailQty"]), + $userId, + $item["T_ItemOutDetailRequestItemOutDetailID"] + ]); + if (!$qryQty) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update qty request failed", $this->db); + exit; + } + } + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$ioID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di approve"; + $this->insertUserActivityIo($ioID, $userId, "Process", $userdesc); + + // generate jurnal sudah tidak dipakai 22-08-2025 + // $this->generateJurnal($ioID); + + // Insert item usage + $this->insertUsage($ioID, $userId); + + $this->db->trans_commit(); + $result = array( + "total" => 1, + "affected_rows" => $this->db->affected_rows() + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function insertUserActivityIo($ioID, $userId, $status, $userdesc) + { + try { + // insert log + $sql_json = "SELECT t_item_out.*, '' as detail + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$ioID]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json io error"); + exit; + } + $row_json = $qry_json->row_array(); + + $sql_json_detail = "SELECT t_item_out_detail.* + FROM t_item_out_detail + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$ioID]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail io error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('IO',?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $status, + $userdesc, + $ioID, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity error", $this->db); + exit; + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function insertUserActivityRio($rioID, $userId, $status) + { + try { + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$rioID]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio error"); + exit; + } + $row_json = $qry_json->row_array(); + + if ($status == "Partial") { + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di kirim sebagian"; + } else { + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah komplit"; + } + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$rioID]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO',?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $status, + $userdesc, + $rioID, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity error", $this->db); + exit; + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function formatRupiah($angka) + { + // Ganti koma ke titik agar jadi desimal yang valid + $angka = str_replace(',', '.', $angka); + + // Validasi input + if (!is_numeric($angka)) { + return 'Input tidak valid'; + } + + // Konversi ke float + $angka = (float)$angka; + + // Bulatkan ke 3 angka desimal + $angka = round($angka, 3); + + // Cek apakah angka desimalnya nol + if (fmod($angka, 1) == 0.0) { + // Tanpa desimal + $formatted = number_format($angka, 0, ',', '.'); + } else { + // Dengan 3 angka desimal + $formatted = number_format($angka, 3, ',', '.'); + } + + return 'Rp ' . $formatted; + } + + public function search() + { + try { + 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"]; + $search = ""; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + if ($search != "") { + $search = '%' . $prm['search'] . '%'; + } else { + $search = '%%'; + } + } + + $status = $prm["status"]; + $filter = ""; + if ($status != 'All') { + $filter .= " AND T_ItemOutStatus = '{$status}'"; + } + + $number_offset = 0; + $number_limit = 10; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sqlCount = "SELECT count(*) as total + FROM t_item_out + JOIN warehouse ON T_ItemOutWarehouseID = WarehouseID + AND WarehouseIsActive = 'Y' + JOIN division ON T_ItemOutDivisionID = DivisionID + AND DivisionIsActive = 'Y' + 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 T_ItemOutIsActive = 'Y' + AND (T_ItemOutDate BETWEEN ? AND ?) + AND (T_ItemOutNumber LIKE ?) + $filter + ORDER BY T_ItemOutNumber DESC"; + $qryCount = $this->db->query($sqlCount, [ + $startDate, + $endDate, + $search + ]); + + $tot_count = 0; + $tot_page = 0; + if ($qryCount) { + $tot_count = $qryCount->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("item out count error", $this->db); + exit; + } + + $sql = "SELECT T_ItemOutID, + T_ItemOutDate, + T_ItemOutNumber, + T_ItemOutNote, + T_ItemOutReceiveUserID, + T_ItemOutStatus, + T_ItemOutApproveID, + T_ItemOutIsConfirm, + 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, + DivisionID, + DivisionCode, + DivisionName + FROM t_item_out + JOIN warehouse ON T_ItemOutWarehouseID = WarehouseID + AND WarehouseIsActive = 'Y' + JOIN division ON T_ItemOutDivisionID = DivisionID + AND DivisionIsActive = 'Y' + 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 T_ItemOutIsActive = 'Y' + AND (T_ItemOutDate BETWEEN ? AND ?) + AND (T_ItemOutNumber LIKE ?) + $filter + ORDER BY T_ItemOutNumber DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $startDate, + $endDate, + $search, + $number_limit, + $number_offset + ]); + // echo $this->db->last_query(); + // exit; + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("get item out error", $this->db); + exit; + } + + $result = array( + "totalPage" => $tot_page, + "totalFilter" => $tot_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getWarehouse() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $regionalID = $prm["regionalID"]; + $branchCode = $prm["branchCode"]; + $filterBranch = ""; + if (!$branchCode == "") { + $filterBranch .= " AND M_BranchCode = '{$branchCode}'"; + } + + $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, + 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 WarehouseIsActive = 'Y' + AND WarehouseIsTransit = 'N' + AND WarehouseS_RegionalID = ? + $filterBranch + ORDER BY WarehouseID ASC + "; + $qry = $this->db->query($sql, [$regionalID]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("get warehouse", $this->db); + exit; + } + $rows = $qry->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 getDepartment() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $sql = "SELECT M_DepartmentID, + M_DepartmentCode, + M_DepartmentName + FROM m_department + WHERE M_DepartmentIsActive = 'Y' + ORDER BY M_DepartmentName ASC"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("get Department", $this->db); + exit; + } + $rows = $qry->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 getDivisionByUser() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + // $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $userId = $prm["userId"]; + + $rows = []; + + $query = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + WHERE DivisionIsActive = 'Y' + ORDER BY DivisionName ASC"; + $exec = $this->db->query($query); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select division", $this->db); + exit; + } + + if ($prm["act"] == "edit") { + $sql = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID + WHERE DivisionIsActive = 'Y' + AND DivisionID = ? + ORDER BY M_UserDivisionID DESC + LIMIT 1"; + $exec = $this->db->query($sql, [$prm["DivisionID"]]); + if ($exec) { + $row = $exec->result_array(); + } else { + $this->sys_error_db("select division", $this->db); + exit; + } + } else { + $sql = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID AND M_UserDivisionM_UserID = ? + WHERE DivisionIsActive = 'Y' + ORDER BY M_UserDivisionID DESC + LIMIT 1"; + $exec = $this->db->query($sql, [$userId]); + if ($exec) { + $row = $exec->result_array(); + } else { + $this->sys_error_db("select division by user", $this->db); + exit; + } + } + + $result = array( + "records" => $rows, + "selected" => $row + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getDetailItemOut() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $itemoutID = isset($prm["itemoutID"]) ? $prm["itemoutID"] : ""; + if ($itemoutID == "" || $itemoutID == null) { + $this->sys_error("Invalid item out ID"); + exit; + } + + $sql = "SELECT + T_ItemOutDetailID as ioDetailID, + T_ItemOutDetailT_ItemOutID as ioDetailioID, + T_ItemOutDetailRequestItemOutID as ioDetailRequestioID, + T_ItemOutDetailM_ItemID as ioDetailItemID, + T_ItemOutDetailItemUnitID as ioDetailUnitID, + T_ItemOutDetailItemBatchNo, + IFNULL(T_ItemOutDetailQty, 0) as rioDReceiveQty, + T_ItemOutID as ioID, + T_ItemOutDate as ioDate, + T_ItemOutNumber as ioNumber, + T_ItemOutWarehouseID as ioWarehouseID, + T_ItemOutNote as ioNote, + T_ItemOutDivisionID as ioDivisionID, + RequestItemOutID as rioID, + RequestItemOutNumber as rioNumber, + RequestItemOutDetailID as rioDID, + RequestItemOutDetailM_ItemID as rioDItemID, + RequestItemOutDetailItemUnitID as rioDItemUnitID, + RequestItemOutDetailQty as rioDQty, + M_ItemID as itemID, + M_ItemCode as itemCode, + M_ItemDesc as itemDesc, + ItemUnitID as unitID, + ItemUnitCode as unitCode, + ItemUnitName as unitName, + StockID, + StockWarehouseID, + StockWarehouseAlmariID, + StockWarehouseRackID, + StockStockNumber, + StockItemID, + StockItemUnitID, + StockItemPrice, + StockBatchNo, + StockED, + StockLastUpdated, + StockUserID, + SUM(stock.StockQty) as StockQty + FROM t_item_out_detail + JOIN t_item_out ON T_ItemOutDetailT_ItemOutID = T_ItemOutID + AND T_ItemOutIsActive = 'Y' + JOIN request_item_out ON T_ItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + JOIN request_item_out_detail ON RequestItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutDetailM_ItemID = T_ItemOutDetailM_ItemID + AND RequestItemOutDetailItemUnitID = T_ItemOutDetailItemUnitID + AND RequestItemOutDetailIsActive = 'Y' + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON T_ItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN stock ON StockItemID = T_ItemOutDetailM_ItemID + AND StockItemUnitID = T_ItemOutDetailItemUnitID + AND StockWarehouseID = T_ItemOutWarehouseID + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + GROUP BY T_ItemOutDetailID + ORDER BY T_ItemOutDetailID DESC"; + $qry = $this->db->query($sql, [$itemoutID]); + if (!$qry) { + $this->sys_error_db('ERROR, get detail item out', $this->db); + exit; + } + $rows = $qry->result_array(); + + foreach ($rows as $key => $value) { + $jsonStr = $value['T_ItemOutDetailItemBatchNo']; + $batches = []; + + if (!empty($jsonStr)) { + $decode = json_decode($jsonStr); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batches = $decode; + } else { + $this->sys_error_db("[Error] decode json for batches number"); + exit; + } + } + $rows[$key]['ItemRequest'] = $batches; + unset($rows[$key]['T_ItemOutDetailItemBatchNo']); + } + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function updateRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $date = isset($prm["date"]) ? $prm["date"] : ""; + if ($date == "" || $date == null) { + $this->sys_error("Invalid Date Use"); + exit; + } + $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : ""; + if ($warehouseID == "" || $warehouseID == null) { + $this->sys_error("Warehouse masih kosong"); + exit; + } + $note = ""; + if (isset($prm["note"])) { + $note = trim($prm["note"]); + } + $divisionID = isset($prm["divisionID"]) ? $prm["divisionID"] : ""; + if ($divisionID == "" || $divisionID == null) { + $this->sys_error("Division masih kosong"); + exit; + } + $IOID = isset($prm["IOID"]) ? $prm["IOID"] : ""; + if ($IOID == "" || $IOID == null) { + $this->sys_error("item out ID masih kosong"); + exit; + } + + $items = isset($prm["items"]) ? $prm["items"] : []; + if (count($items) == 0) { + $this->sys_error("Items cannot be empty"); + exit; + } + + $sql = "UPDATE t_item_out SET + T_ItemOutDate = ?, + T_ItemOutWarehouseID = ?, + T_ItemOutNote = ?, + T_ItemOutDivisionID = ?, + T_ItemOutUserID = ?, + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qry = $this->db->query($sql, [ + $date, + $warehouseID, + $note, + $divisionID, + $userId, + $IOID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update item out", $this->db); + exit; + } + + $sql = "SELECT T_ItemOutDetailID + FROM t_item_out_detail + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ?"; + $qry = $this->db->query($sql, [$IOID]); + if (!$qry) { + $this->sys_error_db("select item out detail error", $this->db); + exit; + } + $dbIoDetailIDs = array_column($qry->result_array(), 'T_ItemOutDetailID'); + + // Buat array ioDetailID dari frontend + $activeIoDetailIDs = []; + foreach ($items as $item) { + if (!empty($item["ioDetailID"])) { + $activeIoDetailIDs[] = $item["ioDetailID"]; + } + } + + // Cari ID yang harus di-nonaktifkan (yang ada di database tapi tidak ada di frontend) + $toDeactivateIDs = array_diff($dbIoDetailIDs, $activeIoDetailIDs); + + // Jika ada yang perlu di-deactivate + if (!empty($toDeactivateIDs)) { + $placeholders = implode(',', array_fill(0, count($toDeactivateIDs), '?')); + $sql = "UPDATE t_item_out_detail SET + T_ItemOutDetailIsActive = 'N', + T_ItemOutDetailLastUpdated = NOW(), + T_ItemOutDetailUserID = ? + WHERE T_ItemOutDetailID IN ($placeholders)"; + $params = array_merge([$userId], $toDeactivateIDs); + $qry = $this->db->query($sql, $params); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, batch deactivate item out detail"); + exit; + } + } + + // Sekarang update atau insert yang dikirim frontend + foreach ($items as $item) { + $ioupdetailID = $item["ioDetailID"]; + + + // encode json list batch number + $jsonBatchNo = "[]"; + if (isset($item['ItemRequest']) && is_array($item['ItemRequest'])) { + $batches = $item['ItemRequest']; + if (sizeof($batches) > 0) { + $jsonResult = json_encode($batches); + if ($jsonResult === false) { + throw new Exception("[Error] Failed to encode json batch number"); + } else { + $jsonBatchNo = $jsonResult; + } + } + } + + if ($ioupdetailID) { + // UPDATE existing + $sql = "UPDATE t_item_out_detail SET + T_ItemOutDetailItemBatchNo = ?, + T_ItemOutDetailQty = ?, + T_ItemOutDetailLastUpdated = NOW(), + T_ItemOutDetailUserID = ? + WHERE T_ItemOutDetailID = ?"; + $qry = $this->db->query($sql, [ + $jsonBatchNo, + intval($item["rioDReceiveQty"]), + $userId, + $ioupdetailID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, update item out detail"); + exit; + } + } else { + // INSERT baru + $sql = "INSERT INTO t_item_out_detail( + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailRequestItemOutID, + T_ItemOutDetailRequestItemOutDetailID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailItemBatchNo, + T_ItemOutDetailQty, + T_ItemOutDetailCreated, + T_ItemOutDetailUserID) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?)"; + $qry = $this->db->query($sql, [ + $IOID, + $item["rioID"], + $item["rioDID"], + $item["itemID"], + $item["unitID"], + $jsonBatchNo, + intval($item["rioDReceiveQty"]), + $userId + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("failed to insert data table item out detail", $this->db); + exit; + } + } + } + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$IOID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di edit"; + $this->insertUserActivityIo($IOID, $userId, "UPDATE", $userdesc); + + $this->db->trans_commit(); + $result = array( + "total" => 1 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function rejectRequest() + { + try { + $this->db->trans_begin(); + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $IOID = ""; + if (isset($prm["IOID"])) { + $IOID = trim($prm["IOID"]); + } + + $sql = "UPDATE t_item_out SET + T_ItemOutStatus = 'Rejected', + T_ItemOutUserID = ?, + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $IOID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed delete item out", $this->db); + exit; + } + + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$IOID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di reject"; + $this->insertUserActivityIo($IOID, $userId, "REJECTED", $userdesc); + $this->db->trans_commit(); + $result = array( + "total" => 1 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function deleteRequest() + { + try { + $this->db->trans_begin(); + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $IOID = ""; + if (isset($prm["IOID"])) { + $IOID = trim($prm["IOID"]); + } + + $sql = "UPDATE t_item_out SET + T_ItemOutIsActive = 'N', + T_ItemOutUserID = ?, + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $IOID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed delete item out", $this->db); + exit; + } + + $sqldetail = "UPDATE t_item_out_detail SET + T_ItemOutDetailIsActive = 'N', + T_ItemOutDetailLastUpdated = NOW(), + T_ItemOutDetailUserID = ? + WHERE T_ItemOutDetailT_ItemOutID = ?"; + $qrydetail = $this->db->query($sqldetail, [ + $userId, + $IOID + ]); + if (!$qrydetail) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed delete item out detail", $this->db); + exit; + } + + $sqlstatus = "UPDATE request_item_out SET + RequestItemOutStatus = 'Process', + RequestItemOutUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qrystatus = $this->db->query($sqlstatus, [ + $userId, + $prm["RIOID"] + ]); + if (!$qrystatus) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update request item out status", $this->db); + exit; + } + + $sqlstatusdetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = 'Process', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailID = ?"; + $qrystatusdetail = $this->db->query($sqlstatusdetail, [ + $userId, + $prm["RIODID"] + ]); + if (!$qrystatusdetail) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update request item out detail status", $this->db); + exit; + } + + $sql = "SELECT t_item_out.* + FROM t_item_out + WHERE T_ItemOutIsActive = 'Y' + AND T_ItemOutID = ?"; + $qry = $this->db->query($sql, [$IOID]); + if (!$qry) { + $this->sys_error_db("select item out error", $this->db); + exit; + } + $row = $qry->row(); + + $userdesc = "Transaksi item out dengan kode " . $row->T_ItemOutNumber . " telah di hapus"; + $this->insertUserActivityIo($IOID, $userId, "DELETE", $userdesc); + $this->db->trans_commit(); + $result = array( + "total" => 1 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function searchDetail() + { + 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 = '%%'; + } + } + + $IOID = ""; + if (isset($prm["IOID"])) { + $IOID = trim($prm["IOID"]); + } + + $number_offset = 0; + $number_limit = 10; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sqlCount = "SELECT count(*) as total + FROM t_item_out_detail + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON T_ItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + ORDER BY T_ItemOutDetailID DESC"; + $qryCount = $this->db->query($sqlCount, [ + $IOID + ]); + + $tot_count = 0; + $tot_page = 0; + if ($qryCount) { + $tot_count = $qryCount->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("item out detail count error", $this->db); + exit; + } + + $sql = "SELECT T_ItemOutDetailID, + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailQty, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ROW_NUMBER() OVER(ORDER BY T_ItemOutDetailID) RowNumber + FROM t_item_out_detail + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON T_ItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + ORDER BY T_ItemOutDetailID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + $IOID, + $number_limit, + $number_offset + ]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("get item out detail error", $this->db); + exit; + } + + $result = array( + "totalPage" => $tot_page, + "totalFilter" => $tot_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function searchItem() + { + 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 = "%%"; + } + } + $warehouseID = $prm["warehouseID"]; + + $number_limit = 10; + $sql = "SELECT + M_ItemID, + M_ItemCode, + M_ItemDesc, + StockQty, + StockItemPrice, + StockBatchNo, + StockED, + StockWarehouseID + FROM stock + JOIN m_item ON M_ItemID = StockItemID + WHERE + StockWarehouseID = ? + AND StockQty > 0 + AND M_ItemIsActive = 'Y' + AND (M_ItemCode LIKE ? OR M_ItemDesc LIKE ?)"; + $qry = $this->db->query($sql, array($warehouseID, $search, $search)); + 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); + } + } + + public function getUnit() + { + 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 = "%%"; + } + } + $itemID = $prm["itemID"]; + + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitIsActive, + ItemUnitUserID, + ItemUnitMapM_ItemID, + ItemUnitMapIsPurchase, + ItemUnitMapIsReport, + ItemUnitMapIsBase + FROM itemunit + JOIN itemunitmap ON ItemUnitMapItemUnitID = ItemUnitID AND ItemUnitMapIsActive ='Y' + AND ItemUnitMapM_ItemID = ? + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE ? + ORDER BY ItemUnitName ASC"; + + $query = $this->db->query($sql, [ + $itemID, + $search + ]); + + 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); + } + } + + public function saveDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $itemID = ""; + if (isset($prm["itemID"])) { + $itemID = trim($prm["itemID"]); + } + $itemUnitID = ""; + if (isset($prm["itemUnitID"])) { + $itemUnitID = trim($prm["itemUnitID"]); + } + $qty = ""; + if (isset($prm["qty"])) { + $qty = trim($prm["qty"]); + } + $IOID = ""; + if (isset($prm["IOID"])) { + $IOID = trim($prm["IOID"]); + } + + $qryChek = "SELECT count(*) as exist + FROM t_item_out_detail + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + AND T_ItemOutDetailM_ItemID = ?"; + $exist = $this->db->query($qryChek, [ + $IOID, + $itemID + ]); + if ($exist) { + $row = $exist->row()->exist; + } else { + $this->sys_error_db("exist error", $this->db); + exit; + } + + if ($row == 0) { + $sql = "INSERT INTO t_item_out_detail( + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailQty, + T_ItemOutDetailIsActive, + T_ItemOutDetailCreated, + T_ItemOutDetailUserID) VALUES(?,?,?,?,'Y',NOW(),?)"; + $qry = $this->db->query($sql, [ + $IOID, + $itemID, + $itemUnitID, + $qty, + $userId + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item out detail", $this->db); + exit; + } + + $this->db->trans_commit(); + + $result = array("total" => 1, "records" => array("xId" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + $qryItem = "SELECT M_ItemDesc FROM m_item WHERE M_ItemID = ?"; + $qryItem = $this->db->query($qryItem, [ + $itemID + ]); + if ($qryItem) { + $rowItem = $qryItem->row()->M_ItemDesc; + } else { + $this->db->trans_rollback(); + $this->sys_error_db("Failed get item error", $this->db); + exit; + } + if ($row != 0) { + array_push($errors, array("msg" => "Data dengan item " . $rowItem . " 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); + } + } + + public function updateDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $itemID = ""; + if (isset($prm["itemID"])) { + $itemID = trim($prm["itemID"]); + } + $itemUnitID = ""; + if (isset($prm["itemUnitID"])) { + $itemUnitID = trim($prm["itemUnitID"]); + } + $qty = ""; + if (isset($prm["qty"])) { + $qty = trim($prm["qty"]); + } + $IOID = ""; + if (isset($prm["IOID"])) { + $IOID = trim($prm["IOID"]); + } + $IODID = ""; + if (isset($prm["IODID"])) { + $IODID = trim($prm["IODID"]); + } + + $sqlCheck = "SELECT count(*) as exist + FROM t_item_out_detail + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ? + AND T_ItemOutDetailM_ItemID = ? + AND T_ItemOutDetailItemUnitID = ? + AND T_ItemOutDetailID != ?"; + $qryCheck = $this->db->query($sqlCheck, [ + $IOID, + $itemID, + $itemUnitID, + $IODID + ]); + if ($qryCheck && $qryCheck->result_array()[0]["exist"] > 0) { + $this->sys_error("Item dan satuan sudah ada"); + exit; + } + + $sql = "UPDATE t_item_out_detail SET + T_ItemOutDetailT_ItemOutID = ?, + T_ItemOutDetailM_ItemID = ?, + T_ItemOutDetailItemUnitID = ?, + T_ItemOutDetailQty = ?, + T_ItemOutDetailLastUpdated = NOW(), + T_ItemOutDetailUserID = ? + WHERE T_ItemOutDetailID = ?"; + $qry = $this->db->query($sql, [ + $IOID, + $itemID, + $itemUnitID, + $qty, + $userId, + $IODID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item out detail 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); + } + } + + public function deleteDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $IODID = ""; + if (isset($prm["IODID"])) { + $IODID = trim($prm["IODID"]); + } + + $sql = "UPDATE t_item_out_detail SET + T_ItemOutDetailIsActive = 'N', + T_ItemOutDetailLastUpdated = NOW(), + T_ItemOutDetailUserID = ? + WHERE T_ItemOutDetailID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $IODID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed delete item out detail 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); + } + } + + public function orderConfirm() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $itemoutID = $prm["itemoutID"]; + + $sqlDetail = "SELECT T_ItemOutDetailID, + T_ItemOutDetailT_ItemOutID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailQty + FROM t_item_out_detail + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ?"; + $qryDetail = $this->db->query($sqlDetail, [$itemoutID]); + if ($qryDetail) { + $rows = $qryDetail->result_array(); + } else { + $this->db->tans_rollback(); + $this->sys_error_db("select item out detail error", $this->db); + exit; + } + + // Ambil Warehouse ID + $sqlHeader = "SELECT T_ItemOutWarehouseID FROM t_item_out WHERE T_ItemOutIsActive = 'Y' AND T_ItemOutID = ?"; + $qryHeader = $this->db->query($sqlHeader, [$itemoutID]); + if (!$qryHeader || $qryHeader->num_rows() == 0) { + $this->db->trans_rollback(); + $this->sys_error("Item Out tidak ditemukan"); + return; + } + $warehouseID = $qryHeader->row()->T_ItemOutWarehouseID; + + // loop detail + foreach ($rows as $row) { + $itemID = $row["T_ItemOutDetailM_ItemID"]; + $unitID = $row["T_ItemOutDetailItemUnitID"]; + $qtyNeeded = $row["T_ItemOutDetailQty"]; + + // Ambil stok berdasarkan Warehouse, Item dan Unit + $sqlStock = "SELECT StockID, StockQty + FROM stock + WHERE StockWarehouseID = ? + AND StockItemID = ? + AND StockItemUnitID = ? + AND StockQty > 0 + ORDER BY StockID ASC"; + $qryStock = $this->db->query($sqlStock, [$warehouseID, $itemID, $unitID]); + if (!$qryStock) { + $this->db->trans_rollback(); + $this->sys_error_db("select stock error", $this->db); + exit; + } + $stocks = $qryStock->result_array(); + + foreach ($stocks as $stock) { + if ($qtyNeeded <= 0) break; + + $stockID = $stock["StockID"]; + $stockQty = $stock["StockQty"]; + + if ($stockQty >= $qtyNeeded) { + // Kurangi stok langsung dengan SQL + $sqlUpdate = "UPDATE stock + SET StockQty = StockQty - ? + WHERE StockID = ?"; + $this->db->query($sqlUpdate, [$qtyNeeded, $stockID]); + + $qtyNeeded = 0; + } + } + + // Jika setelah looping qtyNeeded masih > 0, berarti stok tidak cukup + if ($qtyNeeded > 0) { + $this->db->trans_rollback(); + $this->sys_error("Stok tidak cukup untuk item ID: $itemID"); + return; + } + } + + // update approved + $sqlUpdate = "UPDATE t_item_out SET + T_ItemOutReceiveUserID= ?, + T_ItemOutStatus = 'Process', + T_ItemOutLastUpdated = NOW() + WHERE T_ItemOutID = ?"; + $qryUpdate = $this->db->query($sqlUpdate, [$userId, $itemoutID]); + if (!$qryUpdate) { + $this->db->trans_rollback(); + $this->sys_error_db("update item out 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); + } + } + + public function listRequest() + { + try { + 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"]; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $status = isset($prm["status"]) ? $prm["status"] : ""; + + $number_offset = 0; + $number_limit = 20; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + + $sqlCount = "SELECT count(*) as total + FROM request_item_out_detail + JOIN request_item_out ON RequestItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + AND (RequestItemOutNumber LIKE ? ) + AND (RequestItemOutStatus = ? OR ? = '' ) + AND RequestItemOutDate BETWEEN ? AND ? + JOIN m_item ON RequestItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN stock ON StockItemID = RequestItemOutDetailM_ItemID + AND StockItemUnitID = RequestItemOutDetailItemUnitID + AND StockWarehouseID = RequestItemOutWarehouseID + WHERE RequestItemOutDetailIsActive = 'Y' + GROUP BY RequestItemOutDetailID + ORDER BY RequestItemOutDetailID DESC"; + $qryCount = $this->db->query($sqlCount, ['%' . $search . '%', $status, $status, $startDate, $endDate]); + + $tot_count = 0; + $tot_page = 0; + if ($qryCount) { + $tot_count = $qryCount->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("request item out count error", $this->db); + exit; + } + + $sql = "SELECT RequestItemOutDetailID as rioDID, + RequestItemOutDetailM_ItemID as rioDItemID, + RequestItemOutDetailItemUnitID as rioDItemUnitID, + RequestItemOutDetailQty as rioDQty, + RequestItemOutDetailStatus as rioDStatus, + RequestItemOutID as rioID, + RequestItemOutDate as rioDate, + RequestItemOutNumber as rioNumber, + RequestItemOutNote as rioNote, + RequestItemOutDivisionID as rioDivisionID, + RequestItemOutStatus as rioStatus, + M_ItemID, + M_ItemCode, + M_ItemDesc, + StockID, + StockItemPrice, + SUM(StockQty) AS StockQty + FROM request_item_out_detail + JOIN request_item_out ON RequestItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + AND (RequestItemOutNumber LIKE ?) + AND (RequestItemOutStatus = ? OR ? = '' ) + AND RequestItemOutDate BETWEEN ? AND ? + JOIN m_item ON RequestItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN stock ON StockItemID = RequestItemOutDetailM_ItemID + AND StockItemUnitID = RequestItemOutDetailItemUnitID + AND StockWarehouseID = RequestItemOutWarehouseID + WHERE RequestItemOutDetailIsActive = 'Y' + GROUP BY RequestItemOutDetailID + ORDER BY RequestItemOutDetailID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [ + '%' . $search . '%', + $status, + $status, + $startDate, + $endDate, + $number_limit, + $number_offset + ]); + // echo $this->db->last_query(); + // exit; + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("request item out error", $this->db); + exit; + } + + $result = array( + "totalPage" => $tot_page, + "totalFilter" => $tot_count, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getDivisionUser() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $sql = "SELECT M_UserDivisionID, + M_UserDivisionM_UserID, + M_UserDivisionDivisionID, + M_UserUsername, + DivisionName + FROM m_user + JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON M_UserDivisionDivisionID = DivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserDivisionM_UserID = ?"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalDivision = $qry->result_array(); + if (count($approvalDivision) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } else { + $result = array( + "total" => 1, + "records" => $approvalDivision, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function approveRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $arrRequest = $prm["arrRequest"]; + foreach ($arrRequest as $key => $value) { + $sql = "UPDATE request_item_out SET + RequestItemOutStatus = 'Process', + RequestItemOutApprovedDate = NOW(), + RequestItemOutApprovedUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $value["rioID"] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out error", $this->db); + exit; + } + + $sqlDetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = 'Process', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailID = ?"; + $qryDetail = $this->db->query($sqlDetail, [ + $userId, + $value["rioDID"] + ]); + if (!$qryDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out detail error", $this->db); + exit; + } + } + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$value["rioID"]]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio error"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di approve"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$value["rioID"]]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Process',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $value["rioID"], + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity 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); + } + } + + public function rejectedRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $arrRequest = $prm["arrRequest"]; + foreach ($arrRequest as $key => $value) { + $sql = "UPDATE request_item_out SET + RequestItemOutStatus = 'Rejected', + RequestItemOutUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $value["rioID"] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out error", $this->db); + exit; + } + + $sqlDetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = 'Rejected', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailID = ?"; + $qryDetail = $this->db->query($sqlDetail, [ + $userId, + $value["rioDID"] + ]); + if (!$qryDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out detail error", $this->db); + exit; + } + } + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$value["rioID"]]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio error"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di reject"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$value["rioID"]]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Rejected',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $value["rioID"], + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity 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); + } + } + + public function getItemRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : ""; + $divisionID = isset($prm["divisionID"]) ? $prm["divisionID"] : ""; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $currentPage = isset($prm["currentPage"]) ? $prm["currentPage"] : 1; + + $limit = 10; + $offset = ($currentPage - 1) * $limit; + + $sqlCount = "SELECT COUNT(*) as total FROM ( + SELECT * + FROM request_item_out_detail + JOIN request_item_out ON RequestItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + AND (RequestItemOutStatus = 'Process' OR RequestItemOutStatus = 'Partial') + AND RequestItemOutWarehouseID = ? + AND RequestItemOutDivisionID = ? + JOIN m_item ON RequestItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + AND (M_ItemDesc LIKE ?) + JOIN itemunit ON RequestItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN stock ON StockItemID = M_ItemID + AND StockItemUnitID = RequestItemOutDetailItemUnitID + AND StockWarehouseID = RequestItemOutWarehouseID + LEFT JOIN t_item_out_detail ON T_ItemOutDetailRequestItemOutID = RequestItemOutDetailRequestItemOutID + AND T_ItemOutDetailM_ItemID = RequestItemOutDetailM_ItemID + AND T_ItemOutDetailItemUnitID = RequestItemOutDetailItemUnitID + WHERE RequestItemOutDetailIsActive = 'Y' + AND (RequestItemOutDetailStatus = 'Process' OR RequestItemOutDetailStatus = 'Partial') + GROUP BY RequestItemOutDetailID) x"; + $qryCount = $this->db->query($sqlCount, [$warehouseID, $divisionID, '%' . $search . '%']); + if (!$qryCount) { + $this->sys_error_db("count item list request error", $this->db); + exit; + } + + $rowsCount = $qryCount->result_array(); + $total = ceil($rowsCount[0]["total"] / $limit); + + $sql = "SELECT + RequestItemOutDetailID as rioDID, + RequestItemOutDetailRequestItemOutID as rioDrioID, + RequestItemOutDetailM_ItemID as rioDItemID, + RequestItemOutDetailItemUnitID as rioDItemUnitID, + IFNULL(RequestItemOutDetailQty, 0) as rioDQty, + IFNULL(T_ItemOutDetailQty, 0) as rioDReceiveQty, + RequestItemOutDetailStatus as rioDStatus, + RequestItemOutID as rioID, + RequestItemOutDate as rioDate, + RequestItemOutNumber as rioNumber, + RequestItemOutWarehouseID as rioWarehouseID, + RequestItemOutS_RegionalID as rioRegionalID, + RequestItemOutM_BranchCode as rioBranchCode, + RequestItemOutNote as rioNote, + RequestItemOutDivisionID as rioDivisionID, + RequestItemOutStatus as rioStatus, + M_ItemID as itemID, + M_ItemCode as itemCode, + M_ItemDesc as itemDesc, + ItemUnitID as unitID, + ItemUnitCode as unitCode, + ItemUnitName as unitName, + StockID, + StockWarehouseID, + StockWarehouseAlmariID, + StockWarehouseRackID, + StockStockNumber, + StockItemID, + StockItemUnitID, + StockItemPrice, + StockBatchNo, + StockED, + StockLastUpdated, + StockUserID, + -- GROUP_CONCAT(CONCAT(StockBatchNo, ' (', StockQty, ')')) AS stockFull, + SUM(StockQty) AS StockQty + FROM request_item_out_detail + JOIN request_item_out ON RequestItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + AND (RequestItemOutStatus = 'Process' OR RequestItemOutStatus = 'Partial') + AND RequestItemOutWarehouseID = ? + AND RequestItemOutDivisionID = ? + JOIN m_item ON RequestItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + AND (M_ItemDesc LIKE ?) + JOIN itemunit ON RequestItemOutDetailItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN stock ON StockItemID = M_ItemID + AND StockItemUnitID = RequestItemOutDetailItemUnitID + AND StockWarehouseID = RequestItemOutWarehouseID + LEFT JOIN t_item_out_detail ON T_ItemOutDetailRequestItemOutID = RequestItemOutDetailRequestItemOutID + AND T_ItemOutDetailM_ItemID = RequestItemOutDetailM_ItemID + AND T_ItemOutDetailItemUnitID = RequestItemOutDetailItemUnitID + WHERE RequestItemOutDetailIsActive = 'Y' + AND (RequestItemOutDetailStatus = 'Process' OR RequestItemOutDetailStatus = 'Partial') + GROUP BY RequestItemOutDetailID + ORDER BY RequestItemOutNumber DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$warehouseID, $divisionID, '%' . $search . '%', $limit, $offset]); + if (!$qry) { + $this->sys_error_db("select item request error", $this->db); + exit; + } + + // echo $this->db->last_query(); + // exit; + + $rows = $qry->result_array(); + + foreach ($rows as $key => $value) { + $rows[$key]['ItemRequest'] = []; + } + + + $result = array( + "records" => $rows, + "total" => $total + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // dijagain itemid dan itemunit harus sama + // agar di stock pemakaian tidak terjadi rancu jumlah stocknya karena berdasarkan itemunit + public function insertUsage($ioID, $userID) + { + try { + // 1. Ambil data dari t_item_out_detail + $this->db->trans_begin(); + $sql_tio = "SELECT T_ItemOutID, + T_ItemOutDate, + T_ItemOutWarehouseID, + T_ItemOutDivisionID, + T_ItemOutDetailID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailItemBatchNo, + T_ItemOutDetailQty, + RequestItemOutS_RegionalID, + RequestItemOutM_BranchCode, + M_ItemDesc + FROM t_item_out_detail + JOIN t_item_out ON T_ItemOutDetailT_ItemOutID = T_ItemOutID + AND T_ItemOutIsActive = 'Y' + JOIN request_item_out ON T_ItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ?"; + + $qry_tio = $this->db->query($sql_tio, [$ioID]); + if (!$qry_tio) { + $this->sys_error_db("select t_item_out error", $this->db); + exit; + } + $rows_tio = $qry_tio->result_array(); + if (count($rows_tio) == 0) { + $this->sys_error("No data found in t_item_out_detail"); + exit; + } + + // 2. Ambil data existing dari item_usage + $sqlusage = "SELECT ItemUsageID, + ItemUsageS_RegionalID, + ItemUsageM_BranchCode, + ItemUsageDivisionID, + ItemUsageM_ItemID, + ItemUsageItemUnitID, + ItemUsageQty, + ItemUsagePrice + FROM item_usage WHERE ItemUsageIsActive = 'Y'"; + $qryusage = $this->db->query($sqlusage, []); + if (!$qryusage) { + $this->db->trans_rollback(); + $this->sys_error_db('get select usage error', $this->db); + exit; + } + $rowsusage = $qryusage->result_array(); + + // 3. Buat mapping untuk pencarian cepat (ItemID dan ItemUsageItemUnitID sebagai key) + $usage_map = []; + foreach ($rowsusage as $usage) { + $key = $usage['ItemUsageM_ItemID'] . '_' . $usage['ItemUsageItemUnitID']; + $usage_map[$key] = $usage; + } + // print_r($usage_map); + // exit; + + // 4. Loop data t_item_out_detail + foreach ($rows_tio as $key => $value) { + // Decode batch JSON + $jsonStr = $value["T_ItemOutDetailItemBatchNo"]; + $batches = []; + + if (!empty($jsonStr)) { + $decode = json_decode($jsonStr, true); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batches = $decode; + } else { + $this->sys_error_db("[Error] decode json for batches number"); + exit; + } + } + + // Buat key untuk pengecekan + $check_key = $value["T_ItemOutDetailM_ItemID"] . '_' . $value["T_ItemOutDetailItemUnitID"]; + + // Cek apakah sudah ada di item_usage + if (isset($usage_map[$check_key])) { + // SUDAH ADA - Update qty dan proses detail + $existing_usage = $usage_map[$check_key]; + $item_usage_id = $existing_usage['ItemUsageID']; + + // Update qty di item_usage (opsional, sesuai kebutuhan) + $sql_update = "UPDATE item_usage + SET ItemUsageQty = ItemUsageQty + ?, + ItemUsageUserID = ?, + ItemUsageLastUpdated = NOW() + WHERE ItemUsageID = ?"; + $qry_update = $this->db->query($sql_update, [ + $value["T_ItemOutDetailQty"], + $userID, + $item_usage_id + ]); + if (!$qry_update) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update item usage", $this->db); + exit; + } + } else { + // BELUM ADA - Insert baru + $sql = "INSERT INTO item_usage( + ItemUsageS_RegionalID, + ItemUsageM_BranchCode, + ItemUsageDivisionID, + ItemUsageM_ItemID, + ItemUsageItemUnitID, + ItemUsageQty, + ItemUsagePrice, + ItemUsageIsActive, + ItemUsageUserID, + ItemUsageCreated) VALUES(?,?,?,?,?,?,?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $value["RequestItemOutS_RegionalID"], + $value["RequestItemOutM_BranchCode"], + $value["T_ItemOutDivisionID"], + $value["T_ItemOutDetailM_ItemID"], + $value["T_ItemOutDetailItemUnitID"], + $value["T_ItemOutDetailQty"], + $batches[0]["StockItemPrice"], // Ambil dari batch pertama + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item usage", $this->db); + exit; + } + + $item_usage_id = $this->db->insert_id(); + } + + // 5. Ambil existing detail untuk item_usage_id ini + $sql_detail = "SELECT ItemUsageDetailID, + ItemUsageDetailStockBatchNo, + ItemUsageDetailQtyReq + FROM item_usage_detail + WHERE ItemUsageDetailItemUsageID = ?"; + $qry_detail = $this->db->query($sql_detail, [$item_usage_id]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed get item usage detail", $this->db); + exit; + } + $existing_details = $qry_detail->result_array(); + + // Buat mapping batch no untuk pencarian cepat + $detail_map = []; + foreach ($existing_details as $detail) { + $detail_map[$detail['ItemUsageDetailStockBatchNo']] = $detail; + } + + // 6. Proses setiap batch + foreach ($batches as $k => $v) { + $batch_no = $v["StockBatchNo"]; + + // Cek apakah batch no sudah ada + if (isset($detail_map[$batch_no])) { + // BATCH SUDAH ADA - Update qty + $existing_detail = $detail_map[$batch_no]; + + $sql_update_detail = "UPDATE item_usage_detail + SET ItemUsageDetailQtyReq = ItemUsageDetailQtyReq + ?, + ItemUsageDetailUserID = ?, + ItemUsageDetailLastUpdated = NOW() + WHERE ItemUsageDetailID = ?"; + $qry_update_detail = $this->db->query($sql_update_detail, [ + floatval($v["QtyReq"]), + $userID, + $existing_detail['ItemUsageDetailID'] + ]); + if (!$qry_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update item usage detail", $this->db); + exit; + } + } else { + // BATCH BELUM ADA - Insert baru + $sql_insert_detail = "INSERT INTO item_usage_detail( + ItemUsageDetailItemUsageID, + ItemUsageDetailWarehouseID, + ItemUsageDetailWarehouseName, + ItemUsageDetailStockID, + ItemUsageDetailStockNumber, + ItemUsageDetailStockItemID, + ItemUsageDetailStockItemUnitID, + ItemUsageDetailItemUnitCode, + ItemUsageDetailItemUnitName, + ItemUsageDetailStockItemPrice, + ItemUsageDetailStockBatchNo, + ItemUsageDetailStockED, + ItemUsageDetailStockQty, + ItemUsageDetailQtyReq, + ItemUsageDetailUserID, + ItemUsageDetailCreated) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())"; + $qry_insert_detail = $this->db->query($sql_insert_detail, [ + $item_usage_id, + $v["WarehouseID"], + $v["WarehouseName"], + $v["StockID"], + $v["StockStockNumber"], + $v["StockItemID"], + $v["StockItemUnitID"], + $v["ItemUnitCode"], + $v["ItemUnitName"], + $v["StockItemPrice"], + $v["StockBatchNo"], + $v["StockED"], + $v["StockQty"], + $v["QtyReq"], + $userID + ]); + if (!$qry_insert_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item usage detail", $this->db); + exit; + } + } + } + } + + $this->db->trans_commit(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function insertItemUsage($ioID, $userID) + { + try { + $this->db->trans_begin(); + $sql_tio = "SELECT T_ItemOutID, + T_ItemOutDate, + T_ItemOutWarehouseID, + T_ItemOutDivisionID, + T_ItemOutDetailID, + T_ItemOutDetailM_ItemID, + T_ItemOutDetailItemUnitID, + T_ItemOutDetailItemBatchNo, + T_ItemOutDetailQty, + RequestItemOutS_RegionalID, + RequestItemOutM_BranchCode, + M_ItemDesc + FROM t_item_out_detail + JOIN t_item_out ON T_ItemOutDetailT_ItemOutID = T_ItemOutID + AND T_ItemOutIsActive = 'Y' + JOIN request_item_out ON T_ItemOutDetailRequestItemOutID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + JOIN m_item ON T_ItemOutDetailM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + WHERE T_ItemOutDetailIsActive = 'Y' + AND T_ItemOutDetailT_ItemOutID = ?"; + $qry_tio = $this->db->query($sql_tio, [$ioID]); + if (!$qry_tio) { + $this->sys_error_db("select t_item_out error", $this->db); + exit; + } + $rows_tio = $qry_tio->result_array(); + if (count($rows_tio) == 0) { + $this->sys_error("No data found in t_item_out_detail"); + exit; + } + + foreach ($rows_tio as $key => $value) { + $jsonStr = $value["T_ItemOutDetailItemBatchNo"]; + $batches = []; + + if (!empty($jsonStr)) { + $decode = json_decode($jsonStr, true); + if ($decode !== null && json_last_error() === JSON_ERROR_NONE) { + $batches = $decode; + } else { + $this->sys_error_db("[Error] decode json for batches number"); + exit; + } + } + + // cari harga per item, + $sqlstock = "SELECT * + FROM stock + WHERE StockItemID = ? + AND StockItemUnitID = ? + AND StockWarehouseID = ?"; + $qrystock = $this->db->query($sqlstock, [ + $value["T_ItemOutDetailM_ItemID"], + $value["T_ItemOutDetailItemUnitID"], + $value["T_ItemOutWarehouseID"] + ]); + if (!$qrystock) { + $this->sys_error_db("select stock error", $this->db); + exit; + } + $rowstock = $qrystock->row_array(); + if (!$rowstock) { + $this->sys_error("No stock found for item " . $value["M_ItemDesc"]); + exit; + } + + $sql = "INSERT INTO item_usage( + ItemUsageS_RegionalID, + ItemUsageM_BranchCode, + ItemUsageDivisionID, + ItemUsageM_ItemID, + ItemUsageItemUnitID, + ItemUsageQty, + ItemUsagePrice, + ItemUsageIsActive, + ItemUsageUserID, + ItemUsageCreated) VALUES(?,?,?,?,?,?,?,?,'Y',?,NOW())"; + $qry = $this->db->query($sql, [ + $value["RequestItemOutS_RegionalID"], + $value["RequestItemOutM_BranchCode"], + $value["T_ItemOutDivisionID"], + $value["T_ItemOutDetailM_ItemID"], + $value["T_ItemOutDetailItemUnitID"], + $value["T_ItemOutDetailQty"], + $rowstock["StockItemPrice"], + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item usage", $this->db); + exit; + } + + $last_id = $this->db->insert_id(); + + foreach ($batches as $k => $v) { + $sql = "INSERT INTO item_usage_detail( + ItemUsageDetailItemUsageID, + ItemUsageDetailWarehouseID, + ItemUsageDetailWarehouseName, + ItemUsageDetailStockID, + ItemUsageDetailStockNumber, + ItemUsageDetailStockItemID, + ItemUsageDetailStockItemUnitID, + ItemUsageDetailItemUnitCode, + ItemUsageDetailItemUnitName, + ItemUsageDetailStockItemPrice, + ItemUsageDetailStockBatchNo, + ItemUsageDetailStockED, + ItemUsageDetailStockQty, + ItemUsageDetailQtyReq, + ItemUsageDetailUserID, + ItemUsageDetailCreated) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $last_id, + $v["WarehouseID"], + $v["WarehouseName"], + $v["StockID"], + $v["StockStockNumber"], + $v["StockItemID"], + $v["StockItemUnitID"], + $v["ItemUnitCode"], + $v["ItemUnitName"], + $v["StockItemPrice"], + $v["StockBatchNo"], + $v["StockED"], + $v["StockQty"], + $v["QtyReq"], + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item usage detail", $this->db); + exit; + } + } + } + + $this->db->trans_commit(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getItemBatchListing() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $batchNo = "%"; + if ($prm['batchno'] != '') { + $batchNo = $prm['batchno'] . "%"; + } + + $sqlbatch = "SELECT + WarehouseID, + WarehouseName, + StockID, + StockStockNumber, + StockItemID, + StockItemUnitID, + ItemUnitCode, + ItemUnitName, + StockItemPrice, + StockBatchNo, + StockED, + StockQty + FROM warehouse + JOIN stock ON StockWarehouseID = WarehouseID + AND StockQty > 0 + JOIN itemunit ON ItemUnitID = StockItemUnitID AND ItemUnitIsActive= 'Y' + WHERE WarehouseIsActive = 'Y' AND WarehouseIsTransit = 'N' + AND WarehouseS_RegionalID = ? + AND WarehouseM_BranchID = ? + AND StockItemID = ? + AND StockItemUnitID = ? + AND StockBatchNo LIKE ?"; + $quebatch = $this->db->query($sqlbatch, [ + $prm['regionalid'], + $prm['branchid'], + $prm['itemid'], + $prm['unitid'], + $batchNo + ]); + if (!$quebatch) { + $this->sys_error_db("error get data draft detail transfer"); + exit; + } + $batch = $quebatch->result_array(); + $result = array( + 'records' => $batch, + 'total' => sizeof($batch) + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function getlevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } else { + $result = array( + "total" => 1, + "records" => $approvalLevel, + "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/itemout/Itemusagev3.php b/application/controllers/mockup/itemout/Itemusagev3.php new file mode 100644 index 0000000..b46b594 --- /dev/null +++ b/application/controllers/mockup/itemout/Itemusagev3.php @@ -0,0 +1,1272 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + // $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $userId = $prm["userId"]; + + $rows = []; + + $query = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + WHERE DivisionIsActive = 'Y' + ORDER BY DivisionID ASC + + "; + $exec = $this->db->query($query); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select division", $this->db); + exit; + } + + $sql = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID AND M_UserDivisionM_UserID = ? + WHERE DivisionIsActive = 'Y' + ORDER BY M_UserDivisionID DESC + LIMIT 1"; + $exec = $this->db->query($sql, [$userId]); + if ($exec) { + $row = $exec->result_array(); + } else { + $this->sys_error_db("select division by user", $this->db); + exit; + } + $result = array( + "records" => $rows, + "selected" => $row + ); + + $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; + } + + // $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $divisionID = $prm["divisionID"]; + + $search = $prm["search"]; + if (empty($search)) { + $search = "%"; + } else { + $search = "%" . $search . "%"; + } + + // $filter = ""; + // if ($divisionID != "0") { + // $filter = " AND ItemUsageDivisionID = {$divisionID}"; + // } + + $number_offset = 0; + $number_limit = 10; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sql_total = "SELECT COUNT(*) AS total + FROM item_usage + JOIN division ON ItemUsageDivisionID = DivisionID + AND DivisionIsActive = 'Y' + JOIN m_item ON ItemUsageM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUsageItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN s_regional ON ItemUsageS_RegionalID= S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON ItemUsageM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE ItemUsageIsActive = 'Y' + AND ItemUsageDivisionID = ? + AND (M_ItemDesc LIKE ?)"; + $qry_total = $this->db->query($sql_total, [$divisionID, $search]); + + $tot_count = 0; + $tot_page = 0; + if ($qry_total) { + $tot_count = $qry_total->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("Failed select item usage total", $this->db); + exit; + } + + $sql = "SELECT ItemUsageID, + ItemUsageQty, + ItemUsagePrice, + DivisionID, + DivisionCode, + DivisionName, + DivisionKodeSurat, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + S_RegionalID, + S_RegionalName, + M_BranchID, + M_BranchName, + '' as listItemUsed + FROM item_usage + JOIN division ON ItemUsageDivisionID = DivisionID + AND DivisionIsActive = 'Y' + JOIN m_item ON ItemUsageM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUsageItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + JOIN s_regional ON ItemUsageS_RegionalID= S_RegionalID AND S_RegionalIsActive = 'Y' + LEFT JOIN m_branch ON ItemUsageM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' + WHERE ItemUsageIsActive = 'Y' + AND ItemUsageDivisionID = ? + AND (M_ItemDesc LIKE ?) + ORDER BY ItemUsageID DESC + LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, [$divisionID, $search, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("Failed select item usage", $this->db); + exit; + } + + + + foreach ($rows as $key => $value) { + + $sqldetail = "SELECT + ItemUsageDetailID, + ItemUsageDetailItemUsageID, + ItemUsageDetailWarehouseID as WarehouseID, + ItemUsageDetailWarehouseName as WarehouseName, + ItemUsageDetailStockID as StockID, + ItemUsageDetailStockNumber as StockNumber, + ItemUsageDetailStockItemID as StockItemID, + ItemUsageDetailStockItemUnitID as StockItemUnitID, + ItemUsageDetailItemUnitCode as ItemUnitCode, + ItemUsageDetailItemUnitName as ItemUnitName, + ItemUsageDetailStockItemPrice as StockItemPrice, + ItemUsageDetailStockBatchNo as StockBatchNo, + ItemUsageDetailStockED as StockED, + ItemUsageDetailStockQty as StockQty, + ItemUsageDetailQtyReq as QtyReq, + 0 as amountUsed + FROM item_usage_detail WHERE ItemUsageDetailIsActive = 'Y' + AND ItemUsageDetailItemUsageID = ?"; + $qrydetail = $this->db->query($sqldetail, [$value['ItemUsageID']]); + if ($qrydetail) { + $batches = $qrydetail->result_array(); + } else { + $this->sys_error_db("Failed select item usage detail", $this->db); + exit; + } + + // Hitung total StockQty + $totalStockQtyReq = 0; + foreach ($batches as $batch) { + $totalStockQtyReq += floatval($batch['QtyReq']); + } + + $rows[$key]['TotalStockQtyReq'] = $totalStockQtyReq; + + $rows[$key]['ItemRequest'] = $batches; + } + + $result = array( + "toal_count" => $tot_count, + "total_page" => $tot_page, + "records" => $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; + $itemUnitID = $prm["itemUnitID"]; + + $sql = "SELECT + uc.UnitConvertID, + uc.UnitConvertFromItemUnitID AS FromUnitID, + uf.ItemUnitName AS FromUnitName, + uc.UnitConvertToItemUnitID AS ToUnitID, + ut.ItemUnitName AS ToUnitName, + uc.UnitConvertAmount + FROM unitconvert uc + JOIN itemunit uf ON uf.ItemUnitID = uc.UnitConvertFromItemUnitID + JOIN itemunit ut ON ut.ItemUnitID = uc.UnitConvertToItemUnitID + WHERE uc.UnitConvertIsActive = 'Y' + AND uc.UnitConvertFromItemUnitID = ?"; + $qry = $this->db->query($sql, [$itemUnitID]); + + $rows = $qry->result_array(); + // if ($qry && $qry->num_rows() > 0) { + // } else { + // // fallback → ambil langsung dari itemunit kalau tidak ada konversi + // $sql2 = "SELECT + // 0 AS UnitConvertID, + // iu.ItemUnitID AS FromUnitID, + // iu.ItemUnitName AS FromUnitName, + // iu.ItemUnitID AS ToUnitID, + // iu.ItemUnitName AS ToUnitName, + // 1 AS UnitConvertAmount + // FROM itemunit iu + // WHERE iu.ItemUnitID = ?"; + // $qry2 = $this->db->query($sql2, [$itemUnitID]); + // $rows = $qry2->result_array(); + // } + + $result = array("records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getUnitByItemId() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $itemId = isset($prm["itemId"]) ? $prm["itemId"] : ""; + + if ($itemId == "") { + $this->sys_error("Invalid Item ID"); + exit; + } + + $sql = "SELECT + DISTINCT ItemUnitID as StockItemUnitID, + ItemUnitCode, + ItemUnitName + FROM itemunitmap + JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND ItemUnitIsActive = 'Y' + WHERE ItemUnitMapM_ItemID = ? + AND ItemUnitMapIsActive = 'Y'"; + $query = $this->db->query($sql, [$itemId]); + + if (!$query) { + $this->sys_error_db("item unit 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); + } + } + + function saveItemUsage() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $ItemUsageID = $prm["ItemUsageID"]; + $ItemRequest = $prm["ItemRequest"]; + $date = date('Y-m-d'); + + $sqlnum = "SELECT `fn_numbering`('IU') as IUnumber"; + $qrynum = $this->db->query($sqlnum, []); + $IUnumber = $qrynum->row()->IUnumber; + + foreach ($ItemRequest as $key => $value) { + $amountUsed = intval($value['amountUsed']); + + // ambil amountUsed yang ada isinya maka lakukan insert + if ($amountUsed > 0) { + + // ambil data item_usage_detail dulu + $sqldetail = "SELECT + ItemUsageDetailID, + ItemUsageDetailItemUsageID, + ItemUsageDetailWarehouseID as WarehouseID, + ItemUsageDetailWarehouseName as WarehouseName, + ItemUsageDetailStockID as StockID, + ItemUsageDetailStockNumber as StockNumber, + ItemUsageDetailStockItemID as StockItemID, + ItemUsageDetailStockItemUnitID as StockItemUnitID, + ItemUsageDetailItemUnitCode as ItemUnitCode, + ItemUsageDetailItemUnitName as ItemUnitName, + ItemUsageDetailStockItemPrice as StockItemPrice, + ItemUsageDetailStockBatchNo as StockBatchNo, + ItemUsageDetailStockED as StockED, + ItemUsageDetailStockQty as StockQty, + ItemUsageDetailQtyReq as QtyReq, + 0 as amountUsed + FROM item_usage_detail WHERE ItemUsageDetailIsActive = 'Y' + AND ItemUsageDetailID = ?"; + $qrydetail = $this->db->query($sqldetail, [$value['ItemUsageDetailID']]); + if ($qrydetail) { + $batches = $qrydetail->result_array(); + } else { + $this->sys_error_db("Failed select item usage detail", $this->db); + exit; + } + + foreach ($batches as $k => $batch) { + // cari batch yang sesuai StockID + if ($batch['StockID'] == $value['StockID']) { + $hargaBase = doubleval($batch['StockItemPrice'] ?? 0); + $fromUnitID = intval($batch['StockItemUnitID']); + $toUnitID = intval($value['StockItemUnitID']); // dari request + + if ($fromUnitID == $toUnitID) { + // unit sama persis, tidak perlu konversi + $batches[$k]['QtyReq'] = floatval($batch['QtyReq']) - $amountUsed; + $batches[$k]['amountUsed'] = $amountUsed; + $batches[$k]['HargaPerUnit'] = $hargaBase; + $batches[$k]['TotalHarga'] = round($amountUsed * $hargaBase, 2); + } else if ($fromUnitID != $toUnitID) { + // unit beda, ambil konversi dari unitconvert + $resultAmountConvert = $this->getConvertAmount($fromUnitID, $toUnitID); + + // konversi jumlah + $pemakaianBase = $amountUsed / $resultAmountConvert; + $batches[$k]['QtyReq'] = floatval($batch['QtyReq']) - $pemakaianBase; + + // harga per unit kecil + $hargaPerUnit = $resultAmountConvert > 0 ? $hargaBase / $resultAmountConvert : 0; + $batches[$k]['amountUsed'] = $amountUsed; + $batches[$k]['HargaPerUnit'] = $hargaPerUnit; + $batches[$k]['TotalHarga'] = round($amountUsed * $hargaPerUnit, 2); + } + } + } + + foreach ($batches as $k => $ub) { + $sql = "INSERT INTO item_used( + ItemUsedDate, + ItemUsedNumber, + ItemUsedItemUsageID, + ItemUsedBatchNo, + ItemUsedM_ItemID, + ItemUsedItemUnitID, + ItemUsedQty, + ItemUsedPrice, + ItemUsedTotal, + ItemUsedIsActive, + ItemUsedUserID, + ItemUsedCreated + ) VALUES(?,?,?,?,?,?,?,?,?,'Y',?,NOW())"; + + $qry = $this->db->query($sql, [ + $date, + $IUnumber, + $ItemUsageID, + $value['StockBatchNo'], + $value['StockItemID'], + $value['StockItemUnitID'], + $ub['amountUsed'], + $ub['HargaPerUnit'], + $ub['TotalHarga'], + $userId + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed insert item used", $this->db); + exit; + } + + $sqlUpdate = "UPDATE item_usage_detail + SET ItemUsageDetailQtyReq = ?, + ItemUsageDetailLastUpdated = NOW() + WHERE ItemUsageDetailID = ?"; + $qryUpdate = $this->db->query($sqlUpdate, [ + $ub['QtyReq'], + $ub['ItemUsageDetailID'] + ]); + if (!$qryUpdate) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update item usage detail", $this->db); + exit; + } + } + } + } + + $this->insertUserActivityUsage($ItemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y')); + $this->insertUserActivityUsed($ItemUsageID, $userId, 'SAVE', 'Pemakaian item dengan kode ' . $IUnumber . ' telah dibuat'); + + $this->db->trans_commit(); + + $result = array( + "records" => "0", + "message" => "Item usage saved successfully", + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getConvertAmount($fromUnitID, $toUnitID) + { + $sql = "SELECT UnitConvertAmount + FROM unitconvert + WHERE UnitConvertFromItemUnitID = ? + AND UnitConvertToItemUnitID = ? + AND UnitConvertIsActive = 'Y'"; + $convert = $this->db->query($sql, [$fromUnitID, $toUnitID])->row(); + + if (!$convert) { + $this->sys_error("Konversi unit tidak ditemukan."); + exit; + } + return intval($convert->UnitConvertAmount); + } + + function getItemUsed() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $itemUsageID = $prm["itemUsageID"]; + $startdate = $prm["startdate"]; + $enddate = $prm["enddate"]; + $search = $prm["search"]; + if (empty($search)) { + $search = "%"; + } else { + $search = "%" . $search . "%"; + } + + $statusConfirm = $prm["statusConfirm"]; + if ($statusConfirm == "Y") { + $statusConfirm = "AND ItemUsedIsConfirm = 'Y'"; + } elseif ($statusConfirm == "N") { + $statusConfirm = "AND ItemUsedIsConfirm = 'N'"; + } else { + $statusConfirm = ""; + } + + $number_offset = 0; + $number_limit = 10; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + $sql_total = "SELECT COUNT(*) AS total + FROM item_used + JOIN m_item ON ItemUsedM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + LEFT JOIN m_user ON ItemUsedUserID = M_UserID + AND M_UserIsActive = 'Y' + WHERE ItemUsedIsActive = 'Y' + AND ItemUsedItemUsageID = ? + AND (M_ItemDesc LIKE ?) + AND ItemUsedDate BETWEEN ? AND ? + $statusConfirm"; + $qry_total = $this->db->query($sql_total, [$itemUsageID, $search, $startdate, $enddate]); + $tot_count = 0; + $tot_page = 0; + if ($qry_total) { + $tot_count = $qry_total->result_array()[0]["total"]; + $tot_page = ceil($tot_count / $number_limit); + } else { + $this->sys_error_db("Failed select item used total", $this->db); + exit; + } + + $sql = "SELECT ItemUsedID, + ItemUsedNumber, + ItemUsedBatchNo, + ItemUsedDate, + ItemUsedQty, + ItemUsedPrice, + ItemUsedTotal, + ItemUsedIsConfirm, + ItemUnitID, + ItemUnitName, + M_ItemID, + M_ItemCode, + M_ItemDesc, + M_UserUsername + FROM item_used + JOIN m_item ON ItemUsedM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + LEFT JOIN m_user ON ItemUsedUserID = M_UserID + AND M_UserIsActive = 'Y' + WHERE ItemUsedIsActive = 'Y' + AND ItemUsedItemUsageID = ? + AND (M_ItemDesc LIKE ?) + AND ItemUsedDate BETWEEN ? AND ? + $statusConfirm + ORDER BY ItemUsedID DESC + LIMIT ? OFFSET ?"; + + $qry = $this->db->query($sql, [$itemUsageID, $search, $startdate, $enddate, $number_limit, $number_offset]); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("Failed select item used", $this->db); + exit; + } + $result = array( + "total_count" => $tot_count, + "total_page" => $tot_page, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function updateItemUsed() + { + try { + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $itemUsedID = (int)$payload['itemUsedID']; + $newUsedQty = (float)$payload['ItemUsedQty']; // qty baru + + $this->db->trans_begin(); + + // ambil data lama dari item_used + $sql_used = "SELECT ItemUsedQty, ItemUsedItemUsageID, ItemUsedItemUnitID + FROM item_used WHERE ItemUsedID = ?"; + $oldData = $this->db->query($sql_used, [$itemUsedID])->row(); + + if (!$oldData) { + $this->db->trans_rollback(); + $this->sys_error("Data pemakaian tidak ditemukan."); + return; + } + + $oldQty = (float)$oldData->ItemUsedQty; + $itemUsageID = $oldData->ItemUsedItemUsageID; + $fromUnitID = $oldData->ItemUsedItemUnitID; + + // ambil item_usage untuk tahu unit besar + $sql_usage = "SELECT ItemUsageQty, ItemUsageItemUnitID + FROM item_usage WHERE ItemUsageID = ?"; + $usageData = $this->db->query($sql_usage, [$itemUsageID])->row(); + + if (!$usageData) { + $this->db->trans_rollback(); + $this->sys_error("Data usage tidak ditemukan."); + return; + } + + $currentUsageQty = (float)$usageData->ItemUsageQty; + $toUnitID = $usageData->ItemUsageItemUnitID; // unit besar + + // ambil konversi unit kecil -> unit besar + $sql_convert = "SELECT UnitConvertAmount + FROM unitconvert + WHERE UnitConvertFromItemUnitID = ? + AND UnitConvertToItemUnitID = ?"; + $convert = $this->db->query($sql_convert, [$toUnitID, $fromUnitID])->row(); + + if (!$convert) { + $this->db->trans_rollback(); + $this->sys_error("Konversi unit tidak ditemukan."); + return; + } + + $convertAmount = (float)$convert->UnitConvertAmount; + + // hitung perubahan qty dalam unit besar + $oldQtyInBig = $oldQty / $convertAmount; + $newQtyInBig = $newUsedQty / $convertAmount; + $diffInBig = $newQtyInBig - $oldQtyInBig; + + // jika diff positif (pemakaian bertambah) → stok dikurangi + if ($diffInBig > 0) { + if ($currentUsageQty < $diffInBig) { + $this->db->trans_rollback(); + $this->sys_error("Stok tidak mencukupi. Stok tersedia: {$currentUsageQty}."); + return; + } + $newUsageQty = $currentUsageQty - $diffInBig; + } + // jika diff negatif (pemakaian berkurang) → stok dikembalikan + else { + $newUsageQty = $currentUsageQty + abs($diffInBig); + } + + // update item_usage + $sql_update_usage = "UPDATE item_usage SET + ItemUsageQty = ?, + ItemUsageLastUpdated = NOW(), + ItemUsageUserID = ? + WHERE ItemUsageID = ?"; + $this->db->query($sql_update_usage, [ + $newUsageQty, + $userId, + $itemUsageID + ]); + + // update item_used + $sql_update_used = "UPDATE item_used SET + ItemUsedQty = ?, + ItemUsedLastUpdated = NOW(), + ItemUsedUserID = ? + WHERE ItemUsedID = ?"; + $this->db->query($sql_update_used, [ + $newUsedQty, + $userId, + $itemUsedID + ]); + + $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?"; + $qryu = $this->db->query($sqlu, [$itemUsedID]); + if (!$qryu) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed get item", $this->db); + exit; + } + $rowitem = $qryu->row_array(); + + $this->insertUserActivityUsage($itemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y')); + $this->insertUserActivityUsed($itemUsageID, $userId, 'UPDATE', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah diupdate'); + + $this->db->trans_commit(); + + $this->sys_ok("Item used berhasil diupdate."); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function deleteItemUsed() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $itemUsedID = $payload["itemUsedID"]; + + // ambil data item_used + $sql = "SELECT * FROM item_used WHERE ItemUsedID = ? AND ItemUsedIsActive = 'Y'"; + $itemUsed = $this->db->query($sql, [$itemUsedID])->row(); + + if (!$itemUsed) { + $this->sys_error("Data item_used tidak ditemukan atau sudah tidak aktif"); + return; + } + + // ambil item_usage + $sql_usage = "SELECT * FROM item_usage WHERE ItemUsageID = ?"; + $itemUsage = $this->db->query($sql_usage, [$itemUsed->ItemUsedItemUsageID])->row(); + + if (!$itemUsage) { + $this->sys_error("Data item_usage tidak ditemukan"); + return; + } + + $restoreQty = (float)$itemUsed->ItemUsedQty; + + // cek apakah unit sama atau perlu konversi + if ($itemUsed->ItemUsedItemUnitID != $itemUsage->ItemUsageItemUnitID) { + $sql_convert = "SELECT UnitConvertAmount + FROM unitconvert + WHERE UnitConvertFromItemUnitID = ? + AND UnitConvertToItemUnitID = ?"; + $convert = $this->db->query($sql_convert, [ + $itemUsage->ItemUsageItemUnitID, + $itemUsed->ItemUsedItemUnitID + ])->row(); + + if (!$convert) { + $this->sys_error("Konversi unit tidak ditemukan, tidak bisa restore qty"); + return; + } + + // ubah qty ke unit besar + $restoreQty = $restoreQty / $convert->UnitConvertAmount; + } + + $this->db->trans_begin(); + + // 1. update item_used menjadi tidak aktif + $sql_update_used = "UPDATE item_used SET + ItemUsedIsActive = 'N', + ItemUsedLastUpdated = NOW(), + ItemUsedUserID = ? + WHERE ItemUsedID = ?"; + $this->db->query($sql_update_used, [$userId, $itemUsedID]); + + // 2. kembalikan qty ke item_usage + $sql_update_usage = "UPDATE item_usage SET + ItemUsageQty = ItemUsageQty + ?, + ItemUsageLastUpdated = NOW(), + ItemUsageUserID = ? + WHERE ItemUsageID = ?"; + $this->db->query($sql_update_usage, [ + $restoreQty, + $userId, + $itemUsage->ItemUsageID + ]); + + $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?"; + $qryu = $this->db->query($sqlu, [$itemUsedID]); + if (!$qryu) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed get item", $this->db); + exit; + } + $rowitem = $qryu->row_array(); + + $this->insertUserActivityUsage($itemUsage->ItemUsageID, $userId, 'UPDATE', 'Pemakaian item pada tanggal ' . date('d-m-Y')); + $this->insertUserActivityUsed($itemUsedID, $userId, 'DELETE', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah dihapus'); + $this->db->trans_commit(); + + $this->sys_ok("ItemUsed berhasil dihapus dan qty dikembalikan"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function confirmItemUsed() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $this->db->trans_begin(); + + $itemUsedID = $payload["itemUsedID"]; + + // ambil data item_used + $sql = "SELECT * FROM item_used WHERE ItemUsedID = ? AND ItemUsedIsActive = 'Y'"; + $itemUsed = $this->db->query($sql, [$itemUsedID])->row(); + + if (!$itemUsed) { + $this->db->trans_rollback(); + $this->sys_error("Data item_used tidak ditemukan atau sudah tidak aktif"); + exit; + } + + // update status konfirmasi + $sql_update = "UPDATE item_used SET + ItemUsedIsConfirm = 'Y', + ItemUsedLastUpdated = NOW(), + ItemUsedUserID = ? + WHERE ItemUsedID = ?"; + $this->db->query($sql_update, [$userId, $itemUsedID]); + + // generate jurnal + $this->generateJurnal($itemUsedID); + + $sqlu = "SELECT ItemUsedID, ItemUsedNumber FROM item_used WHERE ItemUsedIsActive = 'Y' AND ItemUsedID = ?"; + $qryu = $this->db->query($sqlu, [$itemUsedID]); + if (!$qryu) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed get item", $this->db); + exit; + } + $rowitem = $qryu->row_array(); + + $this->insertUserActivityUsed($itemUsedID, $userId, 'KONFIRMASI', 'Pemakaian item dengan kode ' . $rowitem['ItemUsedNumber'] . ' telah dikonfirmasi'); + + $this->db->trans_commit(); + $this->sys_ok("ItemUsed berhasil dikonfirmasi"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function generateJurnal($itemusedID) + { + try { + $this->db->trans_begin(); + $user = $this->sys_user; + + $sqldata = "SELECT ItemUsedID, + DATE_FORMAT(ItemUsedDate, '%d-%m-%Y') as ItemUsedDate, + ItemUsedNumber, + ItemUsedBatchNo, + ItemUsedQty, + ItemUsedPrice, + ItemUsedTotal, + ItemUsageID, + ItemUsageQty, + ItemUsagePrice, + ItemUsedTotal, + M_ItemID, + CASE + WHEN M_ItemCode IS NULL OR M_ItemCode = '' + THEN M_ItemDesc + ELSE CONCAT(M_ItemCode, ' - ', M_ItemDesc) + END AS M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + M_UserUsername, + DivisionID, + DivisionCode, + DivisionName + FROM item_used + JOIN item_usage ON ItemUsedItemUsageID = ItemUsageID + AND ItemUsageIsActive = 'Y' + JOIN m_item ON ItemUsedM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUsedItemUnitID = ItemUnitID + AND ItemUnitIsActive = 'Y' + LEFT JOIN m_user ON ItemUsedUserID = M_UserID + LEFT JOIN m_userdivision ON M_UserDivisionM_UserID = M_UserID + AND M_UserDivisionIsActive = 'Y' + LEFT JOIN division ON M_UserDivisionDivisionID = DivisionID + AND DivisionIsActive = 'Y' + WHERE ItemUsedIsActive = 'Y' + AND ItemUsedID = ?"; + $qrydata = $this->db->query($sqldata, [$itemusedID]); + if (!$qrydata) { + $this->db->trans_rollback(); + $this->sys_error_db("get data item used error", $this->db); + exit; + } + $datarow = $qrydata->row_array(); + + // generate numbering jurnal + $sql = "SELECT `fn_numbering`('J') AS numbering"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("get numbering error", $this->db); + $this->db->trans_rollback(); + exit; + } + $numbering = $qry->row_array()["numbering"]; + + // ambil data periode + $sql = "SELECT periodeID FROM periode + WHERE DATE_FORMAT(NOW(), '%Y-%m-%d') BETWEEN periodeStartDate AND periodeEndDate + AND periodeIsActive= 'Y' + AND periodeIsClosed = 'N'"; + $qry = $this->db->query($sql, []); + if (!$qry) { + $this->sys_error_db("get periode error", $this->db); + $this->db->trans_rollback(); + exit; + } + $dataPeriode = $qry->row_array(); + if (empty($dataPeriode)) { + $this->sys_error("Periode untuk generate jurnal tidak ditemukan"); + $this->db->trans_rollback(); + exit; + } + $periodeID = $dataPeriode["periodeID"]; + + $jurnalTitle = "Jurnal pemakaian item No. {$datarow['ItemUsedNumber']} Tanggal {$datarow['ItemUsedDate']}"; + $jurnalDesc = "Jurnal pemakaian item No. {$datarow['ItemUsedNumber']} Tanggal {$datarow['ItemUsedDate']} dengan nama item {$datarow['M_ItemDesc']}, Batch No {$datarow['ItemUsedBatchNo']} oleh {$datarow['M_UserUsername']} divisi {$datarow['DivisionName']}"; + + // ambil item untuk cek persediaan + $sqlItem = "SELECT * FROM m_item WHERE M_ItemID = ?"; + $qryItem = $this->db->query($sqlItem, [ + $datarow["M_ItemID"] + ]); + if (!$sqlItem) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, qry item", $this->db); + exit; + } + $cekItem = $qryItem->row_array(); + + if (empty($cekItem)) { + $this->db->trans_rollback(); + $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} tidak ditemukan", $this->db); + exit; + } + if ($cekItem['M_ItemItem_CategoryID'] == 0 || $cekItem['M_ItemItem_CategoryID'] == null || $cekItem['M_ItemItem_CategoryID'] == '') { + $this->db->trans_rollback(); + $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum memiliki kategori", $this->db); + exit; + } + + // cek persediaan + $date = date('Y-m-d'); + $detailJurnal = []; + if (intval($cekItem['M_ItemItem_CategoryID']) == 1) { + if ($cekItem['M_ItemNat_SubGroupID'] == null || $cekItem['M_ItemNat_SubGroupID'] == 0 || $cekItem['M_ItemNat_SubGroupID'] == '') { + $this->db->trans_rollback(); + $this->sys_error_db("Item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum memiliki sub grup", $this->db); + exit; + } + $sqlSubGrup = "SELECT * FROM map_nat_subgroup + WHERE MapNatSub_NatGroupID = ? + AND MapNatSub_NatSubGroupID = ? + AND MapNatSub_IsActive = 'Y'"; + $qrySubGrup = $this->db->query($sqlSubGrup, [ + $cekItem['M_ItemNat_GroupID'], + $cekItem['M_ItemNat_SubGroupID'] + ]); + if (!$qrySubGrup) { + $this->db->trans_rollback(); + $this->sys_error_db("ERROR, get map nat subgrup", $this->db); + exit; + } + $rowMapNatSubGrup = $qrySubGrup->row_array(); + // print_r($rowMapNatSubGrup); + + if ( + $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'] == null || + $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'] == '' || + + $rowMapNatSubGrup['MapNatSub_PersediaanCoaAccountNo'] == null || + $rowMapNatSubGrup['MapNatSub_PersediaanCoaAccountNo'] == '' || + + $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'] == null || + $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'] == '' + + ) { + $this->db->trans_rollback(); + $this->sys_error_db("Coa persediann, item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum termapping", $this->db);; + exit; + } + + if ( + $rowMapNatSubGrup['MapNatSub_BiayaCoaID'] == null || + $rowMapNatSubGrup['MapNatSub_BiayaCoaID'] == '' || + + $rowMapNatSubGrup['MapNatSub_BiayaCoaAccountNo'] == null || + $rowMapNatSubGrup['MapNatSub_BiayaCoaAccountNo'] == '' || + + $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'] == null || + $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'] == '' + ) { + $this->db->trans_rollback(); + $this->sys_error_db("Coa biaya pemakaian, item {$datarow['ItemUsedNumber']} {$datarow['M_ItemDesc']} belum termapping", $this->db);; + exit; + } + + $detailJurnal = [ + [ + 'coaID' => $rowMapNatSubGrup['MapNatSub_BiayaCoaID'], + 'xdescription' => $rowMapNatSubGrup['MapNatSub_BiayaCoaDescription'], + 'debit' => $datarow['ItemUsedTotal'], + 'credit' => 0 + ], + [ + 'coaID' => $rowMapNatSubGrup['MapNatSub_PersediaanCoaID'], + 'xdescription' => $rowMapNatSubGrup['MapNatSub_PersediaanCoaDescription'], + 'debit' => 0, + 'credit' => $datarow['ItemUsedTotal'] + ] + ]; + } + + $this->saveJurnal( + $date, + $jurnalDesc, + $periodeID, + $numbering, + $jurnalTitle, + $detailJurnal, + $user['M_BranchCompanyID'], + $user['S_RegionalID'], + $user['M_BranchCode'], + $datarow['ItemUsedNumber'] + ); + + $this->db->trans_commit(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveJurnal( + $date, + $jurnalDesc, + $periodeID, + $numbering, + $jurnalTitle, + $detailJurnal, + $branchCompanyID, + $regionalID, + $branchCode, + $noIU + ) { + try { + + $this->db->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $sql = "INSERT INTO jurnal( + jurnalM_BranchCompanyID, + JurnalS_RegionalID, + jurnalM_BranchCode, + jurnalperiodeID, + jurnalNo, + jurnalTitle, + jurnalDescription, + jurnalDate, + jurnalJurnalTypeID, + jurnalIsActive, + jurnalCreated, + jurnalM_UserID + ) VALUES(?,?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry = $this->db->query($sql, array( + $branchCompanyID, + $regionalID, + $branchCode, + $periodeID, + $numbering, + $jurnalTitle, + $jurnalDesc, + $date, + 23, + $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["xdescription"], + $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; + } + + $tx_id = $this->db->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'AUTOITEMUSAGE', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db->query($sql, array( + $last_id, + $tx_id, + $noIU, + $userid, + $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; + } + } + + $this->db->trans_commit(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function insertUserActivityUsage($itemusageID, $userId, $status, $userdesc) + { + try { + // insert log + $sql_json = "SELECT item_usage.* + FROM item_usage + WHERE ItemUsageIsActive = 'Y' + AND ItemUsageID = ?"; + $qry_json = $this->db->query($sql_json, [$itemusageID]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json io error"); + exit; + } + $row_json = $qry_json->row_array(); + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('USAGE',?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $status, + $userdesc, + $itemusageID, + json_encode($row_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity error", $this->db); + exit; + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function insertUserActivityUsed($itemusedID, $userId, $status, $userdesc) + { + try { + // insert log + $sql_json = "SELECT item_used.* + FROM item_used + WHERE ItemUsedIsActive = 'Y' + AND ItemUsedID = ?"; + $qry_json = $this->db->query($sql_json, [$itemusedID]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json io error"); + exit; + } + $row_json = $qry_json->row_array(); + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('USED',?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $status, + $userdesc, + $itemusedID, + json_encode($row_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity error", $this->db); + exit; + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/itemout/RequestItemOut.php b/application/controllers/mockup/itemout/RequestItemOut.php new file mode 100644 index 0000000..1a0ff22 --- /dev/null +++ b/application/controllers/mockup/itemout/RequestItemOut.php @@ -0,0 +1,2231 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + // $currentPage = isset($payload["currentPage"]) ? $payload["currentPage"] : 1; + $pageSize = isset($payload["pageSize"]) ? $payload["pageSize"] : 10; + // $offset = ($currentPage - 1) * $pageSize; + $startDate = isset($payload["startDate"]) ? $payload["startDate"] : ""; + $endDate = isset($payload["endDate"]) ? $payload["endDate"] : ""; + $status = isset($payload["status"]) ? $payload["status"] : ""; + $search = isset($payload["search"]) ? $payload["search"] : ""; + + $approveLevelID = $this->sys_user['M_UserM_ApproveLevelID']; + $flag = $payload['flag']; + + if ($approveLevelID == '1') { + if ($flag == 'G') { + $sqlRIO = " AND RequestItemOutVerifiedUserID = 0"; + } + } else if ($approveLevelID == '2') { + if ($flag == 'G') { + $sqlRIO = " AND RequestItemOutVerifiedUserID != 0"; + } + } + + $totalCount = 0; + $totalPage = 1; + + $number_offset = 0; + $number_limit = 10; + if ($payload["currentPage"] > 0) { + $number_offset = ($payload["currentPage"] - 1) * $number_limit; + } + + $sql = "SELECT COUNT(*) as total + FROM request_item_out + JOIN s_regional ON S_RegionalID = RequestItemOutS_RegionalID + WHERE + RequestItemOutIsActive = 'Y' AND + ( RequestItemOutDate BETWEEN ? AND ? ) AND + ( RequestItemOutStatus = ? OR ? = '' ) AND + ( RequestItemOutNumber LIKE ?) + $sqlRIO + ORDER BY RequestItemOutNumber DESC"; + + $exec = $this->db->query($sql, [$startDate, $endDate, $status, $status, '%' . $search . '%']); + + if ($exec) { + $totalCount = $exec->result_array()[0]["total"]; + $totalPage = ceil($totalCount / $pageSize); + } else { + $this->sys_error_db("count request item out", $this->db); + exit; + } + + $sql = "SELECT DISTINCT RequestItemOutID as rioId, + RequestItemOutNumber as rioNumber, + RequestItemOutWarehouseID as rioWarehouseId, + RequestItemOutDate as rioDate, + RequestItemOutStatus as rioStatus, + RequestItemOutS_RegionalID as rioRegionalId, + S_RegionalName as rioRegionalName, + RequestItemOutM_BranchCode as rioBranchCode, + M_BranchName as rioBranchName, + RequestItemOutNote as rioNote, + RequestItemOutDivisionID as rioDivisionId, + IFNULL(S_RegionalID, '') as S_RegionalID, + IFNULL(S_RegionalName, '') as S_RegionalName, + IFNULL(M_BranchCode, '') as M_BranchCode, + IFNULL(M_BranchName, '') as M_BranchName, + RequestItemOutVerifiedUserID, + RequestItemOutVerifiedDate, + RequestItemOutApprovedUserID, + RequestItemOutApprovedDate + FROM request_item_out + JOIN s_regional ON S_RegionalID = RequestItemOutS_RegionalID + LEFT JOIN m_branch ON M_BranchCode = RequestItemOutM_BranchCode + WHERE + RequestItemOutIsActive = 'Y' AND + ( RequestItemOutDate BETWEEN ? AND ? ) AND + ( RequestItemOutStatus = ? OR ? = '' ) AND + ( RequestItemOutNumber LIKE ?) + $sqlRIO + ORDER BY RequestItemOutNumber DESC + LIMIT ? OFFSET ?"; + + $exec = $this->db->query($sql, [$startDate, $endDate, $status, $status, '%' . $search . '%', $number_limit, $number_offset]); + if (!$exec) { + $this->sys_error_db("select request item out", $this->db); + exit; + } + + $rows = $exec->result_array(); + + + $result = array( + "total" => $totalPage, + "totalFilter" => $totalCount, + "records" => $rows + ); + + $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; + } + + $payload = $this->sys_input; + + // Menggunakan parameter query + $queryCount = "SELECT count(*) as total + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailIsActive = 'Y' + AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?"; + $exec = $this->db->query($queryCount, [$payload['PRID']]); + + $totalCount = 0; + + if ($exec) { + $totalCount = $exec->result_array()[0]["total"]; + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select purchase request detail", $this->db);; + exit; + } + + // Menggunakan parameter query + $query = "SELECT *, + ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectDetailID) RowNumber + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailIsActive = 'Y' + AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ? + ORDER BY PurchaseRequestDirectDetailStatus ASC, + PurchaseRequestDirectDetailID ASC"; + $exec = $this->db->query($query, [$payload['PRID']]); + + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select purchase request detail", $this->db); + exit; + } + + $result = array( + "totalFilter" => $totalCount, + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranch() + { + try { + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, []); + 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 getRegionalBranchByUser() + { + try { + $userId = $this->sys_user["M_UserID"]; + + $query = "SELECT DISTINCT + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + ORDER BY M_BranchName ASC"; + $exec = $this->db->query($query, []); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select branch", $this->db); + exit; + } + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $rioID = isset($prm["RIOID"]) ? $prm["RIOID"] : ""; + + // Menggunakan parameter query untuk delete + $sql = "UPDATE request_item_out SET + RequestItemOutLastUpdated = NOW(), + RequestItemOutUserID = ?, + RequestItemOutIsActive = 'N' + WHERE RequestItemOutID = ?"; + + $deleteParams = [$userId, $rioID]; + + $exec = $this->db->query($sql, $deleteParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("request delete error", $this->db); + exit; + } + + $sql_detail = "UPDATE request_item_out_detail SET + RequestItemOutDetailIsActive = 'N', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailRequestItemOutID = ?"; + $deleteDetailParams = [$userId, $rioID]; + + $execDetail = $this->db->query($sql_detail, $deleteDetailParams); + + if (!$execDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("request dwtail delete error", $this->db); + exit; + } + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'N' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$rioID]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di hapus"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'N' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$rioID]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','DELETE',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $rioID, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $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 saveDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $PRDTotalPrice = intval($payload['PRDAmountRequest']) * intval($payload['PRDEstimationPrice']); + + // Gunakan parameter untuk query existensi + $query = "SELECT COUNT(*) as exist + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailIsActive = 'Y' + AND PurchaseRequestDirectDescription = ? + AND PurchaseRequestDirectDetailPurchaseRequestDirectID = ?"; + $existParams = [$payload['PRDDescriptionDetail'], $payload['PRID']]; + $exist = $this->db->query($query, $existParams); + + if ($exist) { + $row = $exist->row()->exist; + } else { + $this->sys_error_db("exist error", $this->db); + exit; + } + + if ($row == 0) { + // Gunakan parameter untuk query insert + $sql = "INSERT INTO purchase_request_direct_detail( + PurchaseRequestDirectDetailPurchaseRequestDirectID, + PurchaseRequestDirectDescription, + PurchaseRequestDirectDetailAmountRequest, + PurchaseRequestDirectDetailAmount, + PurchaseRequestDirectDetailEstimationPrice, + PurchaseRequestDirectDetailTotalEstimationPrice, + PurchaseRequestDirectDetailTotalRealitationPrice, + PurchaseRequestDirectDetailStatus, + PurchaseRequestDirectDetailIsActive, + PurchaseRequestDirectDetailCreated, + PurchaseRequestDirectDetailLastUpdated, + PurchaseRequestDirectDetailDeleted, + PurchaseRequestDirectDetailCreatedUserID, + PurchaseRequestDirectDetailLastUpdatedUserID, + PurchaseRequestDirectDetailDeletedUserID + ) VALUES (?, ?, ?, NULL, ?, ?, NULL, 'Pending', 'Y', NOW(), NULL, NULL, ?, NULL, NULL)"; + + $insertParams = [ + $payload['PRID'], + $payload['PRDDescriptionDetail'], + $payload['PRDAmountRequest'], + $payload['PRDEstimationPrice'], + $PRDTotalPrice, + $userId + ]; + + $exec = $this->db->query($sql, $insertParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("request insert error", $this->db); + exit; + } else { + // Gunakan parameter untuk query total harga + $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ? + AND PurchaseRequestDirectDetailIsActive = 'Y'"; + $totalPriceParams = [$payload['PRID']]; + $exec = $this->db->query($sqlTotalPrice, $totalPriceParams); + $total = 0; + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } else { + $total = $exec->result_array()[0]["Total"]; + } + + // Gunakan parameter untuk query update + $sql = "UPDATE purchase_request_direct SET + PurchaseRequestDirectTotalEstimation = ?, + PurchaseRequestLastUpdated = NOW(), + PurchaseRequestLastUpdatedUserID = ? + WHERE PurchaseRequestDirectID = ? + AND PurchaseRequestDirectIsActive = 'Y'"; + $updateParams = [$total, $userId, $payload['PRID']]; + $exec = $this->db->query($sql, $updateParams); + } + + $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 updateDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + $PRDTotalPrice = intval($payload["PRDAmountRequest"]) * intval($payload["PRDEstimationPrice"]); + + // Gunakan parameter untuk query update + $sql = "UPDATE purchase_request_direct_detail SET + PurchaseRequestDirectDescription = ?, + PurchaseRequestDirectDetailAmountRequest = ?, + PurchaseRequestDirectDetailEstimationPrice = ?, + PurchaseRequestDirectDetailTotalEstimationPrice = ?, + PurchaseRequestDirectDetailLastUpdated = NOW(), + PurchaseRequestDirectDetailLastUpdatedUserID = ? + WHERE PurchaseRequestDirectDetailID = ?"; + + $updateParams = [ + $payload["PRDDescriptionDetail"], + $payload["PRDAmountRequest"], + $payload["PRDEstimationPrice"], + $PRDTotalPrice, + $userId, + $payload["PRDID"] + ]; + + $exec = $this->db->query($sql, $updateParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("request update error", $this->db); + exit; + } else { + // Gunakan parameter untuk query total harga + $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ? + AND PurchaseRequestDirectDetailIsActive = 'Y'"; + $totalPriceParams = [$payload["PRID"]]; + $exec = $this->db->query($sqlTotalPrice, $totalPriceParams); + $total = 0; + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } else { + $total = $exec->result_array()[0]["Total"]; + } + + // Gunakan parameter untuk query update total + $sql = "UPDATE purchase_request_direct SET + PurchaseRequestDirectTotalEstimation = ?, + PurchaseRequestLastUpdated = NOW(), + PurchaseRequestLastUpdatedUserID = ? + WHERE PurchaseRequestDirectID = ? + AND PurchaseRequestDirectIsActive = 'Y'"; + $updateTotalParams = [$total, $userId, $payload["PRID"]]; + $exec = $this->db->query($sql, $updateTotalParams); + } + + $this->db->trans_commit(); + + $result = array("total" => 1, "records" => array("xId" => $payload["PRDID"])); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Gunakan parameter untuk query delete + $sql = "UPDATE purchase_request_direct_detail SET + PurchaseRequestDirectDetailDeleted = NOW(), + PurchaseRequestDirectDetailDeletedUserID = ?, + PurchaseRequestDirectDetailIsActive = 'N' + WHERE PurchaseRequestDirectDetailID = ?"; + $deleteParams = [$userId, $payload["PRDID"]]; + $exec = $this->db->query($sql, $deleteParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("request delete error", $this->db); + exit; + } else { + // Gunakan parameter untuk query total harga + $sqlTotalPrice = "SELECT SUM(PurchaseRequestDirectDetailTotalEstimationPrice) AS Total + FROM purchase_request_direct_detail + WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ? + AND PurchaseRequestDirectDetailIsActive = 'Y'"; + $totalPriceParams = [$payload["PRID"]]; + $exec = $this->db->query($sqlTotalPrice, $totalPriceParams); + $total = 0; + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } else { + $total = $exec->result_array()[0]["Total"] ?? 0; + } + + // Gunakan parameter untuk query update total + $sql = "UPDATE purchase_request_direct SET + PurchaseRequestDirectTotalEstimation = ?, + PurchaseRequestLastUpdated = NOW(), + PurchaseRequestLastUpdatedUserID = ? + WHERE PurchaseRequestDirectID = ? + AND PurchaseRequestDirectIsActive = 'Y'"; + $updateTotalParams = [$total, $userId, $payload["PRID"]]; + $exec = $this->db->query($sql, $updateTotalParams); + } + + $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 orderRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $this->db->trans_begin(); + + $payload = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + // Gunakan parameter untuk query update detail + $sqlDetail = "UPDATE purchase_request_direct_detail SET + PurchaseRequestDirectDetailLastUpdated = NOW(), + PurchaseRequestDirectDetailLastUpdatedUserID = ? + WHERE PurchaseRequestDirectDetailPurchaseRequestDirectID = ? + AND PurchaseRequestDirectDetailIsActive = 'Y' + AND PurchaseRequestDirectDetailStatus = 'Pending'"; + $detailParams = [$userId, $payload["PRID"]]; + $exec = $this->db->query($sqlDetail, $detailParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } + + // Gunakan parameter untuk query update status + $sql = "UPDATE purchase_request_direct SET + PurchaseRequestDirectStatus = 'Pending', + PurchaseRequestLastUpdated = NOW(), + PurchaseRequestLastUpdatedUserID = ? + WHERE PurchaseRequestDirectID = ? + AND PurchaseRequestDirectIsActive = 'Y'"; + $updateParams = [$userId, $payload["PRID"]]; + $exec = $this->db->query($sql, $updateParams); + + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } + + $this->db->trans_commit(); + + // Gunakan parameter untuk query select + $sql = "SELECT *, + ROW_NUMBER() OVER(ORDER BY PurchaseRequestDirectNumber) RowNumber + FROM purchase_request_direct + WHERE PurchaseRequestDirectIsActive = 'Y' + AND PurchaseRequestCreatedUserID = ? + AND PurchaseRequestDirectID = ?"; + $selectParams = [$userId, $payload["PRID"]]; + $exec = $this->db->query($sql, $selectParams); + + $row = []; + if (!$exec) { + $this->db->trans_rollback(); + $this->sys_error_db("order purchase request error", $this->db); + exit; + } else { + $row = $exec->result_array(); + } + $result = array("total" => 1, "records" => $row); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getDivisionByUser() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + // $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $userId = $prm["userId"]; + + $rows = []; + + $query = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + WHERE DivisionIsActive = 'Y' + ORDER BY DivisionName ASC"; + $exec = $this->db->query($query); + if ($exec) { + $rows = $exec->result_array(); + } else { + $this->db->trans_rollback(); + $this->sys_error_db("select division", $this->db); + exit; + } + + if ($prm["act"] == "edit") { + $sql = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID + WHERE DivisionIsActive = 'Y' + AND DivisionID = ? + ORDER BY M_UserDivisionID DESC + LIMIT 1"; + $exec = $this->db->query($sql, [$prm["DivisionID"]]); + if ($exec) { + $row = $exec->result_array(); + } else { + $this->sys_error_db("select division", $this->db); + exit; + } + } else { + $sql = "SELECT DISTINCT + DivisionID, + DivisionCode, + DivisionName + FROM division + JOIN m_userdivision ON M_UserDivisionDivisionID = DivisionID AND M_UserDivisionM_UserID = ? + WHERE DivisionIsActive = 'Y' + ORDER BY M_UserDivisionID DESC + LIMIT 1"; + $exec = $this->db->query($sql, [$userId]); + if ($exec) { + $row = $exec->result_array(); + } else { + $this->sys_error_db("select division by user", $this->db); + exit; + } + } + + $result = array( + "records" => $rows, + "selected" => $row + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemGroupSubGroup() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $division = isset($prm["division"]) ? $prm["division"] : ""; + + $rows = []; + $rows[] = array("Nat_GroupID" => "", "Nat_GroupCode" => "", "Nat_GroupName" => "Semua Grup", "subGroups" => [ + array("Nat_SubGroupID" => "", "Nat_SubGroupCode" => "", "Nat_SubGroupName" => "Semua Sub Grup") + ]); + + $sql = "SELECT DISTINCT + Nat_GroupID, + Nat_GroupCode, + Nat_GroupName, + '' as subGroups + FROM nat_group + JOIN m_item ON M_ItemNat_GroupID = Nat_GroupID AND M_ItemIsActive = 'Y' + JOIN m_itemdivision ON M_ItemDivisionM_ItemID = M_ItemID AND M_ItemDivisionIsActive = 'Y' AND (M_ItemDivisionDivisionID = ? OR ? = '') + WHERE Nat_GroupIsActive = 'Y' + ORDER BY Nat_GroupID ASC"; + + $query = $this->db->query($sql, [$division, $division]); + + if (!$query) { + $this->sys_error_db("item group list", $this->db); + exit; + } + + $rst = $query->result_array(); + foreach ($rst as $key => $row) { + $row["subGroups"] = array( + array("Nat_SubGroupID" => "", "Nat_SubGroupCode" => "", "Nat_SubGroupName" => "Semua Sub Grup") + ); + if ($row["Nat_GroupID"] != "") { + $sqlSubGroup = "SELECT DISTINCT + Nat_SubGroupID, + Nat_SubGroupCode, + Nat_SubGroupName + FROM nat_subgroup + WHERE Nat_SubGroupIsActive = 'Y' + AND Nat_SubGroupNat_GroupID = ? + ORDER BY Nat_SubGroupID ASC"; + $querySubGroup = $this->db->query($sqlSubGroup, [$row["Nat_GroupID"]]); + if (!$querySubGroup) { + $this->sys_error_db("item sub group list", $this->db); + exit; + } + $subGroups = $querySubGroup->result_array(); + foreach ($subGroups as $keySubGroup => $subGroup) { + $row["subGroups"][] = $subGroup; + } + } + $rows[] = $row; + } + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + + + function getItems() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = isset($prm["search"]) ? $prm["search"] : ""; + $division = isset($prm["division"]) ? $prm["division"] : ""; + $itemGroup = isset($prm["itemGroup"]) ? $prm["itemGroup"] : ""; + $itemSubGroup = isset($prm["itemSubGroup"]) ? $prm["itemSubGroup"] : ""; + $unitPurchase = isset($prm["unitPurchase"]) ? $prm["unitPurchase"] : "purchase"; + $currentPage = isset($prm["currentPage"]) ? $prm["currentPage"] : 1; + $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : 0; + + $params = []; + // Menambahkan parameter untuk unitPurchase + $params[] = $unitPurchase; + $params[] = $unitPurchase; + + $filterDivision = ""; + if ($division != "") { + $filterDivision = "JOIN m_itemdivision ON M_ItemDivisionM_ItemID = M_ItemID AND M_ItemDivisionIsActive = 'Y' AND (M_ItemDivisionDivisionID = ? OR ? = '')"; + $params[] = $division; + $params[] = $division; + } + + $filterItemGroup = ""; + if ($itemGroup != "") { + $filterItemGroup = "JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID AND Nat_GroupIsActive = 'Y' AND (Nat_GroupID = ? OR ? = '')"; + $params[] = $itemGroup; + $params[] = $itemGroup; + } + + $filterItemSubGroup = ""; + if ($itemSubGroup != "") { + $filterItemSubGroup = "JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID AND Nat_SubGroupIsActive = 'Y' AND (Nat_SubGroupID = ? OR ? = '')"; + $params[] = $itemSubGroup; + $params[] = $itemSubGroup; + } + + + $params[] = '%' . $search . '%'; + + $limit = 10; + $offset = ($currentPage - 1) * $limit; + + + $sql = "SELECT COUNT(*) as total FROM ( + SELECT + DISTINCT M_ItemID + FROM m_item + JOIN itemunitmap ON ItemUnitMapM_ItemID = M_ItemID AND + ((ItemUnitMapIsPurchase = 'Y' AND ? = 'purchase') OR + (ItemUnitMapIsBase = 'Y' AND ? = 'base')) AND + ItemUnitMapIsActive = 'Y' + JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND + ItemUnitIsActive = 'Y' + $filterDivision + $filterItemGroup + $filterItemSubGroup + WHERE M_ItemIsActive = 'Y' AND + M_ItemItem_CategoryID = '1' + AND M_ItemDesc LIKE ? + ) as item"; + + $query = $this->db->query($sql, $params); + if (!$query) { + $this->sys_error_db("item list", $this->db); + exit; + } + + $row = $query->row_array(); + $total = ceil($row["total"] / $limit); + + $params[] = $limit; + $params[] = $offset; + + $sql = "SELECT + DISTINCT M_ItemID as itemId, + M_ItemCode as itemCode, + M_ItemDesc as itemDesc, + 0 as qty, + ItemUnitID as unitId, + ItemUnitCode as unitCode, + ItemUnitName as unitName, + 0 as detailId, + 'draft' as status, + 0 as stockDivisi, + 0 as stockWarehouse + FROM m_item + JOIN itemunitmap ON ItemUnitMapM_ItemID = M_ItemID AND + ((ItemUnitMapIsPurchase = 'Y' AND ? = 'purchase') OR + (ItemUnitMapIsBase = 'Y' AND ? = 'base')) AND + ItemUnitMapIsActive = 'Y' + JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND + ItemUnitIsActive = 'Y' + $filterDivision + $filterItemGroup + $filterItemSubGroup + WHERE M_ItemIsActive = 'Y' AND + M_ItemItem_CategoryID = '1' + AND M_ItemDesc LIKE ? + ORDER BY M_ItemDesc ASC + LIMIT ? OFFSET ?"; + + // Parameter akhir yang digunakan untuk query + $searchParam = $params; + + $query = $this->db->query($sql, $searchParam); + + if (!$query) { + $this->sys_error_db("item list", $this->db); + //$this->sys_error($this->db->error()); + exit; + } + // echo $this->db->last_query(); + // exit; + + $rows = $query->result_array(); + if (count($rows) > 0) { + foreach ($rows as $key => $row) { + $rows[$key]["isSelected"] = $row["isSelected"] == "Y" ? true : false; + + $sqldivisi = "SELECT StockID, + StockItemPrice, + StockBatchNo, + StockWarehouseID, + StockItemID, + SUM(StockQty) as stockDivisi + FROM stock + JOIN m_item ON StockItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN m_itemdivision ON M_ItemID = M_ItemDivisionM_ItemID AND M_ItemDivisionIsActive = 'Y' + AND M_ItemDivisionDivisionID = ? + WHERE StockItemID = ? + AND StockItemUnitID = ?"; + $qrydivisi = $this->db->query($sqldivisi, [ + $division, + $row['itemId'], + $row['unitId'] + ]); + if (!$qrydivisi) { + $this->sys_error_db("get stock divisi error", $this->db); + exit; + } + + $rowstokdivisi = $qrydivisi->row_array(); + $rows[$key]["stockDivisi"] = $rowstokdivisi["stockDivisi"]; + + $sqlwarehouse = "SELECT StockID, + StockItemPrice, + StockBatchNo, + StockWarehouseID, + StockItemID, + SUM(StockQty) as stockWarehouse + FROM stock + WHERE StockItemID = ? + AND StockItemUnitID = ? + AND StockWarehouseID = ?"; + $qrywarehouse = $this->db->query($sqlwarehouse, [ + $row['itemId'], + $row['unitId'], + $warehouseID + ]); + if (!$qrywarehouse) { + $this->sys_error_db("get stock gudang error", $this->db); + exit; + } + + $rowstokwarehouse = $qrywarehouse->row_array(); + $rows[$key]["stockWarehouse"] = $rowstokwarehouse["stockWarehouse"]; + } + } + + $result = array( + "records" => $rows, + "total" => $total + ); + + $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"] : ""; + + // Menggunakan parameter query untuk pencarian unit + $sql = "SELECT + ItemUnitID, + ItemUnitCode, + ItemUnitName, + ItemUnitCreated, + ItemUnitLastUpdated, + ItemUnitIsActive, + ItemUnitUserID + FROM itemunit + WHERE ItemUnitIsActive = 'Y' + AND ItemUnitName LIKE ? + ORDER BY ItemUnitName ASC"; + + $searchParam = ['%' . $search . '%']; + + $query = $this->db->query($sql, $searchParam); + + if (!$query) { + $this->sys_error_db("item unit 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); + } + } + + function getSelectedItem() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $prId = isset($prm["prId"]) ? $prm["prId"] : ""; + + if ($prId == "") { + $this->sys_error("Invalid PR ID"); + exit; + } + + + $sql = "SELECT PurchaseRequestDetailID as detailId, + PurchaseRequestDetailM_ItemID as itemId, + M_ItemCode as itemCode, + M_ItemDesc as itemDesc, + PurchaseRequestDetailItemUnitID as unitId, + ItemUnitCode as unitCode, + ItemUnitName as unitName, + PurchaseRequestDetailQty as qty, + PurchaseRequestDetailStatus as status, + PurchaseRequestDetailNote as note + FROM purchase_request_detail + JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUnitID = PurchaseRequestDetailItemUnitID AND ItemUnitIsActive = 'Y' + WHERE + PurchaseRequestDetailPurchaseRequestID = ? AND + PurchaseRequestDetailIsActive = 'Y'"; + $query = $this->db->query($sql, [$prId]); + + if (!$query) { + $this->sys_error_db("item 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); + } + } + + function getUnitByItemId() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $itemId = isset($prm["itemId"]) ? $prm["itemId"] : ""; + + if ($itemId == "") { + $this->sys_error("Invalid Item ID"); + exit; + } + + $sql = "SELECT + DISTINCT ItemUnitID as unitId, + ItemUnitCode as unitCode, + ItemUnitName as unitName + FROM itemunitmap + JOIN itemunit ON ItemUnitID = ItemUnitMapItemUnitID AND ItemUnitIsActive = 'Y' + WHERE ItemUnitMapM_ItemID = ? + AND ItemUnitMapIsActive = 'Y'"; + $query = $this->db->query($sql, [$itemId]); + + if (!$query) { + $this->sys_error_db("item unit 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); + } + } + + function saveRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $itemCategory = isset($prm["itemcategory"]) ? $prm["itemcategory"] : "1"; + $rioDateUse = isset($prm["RIODateUse"]) ? $prm["RIODateUse"] : ""; + $rioDateUse = date("Y-m-d", strtotime($rioDateUse)); + if ($rioDateUse == "" || $rioDateUse == null) { + $this->sys_error("Invalid Date Use"); + exit; + } + $rioRegional = isset($prm["RIORegional"]) ? $prm["RIORegional"] : ""; + if ($rioRegional == "" || $rioRegional == null) { + $this->sys_error("Invalid Regional"); + exit; + } + $rioBranch = isset($prm["RIOBranch"]) ? $prm["RIOBranch"] : ""; + if ($rioBranch == "" || $rioBranch == null) { + $this->sys_error("Invalid Branch"); + exit; + } + $rioWarehouse = isset($prm["RIOWarehouse"]) ? $prm["RIOWarehouse"] : ""; + if ($rioWarehouse == "" || $rioWarehouse == null) { + $this->sys_error("Warehouse masih kosong"); + exit; + } + $rioDivision = isset($prm["RIODivision"]) ? $prm["RIODivision"] : ""; + if ($rioDivision == "" || $rioDivision == null) { + $this->sys_error("Division masih kosong"); + exit; + } + $rioDescription = isset($prm["RIODescription"]) ? $prm["RIODescription"] : ""; + $items = isset($prm["items"]) ? $prm["items"] : []; + if (count($items) == 0) { + $this->sys_error("PR Items cannot be empty"); + exit; + } + + $this->db->trans_begin(); + + $sql = "INSERT INTO request_item_out ( + RequestItemOutNumber, + RequestItemOutDate, + RequestItemOutWarehouseID, + RequestItemOutS_RegionalID, + RequestItemOutM_BranchCode, + RequestItemOutNote, + RequestItemOutDivisionID, + RequestItemOutStatus, + RequestItemOutCreated, + RequestItemOutUserID) + VALUES (fn_numbering('RIO'), ?, ?, ?, ?, ?, ?, 'Draft', ?, ?)"; + $query = $this->db->query($sql, [ + $rioDateUse, + $rioWarehouse, + $rioRegional, + $rioBranch, + $rioDescription, + $rioDivision, + date("Y-m-d H:i:s"), + $userId + ]); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("request item out", $this->db); + exit; + } + + $rioId = $this->db->insert_id(); + + foreach ($items as $key => $item) { + $sql = "INSERT INTO request_item_out_detail ( + RequestItemOutDetailRequestItemOutID, + RequestItemOutDetailM_ItemID, + RequestItemOutDetailItemUnitID, + RequestItemOutDetailQty, + RequestItemOutDetailStatus, + RequestItemOutDetailCreated, + RequestItemOutDetailUserID) + VALUES (?, ?, ?, ?, 'Draft', ?, ?)"; + $query = $this->db->query($sql, [ + $rioId, + $item["itemId"], + $item["unitId"], + intval($item["qty"]), + date("Y-m-d H:i:s"), + $userId + ]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("request detail item out", $this->db); + exit; + } + } + + // insert log + $id = $rioId; + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$id]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah dibuat"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$id]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Draft',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $id, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $this->db); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("Request item out created successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + function getDetailRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $warehouseID = isset($prm["warehouseID"]) ? $prm["warehouseID"] : 0; + $division = isset($prm["division"]) ? $prm["division"] : ""; + $requestId = isset($prm["requestId"]) ? $prm["requestId"] : ""; + if ($requestId == "" || $requestId == null) { + $this->sys_error("Invalid Request ID"); + exit; + } + + $sql = "SELECT + RequestItemOutDetailID as detailId, + RequestItemOutDetailM_ItemID as itemId, + M_ItemCode as itemCode, + M_ItemDesc as itemDesc, + RequestItemOutDetailItemUnitID as unitId, + ItemUnitCode as unitCode, + ItemUnitName as unitName, + RequestItemOutDetailQty as qty, + RequestItemOutDetailStatus as status, + 0 as stockDivisi, + 0 as stockWarehouse + FROM request_item_out_detail + JOIN m_item ON M_ItemID = RequestItemOutDetailM_ItemID AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUnitID = RequestItemOutDetailItemUnitID AND ItemUnitIsActive = 'Y' + WHERE RequestItemOutDetailRequestItemOutID = ? AND RequestItemOutDetailIsActive = 'Y'"; + $query = $this->db->query($sql, [$requestId]); + if (!$query) { + $this->sys_error_db("request item out detail", $this->db); + exit; + } + + $rows = $query->result_array(); + if (count($rows) > 0) { + foreach ($rows as $key => $row) { + $sqldivisi = "SELECT StockID, + StockItemPrice, + StockBatchNo, + StockWarehouseID, + StockItemID, + SUM(StockQty) as stockDivisi + FROM stock + JOIN m_item ON StockItemID = M_ItemID + AND M_ItemIsActive = 'Y' + JOIN m_itemdivision ON M_ItemID = M_ItemDivisionM_ItemID AND M_ItemDivisionIsActive = 'Y' + AND M_ItemDivisionDivisionID = ? + WHERE StockItemID = ? + AND StockItemUnitID = ?"; + $qrydivisi = $this->db->query($sqldivisi, [ + $division, + $row['itemId'], + $row['unitId'] + ]); + if (!$qrydivisi) { + $this->sys_error_db("get stock divisi error", $this->db); + exit; + } + + $rowstokdivisi = $qrydivisi->row_array(); + $rows[$key]["stockDivisi"] = $rowstokdivisi["stockDivisi"]; + + $sqlwarehouse = "SELECT StockID, + StockItemPrice, + StockBatchNo, + StockWarehouseID, + StockItemID, + SUM(StockQty) as stockWarehouse + FROM stock + WHERE StockItemID = ? + AND StockItemUnitID = ? + AND StockWarehouseID = ?"; + $qrywarehouse = $this->db->query($sqlwarehouse, [ + $row['itemId'], + $row['unitId'], + $warehouseID + ]); + if (!$qrywarehouse) { + $this->sys_error_db("get stock gudang error", $this->db); + exit; + } + + $rowstokwarehouse = $qrywarehouse->row_array(); + $rows[$key]["stockWarehouse"] = $rowstokwarehouse["stockWarehouse"]; + } + } + + $result = array( + "records" => $rows + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function updateRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $rioId = isset($prm["RIOID"]) ? $prm["RIOID"] : ""; + $itemCategory = isset($prm["itemcategory"]) ? $prm["itemcategory"] : "1"; + $rioDateUse = isset($prm["RIODateUse"]) ? $prm["RIODateUse"] : ""; + $rioDateUse = date("Y-m-d", strtotime($rioDateUse)); + $dateRequest = date("Y-m-d"); + if ($rioDateUse == "" || $rioDateUse == null) { + $this->sys_error("Invalid Date Use"); + exit; + } + $rioRegional = isset($prm["RIORegional"]) ? $prm["RIORegional"] : ""; + if ($rioRegional == "" || $rioRegional == null) { + $this->sys_error("Invalid Regional"); + exit; + } + $rioBranch = isset($prm["RIOBranch"]) ? $prm["RIOBranch"] : ""; + if ($rioBranch == "" || $rioBranch == null) { + $this->sys_error("Invalid Branch"); + exit; + } + $rioWarehouse = isset($prm["RIOWarehouse"]) ? $prm["RIOWarehouse"] : ""; + if ($rioWarehouse == "" || $rioWarehouse == null) { + $this->sys_error("Warehouse masih kosong"); + exit; + } + $rioDivision = isset($prm["RIODivision"]) ? $prm["RIODivision"] : ""; + if ($rioDivision == "" || $rioDivision == null) { + $this->sys_error("Division masih kosong"); + exit; + } + $rioDescription = isset($prm["RIODescription"]) ? $prm["RIODescription"] : ""; + $items = isset($prm["items"]) ? $prm["items"] : []; + if (count($items) == 0) { + $this->sys_error("PR Items cannot be empty"); + exit; + } + + $this->db->trans_begin(); + $status = ''; + $statusdetail = ''; + if ($prm["act"] == "sendrequest") { + $status = ", RequestItemOutStatus = 'Send Request'"; + $statusdetail = ", RequestItemOutDetailStatus = 'Send Request'"; + } + + $sql = "UPDATE request_item_out SET + RequestItemOutDate = ?, + RequestItemOutWarehouseID = ?, + RequestItemOutS_RegionalID = ?, + RequestItemOutM_BranchCode = ?, + RequestItemOutNote = ?, + RequestItemOutDivisionID = ?, + RequestItemOutLastUpdated = ?, + RequestItemOutUserID = ? + $status + WHERE RequestItemOutID = ?"; + $params = [ + $rioDateUse, + $rioWarehouse, + $rioRegional, + $rioBranch, + $rioDescription, + $rioDivision, + date("Y-m-d H:i:s"), + $userId, + $rioId + ]; + + $query = $this->db->query($sql, $params); + + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("request item out update", $this->db); + exit; + } + + $prId = $this->db->insert_id(); + + foreach ($items as $key => $item) { + if ($item["detailId"] == 0 || $item["detailId"] == "0") { + $sql = "INSERT INTO request_item_out_detail ( + RequestItemOutDetailRequestItemOutID, + RequestItemOutDetailM_ItemID, + RequestItemOutDetailItemUnitID, + RequestItemOutDetailQty, + RequestItemOutDetailStatus, + RequestItemOutDetailCreated, + RequestItemOutDetailUserID) + VALUES (?, ?, ?, ?, 'Draft', ?, ?)"; + $query = $this->db->query($sql, [ + $rioId, + $item["itemId"], + $item["unitId"], + $item["qty"], + date("Y-m-d H:i:s"), + $userId + ]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("request detail item out", $this->db); + exit; + } + } else { + $sql = "UPDATE request_item_out_detail + SET + RequestItemOutDetailM_ItemID = ?, + RequestItemOutDetailItemUnitID = ?, + RequestItemOutDetailQty = ?, + RequestItemOutDetailLastUpdated = ?, + RequestItemOutDetailUserID = ? + $statusdetail + WHERE RequestItemOutDetailID = ?"; + $query = $this->db->query($sql, [ + $item["itemId"], + $item["unitId"], + $item["qty"], + date("Y-m-d H:i:s"), + $userId, + $item["detailId"] + ]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("request item out detail update", $this->db); + exit; + } + } + } + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$rioId]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio"); + exit; + } + $row_json = $qry_json->row_array(); + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$rioId]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio", $this->db); + exit; + } + + $data_json = $row_json; + + if ($prm["act"] == "sendrequest") { + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " mengirimkan permintaan request"; + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Send Request',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $rioId, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log sendrequest", $this->db); + exit; + } + } else { + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah diedit"; + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','UPDATE',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $rioId, + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log update", $this->db); + exit; + } + } + + if ($prm["act"] == "sendrequest") { + // tambahan fungsi notif ke approver + $this->saveNotification($userId, $dateRequest, $row_json['RequestItemOutNumber'], $rioId, $rioBranch, $rioDivision); + } + + $this->db->trans_commit(); + if ($prm["act"] == "sendrequest") { + $this->sys_ok("Send request successfully"); + } else { + $this->sys_ok("Request item out updated successfully"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getWarehouse() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + $regionalId = $prm["regionalId"]; + $branchCode = $prm["branchCode"]; + $filterBranch = ""; + if (!$branchCode == "") { + $filterBranch .= " AND M_BranchCode = '{$branchCode}'"; + } + + if (!$branchCode == "") { + $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, + 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 WarehouseIsActive = 'Y' + AND WarehouseIsTransit = 'N' + AND WarehouseType = 'B' + AND WarehouseS_RegionalID = ? + $filterBranch + ORDER BY WarehouseID ASC + "; + $qry = $this->db->query($sql, [$regionalId]); + } else { + $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, + 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 WarehouseIsActive = 'Y' + AND WarehouseIsTransit = 'N' + AND WarehouseType = 'R' + AND WarehouseS_RegionalID = ? + ORDER BY WarehouseID ASC + "; + $qry = $this->db->query($sql, [$regionalId]); + } + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("get warehouse", $this->db); + exit; + } + $rows = $qry->row_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 getlevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } else { + $result = array( + "total" => 1, + "records" => $approvalLevel, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getDivisionUser() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $sql = "SELECT M_UserDivisionID, + M_UserDivisionM_UserID, + M_UserDivisionDivisionID, + M_UserUsername, + DivisionName + FROM m_user + JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID + AND M_UserDivisionIsActive = 'Y' + JOIN division ON M_UserDivisionDivisionID = DivisionID + AND DivisionIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserDivisionM_UserID = ?"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalDivision = $qry->result_array(); + if (count($approvalDivision) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } else { + $result = array( + "total" => 1, + "records" => $approvalDivision, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function approveRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + + if ($prm["categoryApprove"] == 'K') { + $sql = "UPDATE request_item_out SET + RequestItemOutStatus = 'Process', + RequestItemOutApprovedDate = NOW(), + RequestItemOutApprovedUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $prm["RIOID"] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Approve request item out kacab error", $this->db); + exit; + } + + $sqlDetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = 'Process', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailRequestItemOutID = ?"; + $qryDetail = $this->db->query($sqlDetail, [ + $userId, + $prm["RIOID"] + ]); + if (!$qryDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out detail error", $this->db); + exit; + } + } else if ($prm["categoryApprove"] == "M") { + $sql = "UPDATE request_item_out SET + RequestItemOutVerifiedDate = NOW(), + RequestItemOutVerifiedUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $prm["RIOID"] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Approve request item out manager error", $this->db); + exit; + } + } + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$prm["RIOID"]]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio error"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di approve"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$prm["RIOID"]]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Process',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $prm["RIOID"], + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity error", $this->db); + exit; + } + + $this->readNotif($userId, $prm["RIOID"]); + + $this->db->trans_commit(); + $result = array( + "total" => 1 + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function rejectRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $this->db->trans_begin(); + $prm = $this->sys_input; + $userId = $this->sys_user["M_UserID"]; + + + $sql = "UPDATE request_item_out SET + RequestItemOutStatus = 'Rejected', + RequestItemOutUserID = ?, + RequestItemOutLastUpdated = NOW() + WHERE RequestItemOutID = ?"; + $qry = $this->db->query($sql, [ + $userId, + $prm["RIOID"] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out error", $this->db); + exit; + } + + $sqlDetail = "UPDATE request_item_out_detail SET + RequestItemOutDetailStatus = 'Rejected', + RequestItemOutDetailLastUpdated = NOW(), + RequestItemOutDetailUserID = ? + WHERE RequestItemOutDetailRequestItemOutID = ?"; + $qryDetail = $this->db->query($sqlDetail, [ + $userId, + $prm["RIOID"] + ]); + if (!$qryDetail) { + $this->db->trans_rollback(); + $this->sys_error_db("update request item out detail error", $this->db); + exit; + } + + + // insert log + $sql_json = "SELECT request_item_out.*, '' as detail + FROM request_item_out + WHERE RequestItemOutIsActive = 'Y' + AND RequestItemOutID = ?"; + $qry_json = $this->db->query($sql_json, [$prm["RIOID"]]); + if (!$qry_json) { + $this->db->trans_rollback(); + $this->sys_error_db("select json rio error"); + exit; + } + $row_json = $qry_json->row_array(); + + $userdesc = "Request Item out dengan kode " . $row_json['RequestItemOutNumber'] . " telah di reject"; + + $sql_json_detail = "SELECT request_item_out_detail.* + FROM request_item_out_detail + WHERE RequestItemOutDetailIsActive = 'Y' + AND RequestItemOutDetailRequestItemOutID = ?"; + $qry_json_detail = $this->db->query($sql_json_detail, [$prm["RIOID"]]); + if ($qry_json_detail) { + $row_json["detail"] = $qry_json_detail->result_array(); + } else { + $this->sys_error_db("select detail rio error", $this->db); + exit; + } + + $data_json = $row_json; + + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES('RIO','Process',?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $userdesc, + $prm["RIOID"], + json_encode($data_json), + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert user activity 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); + } + } + + // read notification + function readNotif($userId, $refID) + { + + $this->db->trans_begin(); + + // cari user penerima notifikasi + $sql_get = "SELECT RequestItemOutID, + M_UserID, + M_UserUsername, + NotificationID, + NotificationDetailID, + NotificationDetailStatus, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID + FROM notification + JOIN request_item_out ON NotificationRefID = RequestItemOutID + AND RequestItemOutIsActive = 'Y' + JOIN notification_detail ON NotificationID = NotificationDetailNotificationID + JOIN m_user ON NotificationUserID = M_UserID + WHERE RequestItemOutID = ? + AND NotificationDetailStatus = 'unread'"; + $qry = $this->db->query($sql_get, [$refID]); + if (!$qry) { + $this->sys_error_db("select user notification error", $this->db); + exit; + } + $rowsuser = $qry->result_array(); + + + foreach ($rowsuser as $user) { + + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } + + $this->db->trans_commit(); + } + + // notifications + function saveNotification($userId, $dateRequest, $number, $refID, $branchId, $divisionId) + { + try { + $this->db->trans_begin(); + + $xdate = date('d-m-Y'); + + $sql_user = "SELECT M_UserID, M_UserUsername + FROM m_user + WHERE M_UserIsActive = 'Y' + AND M_UserID = ?"; + $qry_user = $this->db->query($sql_user, [$userId]); + if ($qry_user) { + $username = $qry_user->row_array(); + } else { + $this->sys_error_db("select user error", $this->db); + exit; + } + + $description = "Request Pengeluaran Barang pada tanggal " . $xdate . " oleh " . $username['M_UserUsername'] . " dengan nomor " . $number . ""; + + $sql_menu = "SELECT S_MenuID, + S_MenuName, + S_MenuUrl, + S_MenuLevel + FROM s_menu + WHERE S_MenuID = 68"; + $qry_menu = $this->db->query($sql_menu, []); + if ($qry_menu) { + $rowurl = $qry_menu->row_array(); + } else { + $this->sys_error_db("select menu error", $this->db); + exit; + } + + $url = $rowurl['S_MenuUrl'] . "?flag=N&status=SendRequest&startdate=" . $dateRequest . "&search=" . $number; + + // cari user penerima notifikasi + $sql_receive_user = "SELECT * FROM m_user + JOIN m_branch ON M_UserM_BranchID = M_BranchID + AND M_BranchIsActive = 'Y' + AND M_BranchCode = ? + JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID + AND M_UserDivisionDivisionID != ? + AND M_UserDivisionIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserM_ApproveLevelID IN (2) + + UNION + + SELECT * FROM m_user + JOIN m_branch ON M_UserM_BranchID = M_BranchID + AND M_BranchIsActive = 'Y' + AND M_BranchCode = ? + JOIN m_userdivision ON M_UserID = M_UserDivisionM_UserID + AND M_UserDivisionDivisionID = ? + AND M_UserDivisionIsActive = 'Y' + WHERE M_UserIsActive = 'Y' + AND M_UserM_ApproveLevelID IN (1)"; + $qry_receive_user = $this->db->query($sql_receive_user, [$branchId, $divisionId, $branchId, $divisionId]); + if ($qry_receive_user) { + $rowsuser = $qry_receive_user->result_array(); + } else { + $this->sys_error_db("select receive user error", $this->db); + exit; + } + + $sql = "INSERT INTO notification( + NotificationRefID, + NotificationType, + NotificationDescription, + NotificationUrl, + NotificationUserID, + NotificationCreated) VALUES(?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $refID, + 'Pengeluaran Barang', + $description, + $url, + $userId + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("insert notification error", $this->db); + exit; + } + + $lastid = $this->db->insert_id(); + + // insert ke detail notification + foreach ($rowsuser as $row) { + $sql_detail = "INSERT INTO notification_detail( + NotificationDetailNotificationID, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID, + NotificationDetailStatus, + NotificationDetailCreated, + NotificationDetailUserID) VALUES(?,?,?,?,NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $lastid, + $row['M_UserID'], // user penerima notifikasi + $row['M_UserM_ApproveLevelID'], + 'unread', + $userId + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("insert notification detail error", $this->db); + exit; + } + } + + $this->db->trans_commit(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/Expedition.php b/application/controllers/mockup/masterdata/Expedition.php new file mode 100644 index 0000000..6f57d1c --- /dev/null +++ b/application/controllers/mockup/masterdata/Expedition.php @@ -0,0 +1,712 @@ +isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = "%%"; + if (isset($prm['search'])) { + $search = trim($prm["search"]); + $search = '%' . $prm['search'] . '%'; + } + $order_by = "ExpeditionName"; + if (isset($prm['order_by'])) { + $order_by = trim($prm["order_by"]); + } + $order_type = "asc"; + if (isset($prm['order_type'])) { + $order_type = trim($prm["order_type"]); + } + $order = $order_by . ' ' . $order_type; + $perpage = 10; + $offset = ($prm['current_page'] - 1) * $perpage; + $count = "SELECT count(ExpeditionID) as total + FROM expedition + WHERE + ExpeditionIsActive = 'Y' + AND ExpeditionName like ?"; + $qry_count = $this->db->query($count, array($search)); + $total_count = 0; + $total_page = 0; + if ($qry_count) { + $total_count = $qry_count->row()->total; + $total_page = ceil($total_count / $perpage); + } else { + $this->sys_error_db("Expedition count error", $this->db->last_query()); + exit; + } + $rows = []; + $sql = "SELECT ExpeditionID as id, + ExpeditionName as name, + ExpeditionIsInternal as internal + FROM expedition + WHERE + ExpeditionIsActive = 'Y' + AND ExpeditionName like ? + ORDER BY $order LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql, array($search, $perpage, $offset)); + $lst_qryyy = $this->db->last_query(); + if ($qry) { + $rows = $qry->result_array(); + + if (count($rows) > 0) { + foreach ($rows as $key => $value) { + $sql = "SELECT ExpeditionStaffID as id , + ExpeditionStaffName as staffName, + ExpeditionStaffMobile as staffMobile, + ExpeditionStaffM_StaffID as staffId + FROM expeditionstaff + WHERE ExpeditionStaffIsActive = 'Y' + AND ExpeditionStaffExpeditionID = ?"; + $qry = $this->db->query($sql, array($value['id'])); + if ($qry) { + $rows[$key]['staff'] = + $qry->result_array(); + } + } + } + } else { + $this->sys_error_db("Expedition data error", $this->db->last_query()); + exit; + } + + $result = array( + "total" => $total_page, + "total_filter" => $total_count, + "records" => $rows, + "qry" => $lst_qryyy + ); + $this->sys_ok($result); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function get_staff() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $count = "SELECT count(M_StaffID) as total + FROM m_staff + WHERE M_StaffIsActive = 'Y' + AND M_StaffIsCourier = 'Y' ;"; + $qry_count = $this->db->query($count); + $total_count = 0; + if ($qry_count) { + $total_count = $qry_count->row()->total; + } else { + $this->sys_error_db("Expedition count error", $this->db->last_query()); + exit; + } + $sql = "SELECT M_StaffID as staffId, + M_StaffName as staffName, + M_StaffHP as staffMobile + FROM m_staff + WHERE M_StaffIsActive = 'Y' + AND M_StaffIsCourier = 'Y' ORDER BY M_StaffName asc "; + $qry = $this->db->query($sql); + $staff = $qry->result_array(); + $result = array( + "total_filter" => $total_count, + "records" => $staff, + ); + $this->sys_ok($result); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function add() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $name = ""; + if (isset($prm['name'])) { + $name = trim($prm["name"]); + } + $isInternal = ""; + if (isset($prm['isInternal'])) { + $isInternal = trim($prm["isInternal"]); + } + + $this->db->trans_start(); + $this->db->trans_strict(FALSE); + $last_id = 0; + $staff_log = array(); + $sql = "INSERT INTO expedition + (ExpeditionName, + ExpeditionIsInternal, + ExpeditionIsActive, + ExpeditionCreated, + ExpeditionLastUpdated, + ExpeditionUserID) + VALUES + (?, + ?, + 'Y', + NOW(), + NOW(), + ?)"; + $qry = $this->db->query($sql, array($name, $isInternal, $userid)); + if ($qry) { + $last_id = $this->db->insert_id(); + } else { + $this->sys_error_db("save expedition error", $this->db->last_query()); + exit; + } + if (count($prm['staff']) > 0) { + foreach ($prm['staff'] as $key => $value) { + $stafName = trim($value['staffName']); + $stafMobile = trim($value['staffMobile']); + $staffId = trim($value['staffId']); + $sql = "INSERT INTO expeditionstaff + (ExpeditionStaffExpeditionID, + ExpeditionStaffName, + ExpeditionStaffMobile, + ExpeditionStaffM_StaffID, + ExpeditionStaffIsActive, + ExpeditionStaffUserID, + ExpeditionStaffCreated, + ExpeditionStaffLastUpdated) + VALUES + (?, + ?, + ?, + ?, + 'Y', + ?, + NOW(), + NOW() + )"; + $qry = $this->db->query($sql, array($last_id, $stafName, $stafMobile, $staffId, $userid)); + $insert_id = $this->db->insert_id(); + if (!$qry) { + $this->sys_error_db("save expedition error", $this->db->last_query()); + exit; + } + $sql_json_after = "SELECT * FROM + expeditionstaff + WHERE + ExpeditionStaffID = ?"; + $qry_json_after = $this->db->query($sql_json_after, [$insert_id]); + + $json_after = $qry_json_after->row_array(); + + array_push($staff_log, $qry_json_after->row_array()); + + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "qry" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + + $sql_insert_log = "INSERT INTO acc_one_log.expeditionstaff_log + (ExpeditionStaffLogExpeditionStaffID, + ExpeditionStaffLogStatus, + ExpeditionStaffLogJSONAfter, + ExpeditionStaffLogUserID , + ExpeditionStaffLogCreated) + VALUES(?,'ADD', ?,?, now() )"; + $qry_insert_log = $this->db->query($sql_insert_log, [$insert_id, json_encode($json_after), $userid]); + + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "qry" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + } + } + $sql_json_after = "SELECT * FROM + expedition + WHERE ExpeditionID = ?"; + $affected_rows = $this->db->affected_rows(); + $qry_json_after = $this->db->query($sql_json_after, [$last_id]); + $json_after = $qry_json_after->row_array(); + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "qry" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_after['expeditionstaff'] = $staff_log; + $sql_insert_log = "INSERT INTO acc_one_log.expedition_log + (ExpeditionLogStatus, + ExpeditionLogExpeditionID, + ExpeditionLogJSONAfter, + ExpeditionLogUserID, + ExpeditionLogCreated) + VALUES('ADD',?, ?,?, NOW() )"; + $qry_insert_log = $this->db->query($sql_insert_log, [$last_id, json_encode($json_after), $userid]); + if (!$qry_insert_log) { + $error = array( + "msg" => "failed insert expedition log", + "message" => $this->db->error()["message"], + "qry" => $this->db->last_query(), + "json_after" => $json_after + ); + $this->sys_error_db($error); + exit; + } + $this->db->trans_complete(); + + $result = array( + "affected_rows" => $affected_rows, + "inserted_id" => $last_id, + + ); + $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']; + $name = ""; + if (isset($prm['name'])) { + $name = trim($prm["name"]); + } + $isInternal = ""; + if (isset($prm['isInternal'])) { + $isInternal = trim($prm["isInternal"]); + } + $id = $prm['id']; + $sql_json_before = "SELECT * FROM + expedition + WHERE ExpeditionID = ?"; + $affected_rows = $this->db->affected_rows(); + $qry_json_before = $this->db->query($sql_json_before, [$id]); + if (!$qry_json_before) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_expedition_before = $qry_json_before->row_array(); + + $sql_json_before = "SELECT * FROM + expeditionstaff + WHERE ExpeditionStaffExpeditionID = ?"; + $qry_json_before = $this->db->query($sql_json_before, [$id]); + if (!$qry_json_before) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_expedition_before['expeditionstaff'] = $qry_json_before->result_array(); + $isInternalBefore = $json_expedition_before['ExpeditionIsInternal']; + $this->db->trans_start(); + $this->db->trans_strict(FALSE); + $sql = "UPDATE expedition SET + ExpeditionName = ? , + ExpeditionIsInternal = ?, + ExpeditionLastUpdated = now() + WHERE ExpeditionID = ?"; + $qry = $this->db->query($sql, [$name, $isInternal, $id]); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $last_qry = ""; + //ISINTERNAL SAMA DENGAN KONDISI SEBELUMNYA + if ($isInternalBefore == $isInternal) { + // APABILA STAFF LEBIH DARI 0 + if (count($prm['staff']) > 0) { + $sql = "UPDATE expeditionstaff SET + ExpeditionStaffIsActive = 'N' + WHERE ExpeditionStaffExpeditionID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + //PERULANGAN SETIAP STAFF + foreach ($prm['staff'] as $key => $value) { + $staffName = trim($value['staffName']); + $staffMobile = trim($value['staffMobile']); + $staffId = trim($value['id']); + $mStaffId = trim($value['staffId']); + //APABILA STAFFID YANG AKAN DI UBAH LEBIH DARI 0 + if (intval($staffId) > 0) { + $sql_before = "SELECT * FROM + expeditionstaff + where ExpeditionStaffID = ?"; + + $qry_before = $this->db->query($sql_before, [$staffId]); + if (!$qry_before) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_before = json_encode($qry_before->row_array()); + $sql = "UPDATE expeditionstaff SET + ExpeditionStaffName = ?, + ExpeditionStaffMobile =?, + ExpeditionStaffM_StaffID= ?, + ExpeditionStaffIsActive= 'Y', + ExpeditionStaffLastUpdated= now() + WHERE ExpeditionStaffID = ?"; + $qry = $this->db->query($sql, [$staffName, $staffMobile, $mStaffId, $staffId]); + $last_qry = $this->db->last_query(); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $sql_after = "SELECT * FROM + expeditionstaff + where ExpeditionStaffID = ?"; + $qry_after = $this->db->query($sql_after, [$staffId]); + if (!$qry_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_after = json_encode($qry_after->row_array()); + $sql_insert_log = "INSERT INTO acc_one_log.expeditionstaff_log + VALUES(null,?,'EDIT', ?, ?,?, now() )"; + $qry_insert_log = $this->db->query($sql_insert_log, [$id, $json_before, $json_after, $userid]); + if (!$qry) { + $this->sys_error_db("save expedition error", $this->db->last_query()); + exit; + } + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + //APABILA STAFF ID == 0 + } else { + $sql = "INSERT INTO expeditionstaff + VALUES(null, ?, ?, ?,?,'Y',?, now(), now())"; + $qry = $this->db->query($sql, array($id, $staffName, $staffMobile, $mStaffId, $userid)); + $last_qry = $this->db->last_query(); + $insert_id = $this->db->insert_id(); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $sql_after = "SELECT * FROM + expeditionstaff + where ExpeditionStaffID = ?"; + $qry_after = $this->db->query($sql_after, [$insert_id]); + if (!$qry_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $json_after = json_encode($qry_after->row_array()); + $sql_insert_log = "INSERT INTO acc_one_log.expeditionstaff_log + VALUES(null,?,'ADD', null, ?,?, now() )"; + $qry_insert_log = $this->db->query($sql_insert_log, [$insert_id, $json_after, $userid]); + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + } + } + } + //ISINTERNAL TIDAK SAMA DENGAN KONDISI SEBELUMNYA + } else { + if (count($prm['staff']) > 0) { + $sql = "UPDATE expeditionstaff SET + ExpeditionStaffIsActive = 'N' + WHERE ExpeditionStaffExpeditionID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + foreach ($prm['staff'] as $key => $value) { + $staffName = trim($value['staffName']); + $staffMobile = trim($value['staffMobile']); + $staffId = trim($value['id']); + $mStaffId = trim($value['staffId']); + $sql = "INSERT INTO expeditionstaff + VALUES(null, ?, ?, ?,?,'Y',?, now(), now())"; + $qry = $this->db->query($sql, array($id, $staffName, $staffMobile, $mStaffId, $userid)); + $last_qry = $this->db->last_query(); + $insert_id = $this->db->insert_id(); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + $sql_after = "SELECT * FROM + expeditionstaff + where ExpeditionStaffID = ?"; + $qry_after = $this->db->query($sql_after, [$insert_id]); + if (!$qry_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $json_after = json_encode($qry_after->row_array()); + $sql_insert_log = "INSERT INTO acc_one_log.expeditionstaff_log + VALUES(null,?,'ADD', null, ?,?, now() )"; + $qry_insert_log = $this->db->query($sql_insert_log, [$insert_id, $json_after, $userid]); + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + } + } + } + $this->db->trans_complete(); + $sql_json_after = "SELECT expedition.* FROM + expedition + WHERE ExpeditionID = ?"; + $qry_json_after = $this->db->query($sql_json_after, [$id]); + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $json_after = $qry_json_after->row_array(); + $sql_json_after = "SELECT * FROM + expeditionstaff + WHERE ExpeditionStaffExpeditionID = ?"; + $qry_json_after = $this->db->query($sql_json_after, [$id]); + $json_after['expeditionstaff'] = $qry_json_after->result_array(); + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $sql_insert_log = "INSERT INTO acc_one_log.expedition_log + VALUES(null,'EDIT',?, ?, ?,?, now() )"; + $qry_insert_log = $this->db->query( + $sql_insert_log, + [$id, json_encode($json_expedition_before), json_encode($json_after), $userid] + ); + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $result = array( + "message" => '', + "sql_log" => $this->db->last_query(), + "sql" => $this->db->last_query(), + "last_qry" => $last_qry + ); + $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; + } + $prm = $this->sys_input; + $userid = $this->sys_user['M_UserID']; + $id = ""; + if (isset($prm['id'])) { + $id = trim($prm["id"]); + } + if ($id == "" || !$id) { + $error = array( + "message" => "id is mandatory", + ); + $this->sys_error_db($error); + exit; + } + $this->db->trans_start(); + $this->db->trans_strict(FALSE); + $sql = "UPDATE expedition + SET ExpeditionIsActive = 'N', + ExpeditionLastUpdated = NOW(), + ExpeditionUserID = ? + WHERE ExpeditionID = ?"; + $qry = $this->db->query($sql, [$userid, $id]); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } else { + $sql = "UPDATE expeditionstaff SET + ExpeditionStaffIsActive = 'N', + ExpeditionStaffUserID = ?, + ExpeditionStaffLastUpdated = NOW() + WHERE ExpeditionStaffExpeditionID = ?"; + $qry = $this->db->query($sql, [$userid, $id]); + if (!$qry) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + ); + $this->sys_error_db($error); + exit; + } + } + $this->db->trans_complete(); + $sql_json_after = "SELECT * FROM + expedition + WHERE ExpeditionID = ?"; + $qry_json_after = $this->db->query($sql_json_after, [$id]); + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $json_after = $qry_json_after->row_array(); + $sql_json_after = "SELECT * FROM + expeditionstaff + WHERE ExpeditionStaffExpeditionID = ?"; + $qry_json_after = $this->db->query($sql_json_after, [$id]); + $json_after['expeditionstaff'] = $qry_json_after->result_array(); + if (!$qry_json_after) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $sql_insert_log = "INSERT INTO acc_one_log.expedition_log + VALUES(null,'DELETE',?, NULL, ?,?, now() )"; + $qry_insert_log = $this->db->query( + $sql_insert_log, + [$id, json_encode($json_after), $userid] + ); + if (!$qry_insert_log) { + $error = array( + "message" => $this->db->error()["message"], + "sql" => $this->db->last_query() + + ); + $this->sys_error_db($error); + exit; + } + $result = array( + "message" => '', + "sql_log" => $this->db->last_query(), + "sql" => $this->db->last_query(), + "json_after" => $json_after + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/Priviledge.php b/application/controllers/mockup/masterdata/Priviledge.php new file mode 100755 index 0000000..e00efcb --- /dev/null +++ b/application/controllers/mockup/masterdata/Priviledge.php @@ -0,0 +1,241 @@ +db_onedev = $this->load->database("onedev", true); + } + + public function lookupusergroup() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm['search']; + $all = $prm['all']; + $limit = ''; + if ($all == 'N') { + $limit = ' LIMIT 10'; + } + $sql = "select COUNT(*) as total + from m_usergroup + where + M_UserGroupIsActive = 'Y'"; + $sql_param = array($search); + $total = $this->db_onedev->query($sql, $sql_param)->row()->total; + + + $sql = "select M_UserGroupID as id, M_UserGroupDashboard as dashboard, M_UserGroupName as name, M_UserGroupIsClinic as clinic, M_UserGroupName as description , 'xxx' as usergrouptype + from m_usergroup + where + M_UserGroupName LIKE CONCAT('%','{$search}','%') AND + M_UserGroupIsActive = 'Y' $limit"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + } else { + $this->sys_error_db("m_usergroup select"); + exit; + } + + + $result = array("total" => $total, "total_filter" => count($rows), "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function lookuppriviledge() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $sql = "SELECT S_MenuID as id, S_MenuUrl, S_MenuName as name, '' as childs FROM s_menu WHERE S_MenuParentS_MenuID = 0 AND S_MenuIsActive = 'Y' ORDER BY S_MenuOrder ASC"; + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + if ($prm['code'] == 'R') { + foreach ($rows as $k => $v) { + if ($v['S_MenuUrl'] == '#') { + $sql = " SELECT S_MenuID as id, S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$v['id']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array(); + if ($rows[$k]['childs']) { + foreach ($rows[$k]['childs'] as $kx => $vx) { + if ($vx['S_MenuUrl'] == '#') { + $sql = " SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$vx['id']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'][$kx]['childs'] = $this->db_onedev->query($sql)->result_array(); + } + } + } + } else { + $sql = " SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuID = '{$v['id']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array(); + } + } + } else { + foreach ($rows as $k => $v) { + if ($v['S_MenuUrl'] == '#') { + $sql = " SELECT S_MenuID as id, S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$v['id']}' AND S_MenuRegional = '{$prm['code']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array(); + if ($rows[$k]['childs']) { + foreach ($rows[$k]['childs'] as $kx => $vx) { + if ($vx['S_MenuUrl'] == '#') { + $sql = " SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuParentS_MenuID = '{$vx['id']}' AND S_MenuRegional = '{$prm['code']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'][$kx]['childs'] = $this->db_onedev->query($sql)->result_array(); + } + } + } + } else { + $sql = " SELECT S_MenuID, S_MenuUrl, S_MenuName, S_PrivilegeID, {$prm['id']} as usergroupid, IF(ISNULL(S_PrivilegeID),'N','Y') as status, 'N' as active, '' as childs + FROM s_menu + LEFT JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' AND S_PrivilegeM_UserGroupID = '{$prm['id']}' + WHERE + S_MenuIsActive = 'Y' AND S_MenuID = '{$v['id']}' AND S_MenuRegional = '{$prm['code']}' + ORDER BY S_MenuOrder ASC"; + $rows[$k]['childs'] = $this->db_onedev->query($sql)->result_array(); + } + } + } + } else { + $this->sys_error_db("m_usergroup select"); + exit; + } + + + $result = array("total" => count($rows), "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function save() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $datas = $prm['datas']; + foreach ($datas as $k => $v) { + foreach ($v['childs'] as $kx => $vx) { + if ($vx['active'] == 'Y') { + if (is_null($vx['S_PrivilegeID']) && $vx['status'] == 'Y') { + $sql = "INSERT INTO s_privilege ( + S_PrivilegeM_UserGroupID, + S_PrivilegeS_MenuID, + S_PrivilegeCreated + ) + VALUES( + {$vx['usergroupid']}, + {$vx['S_MenuID']}, + NOW() + )"; + $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + } + + if (!is_null($vx['S_PrivilegeID'])) { + $sql = "UPDATE s_privilege SET + S_PrivilegeIsActive = '{$vx['status']}' + WHERE + S_PrivilegeID = '{$vx['S_PrivilegeID']}' + "; + $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + } + } + if ($vx['childs']) { + foreach ($vx['childs'] as $kxz => $vxz) { + if ($vxz['active'] == 'Y') { + if (is_null($vxz['S_PrivilegeID']) && $vxz['status'] == 'Y') { + $sql = "INSERT INTO s_privilege ( + S_PrivilegeM_UserGroupID, + S_PrivilegeS_MenuID, + S_PrivilegeCreated + ) + VALUES( + {$vxz['usergroupid']}, + {$vxz['S_MenuID']}, + NOW() + )"; + $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + } + + if (!is_null($vxz['S_PrivilegeID'])) { + $sql = "UPDATE s_privilege SET + S_PrivilegeIsActive = '{$vxz['status']}' + WHERE + S_PrivilegeID = '{$vxz['S_PrivilegeID']}' + "; + $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + } + } + } + } + } + } + + + $result = array("total" => 1, "records" => array()); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +} diff --git a/application/controllers/mockup/masterdata/Staffv2.php b/application/controllers/mockup/masterdata/Staffv2.php new file mode 100644 index 0000000..ad11ef7 --- /dev/null +++ b/application/controllers/mockup/masterdata/Staffv2.php @@ -0,0 +1,722 @@ +db_onedev = $this->load->database("onedev", true); + } + + public function search() + { + $prm = $this->sys_input; + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $nik = str_replace("'", "\\'", $prm["snik"]); + $nama = str_replace("'", "\\'", $prm["nama"]); + $status = str_replace("'", "\\'", $prm["status"]); + + // echo $nik; + + $sql_where = "WHERE M_StaffIsActive = 'Y' "; + $sql_param = array(); + if ($nama != "") { + if ($sql_where != "") { + $sql_where .= " and "; + } + $sql_where .= " M_StaffName like ? "; + $sql_param[] = "%$nama%"; + } + if ($nik != "") { + if ($sql_where != "") { + $sql_where .= " and "; + } + $sql_where .= " M_StaffNIK like ? "; + $sql_param[] = "%$nik%"; + } + + //if ($sql_where != "") $sql_where .= " and "; + + // Order masih dalam status registrasi + //$sql_where .= " M_StaffIsActive = 'Y' "; + + + $sql = " SELECT count(*) as total + FROM m_staff + LEFT JOIN m_sex ON M_StaffM_SexID = M_SexID + LEFT JOIN m_position ON M_StaffM_PositionID = M_PositionID + $sql_where + "; + //echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + + $tot_count = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } else { + $this->sys_error_db("m_staff count", $this->db_onedev); + exit; + } + + $sql = "SELECT + m_staff.*, + DATE_FORMAT(M_StaffDOB,'%d-%m-%Y') as M_StaffDOBx, + M_StaffM_SexID, + M_SexID, + m_sexname, + 0 M_ReligionID, + 0 M_StaffM_ReligionID, + 0 M_ReligionName, + '' M_BranchID, + 0 M_StaffM_BranchID, + '' M_BranchName, + 0 M_StaffM_PositionID, + M_PositionID, + M_PositionName, + '' M_CityName, + '' M_SubareaName, + M_StaffIsCourier as iskurir, + '' OHStaffMapIhsNumber + FROM m_staff + LEFT JOIN m_sex ON M_StaffM_SexID = M_SexID + LEFT JOIN m_position ON M_StaffM_PositionID = M_PositionID + $sql_where + ORDER BY M_StaffName ASC + "; + // echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + // echo $this->db_onedev->last_query(); + $rows = $query->result_array(); + if ($rows) { + foreach ($rows as $k => $v) { + $$rows[$k]['M_StaffName'] = stripslashes($rows[$k]['M_StaffName']); + //$rows[$k]['verification_px'] = $this->add_verification_test($v['M_StaffID']); + + } + } + + + //$this->_add_address($rows); + $result = array("total" => $tot_count, "records" => $rows, "sql" => $this->db_onedev->last_query()); + $this->sys_ok($result); + exit; + } + + function getsexreg() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + + $rows['branchs'] = []; + + $query = " SELECT * + FROM m_sex + WHERE + M_SexIsActive = 'Y' + "; + //echo $query; + $rows['sexes'] = $this->db_onedev->query($query)->result_array(); + + $rows['religions'] = []; + + $query = " SELECT *, COUNT(M_StaffID) as used +FROM (SELECT m_position.*,M_StaffID +FROM +m_position +LEFT JOIN m_staff ON M_PositionID = M_StaffM_PositionID AND M_StaffIsActive = 'Y' +WHERE M_PositionIsActive = 'Y') a +GROUP BY M_PositionID +"; + //echo $query; + $rows['positions'] = $this->db_onedev->query($query)->result_array(); + + + + $result = array( + "total" => count($rows), + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + public function addnewposition() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $name_position = $prm['name']; + $userid = $this->sys_user["M_UserID"]; + $sql = "insert into m_position( + M_PositionName, + M_PositionUserID, + M_PositionCreated, + M_PositionLastUpdated + ) + values(?,?,now(),now())"; + $query = $this->db_onedev->query( + $sql, + array( + $name_position, + $userid + ) + ); + //echo $query; + if (!$query) { + $this->sys_error_db("m_position insert"); + exit; + } + $rows = []; + $query = " SELECT *, COUNT(M_StaffID) as used +FROM (SELECT m_position.*,M_StaffID +FROM +m_position +LEFT JOIN m_staff ON M_PositionID = M_StaffM_PositionID AND M_StaffIsActive = 'Y' +WHERE M_PositionIsActive = 'Y') a +GROUP BY M_PositionID + "; + //echo $query; + $rows['positions'] = $this->db_onedev->query($query)->result_array(); + $result = array("total" => 1, "records" => $rows); + $this->sys_ok($result); + $last_id = $this->db_onedev->insert_id(); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function editposition() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + //# ambil parameter input + $prm = $this->sys_input; + $id_staff = $prm['id']; + $name_staff = $prm['name']; + $userid = $this->sys_user["M_UserID"]; + $sqlstaff = "update m_position SET + M_PositionName = ?, + M_PositionUserID = ?, + M_PositionLastUpdated = now() + where + M_PositionID = ? + "; + $querystaff = $this->db_onedev->query( + $sqlstaff, + array( + $name_staff, + $userid, + $id_staff + ) + ); + // echo $query; + if (!$querystaff) { + $this->sys_error_db("m_position update"); + exit; + } + $rows = []; + $query = " SELECT *, COUNT(M_StaffID) as used +FROM (SELECT m_position.*,M_StaffID +FROM +m_position +LEFT JOIN m_staff ON M_PositionID = M_StaffM_PositionID AND M_StaffIsActive = 'Y' +WHERE M_PositionIsActive = 'Y') a +GROUP BY M_PositionID"; + //echo $query; + $rows['positions'] = $this->db_onedev->query($query)->result_array(); + $result = array("total" => 1, "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function deleteposition() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + //# ambil parameter input + $prm = $this->sys_input; + $id_staff = $prm['id']; + $userid = $this->sys_user["M_UserID"]; + $sqlstaff = "update m_position SET + M_PositionIsActive = 'N', + M_PositionUserID = ?, + M_PositionLastUpdated = now() + where + M_PositionID = ? + "; + $querystaff = $this->db_onedev->query( + $sqlstaff, + array( + $userid, + $id_staff + ) + ); + // echo $query; + if (!$querystaff) { + $this->sys_error_db("m_position update"); + exit; + } + $rows = []; + $query = " SELECT * + FROM m_position + WHERE + M_PositionIsActive = 'Y' + "; + //echo $query; + $rows['positions'] = $this->db_onedev->query($query)->result_array(); + $result = array("total" => 1, "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function searchcity() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count = 0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "SELECT count(*) as total + FROM m_city + WHERE + M_CityName like ? + AND M_CityIsActive = 'Y'"; + $query = $this->db_onedev->query($sql, $q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } else { + $this->sys_error_db("m_city count", $this->db_onedev); + exit; + } + + $sql = " + SELECT * + FROM m_city + WHERE + M_CityName like ? + AND M_CityIsActive = 'Y' + ORDER BY M_CityName DESC + "; + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } else { + $this->sys_error_db("m_city rows", $this->db_onedev); + exit; + } + } + function getsubarea() + { + $prm = $this->sys_input; + $query = " SELECT * + FROM m_subarea + WHERE + M_SubareaIsActive = 'Y' AND M_SubareaM_CityID = ? + "; + //echo $query; + $rows = $this->db_onedev->query($query, array($prm['id']))->result_array(); + + $result = array( + "total" => count($rows), + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + + function save() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $pdob = date('Y-m-d', strtotime($prm['M_StaffDOB'])); + $iscourier = $prm['M_StaffIsCourier']; + $userid = $this->sys_user["M_UserID"]; + $prm['M_StaffName'] = str_replace("'", "\\'", $prm['M_StaffName']); + $query = "UPDATE m_staff SET + M_StaffM_BranchID = '{$prm['M_StaffM_BranchID']}', + M_StaffName = '{$prm['M_StaffName']}', + M_StaffDOB = '{$pdob}', + M_StaffM_SexID = '{$prm['M_StaffM_SexID']}', + M_StaffM_ReligionID = '{$prm['M_StaffM_ReligionID']}', + M_StaffAddress = '{$prm['M_StaffAddress']}', + M_StaffM_CityID = '{$prm['M_StaffM_CityID']}', + M_StaffM_SubareaID = '{$prm['M_StaffM_SubareaID']}', + M_StaffHP = '{$prm['M_StaffHP']}', + M_StaffPhone = '{$prm['M_StaffPhone']}', + M_StaffM_PositionID = '{$prm['M_StaffM_PositionID']}', + M_StaffNIK = '{$prm['M_StaffNIK']}', + M_StaffBlood = '{$prm['M_StaffBlood']}', + M_StaffStudy = '{$prm['M_StaffStudy']}', + M_StaffStartDate = '{$prm['M_StaffStartDate']}', + M_StaffEndDate = '{$prm['M_StaffEndDate']}', + M_StaffTimeWork = '{$prm['M_StaffTimeWork']}', + M_StaffTimeWorkSaturday = '{$prm['M_StaffTimeWorkSaturday']}', + M_StaffIsCourier = '{$iscourier}', + M_StaffUserID = '{$userid}' + + WHERE + M_StaffID = '{$prm['M_StaffID']}' + "; + //echo $query; + $rows = $this->db_onedev->query($query); + if (!$rows) { + $this->sys_error_db("update m_staff", $this->db_onedev); + exit; + } + + // if ($rows) { + // $sql = "SELECT OHStaffMapID, + // OHStaffMapM_StaffNIK, + // OHStaffMapIhsNumber + // FROM one_health.oh_staff_map + // WHERE OHStaffMapM_StaffNIK = '{$prm['M_StaffNIK']}'"; + // $qry = $this->db_onedev->query($sql); + // if ($qry) { + // $rows_oh = $qry->result_array(); + // } else { + // $this->sys_error_db("select oh_staff_map", $this->db_onedev); + // exit; + // } + + // if (count($rows_oh) > 0) { + // $sql_oh_staff = "UPDATE one_health.oh_staff_map SET + // OHStaffMapM_StaffNIK = '{$prm['M_StaffNIK']}', + // OHStaffMapIhsNumber = '{$prm['OHStaffMapIhsNumber']}', + // OHStaffMapUserID = '{$userid}', + // OHStaffMapLastUpdated = NOW() + // WHERE OHStaffMapM_StaffNIK = '{$prm['M_StaffNIK']}'"; + // $rows = $this->db_onedev->query($sql_oh_staff); + // // $last_qry = $this->db_onedev->last_query(); + // // print_r($last_qry); + // // exit; + // if (!$rows) { + // $this->db_onedev->trans_rollback(); + // $this->sys_error_db("update oh_staff_map error", $this->db_onedev); + // exit; + // } + // } else { + // if ($prm['M_StaffNIK'] != "" && $prm['OHStaffMapIhsNumber'] != "") { + // $sql_oh_staff = "INSERT INTO one_health.oh_staff_map( + // OHStaffMapM_StaffNIK, + // OHStaffMapIhsNumber, + // OHStaffMapUserID, + // OHStaffMapCreated, + // OHStaffMapLastUpdated + // ) VALUES('{$prm['M_StaffNIK']}','{$prm['OHStaffMapIhsNumber']}','{$userid}',NOW(),NOW())"; + // $rows = $this->db_onedev->query($sql_oh_staff); + // if (!$rows) { + // $this->db_onedev->trans_rollback(); + // $this->sys_error_db("save oh_staff_map error", $this->db_onedev); + // exit; + // } + // } + // } + // } + + $result = array( + "total" => 1, + "records" => array('status' => 'OK') + ); + $this->sys_ok($result); + exit; + } + + function newstaff() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $pdob = date('Y-m-d', strtotime($prm['M_StaffDOB'])); + $iscourier = $prm['M_StaffIsCourier']; + $userid = $this->sys_user["M_UserID"]; + $query = "INSERT INTO m_staff ( + M_StaffM_BranchID, + M_StaffName, + M_StaffDOB, + M_StaffM_SexID, + M_StaffM_ReligionID, + M_StaffAddress, + M_StaffM_CityID, + M_StaffM_SubareaID, + M_StaffHP, + M_StaffPhone, + M_StaffM_PositionID, + M_StaffNIK, + M_StaffBlood, + M_StaffStudy, + M_StaffStartDate , + M_StaffEndDate, + M_StaffTimeWork, + M_StaffTimeWorkSaturday, + M_StaffIsCourier, + M_StaffUserID + ) + VALUES( + '{$prm['M_StaffM_BranchID']}', + '{$prm['M_StaffName']}', + '{$pdob}', + '{$prm['M_StaffM_SexID']}', + '{$prm['M_StaffM_ReligionID']}', + '{$prm['M_StaffAddress']}', + '{$prm['M_StaffM_CityID']}', + '{$prm['M_StaffM_SubareaID']}', + '{$prm['M_StaffHP']}', + '{$prm['M_StaffPhone']}', + '{$prm['M_StaffM_PositionID']}', + '{$prm['M_StaffNIK']}', + '{$prm['M_StaffBlood']}', + '{$prm['M_StaffStudy']}', + '{$prm['M_StaffStartDate']}', + '{$prm['M_StaffEndDate']}', + '{$prm['M_StaffTimeWork']}', + '{$prm['M_StaffTimeWorkSaturday']}', + '{$iscourier}', + '{$userid}' + ) + "; + //echo $query; + $rows = $this->db_onedev->query($query); + $last_id = $this->db_onedev->insert_id(); + if ($rows) { + if ($iscourier == 'Y') { + $querycourier = "INSERT INTO m_courier(M_CourierM_StaffID,M_CourierCreated,M_CourierLastUpdated,M_CourierUserID) + VALUES('{$last_id}',now(),now(),'{$userid}') + "; + $rows = $this->db_onedev->query($querycourier); + } + } + + // if ($rows) { + // if ($prm['M_StaffNIK'] !== "" && $prm['OHStaffMapIhsNumber'] !== "") { + // $sql_oh_staff = "INSERT INTO one_health.oh_staff_map( + // OHStaffMapM_StaffNIK, + // OHStaffMapIhsNumber, + // OHStaffMapUserID, + // OHStaffMapCreated, + // OHStaffMapLastUpdated + // ) VALUES('{$prm['M_StaffNIK']}','{$prm['OHStaffMapIhsNumber']}','{$userid}',NOW(),NOW())"; + // $rows = $this->db_onedev->query($sql_oh_staff); + // if (!$rows) { + // $this->db_onedev->trans_rollback(); + // $this->sys_error_db("save oh_staff_map error", $this->db_onedev); + // exit; + // } + // } + // } + + $result = array( + "total" => 1, + "records" => array('status' => 'OK'), + "id" => $last_id + ); + $this->sys_ok($result); + exit; + } + + function deletestaff() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $query = "UPDATE m_staff SET + M_StaffIsActive = 'N' + WHERE + M_StaffID = '{$prm['M_StaffID']}' + "; + //echo $query; + $rows = $this->db_onedev->query($query); + + $result = array( + "total" => 1, + "records" => array('status' => 'OK') + ); + $this->sys_ok($result); + exit; + } + + function getaddress() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $query = " SELECT m_staffaddress.*, + M_KelurahanName, + M_DistrictID, + M_DistrictName, + M_CityID, + M_CityName, + '' as action + FROM m_staffaddress + JOIN m_kelurahan ON M_StaffAddressM_KelurahanID = M_KelurahanID + JOIN m_district ON M_KelurahanM_DistrictID = M_DistrictID + JOIN m_city ON M_DistrictM_CityID = M_CityID + WHERE + M_StaffAddressIsActive = 'Y' AND M_StaffAddressM_StaffID = ? + "; + //echo $query; + $rows = $this->db_onedev->query($query, array($prm['id']))->result_array(); + if ($rows) { + foreach ($rows as $k => $v) { + $rows[$k]['action'] = 'delete'; + $rows[$k]['action'] .= 'edit'; + } + } + $result = array( + "total" => count($rows), + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + function savenewaddress() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $count_addrs = $this->db_onedev->query("SELECT COUNT(*) as countx FROM m_staffaddress WHERE M_StaffAddressM_StaffID = '{$prm['M_StaffAddressM_StaffID']}' AND M_StaffAddressIsActive = 'Y'")->row()->countx; + + //echo $this->db_onedev->last_query(); + if ($count_addrs == 0) { + $prm['M_StaffAddressNote'] = 'Utama'; + } else { + $count_addrs_utama = $this->db_onedev->query("SELECT COUNT(*) as countx FROM m_staffaddress WHERE M_StaffAddressM_StaffID = '{$prm['M_StaffAddressM_StaffID']}' AND M_StaffAddressNote = 'Utama' AND M_StaffAddressIsActive = 'Y'")->row()->countx; + if ($count_addrs_utama > 0 && strtolower($prm['M_StaffAddressNote']) == 'utama') { + $rx = date('YmdHis'); + $prm['M_StaffAddressNote'] = 'Utama_' . $rx; + } + } + $query = "INSERT INTO m_staffaddress ( + M_StaffAddressM_StaffID, + M_StaffAddressNote, + M_StaffAddressDescription, + M_StaffAddressM_KelurahanID, + M_StaffAddressCreated + ) + VALUES( + '{$prm['M_StaffAddressM_StaffID']}', + '{$prm['M_StaffAddressNote']}', + '{$prm['M_StaffAddressDescription']}', + '{$prm['M_StaffAddressM_KelurahanID']}', + NOW() + ) + "; + //echo $query; + $rows = $this->db_onedev->query($query); + + $result = array( + "total" => 1, + "records" => array('status' => 'OK') + ); + $this->sys_ok($result); + exit; + } + + function saveeditaddress() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $query = "UPDATE m_staffaddress SET + M_StaffAddressM_StaffID = '{$prm['M_StaffAddressM_StaffID']}', + M_StaffAddressNote = '{$prm['M_StaffAddressNote']}', + M_StaffAddressDescription = '{$prm['M_StaffAddressDescription']}', + M_StaffAddressM_KelurahanID = '{$prm['M_StaffAddressM_KelurahanID']}' + WHERE + M_StaffAddressID = '{$prm['M_StaffAddressID']}' + "; + //echo $query; + $rows = $this->db_onedev->query($query); + + $result = array( + "total" => 1, + "records" => array('status' => 'OK') + ); + $this->sys_ok($result); + exit; + } + + function deleteaddress() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $query = "UPDATE m_staffaddress SET + M_StaffAddressIsActive = 'N' + WHERE + M_StaffAddressID = '{$prm['M_StaffAddressID']}' + "; + //echo $query; + $rows = $this->db_onedev->query($query); + + $result = array( + "total" => 1, + "records" => array('status' => 'OK') + ); + $this->sys_ok($result); + exit; + } +} diff --git a/application/controllers/mockup/masterdata/accounting/Journalcashv2.php b/application/controllers/mockup/masterdata/accounting/Journalcashv2.php index 5d10fb3..58d9ade 100644 --- a/application/controllers/mockup/masterdata/accounting/Journalcashv2.php +++ b/application/controllers/mockup/masterdata/accounting/Journalcashv2.php @@ -139,7 +139,9 @@ class Journalcashv2 extends MY_Controller LEFT JOIN m_branch ON jurnalM_BranchCode = M_BranchCode AND M_BranchIsActive = 'Y' WHERE $where_sql GROUP BY jurnalID - ORDER BY jurnalID DESC"; + 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); @@ -163,6 +165,7 @@ class Journalcashv2 extends MY_Controller // 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) { @@ -361,7 +364,6 @@ class Journalcashv2 extends MY_Controller $this->sys_error($message); } } - function getUserApproveLevel() { try { diff --git a/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php b/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php index 751f345..fd3e5f8 100644 --- a/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php +++ b/application/controllers/mockup/masterdata/accounting/Journalgoodreceive.php @@ -118,6 +118,19 @@ class Journalgoodreceive extends MY_Controller exit; } + // 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); diff --git a/application/controllers/mockup/masterdata/accounting/Ruangan.php b/application/controllers/mockup/masterdata/accounting/Ruangan.php index 57c0e40..4f45f5c 100644 --- a/application/controllers/mockup/masterdata/accounting/Ruangan.php +++ b/application/controllers/mockup/masterdata/accounting/Ruangan.php @@ -12,6 +12,77 @@ class Ruangan extends MY_Controller echo "API Ruangan"; } + function listingRegional() + { + try { + if (!$this->isLogin) { + throw new Exception('Invalid token'); + } + + $sql = "SELECT + S_RegionalID, + S_RegionalName + FROM s_regional + WHERE S_RegionalIsActive = 'Y'"; + $que = $this->db->query($sql); + if (!$que) { + throw new Exception('failed to query list regional', 1); + } + $data = $que->result_array(); + + $this->sys_ok([ + "records" => $data, + "total" => count($data) + ]); + } catch (Exception $e) { + $msg = '[Error] ' . $e->getMessage(); + $code = $e->getCode(); + if ($code == 0) { + $this->sys_error($msg); + } else { + $this->sys_error_db($msg); + } + exit; + } + } + + function listingCabang() + { + try { + if (!$this->isLogin) { + throw new Exception('Invalid token'); + } + + $para = $this->sys_input; + + $sql = "SELECT + M_BranchID, + M_BranchName + FROM m_branch + WHERE M_BranchS_RegionalID = ? + AND M_BranchIsActive = 'Y'"; + $que = $this->db->query($sql, [$para['regionalID']]); + if (!$que) { + throw new Exception('failed to query list cabang', 1); + } + $data = $que->result_array(); + + $this->sys_ok([ + "records" => $data, + "total" => count($data) + ]); + } catch (Exception $e) { + $msg = '[Error] ' . $e->getMessage(); + $code = $e->getCode(); + if ($code == 0) { + $this->sys_error($msg); + } else { + $this->sys_error_db($msg); + } + exit; + } + } + function lookupRuangan() { try { @@ -39,9 +110,8 @@ class Ruangan extends MY_Controller b.M_BranchCode AS branch_code, r.M_RuanganCode AS code, r.M_RuanganName AS name, - r.M_RuanganUserID AS user_id, - r.M_RuanganCreated AS created, - r.M_RuanganLastUpdated AS last_updated + s.S_RegionalID AS regional_id, + s.S_RegionalName AS regional_name FROM m_ruangan r JOIN m_branch b ON b.M_BranchID = r.M_RuanganM_BranchID diff --git a/application/controllers/mockup/mutasi/HandoverMutasi.php b/application/controllers/mockup/mutasi/HandoverMutasi.php new file mode 100644 index 0000000..bde2a14 --- /dev/null +++ b/application/controllers/mockup/mutasi/HandoverMutasi.php @@ -0,0 +1,1579 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $start_date = $prm['start_date']; + $end_date = $prm['end_date']; + $search = '%' . $prm['search'] . '%'; + + $page = 0; + $limit = 15; + if ($prm['current_page'] > 0) { + $page = ($prm['current_page'] - 1) * $limit; + } + + $status = $prm['status']; + $status_rm = ""; + if ($status != "") { + $status_rm .= " AND MutasiRequestStatus = '{$status}'"; + } + + $sql = "SELECT DISTINCT MutasiRequestID, + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestTotalValue, + MutasiRequestStatus, + MutasiRequestNote, + MutasiRequestIsVerif, + MutasiRequestVerifUserID, + MutasiRequestVerifDate, + MutasiRequestIsApproved, + MutasiRequestApprovedUserID, + MutasiRequestApprovedDate, + itemCategoryID, + itemCategoryName, + a.M_BranchID as branch_asal_id, + a.M_BranchCode as branch_asal_code, + a.M_BranchName as branch_asal_name, + b.M_BranchID as branch_tujuan_id, + b.M_BranchCode as branch_tujuan_code, + b.M_BranchName as branch_tujuan_name + FROM mutasi_request + JOIN item_category ON MutasiRequestItemCategoryID = itemCategoryID + AND itemCategoryIsActive = 'Y' + JOIN m_branch a ON MutasiRequestFromBranchID = a.M_BranchID + AND a.M_BranchIsActive = 'Y' + JOIN m_branch b ON MutasiRequestToBranchID = b.M_BranchID + AND b.M_BranchIsActive = 'Y' + WHERE MutasiRequestIsActive = 'Y' + $status_rm + AND (MutasiRequestNumber LIKE ?) + AND MutasiRequestDate BETWEEN DATE(?) AND DATE(?) + ORDER BY MutasiRequestID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$search, $start_date, $end_date]); + if (!$qrytotal) { + $this->sys_error_db("['Error'] get total data mutasi", $this->db); + exit; + } + $total = $qrytotal->row_array()['total']; + + $sqldata = $sql . " LIMIT ? OFFSET ?"; + $qrydata = $this->db->query($sqldata, [ + $search, + $start_date, + $end_date, + $limit, + $page + ]); + if (!$qrydata) { + $this->sys_error_db("[Error] get list data mutasi", $this->db); + exit; + } + $rows = $qrydata->result_array(); + + $result = array( + "total_page" => ceil($total / $limit), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y' + AND itemCategoryName LIKE ? + AND itemCategoryID IN (2,3) + ORDER BY itemCategoryName ASC"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getCategory"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchAsal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ?"; + $qry = $this->db->query($sql, [$user['S_RegionalID']]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchAsal"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchTujuan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + AND M_BranchID <> ? + AND M_BranchName LIKE ? + ORDER BY M_BranchName ASC"; + $qry = $this->db->query($sql, [$user['S_RegionalID'], $user['M_BranchID'], $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchTujuan"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getReceiveOrderPo() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $itemCategoryID = $prm["itemCategoryID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT DISTINCT ReceiveOrderPoID, + ReceiveOrderPoNumber, + ReceiveOrderPoIDate, + ReceiveOrderPoWarehouseID, + ReceiveOrderPoM_BranchCode + FROM receive_order_po + JOIN t_barcode_barang ON T_BarcodeBarangReceiveOrderPoID = ReceiveOrderPoID + AND T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangStockID <> 0 + JOIN m_item ON T_BarcodeBarangM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + AND M_ItemItem_CategoryID = ? + WHERE ReceiveOrderPoIsActive = 'Y' + AND ReceiveOrderPoM_BranchCode = ? + AND ReceiveOrderPoIsHandover = 'Y' + AND ReceiveOrderPoConfirmed = 'Y' + AND (ReceiveOrderPoNumber LIKE ?) + GROUP BY ReceiveOrderPoID"; + $qry = $this->db->query($sql, [$itemCategoryID, $branchAsalCode, $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getReceiveOrderPo"); + return; + } + $rows = $qry->result_array(); + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemReceive() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $warhouseID = $prm["warhouseID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $receiveOrderPoID = $prm["receiveOrderPoID"]; + + $totalCount = 0; + $totalPage = 0; + + $number_offset = 0; + $number_limit = 15; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sql_branch = "SELECT M_BranchID, + M_BranchCode + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchCode = ?"; + $qry_branch = $this->db->query($sql_branch, [$branchAsalCode]); + if (!$qry_branch) { + $this->sys_error_db("[Error] Query getItem - branch"); + return; + } + $row_branch = $qry_branch->result_array()[0]; + + $sql = "SELECT + ro.ReceiveOrderPoID, + ro.ReceiveOrderPoNumber, + i.M_ItemID, + i.M_ItemCode, + i.M_ItemDesc, + iu.ItemUnitID, + iu.ItemUnitCode, + iu.ItemUnitName, + s.StockID, + s.StockQty AS stock_total, + COUNT(b.T_BarcodeBarangID) AS barcode_total, + IFNULL(l.qty_locked, 0) AS qty_locked, + (s.StockQty - IFNULL(l.qty_locked, 0)) AS qty_available, + w.WarehouseID, + 0 AS qty_mutasi + FROM t_barcode_barang b + JOIN receive_order_po ro ON b.T_BarcodeBarangReceiveOrderPoID = ro.ReceiveOrderPoID + AND ro.ReceiveOrderPoIsActive = 'Y' + AND ro.ReceiveOrderPoID = ? + JOIN stock s ON s.StockID = b.T_BarcodeBarangStockID + JOIN warehouse w ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + AND w.WarehouseM_BranchID = ? + JOIN m_item i ON i.M_ItemID = b.T_BarcodeBarangM_ItemID + JOIN itemunit iu ON b.T_BarcodeBarangItemUnitID = iu.ItemUnitID + LEFT JOIN ( + SELECT + MutasiStockLockStockID, + SUM(MutasiStockLockQtyLocked) AS qty_locked + FROM mutasi_stock_lock + WHERE MutasiStockLockIsActive = 'Y' + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockType = 'INV' + GROUP BY MutasiStockLockStockID + ) l ON l.MutasiStockLockStockID = s.StockID + WHERE + s.StockWarehouseID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND b.T_BarcodeBarangStockID <> 0 + + AND (i.M_ItemCode LIKE ? OR i.M_ItemDesc LIKE ?) + + GROUP BY + ro.ReceiveOrderPoID, + s.StockID, + i.M_ItemID + ORDER BY ro.ReceiveOrderPoID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search]); + + if ($qrytotal) { + $totalCount = $qrytotal->result_array()[0]['total']; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("[Error] Query getItem - total", $this->db); + exit; + } + + $sql_list = $sql . " LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql_list, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search, $number_limit, $number_offset]); + // echo $this->db->last_query(); + // exit; + if (!$qry) { + $this->sys_error_db("[Error] Query getItem"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "total_page" => $totalPage, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + $detailItems[] = [ + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'itemunit_id' => $item['ItemUnitID'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_id' => 0, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_id' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # INSERT HEADER # + $sql_header = "INSERT INTO mutasi_request( + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestItemCategoryID, + MutasiRequestFromBranchID, + MutasiRequestToBranchID, + MutasiRequestTotalValue, + MutasiRequestNote, + MutasiRequestStatus, + MutasiRequestIsActive, + MutasiRequestCreated, + MutasiRequestUserID) VALUES(?,fn_numbering('RM'),?,?,?,?,?,'Draft','Y',NOW(),?)"; + $qry_header = $this->db->query($sql_header, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'] + ]); + if (!$qry_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table mutasi request", $this->db); + exit; + } + $mrID = $this->db->insert_id(); + + # INSERT DETAIL # + foreach ($detailItems as $d) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $mrID, + $d['receive_order_po_id'], + $d['receive_order_po_number'], + $d['stock_id'], + $d['item_id'], + $d['itemunit_id'], + $d['qty'], + $d['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("['Error'] insert into table mutasi request detail", $this->db); + exit; + } + + // ambil detail_id + $detail_id = $this->db->insert_id(); + + + # VALIDASI STOCK # + if ($d['lock_type'] === 'INV') { + + $sqlCheck = "SELECT + s.StockQty - + COALESCE(( + SELECT SUM(l.MutasiStockLockQtyLocked) + FROM mutasi_stock_lock l + WHERE l.MutasiStockLockStockID = s.StockID + AND l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + ),0) AS qty_available + FROM stock s + WHERE s.StockID = ? + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$d['stock_id']])->row(); + + if (!$row || $row->qty_available < $d['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($d['lock_type'] === 'AST') { + if (empty($d['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + // INSERT STOCK LOCK + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $mrID, + $detail_id, + $d['item_id'], + $d['stock_id'], + $d['barcode_id'], + $prm['branch_asal_id'], + $d['warehouse_id'], + $d['qty'], + $d['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table stock lock", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("Request mutasi created successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemMutasiUpdate() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $mutasiRequestID = $prm['mutasiRequestID']; + + $sql = "SELECT + MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID AS ReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber AS ReceiveOrderPoNumber, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + w.WarehouseID, + s.StockID, + s.StockQty AS stock_total, + IFNULL(bc.barcode_total, 0) AS barcode_total, + COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_locked, + IFNULL(bc.barcode_total, 0) - COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_available, + MutasiRequestDetailQty AS qty_mutasi + FROM mutasi_request_detail + JOIN mutasi_request + ON MutasiRequestDetailMutasiRequestID = MutasiRequestID + JOIN m_item + ON MutasiRequestDetailM_ItemID = M_ItemID + JOIN itemunit + ON MutasiRequestDetailItemUnitID = ItemUnitID + JOIN stock s + ON MutasiRequestDetailStockID = s.StockID + JOIN warehouse w + ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + -- total barcode per stock + PO + LEFT JOIN ( + SELECT + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID, + COUNT(*) AS barcode_total + FROM t_barcode_barang b + WHERE b.T_BarcodeBarangIsActive = 'Y' + GROUP BY + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + ) bc + ON bc.T_BarcodeBarangStockID = s.StockID + AND bc.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + -- barcode yang sedang di-lock + LEFT JOIN ( + SELECT + l.MutasiStockLockT_BarcodeBarangID, + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + FROM mutasi_stock_lock l + JOIN t_barcode_barang b + ON b.T_BarcodeBarangID = l.MutasiStockLockT_BarcodeBarangID + WHERE + l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockType = 'INV' + ) lk + ON lk.T_BarcodeBarangStockID = s.StockID + AND lk.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + WHERE + MutasiRequestDetailIsActive = 'Y' + AND MutasiRequestDetailMutasiRequestID = ? + GROUP BY + MutasiRequestDetailID, + s.StockID, + bc.barcode_total + ORDER BY + MutasiRequestDetailID"; + $qry = $this->db->query($sql, [$mutasiRequestID]); + if (!$qry) { + $this->sys_error_db("[Error] get item update", $this->db); + exit; + } + + $data = $qry->result_array(); + + $result = array( + "records" => $data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + $detailItems[] = [ + 'MutasiRequestDetailID' => $item['MutasiRequestDetailID'], + 'MutasiRequestID' => $item['MutasiRequestDetailMutasiRequestID'], + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'itemunit_id' => $item['ItemUnitID'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_id' => 0, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_id' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # UPDATE MUTASI # + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestDate = ?, + MutasiRequestItemCategoryID = ?, + MutasiRequestFromBranchID = ?, + MutasiRequestToBranchID = ?, + MutasiRequestTotalValue = ?, + MutasiRequestNote = ?, + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'], + $prm['mutasi_request_id'] + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request", $this->db); + exit; + } + + # check jika detail sudah ada # + $sql_check_detail = "SELECT MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID + FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? + AND MutasiRequestDetailIsActive = 'Y'"; + $qry_check_detail = $this->db->query($sql_check_detail, [$prm['mutasi_request_id']]); + if (!$qry_check_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get list check detail mutasi", $this->db); + exit; + } + $list_detail_check = $qry_check_detail->result_array(); + $array_detailID = array_column($list_detail_check, 'MutasiRequestDetailID'); + $input_detail = array_column($detailItems, 'MutasiRequestDetailID'); + + $update_detail = []; + $insert_detail = []; + $delete_detail = []; + + foreach ($detailItems as $key => $value) { + if (empty($value['MutasiRequestDetailID'])) { + $insert_detail[] = $value; + continue; + } + if (in_array($value['MutasiRequestDetailID'], $array_detailID)) { + $update_detail[] = $value; + } + } + + foreach ($list_detail_check as $key => $value) { + if (!in_array($value['MutasiRequestDetailID'], $input_detail)) { + $delete_detail[] = $value; + } + } + + # UPDATE MUTASI DETAIL # + foreach ($update_detail as $k => $v) { + $sql_update_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailMutasiRequestID = ?, + MutasiRequestDetailReceiveOrderPoID = ?, + MutasiRequestDetailReceiveOrderPoNumber = ?, + MutasiRequestDetailStockID = ?, + MutasiRequestDetailM_ItemID = ?, + MutasiRequestDetailItemUnitID = ?, + MutasiRequestDetailQty = ?, + MutasiRequestDetailBookValue = ?, + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID = ?"; + $qry_update_detail = $this->db->query($sql_update_detail, [ + $v['MutasiRequestID'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'], + $v['MutasiRequestDetailID'] + ]); + if (!$qry_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request detail", $this->db); + exit; + } + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + $sqlCheck = "SELECT + s.StockQty - + COALESCE(( + SELECT SUM(l.MutasiStockLockQtyLocked) + FROM mutasi_stock_lock l + WHERE l.MutasiStockLockStockID = s.StockID + AND l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + ),0) AS qty_available + FROM stock s + WHERE s.StockID = ? + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['stock_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + # update stock lock + $sql_update_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockMutasiRequestID = ?, + MutasiStockLockMutasiRequestDetailID = ?, + MutasiStockLockM_ItemID = ?, + MutasiStockLockStockID = ?, + MutasiStockLockT_BarcodeBarangID = ?, + MutasiStockLockM_BranchID = ?, + MutasiStockLockWarehouseID = ?, + MutasiStockLockQtyLocked = ?, + MutasiStockLockType = ?, + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $qry_update_stock_lock = $this->db->query($sql_update_stock_lock, [ + $prm['mutasi_request_id'], + $v['MutasiRequestDetailID'], + $v['item_id'], + $v['stock_id'], + $v['barcode_id'], + $prm['branch_asal_id'], + $v['warehouse_id'], + $v['qty'], + $v['lock_type'], + $user['M_UserID'], + $v['MutasiRequestDetailID'] + ]); + if (!$qry_update_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + # INSERT MUTASI DETAIL BARU # + foreach ($insert_detail as $k => $v) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $prm['mutasi_request_id'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] Re-insert table mutasi request detail", $this->db); + exit; + } + + $detail_id = $this->db->insert_id(); + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + + $sqlCheck = "SELECT + s.StockQty - + COALESCE(( + SELECT SUM(l.MutasiStockLockQtyLocked) + FROM mutasi_stock_lock l + WHERE l.MutasiStockLockStockID = s.StockID + AND l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + ),0) AS qty_available + FROM stock s + WHERE s.StockID = ? + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['stock_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + // INSERT LOCK + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $prm['mutasi_request_id'], + $detail_id, + $v['item_id'], + $v['stock_id'], + $v['barcode_id'], + $prm['branch_asal_id'], + $v['warehouse_id'], + $v['qty'], + $v['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] edit mutasi, insert table stock lock", $this->db); + exit; + } + } + + # DELETE MUTASI DETAIL # + if (count($delete_detail) > 0) { + $delete_id = array_column($delete_detail, 'MutasiRequestDetailID'); + $placeholders = implode(', ', array_fill(0, count($delete_id), '?')); + + $delete_param = array_merge(array($user['M_UserID']), $delete_id); + $sql_delete_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID IN ($placeholders)"; + $qry_delete_detail = $this->db->query($sql_delete_detail, $delete_param); + if (!$qry_delete_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] delete mutasi request detail", $this->db); + exit; + } + + # delete mutasi stock lock + $sql_update_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'INACTIVE', + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $qry_update_stock_lock = $this->db->query($sql_update_stock_lock, $delete_param); + if (!$qry_update_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("Update mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mutasiRequestID = $prm['mutasiRequestID']; + + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestIsActive = 'N', + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi request', $this->db); + exit; + } + + $sql_mutasi_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailMutasiRequestID = ?"; + $qry_mutasi_detail = $this->db->query($sql_mutasi_detail, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi_detail) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi detail', $this->db); + exit; + } + + $sql_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'INACTIVE', + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestID = ?"; + $qry_stock_lock = $this->db->query($sql_stock_lock, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] mutasi stock lock', $this->db); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("Delete Request mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // Approved + // ------------------------------ + function getApproveLevel() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $userId = $this->sys_user["M_UserID"]; + + $sqlevel = "SELECT M_UserM_ApproveLevelID FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ? "; + $qulevel = $this->db->query($sqlevel, [$userId]); + if (!$qulevel) { + $this->sys_error_db("[Error] get approval level user"); + exit; + } + $data = $qulevel->row_array(); + + $this->sys_ok($data); + } + + function approveMutasiRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # get data before + $dataMrBefore = $this->getDataMutasiRequest($prm['mutasiRequestID']); + + if (intval($prm['approvelevel'] == 1)) { + $sql = "UPDATE mutasi_request SET + MutasiRequestStatus = 'Verified', + MutasiRequestIsVerif = 'Y', + MutasiRequestVerifUserID = ?, + MutasiRequestVerifDate = NOW(), + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$user['M_UserID'], $user['M_UserID'], $prm['mutasiRequestID']]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] verif by manager", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($prm['mutasiRequestID']); + $this->insertLogMutasiRequest($prm['mutasiRequestID'], 'VERIFIED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Verified data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Verified data mutasi request by user ID : {$user['M_UserID']}", 'VERIFIED', $prm['mutasiRequestID'], '', $user['M_UserID']); + + + $this->db->trans_commit(); + $this->sys_ok("Success Verified by manager"); + } else if (intval($prm['approvelevel'] == 2)) { + $sql = "UPDATE mutasi_request SET + MutasiRequestStatus = 'Approved', + MutasiRequestIsApproved = 'Y', + MutasiRequestApprovedUserID = ?, + MutasiRequestApprovedDate = NOW(), + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$user['M_UserID'], $user['M_UserID'], $prm['mutasiRequestID']]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] approve by kacab", $this->db); + exit; + } + $dataMrAfter = $this->getDataMutasiRequest($prm['mutasiRequestID']); + $this->insertLogMutasiRequest($prm['mutasiRequestID'], 'APPROVED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Approved data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Approved data mutasi request by user ID : {$user['M_UserID']}", 'APPROVED', $prm['mutasiRequestID'], '', $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Success Approved by kacab"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function rejectMutasiRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mrID = intval($prm["mutasiRequestID"]); + $note = $prm["reject_note"]; + + # get data before + $dataMrBefore = $this->getDataMutasiRequest($mrID); + + # cek mutasi + $mutasi = $this->db->query("SELECT MutasiRequestStatus + FROM mutasi_request + WHERE MutasiRequestID = ? + AND MutasiRequestIsActive = 'Y' + FOR UPDATE + ", [$mrID])->row(); + + if (!$mutasi) { + $this->db->trans_rollback(); + $this->sys_error("Data mutasi tidak ditemukan", $this->db); + exit; + } + + # validasi boleh reject atau tidak + if (!in_array($mutasi->MutasiRequestStatus, ['Draft', 'Verified', 'Approved'])) { + $this->db->trans_rollback(); + $this->sys_error("Mutasi tidak dapat direject pada status ini"); + exit; + } + + #get username + $getUser = $this->db->query("SELECT M_UserID, + M_UserUsername + FROM m_user + WHERE M_UserIsActive = 'Y' + AND M_UserID = ?", [$user['M_UserID']])->row_array(); + if (!$getUser) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get username", $this->db); + exit; + } + + # update status mutasi to rejected + $updMutasi = $this->db->query("UPDATE mutasi_request + SET + MutasiRequestStatus = 'Rejected', + MutasiRequestNote = CONCAT_WS( + '\n', + NULLIF(MutasiRequestNote, ''), + CONCAT('[REJECT] ', ?, ' by user ', ?) + ), + MutasiRequestLastUpdated = NOW() + WHERE MutasiRequestID = ? + ", [$note, $getUser['M_UserUsername'], $mrID]); + + if (!$updMutasi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status mutasi", $this->db); + exit; + } + + # Release stock lock active + $updLock = $this->db->query("UPDATE mutasi_stock_lock + SET + MutasiStockLockStatus = 'RELEASED', + MutasiStockLockLastUpdated = NOW() + WHERE MutasiStockLockMutasiRequestID = ? + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockIsActive = 'Y' + ", [$mrID]); + + if (!$updLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] release stock lock", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($mrID); + $this->insertLogMutasiRequest($mrID, 'REJECTED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Rejected data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Rejected data mutasi request by user ID : {$user['M_UserID']}", 'REJECTED', $mrID, '', $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Mutasi berhasil direject"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function sendHandoverMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $header = $prm["header"]; + $detail = $prm["detail"]; + + # VALIDASI STATUS REQUEST # + if ($header["MutasiRequestStatus"] !== "Approved") { + $this->sys_error("[Error] Mutasi belum di-approve"); + exit; + } + + # CEK SUDAH PERNAH SENT # + $sqlcek = "SELECT 1 FROM mutasi_handover + WHERE MutasiHandoverMutasiRequestID = ? + AND MutasiHandoverStatus = 'Sent' + AND MutasiHandoverIsActive = 'Y'"; + $cek = $this->db->query($sqlcek, [$header["MutasiRequestID"]]); + + if ($cek->num_rows() > 0) { + $this->sys_error("[Error] Mutasi sudah pernah di-handover"); + exit; + } + + # INSERT HANDOVER HEADER # + $sql = "INSERT INTO mutasi_handover( + MutasiHandoverMutasiRequestID, + MutasiHandoverNumber, + MutasiHandoverDate, + MutasiHandoverItemCategoryID, + MutasiHandoverFromBranchID, + MutasiHandoverToBranchID, + MutasiHandoverTotalValue, + MutasiHandoverStatus, + MutasiHandoverNote, + MutasiHandoverCreated, + MutasiHandoverUserID, + MutasiHandoverIsActive + ) VALUES(?, fn_numbering('MH'), NOW(), ?, ?, ?, ?, 'Sent', ?, NOW(), ?, 'Y')"; + $qry = $this->db->query($sql, [ + $header["MutasiRequestID"], + $header["itemCategoryID"], + $header["branch_asal_id"], + $header["branch_tujuan_id"], + $header["MutasiRequestTotalValue"], + $header["MutasiRequestNote"], + $user["M_UserID"] + ]); + + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Insert handover header gagal", $this->db); + exit; + } + + $handoverID = $this->db->insert_id(); + + # INSERT HANDOVER DETAIL # + foreach ($detail as $d) { + + $sql_detail = "INSERT INTO mutasi_handover_detail( + MutasiHandoverDetailMutasiHandoverID, + MutasiHandoverDetailMutasiRequestDetailID, + MutasiHandoverDetailReceiveOrderPoID, + MutasiHandoverDetailM_ItemID, + MutasiHandoverDetailItemUnitID, + MutasiHandoverDetailStockID_From, + MutasiHandoverDetailQty, + MutasiHandoverDetailBookValue, + MutasiHandoverDetailCreated, + MutasiHandoverDetailUserID, + MutasiHandoverDetailIsActive + ) VALUES(?,?,?,?,?,?,?,?,NOW(),?,'Y')"; + + $qry_detail = $this->db->query($sql_detail, [ + $handoverID, + $d["MutasiRequestDetailID"], + $d["ReceiveOrderPoID"], + $d["M_ItemID"], + $d["ItemUnitID"], + $d["StockID"], + $d["qty_mutasi"], + 1, + $user["M_UserID"] + ]); + + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Insert handover detail gagal", $this->db); + exit; + } + } + + $sql_get_header = "SELECT * FROM mutasi_handover WHERE MutasiHandoverID = ?"; + $qry_get_header = $this->db->query($sql_get_header, [$handoverID]); + if (!$qry_get_header) { + $this->db->trans_rollback(); + $this->sys_error_db("Get header handover gagal", $this->db); + exit; + } + $header_handover = $qry_get_header->row_array(); + + $sql_get_detail = "SELECT * FROM mutasi_handover_detail WHERE MutasiHandoverDetailMutasiHandoverID = ? AND MutasiHandoverDetailIsActive = 'Y'"; + $qry_get_detail = $this->db->query($sql_get_detail, [$handoverID]); + if (!$qry_get_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Get detail handover gagal", $this->db); + exit; + } + $detail_handover = $qry_get_detail->result_array(); + $header_handover['details'] = $detail_handover; + + $this->insertUserActivity('MH', "Sent data mutasi handover ID : {$header_handover['MutasiHandoverID']}", 'SENT', $header_handover['MutasiHandoverID'], $header_handover, $user['M_UserID']); + + # GET DATA BEFORE # + $dataMrBefore = $this->getDataMutasiRequest($header['MutasiRequestID']); + + # UPDATE STATUS REQUEST → SENT # + $sqlupd = "UPDATE mutasi_request + SET MutasiRequestStatus = 'Sent', + MutasiRequestLastUpdated = NOW() + WHERE MutasiRequestID = ?"; + $upd = $this->db->query($sqlupd, [$header["MutasiRequestID"]]); + if (!$upd) { + $this->db->trans_rollback(); + $this->sys_error_db("Update status mutasi gagal", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($header['MutasiRequestID']); + $this->insertLogMutasiRequest($header['MutasiRequestID'], 'SENT', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Sent data mutasi request ID : {$header['MutasiRequestID']}"); + $this->insertUserActivity('MR', "Sent data mutasi request ID : {$header['MutasiRequestID']}", 'SENT', $header['MutasiRequestID'], '', $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Handover mutasi berhasil (Sent)"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // ---------------------------------------------------------------------------------- + private function getDataMutasiRequest($id) + { + $sql = "SELECT * FROM mutasi_request WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request", $this->db); + exit; + } + $header = $qry->row_array(); + + $sqldetail = "SELECT * FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? AND MutasiRequestDetailIsActive = 'Y'"; + $qrydetail = $this->db->query($sqldetail, [$id]); + if (!$qrydetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request detail", $this->db); + exit; + } + $detail = $qrydetail->result_array(); + $header['details'] = $detail; + return $header; + } + + // + private function insertUserActivity( + $code, + $user_desc = '', + $status, + $reff_id, + $data = '', + $userId + ) { + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $code, + $status, + $user_desc, + $reff_id, + !empty($data) ? json_encode($data) : '', + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $this->db); + exit; + } + } + + private function insertLogMutasiRequest( + $id, + $type, + $dataBefore, + $dataAfter, + $userID, + $desc = '' + ) { + $sql = "INSERT INTO acc_one_log.mutasi_request_log( + MutasiRequestLogMutasiRequestID, + MutasiRequestLogType, + MutasiRequestLogDesc, + MutasiRequestLogJsonBefore, + MutasiRequestLogJsonAfter, + MutasiRequestLogUserID, + MutasiRequestLogCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $id, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert log mutasi request", $this->db); + exit; + } + } +} diff --git a/application/controllers/mockup/mutasi/ReceiveMutasi.php b/application/controllers/mockup/mutasi/ReceiveMutasi.php new file mode 100644 index 0000000..271cf2f --- /dev/null +++ b/application/controllers/mockup/mutasi/ReceiveMutasi.php @@ -0,0 +1,1006 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $start_date = $prm['start_date']; + $end_date = $prm['end_date']; + $search = '%' . $prm['search'] . '%'; + + $page = 0; + $limit = 15; + if ($prm['current_page'] > 0) { + $page = ($prm['current_page'] - 1) * $limit; + } + + $status = $prm['status']; + $status_rm = ""; + if ($status != "") { + $status_rm .= " AND MutasiHandoverStatus = '{$status}'"; + } + + $sql = "SELECT DISTINCT MutasiHandoverID, + MutasiHandoverMutasiRequestID, + MutasiHandoverNumber, + DATE_FORMAT(MutasiHandoverDate, '%Y-%m-%d') as MutasiHandoverDate, + DATE_FORMAT(MutasiHandoverReceiveDate, '%Y-%m-%d') as MutasiHandoverReceiveDate, + M_UserUsername, + MutasiHandoverReceiveUserID, + MutasiHandoverFromBranchID, + MutasiHandoverToBranchID, + MutasiHandoverStatus, + MutasiHandoverNote, + MutasiHandoverIsActive, + itemCategoryID, + itemCategoryName, + a.M_BranchID as branch_asal_id, + a.M_BranchCode as branch_asal_code, + a.M_BranchName as branch_asal_name, + b.M_BranchID as branch_tujuan_id, + b.M_BranchCode as branch_tujuan_code, + b.M_BranchName as branch_tujuan_name, + WarehouseID, + CASE + WHEN WarehouseType = 'B' THEN CONCAT(WarehouseCode,' ', WarehouseName, ' - ', b.M_BranchName) + ELSE '' + END WarehouseName, + M_RuanganID, + M_RuanganName + FROM mutasi_handover + JOIN item_category ON MutasiHandoverItemCategoryID = itemCategoryID + AND itemCategoryIsActive = 'Y' + JOIN m_branch a ON MutasiHandoverFromBranchID = a.M_BranchID + AND a.M_BranchIsActive = 'Y' + JOIN m_branch b ON MutasiHandoverToBranchID = b.M_BranchID + AND b.M_BranchIsActive = 'Y' + LEFT JOIN m_user ON MutasiHandoverReceiveUserID = M_UserID + LEFT JOIN warehouse ON MutasiHandoverReceiveWarehouseID = WarehouseID + AND WarehouseIsActive = 'Y' + LEFT JOIN m_ruangan ON MutasiHandoverReceiveM_RuanganID = M_RuanganID + AND M_RuanganIsActive = 'Y' + WHERE MutasiHandoverIsActive = 'Y' + $status_rm + AND (MutasiHandoverNumber LIKE ?) + AND DATE(MutasiHandoverDate) BETWEEN DATE(?) AND DATE(?) + ORDER BY MutasiHandoverID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$search, $start_date, $end_date]); + if (!$qrytotal) { + $this->sys_error_db("['Error'] get total data handover", $this->db); + exit; + } + $total = $qrytotal->row_array()['total']; + + $sqldata = $sql . " LIMIT ? OFFSET ?"; + $qrydata = $this->db->query($sqldata, [ + $search, + $start_date, + $end_date, + $limit, + $page + ]); + if (!$qrydata) { + $this->sys_error_db("[Error] get list data mutasi", $this->db); + exit; + } + $rows = $qrydata->result_array(); + + $result = array( + "total_page" => ceil($total / $limit), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y' + AND itemCategoryName LIKE ? + AND itemCategoryID IN (2,3) + ORDER BY itemCategoryName ASC"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getCategory"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchAsal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ?"; + $qry = $this->db->query($sql, [$user['S_RegionalID']]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchAsal"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchTujuan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + $search = '%' . $prm["search"] . '%'; + $branchid = $prm['branch_id']; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + AND M_BranchID = ? + AND M_BranchName LIKE ? + ORDER BY M_BranchName ASC"; + $qry = $this->db->query($sql, [$user['S_RegionalID'], $branchid, $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchTujuan"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemDetail() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $mutasiHandoverID = $prm['mutasiHandoverID']; + + $sql = "SELECT MutasiHandoverDetailID, + MutasiHandoverDetailMutasiHandoverID, + MutasiRequestNumber, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + WarehouseID, + WarehouseName, + s.StockID, + s.StockQty as stock_total, + IFNULL(bc.barcode_total, 0) AS barcode_total, + COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_locked, + IFNULL(bc.barcode_total, 0) - COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_available, + MutasiHandoverDetailQty as qty_mutasi + FROM mutasi_handover_detail + JOIN mutasi_handover ON MutasiHandoverDetailMutasiHandoverID = MutasiHandoverID + JOIN mutasi_request ON MutasiHandoverMutasiRequestID = MutasiRequestID + JOIN m_item ON MutasiHandoverDetailM_ItemID = M_ItemID + JOIN itemunit ON MutasiHandoverDetailItemUnitID = ItemUnitID + JOIN stock s ON MutasiHandoverDetailStockID_From = s.StockID + JOIN warehouse w ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + -- total barcode per stock + PO + LEFT JOIN ( + SELECT + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID, + COUNT(*) AS barcode_total + FROM t_barcode_barang b + WHERE b.T_BarcodeBarangIsActive = 'Y' + GROUP BY + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + ) bc + ON bc.T_BarcodeBarangStockID = s.StockID + AND bc.T_BarcodeBarangReceiveOrderPoID = MutasiHandoverDetailReceiveOrderPoID + -- barcode yang sedang di-lock + LEFT JOIN ( + SELECT + l.MutasiStockLockT_BarcodeBarangID, + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + FROM mutasi_stock_lock l + JOIN t_barcode_barang b + ON b.T_BarcodeBarangID = l.MutasiStockLockT_BarcodeBarangID + WHERE + l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockType = 'INV' + ) lk + ON lk.T_BarcodeBarangStockID = s.StockID + AND lk.T_BarcodeBarangReceiveOrderPoID = MutasiHandoverDetailReceiveOrderPoID + WHERE MutasiHandoverDetailIsActive = 'Y' + AND MutasiHandoverDetailMutasiHandoverID = ? + GROUP BY + MutasiHandoverDetailID, + s.StockID, + bc.barcode_total + ORDER BY + MutasiHandoverDetailID"; + $qry = $this->db->query($sql, [$mutasiHandoverID]); + if (!$qry) { + $this->sys_error_db("[Error] get item detail", $this->db); + exit; + } + + $data = $qry->result_array(); + + $result = array( + "records" => $data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getWarehouse() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $branchid = $prm['branch_id']; + $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, + $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 getRuangan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $payload = $this->sys_input; + $branchid = $payload['branch_id']; + $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, [$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 receive() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mutasi_handover_id = $prm['mutasi_handover_id']; + $warehouse_id = $prm['warehouse_id']; + $ruangan_id = $prm['ruangan_id']; + + $sql_mutasi_handover = "SELECT MutasiHandoverID, + MutasiHandoverMutasiRequestID, + MutasiHandoverNumber, + MutasiHandoverDate, + MutasiHandoverReceiveDate, + MutasiHandoverReceiveUserID, + MutasiHandoverItemCategoryID, + MutasiHandoverFromBranchID, + MutasiHandoverToBranchID + FROM mutasi_handover + WHERE MutasiHandoverIsActive = 'Y' + AND MutasiHandoverID = ?"; + $qry_mutasi_handover = $this->db->query($sql_mutasi_handover, [$mutasi_handover_id]); + if (!$qry_mutasi_handover) { + $this->sys_error_db("[Error] get mutasi handover", $this->db); + exit; + } + $data_mh = $qry_mutasi_handover->row_array(); + if ($data_mh['MutasiHandoverStatus'] == 'Received') { + $this->sys_error("Mutasi sudah pernah diterima", $this->db); + exit; + } + + $sql_detail_mh = "SELECT MutasiHandoverDetailID, + MutasiHandoverDetailMutasiHandoverID, + MutasiHandoverDetailMutasiRequestDetailID, + MutasiHandoverDetailReceiveOrderPoID, + MutasiHandoverDetailM_ItemID, + MutasiHandoverDetailItemUnitID, + MutasiHandoverDetailStockID_From, + MutasiHandoverDetailStockID_To, + MutasiHandoverDetailQty, + MutasiHandoverDetailBookValue + FROM mutasi_handover_detail + WHERE MutasiHandoverDetailIsActive = 'Y' + AND MutasiHandoverDetailMutasiHandoverID = ?"; + $qry_detail_mh = $this->db->query($sql_detail_mh, [$mutasi_handover_id]); + if (!$qry_detail_mh) { + $this->sys_error_db("[Error] get mutasi handover detail", $this->db); + exit; + } + $data_detail_mh = $qry_detail_mh->result_array(); + + # Update mutasi handover + $sql_update_mh = "UPDATE mutasi_handover SET + MutasiHandoverReceiveDate = NOW(), + MutasiHandoverReceiveUserID = ?, + MutasiHandoverReceiveWarehouseID = ?, + MutasiHandoverReceiveM_RuanganID = ?, + MutasiHandoverStatus = 'Received', + MutasiHandoverLastUpdated = NOW(), + MutasiHandoverUserID = ? + WHERE MutasiHandoverID = ?"; + $qry_update_mh = $this->db->query($sql_update_mh, [ + $user['M_UserID'], + $warehouse_id, + $ruangan_id, + $user['M_UserID'], + $mutasi_handover_id + ]); + if (!$qry_update_mh) { + $this->db->trans_rollback(); + $this->sys_error_db("Update mutasi handover gagal", $this->db); + exit; + } + + foreach ($data_detail_mh as $detail) { + # Kurangi stock asal + $sql_upd_stock = "UPDATE stock SET + StockQty = StockQty - ?, + StockLastUpdated = NOW(), + StockUserID = ? + WHERE StockID = ?"; + $qry_upd_stock = $this->db->query($sql_upd_stock, [ + intval($detail['MutasiHandoverDetailQty']), + $user['M_UserID'], + $detail['MutasiHandoverDetailStockID_From'], + ]); + if (!$qry_upd_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("Update stock asal gagal", $this->db); + exit; + } + + # ambil harga dari stock asal + $sql_cek_price = "SELECT StockItemPrice + FROM stock + WHERE StockID = ?"; + $qry_cek_price = $this->db->query($sql_cek_price, [ + $detail['MutasiHandoverDetailStockID_From'] + ]); + if (!$qry_cek_price) { + $this->db->trans_rollback(); + $this->sys_error_db("Cek harga stock asal gagal", $this->db); + exit; + } + $stock_price_asal = $qry_cek_price->row_array(); + + # Cari atau buat stock tujuan + $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 = ?"; + $qry_cek_stock = $this->db->query($sql_cek_stock, [ + $detail['MutasiHandoverDetailM_ItemID'], + $detail['MutasiHandoverDetailItemUnitID'], + $warehouse_id, + $data_mh['MutasiHandoverItemCategoryID'] + ]); + if (!$qry_cek_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("Cek stock tujuan gagal", $this->db); + exit; + } + + $stock_data = $qry_cek_stock->row_array(); + $stock_ID = $stock_data['StockID']; + $stock_qty_ori = intval($stock_data['StockQty']); + $stock_qty_price = doubleval($stock_data['StockItemPrice']); + $stock_qty_end = 0; + + if (!empty($stock_data)) { + // calculate stock qty + $stock_qty_end = $stock_qty_ori + intval($detail['MutasiHandoverDetailQty']); + + $sql_update_stock = "UPDATE stock SET + StockItemPrice = ?, + StockQty = ?, + StockLastUpdated = NOW(), + StockUserID = ? + WHERE StockID = ?"; + $que_update_stock = $this->db->query($sql_update_stock, [ + $stock_qty_price, + $stock_qty_end, + $user['M_UserID'], + $stock_ID + ]); + if (!$que_update_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert update stock", $this->db); + exit; + } + } else { + // insert stock baru + $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, [ + $warehouse_id, + $detail['MutasiHandoverDetailM_ItemID'], + $detail['MutasiHandoverDetailItemUnitID'], + $stock_price_asal['StockItemPrice'], + $detail['MutasiHandoverDetailQty'], + $user['M_UserID'] + ]); + if (!$que_insert_stock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert new stock"); + exit; + } + + $stock_ID = $this->db->insert_id(); + $stock_qty_end = intval($detail['MutasiHandoverDetailQty']); + } + + # update mutasi_handover_detail stockID_To + $sql_upd_stock_id_mh = "UPDATE mutasi_handover_detail SET + MutasiHandoverDetailStockID_To = ?, + MutasiHandoverDetailLastUpdated = NOW(), + MutasiHandoverDetailUserID = ? + WHERE MutasiHandoverDetailID = ?"; + $qry_upd_stock_id_mh = $this->db->query($sql_upd_stock_id_mh, [ + $stock_ID, + $user['M_UserID'], + $detail['MutasiHandoverDetailID'] + ]); + if (!$qry_upd_stock_id_mh) { + $this->db->trans_rollback(); + $this->sys_error_db("Update stockID_To mutasi handover detail gagal", $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(), ?, ?, ?, 'MRB', ?, ?, 0, ?, ?)"; + $que_stock_card = $this->db->query($sql_stock_card, [ + $warehouse_id, + $detail['MutasiHandoverDetailM_ItemID'], + $detail['MutasiHandoverDetailItemUnitID'], + $stock_ID, + $stock_qty_ori, + $detail['MutasiHandoverDetailQty'], + $stock_qty_end, + $user['M_UserID'] + ]); + if (!$que_stock_card) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert stock card"); + exit; + } + + # get barcode untuk nonaktifkan barcode lama # + $sql_get_barcode = "SELECT MutasiStockLockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockQtyLocked, + MutasiStockLockType + FROM mutasi_stock_lock + WHERE MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockIsActive = 'Y' + AND MutasiStockLockMutasiRequestID = ? + AND MutasiStockLockStockID = ? + AND MutasiStockLockM_BranchID = ?"; + $qry_get_barcode = $this->db->query($sql_get_barcode, [ + $data_mh['MutasiHandoverMutasiRequestID'], + $detail['MutasiHandoverDetailStockID_From'], + $data_mh['MutasiHandoverFromBranchID'] + ]); + if (!$qry_get_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("Get stock barcode gagal", $this->db); + exit; + } + $barcodes = $qry_get_barcode->result_array(); + + # cek qty detail vs barcode, qty tidak boleh lebih besar dari barcode + if (count($barcodes) < intval($detail['MutasiHandoverDetailQty'])) { + $this->db->trans_rollback(); + $this->sys_error("Jumlah barcode tidak mencukupi untuk mutasi"); + exit; + } + + # Nonaktifkan barcode lama + foreach ($barcodes as $bc) { + $sql_upd_barcode = "UPDATE t_barcode_barang SET + T_BarcodeBarangIsActive = 'N', + T_BarcodeBarangUserID = ?, + T_BarcodeBarangLastUpdated = NOW() + WHERE T_BarcodeBarangID = ?"; + $qry_upd_barcode = $this->db->query($sql_upd_barcode, [ + $user['M_UserID'], + $bc['MutasiStockLockT_BarcodeBarangID'] + ]); + if (!$qry_upd_barcode) { + $this->db->trans_rollback(); + $this->sys_error_db("Update barcode lama gagal", $this->db); + exit; + } + } + + # Generate barcode baru + if (count($barcodes) > 0) { + for ($i = 0; $i < count($barcodes); $i++) { + # generate nomor barcode # + $noBarcode = $this->generateNoBarcode($user, $ruangan_id, 'BNP', $detail['MutasiHandoverDetailM_ItemID']); + + # INSERT INTO t_barcode_barang # + $sqlInsertBarcode = "INSERT INTO t_barcode_barang( + T_BarcodeBarangStockID, + T_BarcodeBarangReceiveOrderPoID, + T_BarcodeBarangReceiveOrderPoDetailID, + T_BarcodeBarangRefID, + T_BarcodeBarangRefType, + T_BarcodeBarangM_ItemID, + T_BarcodeBarangItemUnitID, + T_BarcodeBarangNumber, + T_BarcodeBarangM_RuanganID, + T_BarcodeBarangM_BranchID, + T_BarcodeBarangIsActive, + T_BarcodeBarangUserID, + T_BarcodeBarangCreated) VALUES(?,0,0,?,'MUTASI',?,?,?,?,?,'Y',?,NOW())"; + $qryInsertBarcode = $this->db->query($sqlInsertBarcode, array( + $stock_ID, + $mutasi_handover_id, + $detail['MutasiHandoverDetailM_ItemID'], + $detail['MutasiHandoverDetailItemUnitID'], + $noBarcode, + $ruangan_id, + $data_mh['MutasiHandoverToBranchID'], + $user['M_UserID'] + )); + if (!$qryInsertBarcode) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert data barcode item"); + exit; + } + } + } + + # CONSUMED LOCK STOCK + $sql_consumed_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'CONSUMED', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ? + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockType = 'INV' + AND MutasiStockLockIsActive = 'Y'"; + $qry_consumed_lock = $this->db->query($sql_consumed_lock, [ + $user['M_UserID'], + $detail['MutasiHandoverDetailMutasiRequestDetailID'] + ]); + if (!$qry_consumed_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("Update lock stock gagal", $this->db); + exit; + } + } + + // UPDATE STATUS + $sql_upd_handover = "UPDATE mutasi_handover + SET MutasiHandoverStatus = 'Received', + MutasiHandoverReceiveDate = NOW(), + MutasiHandoverReceiveUserID = ?, + MutasiHandoverReceiveWarehouseID = ?, + MutasiHandoverReceiveM_RuanganID = ? + WHERE MutasiHandoverID = ?"; + $qry_upd_handover = $this->db->query($sql_upd_handover, [ + $user['M_UserID'], + $warehouse_id, + $ruangan_id, + $data_mh['MutasiHandoverID'] + ]); + if (!$qry_upd_handover) { + $this->db->trans_rollback(); + $this->sys_error_db("Update status mutasi handover gagal", $this->db); + exit; + } + + // LOG MUTASI HANDOVER + $sql_get_header = "SELECT * FROM mutasi_handover WHERE MutasiHandoverID = ?"; + $qry_get_header = $this->db->query($sql_get_header, [$data_mh['MutasiHandoverID']]); + if (!$qry_get_header) { + $this->db->trans_rollback(); + $this->sys_error_db("Get header handover gagal", $this->db); + exit; + } + $header_handover = $qry_get_header->row_array(); + + $sql_get_detail = "SELECT * FROM mutasi_handover_detail WHERE MutasiHandoverDetailMutasiHandoverID = ? AND MutasiHandoverDetailIsActive = 'Y'"; + $qry_get_detail = $this->db->query($sql_get_detail, [$data_mh['MutasiHandoverID']]); + if (!$qry_get_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("Get detail handover gagal", $this->db); + exit; + } + $detail_handover = $qry_get_detail->result_array(); + $header_handover['details'] = $detail_handover; + + $this->insertUserActivity('MH', "Received data mutasi handover ID : {$header_handover['MutasiHandoverID']}", 'RECEIVED', $header_handover['MutasiHandoverID'], $header_handover, $user['M_UserID']); + + # get data before + $dataMrBefore = $this->getDataMutasiRequest($data_mh['MutasiHandoverMutasiRequestID']); + + $sql_upd_request = "UPDATE mutasi_request + SET MutasiRequestStatus = 'Received', + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_upd_request = $this->db->query($sql_upd_request, [ + $user['M_UserID'], + $data_mh['MutasiHandoverMutasiRequestID'] + ]); + if (!$qry_upd_request) { + $this->db->trans_rollback(); + $this->sys_error_db("Update status mutasi request gagal", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($data_mh['MutasiHandoverMutasiRequestID']); + $this->insertLogMutasiRequest($data_mh['MutasiHandoverMutasiRequestID'], 'RECEIVED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Received data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Received data mutasi request by user ID : {$user['M_UserID']}", 'RECEIVED', $data_mh['MutasiHandoverMutasiRequestID'], '', $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Mutasi berhasil diterima"); + } 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; + $mutasi_handover_id = $param['mutasi_handover_id']; + + $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_BarcodeBarangRefID = ? + AND T_BarcodeBarangIsActive = 'Y' + ORDER BY T_BarcodeBarangID"; + $que = $this->db->query($sql, [$mutasi_handover_id]); + 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 ----------------------------------------------- // + 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 getDataMutasiRequest($id) + { + $sql = "SELECT * FROM mutasi_request WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request", $this->db); + exit; + } + $header = $qry->row_array(); + + $sqldetail = "SELECT * FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? AND MutasiRequestDetailIsActive = 'Y'"; + $qrydetail = $this->db->query($sqldetail, [$id]); + if (!$qrydetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request detail", $this->db); + exit; + } + $detail = $qrydetail->result_array(); + $header['details'] = $detail; + return $header; + } + + // + private function insertUserActivity( + $code, + $user_desc = '', + $status, + $reff_id, + $data = '', + $userId + ) { + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $code, + $status, + $user_desc, + $reff_id, + !empty($data) ? json_encode($data) : '', + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $this->db); + exit; + } + } + + private function insertLogMutasiRequest( + $id, + $type, + $dataBefore, + $dataAfter, + $userID, + $desc = '' + ) { + $sql = "INSERT INTO acc_one_log.mutasi_request_log( + MutasiRequestLogMutasiRequestID, + MutasiRequestLogType, + MutasiRequestLogDesc, + MutasiRequestLogJsonBefore, + MutasiRequestLogJsonAfter, + MutasiRequestLogUserID, + MutasiRequestLogCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $id, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert log mutasi request", $this->db); + exit; + } + } +} diff --git a/application/controllers/mockup/mutasi/Requestmutasi.php b/application/controllers/mockup/mutasi/Requestmutasi.php new file mode 100644 index 0000000..b3a58b7 --- /dev/null +++ b/application/controllers/mockup/mutasi/Requestmutasi.php @@ -0,0 +1,1401 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $start_date = $prm['start_date']; + $end_date = $prm['end_date']; + $search = '%' . $prm['search'] . '%'; + + $page = 0; + $limit = 15; + if ($prm['current_page'] > 0) { + $page = ($prm['current_page'] - 1) * $limit; + } + + $status = $prm['status']; + $status_rm = ""; + if ($status != "") { + $status_rm .= " AND MutasiRequestStatus = '{$status}'"; + } + + $sql = "SELECT DISTINCT MutasiRequestID, + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestTotalValue, + MutasiRequestStatus, + MutasiRequestNote, + itemCategoryID, + itemCategoryName, + a.M_BranchID as branch_asal_id, + a.M_BranchCode as branch_asal_code, + a.M_BranchName as branch_asal_name, + b.M_BranchID as branch_tujuan_id, + b.M_BranchCode as branch_tujuan_code, + b.M_BranchName as branch_tujuan_name + FROM mutasi_request + JOIN item_category ON MutasiRequestItemCategoryID = itemCategoryID + AND itemCategoryIsActive = 'Y' + JOIN m_branch a ON MutasiRequestFromBranchID = a.M_BranchID + AND a.M_BranchIsActive = 'Y' + JOIN m_branch b ON MutasiRequestToBranchID = b.M_BranchID + AND b.M_BranchIsActive = 'Y' + WHERE MutasiRequestIsActive = 'Y' + $status_rm + AND (MutasiRequestNumber LIKE ?) + AND MutasiRequestDate BETWEEN DATE(?) AND DATE(?) + ORDER BY MutasiRequestID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$search, $start_date, $end_date]); + if (!$qrytotal) { + $this->sys_error_db("['Error'] get total data mutasi", $this->db); + exit; + } + $total = $qrytotal->row_array()['total']; + + $sqldata = $sql . " LIMIT ? OFFSET ?"; + $qrydata = $this->db->query($sqldata, [ + $search, + $start_date, + $end_date, + $limit, + $page + ]); + if (!$qrydata) { + $this->sys_error_db("[Error] get list data mutasi", $this->db); + exit; + } + $rows = $qrydata->result_array(); + + $result = array( + "total_page" => ceil($total / $limit), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y' + AND itemCategoryName LIKE ? + AND itemCategoryID IN (2,3) + ORDER BY itemCategoryName ASC"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getCategory"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchAsal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry = $this->db->query($sql, [$user['M_BranchID']]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchAsal"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchTujuan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + AND M_BranchID <> ? + AND M_BranchName LIKE ? + ORDER BY M_BranchName ASC"; + $qry = $this->db->query($sql, [$user['S_RegionalID'], $user['M_BranchID'], $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchTujuan"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getReceiveOrderPo() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $itemCategoryID = $prm["itemCategoryID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT DISTINCT ReceiveOrderPoID, + ReceiveOrderPoNumber, + ReceiveOrderPoIDate, + ReceiveOrderPoWarehouseID, + ReceiveOrderPoM_BranchCode + FROM receive_order_po + JOIN t_barcode_barang ON T_BarcodeBarangReceiveOrderPoID = ReceiveOrderPoID + AND T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangStockID <> 0 + JOIN m_item ON T_BarcodeBarangM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + AND M_ItemItem_CategoryID = ? + WHERE ReceiveOrderPoIsActive = 'Y' + AND ReceiveOrderPoM_BranchCode = ? + AND ReceiveOrderPoIsHandover = 'Y' + AND ReceiveOrderPoConfirmed = 'Y' + AND (ReceiveOrderPoNumber LIKE ?) + GROUP BY ReceiveOrderPoID + ORDER BY ReceiveOrderPoNumber DESC"; + $qry = $this->db->query($sql, [$itemCategoryID, $branchAsalCode, $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getReceiveOrderPo"); + return; + } + $rows = $qry->result_array(); + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemReceive() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $warhouseID = $prm["warhouseID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $receiveOrderPoID = $prm["receiveOrderPoID"]; + + $totalCount = 0; + $totalPage = 0; + + $number_offset = 0; + $number_limit = 15; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sql_branch = "SELECT M_BranchID, + M_BranchCode + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchCode = ?"; + $qry_branch = $this->db->query($sql_branch, [$branchAsalCode]); + if (!$qry_branch) { + $this->sys_error_db("[Error] Query getItem - branch"); + return; + } + $row_branch = $qry_branch->result_array()[0]; + + $sql = "SELECT + ro.ReceiveOrderPoID, + ro.ReceiveOrderPoNumber, + i.M_ItemID, + i.M_ItemCode, + i.M_ItemDesc, + iu.ItemUnitID, + iu.ItemUnitCode, + iu.ItemUnitName, + s.StockID, + s.StockQty AS stock_total, + COUNT(b.T_BarcodeBarangID) AS barcode_total, + COUNT(DISTINCT l.MutasiStockLockT_BarcodeBarangID) AS qty_locked, + (COUNT(b.T_BarcodeBarangID) - COUNT(DISTINCT l.MutasiStockLockT_BarcodeBarangID)) AS qty_available, + w.WarehouseID, + 0 AS qty_mutasi, + GROUP_CONCAT(b.T_BarcodeBarangID) as barcode_ids + FROM t_barcode_barang b + JOIN receive_order_po ro ON b.T_BarcodeBarangReceiveOrderPoID = ro.ReceiveOrderPoID + AND ro.ReceiveOrderPoIsActive = 'Y' + AND ro.ReceiveOrderPoID = ? + JOIN stock s ON s.StockID = b.T_BarcodeBarangStockID + JOIN warehouse w ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + AND w.WarehouseM_BranchID = ? + JOIN m_item i ON i.M_ItemID = b.T_BarcodeBarangM_ItemID + JOIN itemunit iu ON b.T_BarcodeBarangItemUnitID = iu.ItemUnitID + LEFT JOIN ( + SELECT MutasiStockLockT_BarcodeBarangID + FROM mutasi_stock_lock + WHERE MutasiStockLockIsActive = 'Y' + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockType = 'INV' + ) l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + WHERE + s.StockWarehouseID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND b.T_BarcodeBarangStockID <> 0 + + AND (i.M_ItemCode LIKE ? OR i.M_ItemDesc LIKE ?) + + GROUP BY + ro.ReceiveOrderPoID, + s.StockID, + i.M_ItemID + ORDER BY ro.ReceiveOrderPoID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search]); + + if ($qrytotal) { + $totalCount = $qrytotal->result_array()[0]['total']; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("[Error] Query getItem - total", $this->db); + exit; + } + + $sql_list = $sql . " LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql_list, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search, $number_limit, $number_offset]); + if (!$qry) { + $this->sys_error_db("[Error] Query getItem"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "total_page" => $totalPage, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function getDataMutasiRequest($id) + { + $sql = "SELECT * FROM mutasi_request WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request", $this->db); + exit; + } + $header = $qry->row_array(); + + $sqldetail = "SELECT * FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? AND MutasiRequestDetailIsActive = 'Y'"; + $qrydetail = $this->db->query($sqldetail, [$id]); + if (!$qrydetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request detail", $this->db); + exit; + } + $detail = $qrydetail->result_array(); + $header['details'] = $detail; + return $header; + } + + function saveMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + # GET BARCODE IDS FIFO # + $sql_barcode_ids = "SELECT T_BarcodeBarangID, + T_BarcodeBarangStockID, + T_BarcodeBarangNumber + FROM t_barcode_barang + WHERE T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangReceiveOrderPoID = ? + ORDER BY T_BarcodeBarangID ASC"; + $qry_barcode_ids = $this->db->query($sql_barcode_ids, [$item["ReceiveOrderPoID"]]); + if (!$qry_barcode_ids) { + $this->sys_error_db("[Error] Query getBarcode", $this->db); + exit; + } + $barcode_rows = $qry_barcode_ids->result_array(); + $selected_barcodes = []; + $count = 0; + foreach ($barcode_rows as $b) { + if ($count >= intval($item['qty_mutasi'])) { + break; + } + $selected_barcodes[] = $b; + $count++; + } + + $detailItems[] = [ + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'item_desc' => $item['M_ItemDesc'], + 'itemunit_id' => $item['ItemUnitID'], + 'itemunit_name' => $item['ItemUnitName'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_ids' => $selected_barcodes, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_ids' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # INSERT HEADER # + $sql_header = "INSERT INTO mutasi_request( + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestItemCategoryID, + MutasiRequestFromBranchID, + MutasiRequestToBranchID, + MutasiRequestTotalValue, + MutasiRequestNote, + MutasiRequestStatus, + MutasiRequestIsActive, + MutasiRequestCreated, + MutasiRequestUserID) VALUES(?,fn_numbering('RM'),?,?,?,?,?,'Draft','Y',NOW(),?)"; + $qry_header = $this->db->query($sql_header, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'] + ]); + if (!$qry_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table mutasi request", $this->db); + exit; + } + $mrID = $this->db->insert_id(); + + # INSERT DETAIL # + $logDesc = []; + foreach ($detailItems as $d) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $mrID, + $d['receive_order_po_id'], + $d['receive_order_po_number'], + $d['stock_id'], + $d['item_id'], + $d['itemunit_id'], + $d['qty'], + $d['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("['Error'] insert into table mutasi request detail", $this->db); + exit; + } + + // ambil detail_id + $detail_id = $this->db->insert_id(); + + $logDesc[] = "- ADD {$d['item_desc']} {$d['qty']} {$d['itemunit_name']} dengan receive po number {$d['receive_order_po_number']}"; + + + # VALIDASI STOCK # + if ($d['lock_type'] === 'INV') { + + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$d['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $d['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($d['lock_type'] === 'AST') { + if (empty($d['barcode_ids'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + // INSERT STOCK LOCK + if (count($d['barcode_ids']) > 0) { + foreach ($d['barcode_ids'] as $b) { + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $mrID, + $detail_id, + $d['item_id'], + $d['stock_id'], + $b['T_BarcodeBarangID'], + $prm['branch_asal_id'], + $d['warehouse_id'], + 1, + $d['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table stock lock", $this->db); + exit; + } + } + } + } + + $dataMrAfter = $this->getDataMutasiRequest($mrID); + $this->insertLogMutasiRequest($mrID, 'ADD', '', $dataMrAfter, $user['M_UserID'], implode("\n", $logDesc)); + $this->insertUserActivity('MR', implode("\n", $logDesc), 'ADD', $mrID, $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Request mutasi created successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemMutasiUpdate() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $mutasiRequestID = $prm['mutasiRequestID']; + + $sql = "SELECT + MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID AS ReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber AS ReceiveOrderPoNumber, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + w.WarehouseID, + s.StockID, + s.StockQty AS stock_total, + IFNULL(bc.barcode_total, 0) AS barcode_total, + COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_locked, + IFNULL(bc.barcode_total, 0) - COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_available, + MutasiRequestDetailQty AS qty_mutasi + FROM mutasi_request_detail + JOIN mutasi_request + ON MutasiRequestDetailMutasiRequestID = MutasiRequestID + JOIN m_item + ON MutasiRequestDetailM_ItemID = M_ItemID + JOIN itemunit + ON MutasiRequestDetailItemUnitID = ItemUnitID + JOIN stock s + ON MutasiRequestDetailStockID = s.StockID + JOIN warehouse w + ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + -- total barcode per stock + PO + LEFT JOIN ( + SELECT + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID, + COUNT(*) AS barcode_total + FROM t_barcode_barang b + WHERE b.T_BarcodeBarangIsActive = 'Y' + GROUP BY + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + ) bc + ON bc.T_BarcodeBarangStockID = s.StockID + AND bc.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + -- barcode yang sedang di-lock + LEFT JOIN ( + SELECT + l.MutasiStockLockT_BarcodeBarangID, + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + FROM mutasi_stock_lock l + JOIN t_barcode_barang b + ON b.T_BarcodeBarangID = l.MutasiStockLockT_BarcodeBarangID + WHERE + l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockType = 'INV' + ) lk + ON lk.T_BarcodeBarangStockID = s.StockID + AND lk.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + WHERE + MutasiRequestDetailIsActive = 'Y' + AND MutasiRequestDetailMutasiRequestID = ? + GROUP BY + MutasiRequestDetailID, + s.StockID, + bc.barcode_total + ORDER BY + MutasiRequestDetailID"; + $qry = $this->db->query($sql, [$mutasiRequestID]); + if (!$qry) { + $this->sys_error_db("[Error] get item update", $this->db); + exit; + } + + $data = $qry->result_array(); + + $result = array( + "records" => $data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # get data mutasi for log # + $dataMrBefore = $this->getDataMutasiRequest($prm['mutasi_request_id']); + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + # GET BARCODE IDS FIFO # + $sql_barcode_ids = "SELECT T_BarcodeBarangID, + T_BarcodeBarangStockID, + T_BarcodeBarangNumber + FROM t_barcode_barang + WHERE T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangReceiveOrderPoID = ? + ORDER BY T_BarcodeBarangID ASC"; + $qry_barcode_ids = $this->db->query($sql_barcode_ids, [$item["ReceiveOrderPoID"]]); + if (!$qry_barcode_ids) { + $this->sys_error_db("[Error] Query getBarcode", $this->db); + exit; + } + $barcode_rows = $qry_barcode_ids->result_array(); + $selected_barcodes = []; + $count = 0; + foreach ($barcode_rows as $b) { + if ($count >= intval($item['qty_mutasi'])) { + break; + } + $selected_barcodes[] = $b; + $count++; + } + + $detailItems[] = [ + 'MutasiRequestDetailID' => $item['MutasiRequestDetailID'], + 'MutasiRequestID' => $item['MutasiRequestDetailMutasiRequestID'], + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'itemunit_id' => $item['ItemUnitID'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_ids' => $selected_barcodes, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_id' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # UPDATE MUTASI # + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestDate = ?, + MutasiRequestItemCategoryID = ?, + MutasiRequestFromBranchID = ?, + MutasiRequestToBranchID = ?, + MutasiRequestTotalValue = ?, + MutasiRequestNote = ?, + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'], + $prm['mutasi_request_id'] + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request", $this->db); + exit; + } + + # check jika detail sudah ada # + $sql_check_detail = "SELECT MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID + FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? + AND MutasiRequestDetailIsActive = 'Y'"; + $qry_check_detail = $this->db->query($sql_check_detail, [$prm['mutasi_request_id']]); + if (!$qry_check_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get list check detail mutasi", $this->db); + exit; + } + $list_detail_check = $qry_check_detail->result_array(); + $array_detailID = array_column($list_detail_check, 'MutasiRequestDetailID'); + $input_detail = array_column($detailItems, 'MutasiRequestDetailID'); + + $update_detail = []; + $insert_detail = []; + $delete_detail = []; + + foreach ($detailItems as $key => $value) { + if (empty($value['MutasiRequestDetailID'])) { + $insert_detail[] = $value; + continue; + } + if (in_array($value['MutasiRequestDetailID'], $array_detailID)) { + $update_detail[] = $value; + } + } + + foreach ($list_detail_check as $key => $value) { + if (!in_array($value['MutasiRequestDetailID'], $input_detail)) { + $delete_detail[] = $value; + } + } + + # UPDATE MUTASI DETAIL # + foreach ($update_detail as $k => $v) { + $sql_update_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailMutasiRequestID = ?, + MutasiRequestDetailReceiveOrderPoID = ?, + MutasiRequestDetailReceiveOrderPoNumber = ?, + MutasiRequestDetailStockID = ?, + MutasiRequestDetailM_ItemID = ?, + MutasiRequestDetailItemUnitID = ?, + MutasiRequestDetailQty = ?, + MutasiRequestDetailBookValue = ?, + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID = ?"; + $qry_update_detail = $this->db->query($sql_update_detail, [ + $v['MutasiRequestID'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'], + $v['MutasiRequestDetailID'] + ]); + if (!$qry_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request detail", $this->db); + exit; + } + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + # tentukan barcode yang di insert, update, delete # + $sql_lock = "SELECT MutasiStockLockT_BarcodeBarangID as T_BarcodeBarangID + FROM mutasi_stock_lock WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $row_lock = $this->db->query($sql_lock, [$v['MutasiRequestDetailID']]); + if (!$row_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi stock lock", $this->db); + exit; + } + $lock_data = $row_lock->result_array(); + $array_barcodeID = array_column($lock_data, 'T_BarcodeBarangID'); + $input_barcode = array_column($v['barcode_ids'], 'T_BarcodeBarangID'); + + $update_barcode = []; + $insert_barcode = []; + $delete_barcode = []; + + foreach ($v['barcode_ids'] as $key => $value) { + if (!in_array($value['T_BarcodeBarangID'], $array_barcodeID)) { + $insert_barcode[] = $value; + continue; + } + if (in_array($value['T_BarcodeBarangID'], $array_barcodeID)) { + $update_barcode[] = $value; + } + } + + foreach ($lock_data as $key => $value) { + if (!in_array($value['T_BarcodeBarangID'], $input_barcode)) { + $delete_barcode[] = $value; + } + } + + # UPDATE STOCK LOCK + foreach ($update_barcode as $k => $ub) { + $sql_update_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockMutasiRequestID = ?, + MutasiStockLockMutasiRequestDetailID = ?, + MutasiStockLockM_ItemID = ?, + MutasiStockLockStockID = ?, + MutasiStockLockT_BarcodeBarangID = ?, + MutasiStockLockM_BranchID = ?, + MutasiStockLockWarehouseID = ?, + MutasiStockLockQtyLocked = ?, + MutasiStockLockType = ?, + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockT_BarcodeBarangID = ?"; + $qry_update_lock = $this->db->query($sql_update_lock, [ + $prm['mutasi_request_id'], + $v['MutasiRequestDetailID'], + $v['item_id'], + $v['stock_id'], + $ub['T_BarcodeBarangID'], + $prm['branch_asal_id'], + $v['warehouse_id'], + 1, + $v['lock_type'], + $user['M_UserID'], + $ub['T_BarcodeBarangID'] + ]); + if (!$qry_update_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + # INSERT STOCK LOCK + foreach ($insert_barcode as $k => $ib) { + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + $qryLock = $this->db->query($sqlLock, [ + $v['MutasiRequestID'], + $v['MutasiRequestDetailID'], + $v['item_id'], + $v['stock_id'], + $ib['T_BarcodeBarangID'], + $prm['branch_asal_id'], + $v['warehouse_id'], + 1, + $v['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table stock lock", $this->db); + exit; + } + } + + # DELETE STOCK LOCK + foreach ($delete_barcode as $k => $db) { + $sql_delete_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'INACTIVE', + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ? + AND MutasiStockLockT_BarcodeBarangID = ?"; + $qry_delete_lock = $this->db->query($sql_delete_lock, [ + $user['M_UserID'], + $v['MutasiRequestDetailID'], + $db['T_BarcodeBarangID'] + ]); + if (!$qry_delete_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] delete mutasi stock lock", $this->db); + exit; + } + } + } + + # INSERT MUTASI DETAIL BARU # + foreach ($insert_detail as $k => $v) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $prm['mutasi_request_id'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] Re-insert table mutasi request detail", $this->db); + exit; + } + + $detail_id = $this->db->insert_id(); + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + # INSERT STOCK LOCK + if (count($v['barcode_ids']) > 0) { + foreach ($v['barcode_ids'] as $b) { + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $prm['mutasi_request_id'], + $detail_id, + $v['item_id'], + $v['stock_id'], + $b['T_BarcodeBarangID'], + $prm['branch_asal_id'], + $v['warehouse_id'], + 1, + $v['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table stock lock", $this->db); + exit; + } + } + } + } + + + # DELETE MUTASI DETAIL # + if (count($delete_detail) > 0) { + $delete_id = array_column($delete_detail, 'MutasiRequestDetailID'); + $placeholders = implode(', ', array_fill(0, count($delete_id), '?')); + + $delete_param = array_merge(array($user['M_UserID']), $delete_id); + $sql_delete_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID IN ($placeholders)"; + $qry_delete_detail = $this->db->query($sql_delete_detail, $delete_param); + if (!$qry_delete_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] delete mutasi request detail", $this->db); + exit; + } + + # delete mutasi stock lock + $sql_update_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'INACTIVE', + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $qry_update_stock_lock = $this->db->query($sql_update_stock_lock, $delete_param); + if (!$qry_update_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + $dataMrAfter = $this->getDataMutasiRequest($prm['mutasi_request_id']); + $this->insertLogMutasiRequest($prm['mutasi_request_id'], 'EDIT', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Edit data mutasi request ID : {$prm['mutasi_request_id']}"); + $this->insertUserActivity('MR', "Edit data mutasi request ID : {$prm['mutasi_request_id']}", 'EDIT', $prm['mutasi_request_id'], $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Update mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mutasiRequestID = $prm['mutasiRequestID']; + + # get data before for log # + $dataMrBefore = $this->getDataMutasiRequest($mutasiRequestID); + + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestIsActive = 'N', + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi request', $this->db); + exit; + } + + $sql_mutasi_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailMutasiRequestID = ?"; + $qry_mutasi_detail = $this->db->query($sql_mutasi_detail, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi_detail) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi detail', $this->db); + exit; + } + + $sql_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockStatus = 'INACTIVE', + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestID = ?"; + $qry_stock_lock = $this->db->query($sql_stock_lock, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] mutasi stock lock', $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($mutasiRequestID); + $this->insertLogMutasiRequest($mutasiRequestID, 'DELETE', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Delete data mutasi request ID : {$mutasiRequestID}"); + $this->insertUserActivity('MR', "Delete data mutasi request ID : {$mutasiRequestID}", 'DELETE', $mutasiRequestID, $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Delete Request mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // + private function insertUserActivity( + $code, + $user_desc = '', + $status, + $reff_id, + $userId + ) { + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityUserID, + UserActivityCreated + ) VALUES(?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $code, + $status, + $user_desc, + $reff_id, + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $this->db); + exit; + } + } + + private function insertLogMutasiRequest( + $id, + $type, + $dataBefore, + $dataAfter, + $userID, + $desc = '' + ) { + $sql = "INSERT INTO acc_one_log.mutasi_request_log( + MutasiRequestLogMutasiRequestID, + MutasiRequestLogType, + MutasiRequestLogDesc, + MutasiRequestLogJsonBefore, + MutasiRequestLogJsonAfter, + MutasiRequestLogUserID, + MutasiRequestLogCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $id, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert log mutasi request", $this->db); + exit; + } + } +} diff --git a/application/controllers/mockup/mutasi/RequestmutasiApproved.php b/application/controllers/mockup/mutasi/RequestmutasiApproved.php new file mode 100644 index 0000000..cc25660 --- /dev/null +++ b/application/controllers/mockup/mutasi/RequestmutasiApproved.php @@ -0,0 +1,1420 @@ +isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $start_date = $prm['start_date']; + $end_date = $prm['end_date']; + $search = '%' . $prm['search'] . '%'; + + $page = 0; + $limit = 15; + if ($prm['current_page'] > 0) { + $page = ($prm['current_page'] - 1) * $limit; + } + + $status = $prm['status']; + $status_rm = ""; + if ($status != "") { + $status_rm .= " AND MutasiRequestStatus = '{$status}'"; + } + + $sql = "SELECT DISTINCT MutasiRequestID, + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestTotalValue, + MutasiRequestStatus, + MutasiRequestNote, + MutasiRequestIsVerif, + MutasiRequestVerifUserID, + MutasiRequestVerifDate, + MutasiRequestIsApproved, + MutasiRequestApprovedUserID, + MutasiRequestApprovedDate, + itemCategoryID, + itemCategoryName, + a.M_BranchID as branch_asal_id, + a.M_BranchCode as branch_asal_code, + a.M_BranchName as branch_asal_name, + b.M_BranchID as branch_tujuan_id, + b.M_BranchCode as branch_tujuan_code, + b.M_BranchName as branch_tujuan_name + FROM mutasi_request + JOIN item_category ON MutasiRequestItemCategoryID = itemCategoryID + AND itemCategoryIsActive = 'Y' + JOIN m_branch a ON MutasiRequestFromBranchID = a.M_BranchID + AND a.M_BranchIsActive = 'Y' + JOIN m_branch b ON MutasiRequestToBranchID = b.M_BranchID + AND b.M_BranchIsActive = 'Y' + WHERE MutasiRequestIsActive = 'Y' + $status_rm + AND (MutasiRequestNumber LIKE ?) + AND MutasiRequestDate BETWEEN DATE(?) AND DATE(?) + ORDER BY MutasiRequestID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$search, $start_date, $end_date]); + if (!$qrytotal) { + $this->sys_error_db("['Error'] get total data mutasi", $this->db); + exit; + } + $total = $qrytotal->row_array()['total']; + + $sqldata = $sql . " LIMIT ? OFFSET ?"; + $qrydata = $this->db->query($sqldata, [ + $search, + $start_date, + $end_date, + $limit, + $page + ]); + if (!$qrydata) { + $this->sys_error_db("[Error] get list data mutasi", $this->db); + exit; + } + $rows = $qrydata->result_array(); + + $result = array( + "total_page" => ceil($total / $limit), + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getCategory() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT itemCategoryID, + itemCategoryName + FROM item_category + WHERE itemCategoryIsActive = 'Y' + AND itemCategoryName LIKE ? + AND itemCategoryID IN (2,3) + ORDER BY itemCategoryName ASC"; + $qry = $this->db->query($sql, [$search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getCategory"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchAsal() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ?"; + $qry = $this->db->query($sql, [$user['S_RegionalID']]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchAsal"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getBranchTujuan() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $user = $this->sys_user; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = ? + AND M_BranchID <> ? + AND M_BranchName LIKE ? + ORDER BY M_BranchName ASC"; + $qry = $this->db->query($sql, [$user['S_RegionalID'], $user['M_BranchID'], $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getBranchTujuan"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getReceiveOrderPo() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $itemCategoryID = $prm["itemCategoryID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $search = '%' . $prm["search"] . '%'; + + $sql = "SELECT DISTINCT ReceiveOrderPoID, + ReceiveOrderPoNumber, + ReceiveOrderPoIDate, + ReceiveOrderPoWarehouseID, + ReceiveOrderPoM_BranchCode + FROM receive_order_po + JOIN t_barcode_barang ON T_BarcodeBarangReceiveOrderPoID = ReceiveOrderPoID + AND T_BarcodeBarangIsActive = 'Y' + AND T_BarcodeBarangStockID <> 0 + JOIN m_item ON T_BarcodeBarangM_ItemID = M_ItemID + AND M_ItemIsActive = 'Y' + AND M_ItemItem_CategoryID = ? + WHERE ReceiveOrderPoIsActive = 'Y' + AND ReceiveOrderPoM_BranchCode = ? + AND ReceiveOrderPoIsHandover = 'Y' + AND ReceiveOrderPoConfirmed = 'Y' + AND (ReceiveOrderPoNumber LIKE ?) + GROUP BY ReceiveOrderPoID"; + $qry = $this->db->query($sql, [$itemCategoryID, $branchAsalCode, $search]); + if (!$qry) { + $this->sys_error_db("[Error] Query getReceiveOrderPo"); + return; + } + $rows = $qry->result_array(); + $result = array( + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemReceive() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $search = '%' . $prm["search"] . '%'; + + $warhouseID = $prm["warhouseID"]; + $branchAsalCode = $prm["branchAsalCode"]; + $receiveOrderPoID = $prm["receiveOrderPoID"]; + + $totalCount = 0; + $totalPage = 0; + + $number_offset = 0; + $number_limit = 15; + if ($prm["current_page"] > 0) { + $number_offset = ($prm["current_page"] - 1) * $number_limit; + } + + $sql_branch = "SELECT M_BranchID, + M_BranchCode + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchCode = ?"; + $qry_branch = $this->db->query($sql_branch, [$branchAsalCode]); + if (!$qry_branch) { + $this->sys_error_db("[Error] Query getItem - branch"); + return; + } + $row_branch = $qry_branch->result_array()[0]; + + $sql = "SELECT + ro.ReceiveOrderPoID, + ro.ReceiveOrderPoNumber, + i.M_ItemID, + i.M_ItemCode, + i.M_ItemDesc, + iu.ItemUnitID, + iu.ItemUnitCode, + iu.ItemUnitName, + s.StockID, + s.StockQty AS stock_total, + COUNT(b.T_BarcodeBarangID) AS barcode_total, + IFNULL(l.qty_locked, 0) AS qty_locked, + (s.StockQty - IFNULL(l.qty_locked, 0)) AS qty_available, + w.WarehouseID, + 0 AS qty_mutasi + FROM t_barcode_barang b + JOIN receive_order_po ro ON b.T_BarcodeBarangReceiveOrderPoID = ro.ReceiveOrderPoID + AND ro.ReceiveOrderPoIsActive = 'Y' + AND ro.ReceiveOrderPoID = ? + JOIN stock s ON s.StockID = b.T_BarcodeBarangStockID + JOIN warehouse w ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + AND w.WarehouseM_BranchID = ? + JOIN m_item i ON i.M_ItemID = b.T_BarcodeBarangM_ItemID + JOIN itemunit iu ON b.T_BarcodeBarangItemUnitID = iu.ItemUnitID + LEFT JOIN ( + SELECT + MutasiStockLockStockID, + SUM(MutasiStockLockQtyLocked) AS qty_locked + FROM mutasi_stock_lock + WHERE MutasiStockLockIsActive = 'Y' + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockType = 'INV' + GROUP BY MutasiStockLockStockID + ) l ON l.MutasiStockLockStockID = s.StockID + WHERE + s.StockWarehouseID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND b.T_BarcodeBarangStockID <> 0 + + AND (i.M_ItemCode LIKE ? OR i.M_ItemDesc LIKE ?) + + GROUP BY + ro.ReceiveOrderPoID, + s.StockID, + i.M_ItemID + ORDER BY ro.ReceiveOrderPoID DESC"; + + $sqltotal = "SELECT COUNT(*) as total FROM ($sql) as x"; + $qrytotal = $this->db->query($sqltotal, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search]); + + if ($qrytotal) { + $totalCount = $qrytotal->result_array()[0]['total']; + $totalPage = ceil($totalCount / $number_limit); + } else { + $this->sys_error_db("[Error] Query getItem - total", $this->db); + exit; + } + + $sql_list = $sql . " LIMIT ? OFFSET ?"; + $qry = $this->db->query($sql_list, [$receiveOrderPoID, $row_branch['M_BranchID'], $warhouseID, $search, $search, $number_limit, $number_offset]); + // echo $this->db->last_query(); + // exit; + if (!$qry) { + $this->sys_error_db("[Error] Query getItem"); + return; + } + + $rows = $qry->result_array(); + + $result = array( + "total_page" => $totalPage, + "records" => $rows + ); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + $detailItems[] = [ + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'itemunit_id' => $item['ItemUnitID'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_id' => 0, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_id' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # INSERT HEADER # + $sql_header = "INSERT INTO mutasi_request( + MutasiRequestDate, + MutasiRequestNumber, + MutasiRequestItemCategoryID, + MutasiRequestFromBranchID, + MutasiRequestToBranchID, + MutasiRequestTotalValue, + MutasiRequestNote, + MutasiRequestStatus, + MutasiRequestIsActive, + MutasiRequestCreated, + MutasiRequestUserID) VALUES(?,fn_numbering('RM'),?,?,?,?,?,'Draft','Y',NOW(),?)"; + $qry_header = $this->db->query($sql_header, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'] + ]); + if (!$qry_header) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert into table mutasi request", $this->db); + exit; + } + $mrID = $this->db->insert_id(); + + # INSERT DETAIL # + foreach ($detailItems as $d) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $mrID, + $d['receive_order_po_id'], + $d['receive_order_po_number'], + $d['stock_id'], + $d['item_id'], + $d['itemunit_id'], + $d['qty'], + $d['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("['Error'] insert into table mutasi request detail", $this->db); + exit; + } + + // ambil detail_id + $detail_id = $this->db->insert_id(); + + + # VALIDASI STOCK # + if ($d['lock_type'] === 'INV') { + + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$d['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $d['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($d['lock_type'] === 'AST') { + if (empty($d['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + // INSERT STOCK LOCK + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $mrID, + $detail_id, + $d['item_id'], + $d['stock_id'], + $d['barcode_id'], + $prm['branch_asal_id'], + $d['warehouse_id'], + $d['qty'], + $d['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert table stock lock", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("Request mutasi created successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getItemMutasiUpdate() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $prm = $this->sys_input; + $mutasiRequestID = $prm['mutasiRequestID']; + + $sql = "SELECT + MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID AS ReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber AS ReceiveOrderPoNumber, + M_ItemID, + M_ItemCode, + M_ItemDesc, + ItemUnitID, + ItemUnitCode, + ItemUnitName, + w.WarehouseID, + s.StockID, + s.StockQty AS stock_total, + IFNULL(bc.barcode_total, 0) AS barcode_total, + COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_locked, + IFNULL(bc.barcode_total, 0) - COUNT(DISTINCT lk.MutasiStockLockT_BarcodeBarangID) AS qty_available, + MutasiRequestDetailQty AS qty_mutasi + FROM mutasi_request_detail + JOIN mutasi_request + ON MutasiRequestDetailMutasiRequestID = MutasiRequestID + JOIN m_item + ON MutasiRequestDetailM_ItemID = M_ItemID + JOIN itemunit + ON MutasiRequestDetailItemUnitID = ItemUnitID + JOIN stock s + ON MutasiRequestDetailStockID = s.StockID + JOIN warehouse w + ON s.StockWarehouseID = w.WarehouseID + AND w.WarehouseIsActive = 'Y' + -- total barcode per stock + PO + LEFT JOIN ( + SELECT + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID, + COUNT(*) AS barcode_total + FROM t_barcode_barang b + WHERE b.T_BarcodeBarangIsActive = 'Y' + GROUP BY + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + ) bc + ON bc.T_BarcodeBarangStockID = s.StockID + AND bc.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + -- barcode yang sedang di-lock + LEFT JOIN ( + SELECT + l.MutasiStockLockT_BarcodeBarangID, + b.T_BarcodeBarangStockID, + b.T_BarcodeBarangReceiveOrderPoID + FROM mutasi_stock_lock l + JOIN t_barcode_barang b + ON b.T_BarcodeBarangID = l.MutasiStockLockT_BarcodeBarangID + WHERE + l.MutasiStockLockIsActive = 'Y' + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockType = 'INV' + ) lk + ON lk.T_BarcodeBarangStockID = s.StockID + AND lk.T_BarcodeBarangReceiveOrderPoID = MutasiRequestDetailReceiveOrderPoID + WHERE + MutasiRequestDetailIsActive = 'Y' + AND MutasiRequestDetailMutasiRequestID = ? + GROUP BY + MutasiRequestDetailID, + s.StockID, + bc.barcode_total + ORDER BY + MutasiRequestDetailID"; + $qry = $this->db->query($sql, [$mutasiRequestID]); + if (!$qry) { + $this->sys_error_db("[Error] get item update", $this->db); + exit; + } + + $data = $qry->result_array(); + + $result = array( + "records" => $data + ); + + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function saveEditMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # VALIDASI HEADER # + if (intval($prm["branch_asal_id"]) == intval($prm["branch_tujuan_id"])) { + $this->sys_error("Branch Asal dan Branch Tujuan tidak boleh sama"); + exit; + } + if (count($prm["list_mutasi"]) == 0) { + $this->sys_error("Tidak ada item untuk dimutasi"); + exit; + } + + # CEK JENIS # + $isInventaris = (intval($prm["category_id"]) === 2); + $isAsset = (intval($prm["category_id"]) === 3); + + if ($isAsset && count($prm["list_mutasi"]) > 1) { + $this->sys_error("Mutasi asset hanya boleh 1 item"); + exit; + } + + # HITUNG NILAI # + $totalValue = 0; + foreach ($prm["list_mutasi"] as $item) { + if ($isInventaris) { + if (intval($item['qty_mutasi']) <= 0 || intval($item['qty_mutasi']) > intval($item['qty_available'])) { + $this->sys_error('QTY mutasi melebihi item yang tersedia'); + exit; + } + + $detailItems[] = [ + 'MutasiRequestDetailID' => $item['MutasiRequestDetailID'], + 'MutasiRequestID' => $item['MutasiRequestDetailMutasiRequestID'], + 'receive_order_po_id' => $item['ReceiveOrderPoID'], + 'receive_order_po_number' => $item['ReceiveOrderPoNumber'], + 'item_id' => $item['M_ItemID'], + 'itemunit_id' => $item['ItemUnitID'], + 'stock_id' => $item['StockID'], + 'warehouse_id' => $item['WarehouseID'], + 'barcode_id' => 0, + 'qty' => $item['qty_mutasi'], + 'book_value' => 1, + 'lock_type' => 'INV' + ]; + + $totalValue = 1; + } else { + // ASSET + if (intval($item['qty_mutasi']) != 1) { + $this->sys_error("Qty asset harus 1"); + exit; + } + + // $asset = getAssetByItemID($item['M_ItemID']); + // $itemBookValue = $asset->BookValue; + // $totalValue = $itemBookValue; + + // $detailItems[] = [ + // 'item_id' => $item['M_ItemID'], + // 'itemunit_id' => $item['ItemUnitID'], + // 'stock_id' => $item['StockID'], + // 'warehouse_id' => $item['WarehouseID'], + // 'barcode_id' => $item['T_BarcodeBarangID'], + // 'qty' => 1, + // 'book_value' => 1, // nanti diganti nilai buku + // 'lock_type' => 'AST' + // ]; + + // $totalValue = 1; // atau nilai buku asset + + } + } + + # UPDATE MUTASI # + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestDate = ?, + MutasiRequestItemCategoryID = ?, + MutasiRequestFromBranchID = ?, + MutasiRequestToBranchID = ?, + MutasiRequestTotalValue = ?, + MutasiRequestNote = ?, + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $prm['mutasi_date'], + $prm['category_id'], + $prm['branch_asal_id'], + $prm['branch_tujuan_id'], + $totalValue, + $prm['note'], + $user['M_UserID'], + $prm['mutasi_request_id'] + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request", $this->db); + exit; + } + + # check jika detail sudah ada # + $sql_check_detail = "SELECT MutasiRequestDetailID, + MutasiRequestDetailMutasiRequestID + FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? + AND MutasiRequestDetailIsActive = 'Y'"; + $qry_check_detail = $this->db->query($sql_check_detail, [$prm['mutasi_request_id']]); + if (!$qry_check_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get list check detail mutasi", $this->db); + exit; + } + $list_detail_check = $qry_check_detail->result_array(); + $array_detailID = array_column($list_detail_check, 'MutasiRequestDetailID'); + $input_detail = array_column($detailItems, 'MutasiRequestDetailID'); + + $update_detail = []; + $insert_detail = []; + $delete_detail = []; + + foreach ($detailItems as $key => $value) { + if (empty($value['MutasiRequestDetailID'])) { + $insert_detail[] = $value; + continue; + } + if (in_array($value['MutasiRequestDetailID'], $array_detailID)) { + $update_detail[] = $value; + } + } + + foreach ($list_detail_check as $key => $value) { + if (!in_array($value['MutasiRequestDetailID'], $input_detail)) { + $delete_detail[] = $value; + } + } + + # UPDATE MUTASI DETAIL # + foreach ($update_detail as $k => $v) { + $sql_update_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailMutasiRequestID = ?, + MutasiRequestDetailReceiveOrderPoID = ?, + MutasiRequestDetailReceiveOrderPoNumber = ?, + MutasiRequestDetailStockID = ?, + MutasiRequestDetailM_ItemID = ?, + MutasiRequestDetailItemUnitID = ?, + MutasiRequestDetailQty = ?, + MutasiRequestDetailBookValue = ?, + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID = ?"; + $qry_update_detail = $this->db->query($sql_update_detail, [ + $v['MutasiRequestID'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'], + $v['MutasiRequestDetailID'] + ]); + if (!$qry_update_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi request detail", $this->db); + exit; + } + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + # update stock lock + $sql_update_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockMutasiRequestID = ?, + MutasiStockLockMutasiRequestDetailID = ?, + MutasiStockLockM_ItemID = ?, + MutasiStockLockStockID = ?, + MutasiStockLockT_BarcodeBarangID = ?, + MutasiStockLockM_BranchID = ?, + MutasiStockLockWarehouseID = ?, + MutasiStockLockQtyLocked = ?, + MutasiStockLockType = ?, + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $qry_update_stock_lock = $this->db->query($sql_update_stock_lock, [ + $prm['mutasi_request_id'], + $v['MutasiRequestDetailID'], + $v['item_id'], + $v['stock_id'], + $v['barcode_id'], + $prm['branch_asal_id'], + $v['warehouse_id'], + $v['qty'], + $v['lock_type'], + $user['M_UserID'], + $v['MutasiRequestDetailID'] + ]); + if (!$qry_update_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + # INSERT MUTASI DETAIL BARU # + foreach ($insert_detail as $k => $v) { + $sql_detail = "INSERT INTO mutasi_request_detail( + MutasiRequestDetailMutasiRequestID, + MutasiRequestDetailReceiveOrderPoID, + MutasiRequestDetailReceiveOrderPoNumber, + MutasiRequestDetailStockID, + MutasiRequestDetailM_ItemID, + MutasiRequestDetailItemUnitID, + MutasiRequestDetailQty, + MutasiRequestDetailBookValue, + MutasiRequestDetailIsActive, + MutasiRequestDetailCreated, + MutasiRequestDetailUserID + ) VALUES(?,?,?,?,?,?,?,?,'Y',NOW(),?)"; + $qry_detail = $this->db->query($sql_detail, [ + $prm['mutasi_request_id'], + $v['receive_order_po_id'], + $v['receive_order_po_number'], + $v['stock_id'], + $v['item_id'], + $v['itemunit_id'], + $v['qty'], + $v['book_value'], + $user['M_UserID'] + ]); + if (!$qry_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] Re-insert table mutasi request detail", $this->db); + exit; + } + + $detail_id = $this->db->insert_id(); + + # cek qty tersedia (inventaris) + if ($v['lock_type'] === 'INV') { + + $sqlCheck = "SELECT COUNT(*) AS qty_available + FROM t_barcode_barang b + LEFT JOIN mutasi_stock_lock l + ON l.MutasiStockLockT_BarcodeBarangID = b.T_BarcodeBarangID + AND l.MutasiStockLockStatus = 'ACTIVE' + AND l.MutasiStockLockIsActive = 'Y' + WHERE + b.T_BarcodeBarangReceiveOrderPoID = ? + AND b.T_BarcodeBarangIsActive = 'Y' + AND l.MutasiStockLockID IS NULL + FOR UPDATE"; + + $row = $this->db->query($sqlCheck, [$v['receive_order_po_id']])->row(); + + if (!$row || $row->qty_available < $v['qty']) { + $this->db->trans_rollback(); + $this->sys_error("Stock tidak mencukupi (sudah di-lock)"); + exit; + } + } else if ($v['lock_type'] === 'AST') { + if (empty($v['barcode_id'])) { + $this->db->trans_rollback(); + $this->sys_error("Asset wajib memiliki barcode"); + exit; + } + } + + // INSERT LOCK + $sqlLock = "INSERT INTO mutasi_stock_lock( + MutasiStockLockMutasiRequestID, + MutasiStockLockMutasiRequestDetailID, + MutasiStockLockM_ItemID, + MutasiStockLockStockID, + MutasiStockLockT_BarcodeBarangID, + MutasiStockLockM_BranchID, + MutasiStockLockWarehouseID, + MutasiStockLockQtyLocked, + MutasiStockLockType, + MutasiStockLockStatus, + MutasiStockLockIsActive, + MutasiStockLockCreated, + MutasiStockLockUserID + ) VALUES(?,?,?,?,?,?,?,?,?,'ACTIVE','Y',NOW(),?)"; + + $qryLock = $this->db->query($sqlLock, [ + $prm['mutasi_request_id'], + $detail_id, + $v['item_id'], + $v['stock_id'], + $v['barcode_id'], + $prm['branch_asal_id'], + $v['warehouse_id'], + $v['qty'], + $v['lock_type'], + $user['M_UserID'] + ]); + if (!$qryLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] edit mutasi, insert table stock lock", $this->db); + exit; + } + } + + # DELETE MUTASI DETAIL # + if (count($delete_detail) > 0) { + $delete_id = array_column($delete_detail, 'MutasiRequestDetailID'); + $placeholders = implode(', ', array_fill(0, count($delete_id), '?')); + + $delete_param = array_merge(array($user['M_UserID']), $delete_id); + $sql_delete_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailID IN ($placeholders)"; + $qry_delete_detail = $this->db->query($sql_delete_detail, $delete_param); + if (!$qry_delete_detail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] delete mutasi request detail", $this->db); + exit; + } + + # delete mutasi stock lock + $sql_update_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestDetailID = ?"; + $qry_update_stock_lock = $this->db->query($sql_update_stock_lock, $delete_param); + if (!$qry_update_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update mutasi stock lock", $this->db); + exit; + } + } + + $this->db->trans_commit(); + $this->sys_ok("Update mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function deleteMutasi() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mutasiRequestID = $prm['mutasiRequestID']; + + $sql_mutasi = "UPDATE mutasi_request SET + MutasiRequestIsActive = 'N', + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry_mutasi = $this->db->query($sql_mutasi, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi request', $this->db); + exit; + } + + $sql_mutasi_detail = "UPDATE mutasi_request_detail SET + MutasiRequestDetailIsActive = 'N', + MutasiRequestDetailLastUpdated = NOW(), + MutasiRequestDetailUserID = ? + WHERE MutasiRequestDetailMutasiRequestID = ?"; + $qry_mutasi_detail = $this->db->query($sql_mutasi_detail, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_mutasi_detail) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] delete mutasi detail', $this->db); + exit; + } + + $sql_stock_lock = "UPDATE mutasi_stock_lock SET + MutasiStockLockIsActive = 'N', + MutasiStockLockLastUpdated = NOW(), + MutasiStockLockUserID = ? + WHERE MutasiStockLockMutasiRequestID = ?"; + $qry_stock_lock = $this->db->query($sql_stock_lock, [ + $user['M_UserID'], + $mutasiRequestID + ]); + if (!$qry_stock_lock) { + $this->db->trans_rollback(); + $this->sys_error_db('[Error] mutasi stock lock', $this->db); + exit; + } + + $this->db->trans_commit(); + $this->sys_ok("Delete Request mutasi successfully"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + // Approved + // ------------------------------ + function getApproveLevel() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $userId = $this->sys_user["M_UserID"]; + + $sqlevel = "SELECT M_UserM_ApproveLevelID FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ? "; + $qulevel = $this->db->query($sqlevel, [$userId]); + if (!$qulevel) { + $this->sys_error_db("[Error] get approval level user"); + exit; + } + $data = $qulevel->row_array(); + + $this->sys_ok($data); + } + + function approveMutasiRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + # get data before + $dataMrBefore = $this->getDataMutasiRequest($prm['mutasiRequestID']); + + if (intval($prm['approvelevel'] == 1)) { + $sql = "UPDATE mutasi_request SET + MutasiRequestStatus = 'Verified', + MutasiRequestIsVerif = 'Y', + MutasiRequestVerifUserID = ?, + MutasiRequestVerifDate = NOW(), + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$user['M_UserID'], $user['M_UserID'], $prm['mutasiRequestID']]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] verif by manager", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($prm['mutasiRequestID']); + $this->insertLogMutasiRequest($prm['mutasiRequestID'], 'VERIFIED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Verified data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Verified data mutasi request by user ID : {$user['M_UserID']}", 'VERIFIED', $prm['mutasiRequestID'], $user['M_UserID']); + + + $this->db->trans_commit(); + $this->sys_ok("Success Verified by manager"); + } else if (intval($prm['approvelevel'] == 2)) { + $sql = "UPDATE mutasi_request SET + MutasiRequestStatus = 'Approved', + MutasiRequestIsApproved = 'Y', + MutasiRequestApprovedUserID = ?, + MutasiRequestApprovedDate = NOW(), + MutasiRequestLastUpdated = NOW(), + MutasiRequestUserID = ? + WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$user['M_UserID'], $user['M_UserID'], $prm['mutasiRequestID']]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] approve by kacab", $this->db); + exit; + } + $dataMrAfter = $this->getDataMutasiRequest($prm['mutasiRequestID']); + $this->insertLogMutasiRequest($prm['mutasiRequestID'], 'APPROVED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Approved data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Approved data mutasi request by user ID : {$user['M_UserID']}", 'APPROVED', $prm['mutasiRequestID'], $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Success Approved by kacab"); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function rejectMutasiRequest() + { + try { + if (!$this->isLogin) { + $this->sys_error("invalid token"); + exit; + } + + $this->db->trans_begin(); + $prm = $this->sys_input; + $user = $this->sys_user; + + $mrID = intval($prm["mutasiRequestID"]); + $note = $prm["reject_note"]; + + # get data before + $dataMrBefore = $this->getDataMutasiRequest($mrID); + + # cek mutasi + $mutasi = $this->db->query("SELECT MutasiRequestStatus + FROM mutasi_request + WHERE MutasiRequestID = ? + AND MutasiRequestIsActive = 'Y' + FOR UPDATE + ", [$mrID])->row(); + + if (!$mutasi) { + $this->db->trans_rollback(); + $this->sys_error("Data mutasi tidak ditemukan", $this->db); + exit; + } + + # validasi boleh reject atau tidak + if (!in_array($mutasi->MutasiRequestStatus, ['Draft', 'Verified', 'Approved'])) { + $this->db->trans_rollback(); + $this->sys_error("Mutasi tidak dapat direject pada status ini"); + exit; + } + + #get username + $getUser = $this->db->query("SELECT M_UserID, + M_UserUsername + FROM m_user + WHERE M_UserIsActive = 'Y' + AND M_UserID = ?", [$user['M_UserID']])->row_array(); + if (!$getUser) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get username", $this->db); + exit; + } + + # update status mutasi to rejected + $updMutasi = $this->db->query("UPDATE mutasi_request + SET + MutasiRequestStatus = 'Rejected', + MutasiRequestNote = CONCAT_WS( + '\n', + NULLIF(MutasiRequestNote, ''), + CONCAT('[REJECT] ', ?, ' by user ', ?) + ), + MutasiRequestLastUpdated = NOW() + WHERE MutasiRequestID = ? + ", [$note, $getUser['M_UserUsername'], $mrID]); + + if (!$updMutasi) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] update status mutasi", $this->db); + exit; + } + + # Release stock lock active + $updLock = $this->db->query("UPDATE mutasi_stock_lock + SET + MutasiStockLockStatus = 'RELEASED', + MutasiStockLockLastUpdated = NOW() + WHERE MutasiStockLockMutasiRequestID = ? + AND MutasiStockLockStatus = 'ACTIVE' + AND MutasiStockLockIsActive = 'Y' + ", [$mrID]); + + if (!$updLock) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] release stock lock", $this->db); + exit; + } + + $dataMrAfter = $this->getDataMutasiRequest($mrID); + $this->insertLogMutasiRequest($mrID, 'REJECTED', $dataMrBefore, $dataMrAfter, $user['M_UserID'], "Rejected data mutasi request by user ID : {$user['M_UserID']}"); + $this->insertUserActivity('MR', "Rejected data mutasi request by user ID : {$user['M_UserID']}", 'REJECTED', $mrID, $user['M_UserID']); + + $this->db->trans_commit(); + $this->sys_ok("Mutasi berhasil direject"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + private function getDataMutasiRequest($id) + { + $sql = "SELECT * FROM mutasi_request WHERE MutasiRequestID = ?"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request", $this->db); + exit; + } + $header = $qry->row_array(); + + $sqldetail = "SELECT * FROM mutasi_request_detail + WHERE MutasiRequestDetailMutasiRequestID = ? AND MutasiRequestDetailIsActive = 'Y'"; + $qrydetail = $this->db->query($sqldetail, [$id]); + if (!$qrydetail) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] get mutasi request detail", $this->db); + exit; + } + $detail = $qrydetail->result_array(); + $header['details'] = $detail; + return $header; + } + + // + private function insertUserActivity( + $code, + $user_desc = '', + $status, + $reff_id, + $userId + ) { + $sql_log = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityUserID, + UserActivityCreated + ) VALUES(?,?,?,?,?,NOW())"; + $qry_log = $this->db->query($sql_log, [ + $code, + $status, + $user_desc, + $reff_id, + $userId + ]); + if (!$qry_log) { + $this->db->trans_rollback(); + $this->sys_error_db("insert log", $this->db); + exit; + } + } + + private function insertLogMutasiRequest( + $id, + $type, + $dataBefore, + $dataAfter, + $userID, + $desc = '' + ) { + $sql = "INSERT INTO acc_one_log.mutasi_request_log( + MutasiRequestLogMutasiRequestID, + MutasiRequestLogType, + MutasiRequestLogDesc, + MutasiRequestLogJsonBefore, + MutasiRequestLogJsonAfter, + MutasiRequestLogUserID, + MutasiRequestLogCreated + ) VALUES(?,?,?,?,?,?,NOW())"; + $qry = $this->db->query($sql, [ + $id, + $type, + $desc, + !empty($dataBefore) ? json_encode($dataBefore) : '', + !empty($dataAfter) ? json_encode($dataAfter) : '', + $userID + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("[Error] insert log mutasi request", $this->db); + exit; + } + } +} diff --git a/application/controllers/mockup/nonpersediaanapproved/Nonpersediaanapproved.php b/application/controllers/mockup/nonpersediaanapproved/Nonpersediaanapproved.php new file mode 100644 index 0000000..5766855 --- /dev/null +++ b/application/controllers/mockup/nonpersediaanapproved/Nonpersediaanapproved.php @@ -0,0 +1,715 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + + public function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $startDate = $prm['startDate']; + $endDate = $prm['endDate']; + $status = $prm['status']; + $page = $prm['page']; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $approveLevelID = $user['M_UserM_ApproveLevelID']; + $flag = $prm['flag']; + + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + $sqlStatus = ''; + if ($status != 'All') { + $sqlStatus = "AND PurchaseRequestStatus = '{$status}'"; + } + $number_limit = 20; + $number_offset = 0; + if ($prm['page'] > 0) { + $number_offset = ($prm['page'] - 1) * $number_limit; + } + + if ($approveLevelID == '1') { + if ($flag == 'G') { + $sqlStockRequest = " AND (PurchaseRequestVerifiedBy = 0 OR PurchaseRequestVerifiedBy IS NULL) "; + } + } else if ($approveLevelID == '2') { + if ($flag == 'G') { + $sqlStockRequest = " AND PurchaseRequestApprovedBy IS NULL"; + } + } + + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?;"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } + + $totalStart = $approvalLevel[0]['M_ApproveLevelStartTotal']; + $totalEnd = $approvalLevel[0]['M_ApproveLevelEndTotal']; + + $sql = "SELECT + COUNT(PurchaseRequestID) total + FROM purchase_request + JOIN s_regional + ON PurchaseRequestS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + JOIN item_category + ON PurchaseRequestItemCategoryID = ItemCategoryID + AND ItemCategoryIsActive = 'Y' + JOIN m_user b + ON PurchaseRequestRequestedBy = b.M_UserID + AND b.M_UserIsActive = 'Y' + AND S_RegionalIsActive = 'Y' + LEFT JOIN m_user a + ON PurchaseRequestApprovedBy = a.M_UserID + AND a.M_UserIsActive = 'Y' + LEFT JOIN + m_branch + ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' AND PurchaseRequestItemCategoryID <> 1 + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + AND (PurchaseRequestDate BETWEEN ? AND ?) AND PurchaseRequestS_RegionalID = ? + $sqlBranch + $sqlStatus + $sqlStockRequest + -- AND PurchaseRequestTotal BETWEEN $totalStart AND $totalEnd + "; + $qry = $this->db->query($sql, [$search, $search, $search, $startDate, $endDate, $regionalID]); + if (!$qry) { + $this->sys_error_db("Error searching"); + exit; + } + $total = $qry->row_array()['total']; + $tot_page = ceil($total / $number_limit); + $params = [$search, $search, $search, $startDate, $endDate, $regionalID]; + + $params[] = $number_limit; + $params[] = $number_offset; + $sql = "SELECT + PurchaseRequestID prID, + DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') prDate, + PurchaseRequestNumber prNumber, + PurchaseRequestRefNumber prRefNumber, + PurchaseRequestNote prNote, + PurchaseRequestTotal prTotal, + PurchaseRequestItemCategoryID prItemType, + ItemCategoryName prItemTypeName, + PurchaseRequestStatus prStatus, + IFNULL(PurchaseRequestVerifiedBy, 0) AS PurchaseRequestVerifiedBy, + PurchaseRequestVerifiedDate, + DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') prApprovedDate, + a.M_userUserName prApprovedBy, + b.M_UserID prRequestedByID, + b.M_userUserName prRequestedBy, + b.M_UserM_BranchID prRequestedByFromBranch, + S_RegionalName prRegionalName, + M_BranchName prBranchName, + IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') prItemName + FROM purchase_request + JOIN s_regional + ON PurchaseRequestS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + JOIN item_category + ON PurchaseRequestItemCategoryID = ItemCategoryID + AND ItemCategoryIsActive = 'Y' + JOIN m_user b + ON PurchaseRequestRequestedBy = b.M_UserID + AND b.M_UserIsActive = 'Y' + LEFT JOIN m_user a + ON PurchaseRequestApprovedBy = a.M_UserID + AND a.M_UserIsActive = 'Y' + LEFT JOIN + m_branch + ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' AND PurchaseRequestItemCategoryID <> 1 + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + AND (PurchaseRequestDate BETWEEN ? AND ?) AND PurchaseRequestS_RegionalID = ? + $sqlBranch + $sqlStatus + $sqlStockRequest + -- AND PurchaseRequestTotal BETWEEN $totalStart AND $totalEnd --PurchaseRequestTotal masih selalu 0, belum disimpan + LIMIT ? OFFSET ? + "; + $qry = $this->db->query($sql, $params); + if (!$qry) { + $this->sys_error_db("Error searching"); + exit; + } + // echo $this->db->last_query(); + // exit; + $data = $qry->result_array(); + + $result = array( + 'total' => $tot_page, + 'records' => $data, + // "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + function getlevel() + { + try { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + } + + $payload = $this->sys_input; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } else { + $result = array( + "total" => 1, + "records" => $approvalLevel, + "sql" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function insert_act_log($code, $status, $description, $refId, $data, $userId) + { + $sql = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated) + VALUES (?,?,?,?,?,?,?)"; + $query = $this->db->query($sql, [$code, $status, $description, $refId, $data, $userId, date("Y-m-d H:i:s")]); + if (!$query) { + $this->sys_error_db("user activity", $this->db); + exit; + } + } + function getDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + + $sql = "SELECT + PurchaseRequestDetailID prDetailID, + PurchaseRequestDetailPurchaseRequestID prDetailPrID, + PurchaseRequestDetailM_ItemID prDetailItemID, + M_ItemDesc prDetailItemName, + M_ItemCode prDetailItemCode, + PurchaseRequestDetailQty prDetailItemQty, + PurchaseRequestDetailPrice prDetailItemPrice + FROM purchase_request_detail + JOIN m_item + ON PurchaseRequestDetailM_ItemID = M_ItemID + WHERE PurchaseRequestDetailPurchaseRequestID = ? + AND PurchaseRequestDetailIsActive = 'Y';"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get detail"); + + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + function approve() + { + $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']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + $pr = $prm['pr']; + $total = $prm['total']; + $type = $prm['type']; + + // get user level approval + $sqlevel = "SELECT M_UserM_ApproveLevelID FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ?"; + $qulevel = $this->db->query($sqlevel, [$userid]); + if (!$qulevel) { + $this->sys_error_db("[Error] get approval level user"); + exit; + } + $userlevel = $qulevel->row_array()['M_UserM_ApproveLevelID']; + + $datas_log = array(); + $sql = "SELECT * FROM purchase_request WHERE PurchaseRequestID = ? AND PurchaseRequestIsActive = 'Y'"; + $query = $this->db->query($sql, [$pr['prID']]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("purchase request select", $this->db); + exit; + } + $header = $query->row_array(); + + + $datas_log['header'] = $header; + $sql = "SELECT * + FROM purchase_request_detail + JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUnitID = PurchaseRequestDetailItemUnitID AND ItemUnitIsActive = 'Y' + WHERE PurchaseRequestDetailPurchaseRequestID = ? AND PurchaseRequestDetailIsActive = 'Y'"; + $query = $this->db->query($sql, [$pr['prID']]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("purchase request detail select", $this->db); + exit; + } + $details = $query->result_array(); + $datas_log['details'] = $details; + + if ($type == 'A') { + // verifikasi jika manager + if ($userlevel == '1') { + $sql = "UPDATE purchase_request SET + PurchaseRequestVerifiedBy = ?, + PurchaseRequestVerifiedDate = NOW() + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, [$userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error verifikasi manager"); + $this->db->trans_rollback(); + exit; + } + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah diverifikasi"; + $this->insert_act_log("PRNP", "Verified", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + + if ($userlevel == '2') { + // -- PurchaseRequestTotal = ?, + $sql = "UPDATE purchase_request + SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NOW(), + PurchaseRequestApprovedBy = ? + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Approved', $userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ? + AND PurchaseRequestDetailStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Approved', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di approved"; + $this->insert_act_log("PRNP", "Approved", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + } else if ($type == 'R') { + $sql = "UPDATE purchase_request + SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NOW(), + PurchaseRequestApprovedBy = ? + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Rejected', $userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ? + AND PurchaseRequestDetailStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Rejected', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di reject"; + $this->insert_act_log("PRNP", "Rejected", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } else if ($type == 'U') { + + // un approve kacab/reg + if ($userlevel == '2') { + // -- PurchaseRequestTotal = ?, + $sql = "UPDATE purchase_request + SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NULL, + PurchaseRequestApprovedBy = NULL + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Approved'"; + $qry = $this->db->query($sql, ['Pending', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ? + AND PurchaseRequestDetailStatus = 'Approved'"; + $qry = $this->db->query($sql, ['Pending', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di unapproved"; + $this->insert_act_log("PRNP", "Unapproved", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + } + + // update notification + $this->readNotif($type, $userlevel, $userid, $pr['prID']); + + $this->db->trans_commit(); + + $this->sys_ok('Berhasil'); + } + + // read notification + function readNotif($type, $userlevel, $userId, $refID) + { + + $this->db->trans_begin(); + + // cari user penerima notifikasi + if ($type == "U") { + $sql_get = "SELECT PurchaseRequestID, + M_UserID, + M_UserUsername, + NotificationID, + NotificationDetailID, + NotificationDetailStatus, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID + FROM notification + JOIN purchase_request ON NotificationRefID = PurchaseRequestID + AND PurchaseRequestIsActive = 'Y' + JOIN notification_detail ON NotificationID = NotificationDetailNotificationID + JOIN m_user ON NotificationUserID = M_UserID + WHERE PurchaseRequestID = ? + AND NotificationDetailStatus = 'read'"; + $qry = $this->db->query($sql_get, [$refID]); + if (!$qry) { + $this->sys_error_db("select user notification error", $this->db); + exit; + } + $rowsuser = $qry->result_array(); + } else { + $sql_get = "SELECT PurchaseRequestID, + M_UserID, + M_UserUsername, + NotificationID, + NotificationDetailID, + NotificationDetailStatus, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID + FROM notification + JOIN purchase_request ON NotificationRefID = PurchaseRequestID + AND PurchaseRequestIsActive = 'Y' + JOIN notification_detail ON NotificationID = NotificationDetailNotificationID + JOIN m_user ON NotificationUserID = M_UserID + WHERE PurchaseRequestID = ? + AND NotificationDetailStatus = 'unread'"; + $qry = $this->db->query($sql_get, [$refID]); + if (!$qry) { + $this->sys_error_db("select user notification error", $this->db); + exit; + } + $rowsuser = $qry->result_array(); + } + + + foreach ($rowsuser as $user) { + + if ($type == "A") { + if ($userlevel === '1') { + // verifikasi manager + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } else if ($userlevel === '2') { + // approve kepala cabang / regional + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } + } else if ($type == "R") { + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } else if ($type == "U") { + if ($userlevel === '2') { + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'unread', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } + } + } + + $this->db->trans_commit(); + } + + function updateqty() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + + $arrItems = $prm["arrItems"]; + + if (count($arrItems) > 0) { + foreach ($arrItems as $key => $value) { + $sql = "UPDATE purchase_request_detail SET + PurchaseRequestDetailQty = ?, + PurchaseRequestDetailLastUpdated = NOW(), + PurchaseRequestDetailLastUpdatedUserID = ? + WHERE PurchaseRequestDetailID = ?"; + $qry = $this->db->query($sql, [ + $value['prDetailItemQty'], + $userId, + $value['prDetailID'] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update qty", $this->db); + exit; + } + } + } + + $this->db->trans_commit(); + $this->sys_ok("Berhasil update qty"); + } + + private function safeJsonEncode($data) + { + // Coba encode data ke JSON + $jsonData = json_encode($data); + + // Cek apakah terjadi error saat encode + if (json_last_error() !== JSON_ERROR_NONE) { + $errorMsg = json_last_error_msg(); + error_log("JSON encode error: " . $errorMsg); + + // Lakukan sanitasi dan perbaikan data + $fixedData = $this->fixJsonEncodeIssues($data, $errorMsg); + + // Coba encode lagi setelah diperbaiki + $jsonData = json_encode($fixedData); + + // Jika masih error, log dan kembalikan objek kosong + if (json_last_error() !== JSON_ERROR_NONE) { + error_log("Failed to fix JSON encode issues: " . json_last_error_msg()); + // Kembalikan objek kosong jika masih gagal + return '{}'; + } + } + + return $jsonData; + } + + // Fungsi untuk memperbaiki masalah encoding JSON + private function fixJsonEncodeIssues($data, $errorMsg) + { + // Buat salinan data untuk dimodifikasi + $fixedData = $data; + + // Tangani berbagai jenis error + if (strpos($errorMsg, 'Malformed UTF-8') !== false) { + // Perbaiki masalah karakter UTF-8 + $fixedData = $this->fixUTF8Issues($fixedData); + } else if (strpos($errorMsg, 'Inf and NaN cannot be JSON encoded') !== false) { + // Perbaiki masalah nilai Infinity atau NaN + $fixedData = $this->fixInfNanIssues($fixedData); + } else { + // Konversi semua nilai numerik menjadi string untuk menghindari masalah presisi + $fixedData = $this->convertNumericValuesToStrings($fixedData); + + // Perbaiki masalah referensi recursif + $fixedData = $this->fixRecursiveReferences($fixedData); + } + + return $fixedData; + } + + // Perbaiki masalah karakter UTF-8 + private function fixUTF8Issues($data) + { + if (is_string($data)) { + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } else if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = $this->fixUTF8Issues($value); + } + } + return $data; + } + + // Perbaiki masalah nilai Infinity atau NaN + private function fixInfNanIssues($data) + { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_float($value) && (is_nan($value) || is_infinite($value))) { + $data[$key] = (string)$value; // Konversi ke string + } else if (is_array($value)) { + $data[$key] = $this->fixInfNanIssues($value); + } + } + } + return $data; + } + + // Perbaiki masalah referensi recursif + private function fixRecursiveReferences($data, $depth = 0) + { + // Batasi kedalaman rekursi untuk menghindari infinite loop + if ($depth > 50) { + return "[MAX_DEPTH_REACHED]"; + } + + if (is_array($data)) { + $result = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $result[$key] = $this->fixRecursiveReferences($value, $depth + 1); + } else { + $result[$key] = $value; + } + } + return $result; + } + + return $data; + } + + // Cari dan konversi numerik ke string secara rekursif + private function convertNumericValuesToStrings($data) + { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->convertNumericValuesToStrings($value); + } else if (is_numeric($value)) { + $data[$key] = (string)$value; + } else if (is_bool($value)) { + $data[$key] = $value ? "true" : "false"; + } + } + } + return $data; + } +} diff --git a/application/controllers/mockup/purchaserequestkacab/Purchaserequestkacab.php b/application/controllers/mockup/purchaserequestkacab/Purchaserequestkacab.php new file mode 100644 index 0000000..c83d095 --- /dev/null +++ b/application/controllers/mockup/purchaserequestkacab/Purchaserequestkacab.php @@ -0,0 +1,701 @@ +db->query("select database() as current_db")->result(); + // print_r($cek); + } + public function __construct() + { + parent::__construct(); + } + + public function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = '%' . $prm['search'] . '%'; + + $startDate = $prm['startDate']; + $endDate = $prm['endDate']; + $status = $prm['status']; + $page = $prm['page']; + $flag = $prm['flag']; + $user = $this->sys_user; + $regionalID = $user['S_RegionalID']; + $branchCode = $user['M_BranchCode']; + $loginType = $user['M_UserLocationFlag']; + $userID = $user['M_UserID']; + $approveLevelID = $user['M_UserM_ApproveLevelID']; + + $sqlBranch = ''; + if ($loginType == 'B' || $loginType == 'RB') { + $sqlBranch = "AND PurchaseRequestM_BranchCode = '{$branchCode}'"; + } + $sqlStatus = ''; + if ($status != 'All') { + $sqlStatus = "AND PurchaseRequestStatus = '{$status}'"; + } + $number_limit = 20; + $number_offset = 0; + if ($page > 0) { + $number_offset = ($prm['page'] - 1) * $number_limit; + } + + if ($approveLevelID == '1') { + if ($flag == 'G') { + $sqlStockRequest = " AND (PurchaseRequestVerifiedBy = 0 OR PurchaseRequestVerifiedBy IS NULL) "; + } + } else if ($approveLevelID == '2') { + if ($flag == 'G') { + $sqlStockRequest = " AND PurchaseRequestApprovedBy IS NULL"; + } + } + + + $sql = "SELECT m_approve_level.* FROM m_user + JOIN m_approve_level + ON M_UserM_ApproveLevelID = M_ApproveLevelID + WHERE M_UserID = ?;"; + $qry = $this->db->query($sql, [$userID]); + if (!$qry) { + $this->sys_error_db("Error cek approval level"); + exit; + } + $approvalLevel = $qry->result_array(); + if (count($approvalLevel) == 0) { + $result = array( + 'total' => 0, + 'records' => [] + ); + $this->sys_ok($result); + exit; + } + + $totalStart = $approvalLevel[0]['M_ApproveLevelStartTotal']; + $totalEnd = $approvalLevel[0]['M_ApproveLevelEndTotal']; + + $sql = "SELECT + COUNT(PurchaseRequestID) total + FROM purchase_request + JOIN s_regional + ON PurchaseRequestS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + JOIN item_category + ON PurchaseRequestItemCategoryID = ItemCategoryID + AND ItemCategoryIsActive = 'Y' + JOIN m_user b + ON PurchaseRequestRequestedBy = b.M_UserID + AND b.M_UserIsActive = 'Y' + AND S_RegionalIsActive = 'Y' + LEFT JOIN m_user a + ON PurchaseRequestApprovedBy = a.M_UserID + AND a.M_UserIsActive = 'Y' + LEFT JOIN + m_branch + ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' AND PurchaseRequestItemCategoryID = 1 + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + AND (PurchaseRequestDate BETWEEN ? AND ?) AND PurchaseRequestS_RegionalID = ? + $sqlStockRequest + $sqlBranch + $sqlStatus"; + $qry = $this->db->query($sql, [$search, $search, $search, $startDate, $endDate, $regionalID]); + if (!$qry) { + $this->sys_error_db("Error searching"); + exit; + } + $total = $qry->row_array()['total']; + $tot_page = ceil($total / $number_limit); + $params = [$search, $search, $search, $startDate, $endDate, $regionalID]; + + $params[] = $number_limit; + $params[] = $number_offset; + $sql = "SELECT + PurchaseRequestID prID, + DATE_FORMAT(PurchaseRequestDate, '%d-%m-%Y') prDate, + PurchaseRequestNumber prNumber, + PurchaseRequestRefNumber prRefNumber, + PurchaseRequestNote prNote, + PurchaseRequestTotal prTotal, + PurchaseRequestItemCategoryID prItemType, + ItemCategoryName prItemTypeName, + PurchaseRequestStatus prStatus, + IFNULL(PurchaseRequestVerifiedBy, 0) AS PurchaseRequestVerifiedBy, + DATE_FORMAT(PurchaseRequestApprovedDate, '%d-%m-%Y %H:%i') prApprovedDate, + a.M_userUserName prApprovedBy, + b.M_UserID prRequestedByID, + b.M_userUserName prRequestedBy, + b.M_UserM_BranchID prRequestedByFromBranch, + S_RegionalName prRegionalName, + M_BranchName prBranchName, + IFNULL(`fn_getitemnamebyprid`(PurchaseRequestID), '') prItemName + FROM purchase_request + JOIN s_regional + ON PurchaseRequestS_RegionalID = S_RegionalID + AND S_RegionalIsActive = 'Y' + JOIN item_category + ON PurchaseRequestItemCategoryID = ItemCategoryID + AND ItemCategoryIsActive = 'Y' + JOIN m_user b + ON PurchaseRequestRequestedBy = b.M_UserID + AND b.M_UserIsActive = 'Y' + LEFT JOIN m_user a + ON PurchaseRequestApprovedBy = a.M_UserID + AND a.M_UserIsActive = 'Y' + LEFT JOIN + m_branch + ON PurchaseRequestM_BranchCode = M_BranchCode + WHERE PurchaseRequestIsActive = 'Y' AND PurchaseRequestItemCategoryID = 1 + AND (PurchaseRequestNumber LIKE ? OR PurchaseRequestRefNumber LIKE ? OR PurchaseRequestRequestedBy LIKE ?) + AND (PurchaseRequestDate BETWEEN ? AND ?) AND PurchaseRequestS_RegionalID = ? + $sqlStockRequest + $sqlBranch + $sqlStatus + ORDER BY prDate,prNumber + DESC + LIMIT ? OFFSET ? + "; + $qry = $this->db->query($sql, $params); + if (!$qry) { + $this->sys_error_db("Error searching"); + exit; + } + //echo $this->db->last_query(); + //exit; + $data = $qry->result_array(); + + $result = array( + 'total' => $tot_page, + 'records' => $data, + // "qry" => $this->db->last_query() + ); + + $this->sys_ok($result); + } + + function getDetail() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + + $sql = "SELECT + PurchaseRequestID as prDetailPrID, + PurchaseRequestDetailID as prDetailID, + PurchaseRequestDetailM_ItemID as prDetailItemID, + M_ItemDesc as prDetailItemName, + M_ItemCode as prDetailItemCode, + PurchaseRequestDetailQty as prDetailItemQty, + PurchaseRequestDetailPrice as prDetailItemPrice, + PurchaseRequestDetailItemUnitID, + ItemUnitName as prDetailItemUnitName, + SUM(StockQty) AS CurrentStockQty + FROM purchase_request + JOIN purchase_request_detail ON PurchaseRequestDetailPurchaseRequestID = PurchaseRequestID + AND PurchaseRequestDetailIsActive = 'Y' + JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID + JOIN itemunit ON ItemUnitID = PurchaseRequestDetailItemUnitID + LEFT JOIN m_branch ON M_BranchCode = PurchaseRequestM_BranchCode + JOIN warehouse ON WarehouseS_RegionalID = PurchaseRequestS_RegionalID + AND WarehouseM_BranchID = COALESCE(M_BranchID, 0) + AND WarehouseIsTransit = 'N' + LEFT JOIN stock ON StockWarehouseID = WarehouseID + AND StockItemID = PurchaseRequestDetailM_ItemID + AND StockItemUnitID = PurchaseRequestDetailItemUnitID + WHERE PurchaseRequestID = ? + GROUP BY + PurchaseRequestDetailID, + PurchaseRequestDetailM_ItemID, + PurchaseRequestDetailItemUnitID, + M_ItemDesc, + M_ItemCode, + ItemUnitName"; + $qry = $this->db->query($sql, [$id]); + if (!$qry) { + $this->sys_error_db("Error get detail"); + + exit; + } + $data = $qry->result_array(); + $this->sys_ok($data); + } + + function approve() + { + $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']; + $user = $this->sys_user; + $userid = $user["M_UserID"]; + $pr = $prm['pr']; + $total = $prm['total']; + $type = $prm['type']; + + // get user level approval + $sqlevel = "SELECT M_UserM_ApproveLevelID FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ?"; + $qulevel = $this->db->query($sqlevel, [$userid]); + if (!$qulevel) { + $this->sys_error_db("[Error] get approval level user"); + exit; + } + $userlevel = $qulevel->row_array()['M_UserM_ApproveLevelID']; + + $datas_log = array(); + $sql = "SELECT * FROM purchase_request WHERE PurchaseRequestID = ? AND PurchaseRequestIsActive = 'Y'"; + $query = $this->db->query($sql, [$pr['prID']]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("purchase request select", $this->db); + exit; + } + $header = $query->row_array(); + + + $datas_log['header'] = $header; + $sql = "SELECT * + FROM purchase_request_detail + JOIN m_item ON M_ItemID = PurchaseRequestDetailM_ItemID AND M_ItemIsActive = 'Y' + JOIN itemunit ON ItemUnitID = PurchaseRequestDetailItemUnitID AND ItemUnitIsActive = 'Y' + WHERE PurchaseRequestDetailPurchaseRequestID = ? AND PurchaseRequestDetailIsActive = 'Y'"; + $query = $this->db->query($sql, [$pr['prID']]); + if (!$query) { + $this->db->trans_rollback(); + $this->sys_error_db("purchase request detail select", $this->db); + exit; + } + $details = $query->result_array(); + $datas_log['details'] = $details; + + if ($type == 'A') { + // verifikasi jika manager + if ($userlevel == '1') { + $sql = "UPDATE purchase_request SET + PurchaseRequestVerifiedBy = ?, + PurchaseRequestVerifiedDate = NOW() + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, [$userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error verifikasi manager"); + $this->db->trans_rollback(); + exit; + } + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di verifikasi"; + $this->insert_act_log("PRP", "Verified", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + + // approve jika kepala cabang / regional + if ($userlevel == '2') { + // -- PurchaseRequestTotal = ?, + $sql = "UPDATE purchase_request SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NOW(), + PurchaseRequestApprovedBy = ? + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Approved', $userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ?"; + $qry = $this->db->query($sql, ['Approved', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di approved"; + $this->insert_act_log("PRP", "Approved", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + } else if ($type == 'R') { + $sql = "UPDATE purchase_request + SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NOW(), + PurchaseRequestApprovedBy = ? + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Pending'"; + $qry = $this->db->query($sql, ['Rejected', $userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ?"; + $qry = $this->db->query($sql, ['Rejected', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di reject"; + $this->insert_act_log("PRP", "Rejected", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } else if ($type == 'U') { + // un approve jika kepala cabang / regional + if ($userlevel == '2') { + // -- PurchaseRequestTotal = ?, + $sql = "UPDATE purchase_request SET + PurchaseRequestStatus = ?, + PurchaseRequestApprovedDate = NULL, + PurchaseRequestApprovedBy = NULL + WHERE PurchaseRequestID = ? + AND PurchaseRequestStatus = 'Approved'"; + $qry = $this->db->query($sql, ['Pending', $userid, $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error Approve"); + $this->db->trans_rollback(); + exit; + } + $sql = "UPDATE purchase_request_detail + SET PurchaseRequestDetailStatus = ? + WHERE PurchaseRequestDetailPurchaseRequestID = ?"; + $qry = $this->db->query($sql, ['Pending', $pr['prID']]); + if (!$qry) { + $this->sys_error_db("Error update detail"); + $this->db->trans_rollback(); + exit; + } + $messages = "Purchase Request dengan kode " . $header['PurchaseRequestNumber'] . " telah di unapproved"; + $this->insert_act_log("PRP", "Unapproved", $messages, $pr['prID'], $this->safeJsonEncode($datas_log), $userid); + } + } + + // update notification + $this->readNotif($type, $userlevel, $userid, $pr['prID']); + + $this->db->trans_commit(); + + $this->sys_ok('Berhasil'); + } + + // read notification + function readNotif($type, $userlevel, $userId, $refID) + { + + $this->db->trans_begin(); + + // cari user penerima notifikasi + if ($type == "U") { + $sql_get = "SELECT PurchaseRequestID, + M_UserID, + M_UserUsername, + NotificationID, + NotificationDetailID, + NotificationDetailStatus, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID + FROM notification + JOIN purchase_request ON NotificationRefID = PurchaseRequestID + AND PurchaseRequestIsActive = 'Y' + JOIN notification_detail ON NotificationID = NotificationDetailNotificationID + JOIN m_user ON NotificationUserID = M_UserID + WHERE PurchaseRequestID = ? + AND NotificationDetailStatus = 'read'"; + $qry = $this->db->query($sql_get, [$refID]); + if (!$qry) { + $this->sys_error_db("select user notification error", $this->db); + exit; + } + $rowsuser = $qry->result_array(); + } else { + $sql_get = "SELECT PurchaseRequestID, + M_UserID, + M_UserUsername, + NotificationID, + NotificationDetailID, + NotificationDetailStatus, + NotificationDetailM_UserID, + NotificationDetailM_ApproveLevelID + FROM notification + JOIN purchase_request ON NotificationRefID = PurchaseRequestID + AND PurchaseRequestIsActive = 'Y' + JOIN notification_detail ON NotificationID = NotificationDetailNotificationID + JOIN m_user ON NotificationUserID = M_UserID + WHERE PurchaseRequestID = ? + AND NotificationDetailStatus = 'unread'"; + $qry = $this->db->query($sql_get, [$refID]); + if (!$qry) { + $this->sys_error_db("select user notification error", $this->db); + exit; + } + $rowsuser = $qry->result_array(); + } + + + foreach ($rowsuser as $user) { + + if ($type == "A") { + if ($userlevel === '1') { + // verifikasi manager + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } else if ($userlevel === '2') { + // approve kepala cabang / regional + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } + } else if ($type == "R") { + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'read', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } else if ($type == "U") { + if ($userlevel === '2') { + $sql = "UPDATE notification_detail SET + NotificationDetailStatus = 'unread', + NotificationDetailLastUpdated = NOW(), + NotificationDetailUserID = ? + WHERE NotificationDetailNotificationID = ? + AND NotificationDetailM_ApproveLevelID = ?"; + $qry = $this->db->query($sql, [$userId, $user["NotificationID"], $user["NotificationDetailM_ApproveLevelID"]]); + if (!$qry) { + $this->sys_error_db("update notification error", $this->db); + exit; + } + } + } + } + + $this->db->trans_commit(); + } + + function getUserApproveLevel() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $userId = $this->sys_user["M_UserID"]; + + $sqlevel = "SELECT M_UserM_ApproveLevelID FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ?"; + $qulevel = $this->db->query($sqlevel, [$userId]); + if (!$qulevel) { + $this->sys_error_db("[Error] get approval level user"); + exit; + } + $data = $qulevel->row_array(); + + $this->sys_ok($data); + } + + function updateqty() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db->trans_begin(); + $userId = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + + $arrItems = $prm["arrItems"]; + + if (count($arrItems) > 0) { + foreach ($arrItems as $key => $value) { + $sql = "UPDATE purchase_request_detail SET + PurchaseRequestDetailQty = ?, + PurchaseRequestDetailLastUpdated = NOW(), + PurchaseRequestDetailLastUpdatedUserID = ? + WHERE PurchaseRequestDetailID = ?"; + $qry = $this->db->query($sql, [ + $value['prDetailItemQty'], + $userId, + $value['prDetailID'] + ]); + if (!$qry) { + $this->db->trans_rollback(); + $this->sys_error_db("Failed update qty", $this->db); + exit; + } + } + } + + $this->db->trans_commit(); + $this->sys_ok("Berhasil update qty"); + } + + function insert_act_log($code, $status, $description, $refId, $data, $userId) + { + $sql = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated) + VALUES (?,?,?,?,?,?,?)"; + $query = $this->db->query($sql, [$code, $status, $description, $refId, $data, $userId, date("Y-m-d H:i:s")]); + if (!$query) { + $this->sys_error_db("user activity", $this->db); + exit; + } + } + + private function safeJsonEncode($data) + { + // Coba encode data ke JSON + $jsonData = json_encode($data); + + // Cek apakah terjadi error saat encode + if (json_last_error() !== JSON_ERROR_NONE) { + $errorMsg = json_last_error_msg(); + error_log("JSON encode error: " . $errorMsg); + + // Lakukan sanitasi dan perbaikan data + $fixedData = $this->fixJsonEncodeIssues($data, $errorMsg); + + // Coba encode lagi setelah diperbaiki + $jsonData = json_encode($fixedData); + + // Jika masih error, log dan kembalikan objek kosong + if (json_last_error() !== JSON_ERROR_NONE) { + error_log("Failed to fix JSON encode issues: " . json_last_error_msg()); + // Kembalikan objek kosong jika masih gagal + return '{}'; + } + } + + return $jsonData; + } + + // Fungsi untuk memperbaiki masalah encoding JSON + private function fixJsonEncodeIssues($data, $errorMsg) + { + // Buat salinan data untuk dimodifikasi + $fixedData = $data; + + // Tangani berbagai jenis error + if (strpos($errorMsg, 'Malformed UTF-8') !== false) { + // Perbaiki masalah karakter UTF-8 + $fixedData = $this->fixUTF8Issues($fixedData); + } else if (strpos($errorMsg, 'Inf and NaN cannot be JSON encoded') !== false) { + // Perbaiki masalah nilai Infinity atau NaN + $fixedData = $this->fixInfNanIssues($fixedData); + } else { + // Konversi semua nilai numerik menjadi string untuk menghindari masalah presisi + $fixedData = $this->convertNumericValuesToStrings($fixedData); + + // Perbaiki masalah referensi recursif + $fixedData = $this->fixRecursiveReferences($fixedData); + } + + return $fixedData; + } + + // Perbaiki masalah karakter UTF-8 + private function fixUTF8Issues($data) + { + if (is_string($data)) { + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } else if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = $this->fixUTF8Issues($value); + } + } + return $data; + } + + // Perbaiki masalah nilai Infinity atau NaN + private function fixInfNanIssues($data) + { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_float($value) && (is_nan($value) || is_infinite($value))) { + $data[$key] = (string)$value; // Konversi ke string + } else if (is_array($value)) { + $data[$key] = $this->fixInfNanIssues($value); + } + } + } + return $data; + } + + // Perbaiki masalah referensi recursif + private function fixRecursiveReferences($data, $depth = 0) + { + // Batasi kedalaman rekursi untuk menghindari infinite loop + if ($depth > 50) { + return "[MAX_DEPTH_REACHED]"; + } + + if (is_array($data)) { + $result = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $result[$key] = $this->fixRecursiveReferences($value, $depth + 1); + } else { + $result[$key] = $value; + } + } + return $result; + } + + return $data; + } + + // Cari dan konversi numerik ke string secara rekursif + private function convertNumericValuesToStrings($data) + { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->convertNumericValuesToStrings($value); + } else if (is_numeric($value)) { + $data[$key] = (string)$value; + } else if (is_bool($value)) { + $data[$key] = $value ? "true" : "false"; + } + } + } + return $data; + } +} diff --git a/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris.php b/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris.php index b9e1740..e29a989 100644 --- a/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris.php +++ b/application/controllers/mockup/receive-item-po/ReceiveItemPoInventaris.php @@ -98,7 +98,6 @@ class ReceiveItemPoInventaris extends MY_Controller rod.ReceiveOrderPoDetailID, rod.ReceiveOrderPoItemID, rod.ReceiveOrderPoItemUnitID, - pod.PurchaseOrderDetailPurchaseRequestID AS PurchaseRequestID, mi.M_ItemDesc, rod.ReceiveOrderPoDetailQty AS originalQty, COALESCE(ahd_count.InsertedQty, 0) AS serahQty, @@ -108,7 +107,6 @@ class ReceiveItemPoInventaris extends MY_Controller ELSE 'N' END AS isHandoverDone FROM receive_order_po_detail rod - JOIN purchase_order_detail pod ON pod.PurchaseOrderDetailID = rod.ReceiveOrderPoDetailPurchaseOrderDetailID JOIN m_item mi ON mi.M_ItemID = rod.ReceiveOrderPoItemID LEFT JOIN ( SELECT @@ -2675,32 +2673,33 @@ class ReceiveItemPoInventaris extends MY_Controller } $data_prid = $que_get_prid->row_array(); - foreach ($param['item'] as $key => $item) { - # 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, [ - $item['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(); + # 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(); + + foreach ($param['item'] as $key => $item) { $qty_invnt = intval($item['serahQty']); for ($i = 0; $i < $qty_invnt; $i++) { diff --git a/application/controllers/mockup/supplierpaymentapprovedv3/Billv2.php b/application/controllers/mockup/supplierpaymentapprovedv3/Billv2.php new file mode 100644 index 0000000..c8003d9 --- /dev/null +++ b/application/controllers/mockup/supplierpaymentapprovedv3/Billv2.php @@ -0,0 +1,264 @@ +isLogin) { + throw new Exception("Invalid token", 1); + } + + $params = $this->sys_input; + + $keyword = "%"; + if ($params['search'] != '') { + $keyword .= $params['search'] . "%"; + } + + $offset = 0; + $limit = 5; + if ($params['currentpage'] > 0) { + $offset = ($params['currentpage'] - 1) * $limit; + } + + $sql_base = "SELECT + SupplierPaymentID, + SupplierPaymentDate, + SupplierPaymentNumber, + SupplierPaymentAmount, + SupplierPaymentStatus, + SupplierPaymentIsVerif, + SupplierPaymentIsApproved, + SupplierInvoiceID, + SupplierInvoiceNumber, + SupplierInvoiceDraftPaymentDate, + SupplierCode, + SupplierName + FROM supplier_payment + JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID + AND SupplierPaymentNumber LIKE ? + AND (SupplierPaymentDate BETWEEN DATE(?) AND DATE(?)) + AND (SupplierPaymentStatus = ? OR ? = 'All') + JOIN supplier ON SupplierID = SupplierInvoiceSupplierID + WHERE SupplierPaymentIsActive = 'Y' + ORDER BY SupplierPaymentID DESC"; + + $sql_data = $sql_base . " LIMIT ? OFFSET ? "; + $que_data = $this->db->query($sql_data, [ + $keyword, $params['startdate'], $params['enddate'], + $params['status'], $params['status'], $limit, $offset + ]); + if (!$que_data) { + throw new Exception("[Error] failed get data supplier payment", 2); + } + + $sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) AS x"; + $que_total = $this->db->query($sql_total, [ + $keyword, $params['startdate'], $params['enddate'], + $params['status'], $params['status'] + ]); + if (!$que_total) { + throw new Exception("[Error] failed get total data supplier payment", 2); + } + + $output = [ + "records" => $que_data->result_array(), + "total" =>$que_total->row_array()['total'] + ]; + + $this->sys_ok($output); + exit; + } catch (Exception $exc) { + $message = $exc->getMessage(); + $code = $exc->getCode(); + + if ($code == 1) { + $this->sys_error($message); + } else { + $this->sys_error_db($message); + } + exit; + } + } + + public function searchDetail() { + try { + if (!$this->isLogin) { + throw new Exception("invalid token", 1); + } + + $para = $this->sys_input; + + $sql = "SELECT + SupplierInvoiceID, + SupplierInvoiceRefNumber, + SupplierInvoiceDeliveryOrderNumber, + SupplierInvoiceSupplierInvoiceNumber, + SupplierInvoiceSupplierInvoiceDate, + SupplierInvoiceSubTotal, + SupplierInvoiceTaxPercentPph, + SupplierInvoiceTaxPercentPpn, + SupplierInvoiceTaxAmountPpn, + SupplierInvoiceDiscountAmount, + SupplierInvoiceDiscountPercent, + SupplierInvoiceShippingCost, + SupplierInvoiceGrandTotal, + SupplierInvoiceAdjustmentAmount, + SupplierInvoiceAdjustmentNote, + SupplierInvoiceNote, + IF (SupplierInvoiceDiscountAmount > 0, 'R', 'P') AS DiscountType + FROM supplier_payment + JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID + AND SupplierPaymentID = ? + AND SupplierPaymentIsActive = 'Y'"; + $que = $this->db->query($sql, [$para['paymentID']]); + if (!$que) { + throw new Exception("[Error] failed get row data", 2); + } + $data = $que->row_array(); + + $sql_detail = "SELECT + SupplierInvoiceDetailID, + SupplierInvoiceDetailSupplierInvoiceID, + SupplierInvoiceDetailPurchaseOrderID, + SupplierInvoiceDetailPurchaseOrderSummaryID, + SupplierInvoiceDetailReceiveOrderPoID, + SupplierInvoiceDetailReceiveOrderPoDetailID, + SupplierInvoiceDetailItemID, + SupplierInvoiceDetailItemUnitID, + SupplierInvoiceDetailDescription, + SupplierInvoiceDetailQty, + SupplierInvoiceDetailPrice, + SupplierInvoiceDetailDiscountPercent, + SupplierInvoiceDetailDiscountDiscountRupiah, + SupplierInvoiceDetailDiscountDiscountType, + SupplierInvoiceDetailDiscountAmount, + (SupplierInvoiceDetailPrice - SupplierInvoiceDetailDiscountAmount) AS DiscountedPrice, + SupplierInvoiceDetailDiscountPoProrata, + SupplierInvoiceDetailTotal, + M_ItemCode, + M_ItemDesc + FROM supplier_payment_detail + JOIN supplier_invoice_detail ON SupplierInvoiceDetailIsActive = 'Y' + AND SupplierPaymentDetailSupplierPaymentID = ? + AND SupplierInvoiceDetailSupplierInvoiceID = ? + JOIN m_item ON M_ItemID = SupplierInvoiceDetailItemID + AND M_ItemIsActive = 'Y' + GROUP BY SupplierInvoiceDetailID"; + $que_detail = $this->db->query($sql_detail, [ + $para['paymentID'], $data['SupplierInvoiceID'] + ]); + if (!$que_detail) { + throw new Exception("[Error] failed to get item payments", 2); + } + + $data['detail'] = $que_detail->result_array(); + + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $code = $exc->getCode(); + + if ($code == 1) { + $this->sys_error($message); + } else { + $this->sys_error_db($message); + } + exit; + } + } + + public function getUserApproveLevel() { + try { + if (!$this->isLogin) { + throw new Exception("Invalid token", 1); + } + + $userid = $this->sys_user['M_UserID']; + $sql_level = "SELECT M_UserM_ApproveLevelID AS level + FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserID = ? "; + $que_level = $this->db->query($sql_level, [$userid]); + if (!$que_level) { + throw new Exception("[Error] failed get user approve level", 2); + } + $data = $que_level->row_array(); + $this->sys_ok($data); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $code = $exc->getCode(); + + if ($code == 1) { + $this->sys_error($message); + } else { + $this->sys_error_db($message); + } + exit; + } + } + + public function updateStatusPayment() { + try { + if (!$this->isLogin) { + throw new Exception("Invalid token", 1); + } + + $this->db->trans_begin(); + $para = $this->sys_input; + $user = $this->sys_user; + + if ($para['userlevel'] == '1') { + $sql = "UPDATE supplier_payment SET + SupplierPaymentIsVerif = 'Y', + SupplierPaymentStatus = 'Verified', + SupplierPaymentVerifUserID = ?, + SupplierPaymentVerifDate = NOW() + WHERE SupplierPaymentID = ? + AND SupplierPaymentIsActive = 'Y'"; + $query = $this->db->query($sql, [ + $user['M_UserID'], $para['paymentID'] + ]); + if (!$query) { + $this->db->trans_rollback(); + throw new Exception("[Error] failed update status verified", 2); + } + } + + if ($para['userlevel'] == '2') { + $sql = "UPDATE supplier_payment SET + SupplierPaymentIsApproved = 'Y', + SupplierPaymentStatus = 'Approved', + SupplierPaymentApprovedUserID = ?, + SupplierPaymentApprovedDate = NOW() + WHERE SupplierPaymentID = ? + AND SupplierPaymentIsActive = 'Y'"; + $query = $this->db->query($sql, [ + $user['M_UserID'], $para['paymentID'] + ]); + if (!$query) { + $this->db->trans_rollback(); + throw new Exception("[Error] failed update status approved", 2); + } + } + + $this->db->trans_commit(); + $this->sys_ok("[Success] success update status Payment"); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $code = $exc->getCode(); + + if ($code == 1) { + $this->sys_error($message); + } else { + $this->sys_error_db($message); + } + exit; + } + } +} \ No newline at end of file diff --git a/application/controllers/mockup/supplierpaymentfailed/Bill.php b/application/controllers/mockup/supplierpaymentfailed/Bill.php new file mode 100644 index 0000000..4a051d8 --- /dev/null +++ b/application/controllers/mockup/supplierpaymentfailed/Bill.php @@ -0,0 +1,769 @@ +db_onedev = $this->load->database("onedev", true); + } + + public function add_notes($orderid){ + $sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id, + SupplierPaymentID as note_id, + SupplierPaymentDetailSupplierInvoiceDetailID as detail_id, + SupplierPaymentDate as note_date, + SupplierPaymentNumber as note_number, + GROUP_CONCAT(DISTINCT coaDescription separator ' , ') as paymenttypes_name, + SUM(SupplierPaymentDetailAmount) as note_amount, + M_UserUsername as note_user, + SupplierPaymentDetailIsActive as note_active, + 'xxx' as tests, + 'N' as show_detail, + SupplierPaymentNote as keterangan, + SupplierPaymentCoaID, + coaID, + coaDescription, + SupplierPaymentIsConfirm + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN coa ON SupplierPaymentCoaID = coaID + LEFT JOIN m_user ON SupplierPaymentUserID = M_UserID + WHERE + SupplierPaymentSupplierInvoiceID = {$orderid} + AND + SupplierPaymentIsActive = 'Y' + GROUP BY SupplierPaymentID"; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + if($rows){ + foreach($rows as $k => $v){ + $rows[$k]['tests'] = $this->add_tests($v['note_id']); + } + } + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } + } + public function add_tagihans($orderid){ + $sql = "SELECT SupplierInvoiceID as tagihan_id, + PurchaseOrderNumber as tagihan_number, + jurnalTxDescription as pasien, + jurnalTxCredit as tagihan_total, + IF(SupplierPaymentDetailID IS NULL , jurnalTxCredit, jurnalTxCredit - SUM(SupplierPaymentDetailAmount)) as tagihan_tagihan, + 0 as tagihan_bayar, + DATE_FORMAT(SupplierInvoiceDueDate,'%d-%m-%Y') as tagihan_duedate, + SupplierInvoiceIsActive as tagihan_active, + 'N' as show_detail, + jurnalTxID SupplierInvoiceDetailID, + PurchaseOrderID SupplierInvoiceDetailPurchaseOrderID + + FROM supplier_invoice + JOIN purchase_order ON SupplierInvoicePurchaseOrderID = PurchaseOrderID + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563 + LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierInvoiceIsActive = 'Y' + LEFT JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID AND SupplierPaymentDetailIsActive = 'Y' + WHERE + SupplierInvoiceID = {$orderid} + GROUP BY jurnalTxID + "; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } +} + public function add_tests($orderid){ + $sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id, + SupplierPaymentID as note_id, + SupplierPaymentDate as note_date, + SupplierPaymentNumber as note_number, + GROUP_CONCAT(coaDescription separator ' , ') as paymenttypes_name, + SUM(SupplierPaymentDetailAmount) as note_amount, + M_UserUsername as note_user, + SupplierPaymentDetailIsActive as note_active, + PurchaseOrderNumber, + SupplierInvoiceDetailTotal, + SupplierPaymentDetailAmount + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID + LEFT JOIN supplier_invoice_detail ON SupplierPaymentDetailSupplierInvoiceDetailID = SupplierInvoiceDetailID + LEFT JOIN purchase_order ON SupplierInvoiceDetailPurchaseOrderID = PurchaseOrderID + JOIN coa ON SupplierPaymentCoaID = coaID + LEFT JOIN m_user ON SupplierPaymentDetailUserID = M_UserID + WHERE + SupplierPaymentID = {$orderid} + GROUP BY SupplierPaymentDetailID"; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + if($rows){ + } + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } +} +function searchsupplier(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = " + SELECT count(*) as total + FROM supplier + WHERE + SupplierName like ? + AND SupplierIsActive = 'Y' + ORDER BY SupplierName DESC + "; + + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_city count",$this->db_onedev); + exit; + } + $sql = " + SELECT * + FROM supplier + WHERE + SupplierName like ? + AND SupplierIsActive = 'Y' + ORDER BY SupplierName DESC + "; + + + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_city rows",$this->db_onedev); + exit; + } + } + function searchinvpayment(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "SELECT count(*) as total + FROM supplier_payment + JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID + AND SupplierInvoiceSupplierID = {$prm['companyid']} + WHERE + SupplierPaymentNumber like ? + AND SupplierPaymentIsActive = 'Y' + AND SupplierPaymentIsConfirm = 'Y' + ORDER BY SupplierPaymentID ASC + "; + + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_city count",$this->db_onedev); + exit; + } + $sql = " + SELECT *, CONCAT(SupplierPaymentNumber,' - ',coaDescription, ' Rp. ',SupplierPaymentAmount) PaymentName + FROM supplier_payment + JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID + AND SupplierInvoiceSupplierID = {$prm['companyid']} + JOIN coa ON SupplierPaymentCoaID = coaID + WHERE + SupplierPaymentNumber like ? + AND SupplierPaymentIsActive = 'Y' + AND SupplierPaymentIsConfirm = 'Y' + ORDER BY SupplierPaymentID ASC + "; + + + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_city rows",$this->db_onedev); + exit; + } + } + public function search() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $supplier = $prm["supplier"]; + $search = $prm["search"]; + $status = $prm["status"]; + $startdate = $prm["startdate"]; + $enddate = $prm["enddate"]; + $regionalid = $this->sys_user['S_RegionalID']; + + $number_limit = 10; + $number_offset = ($prm['current_page'] - 1) * $number_limit ; + + $where = "SupplierPaymentIsFailed = 'Y' + AND (SupplierInvoiceNumber LIKE '%{$search}%' AND SupplierName LIKE '%{$supplier}%') + AND PurchaseOrderS_RegionalID = {$regionalid} + AND SupplierPaymentConfirmDate BETWEEN '{$startdate}' AND '{$enddate}'"; + + + + + $sql = " SELECT count(*) as total + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID + LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID + JOIN purchase_order ON PurchaseOrderID = SupplierInvoicePurchaseOrderID + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563 + WHERE + $where + "; + // echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + + + $tot_count = 0; + $tot_page = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + $tot_page = ceil($tot_count/$number_limit); + } else { + $this->sys_error_db("supplier_invoice count", $this->db_onedev); + exit; + } + + + $sql = "SELECT SupplierInvoiceID, + SupplierPaymentID, + SupplierPaymentDetailSupplierInvoiceDetailID, + DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar, + DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d%m%Y') as tanggalbayartext, + SupplierPaymentDate as note_date, + SupplierPaymentNumber as note_number, + GROUP_CONCAT(DISTINCT coaDescription separator ' , ') as paymenttypes_name, + SUM(SupplierPaymentDetailAmount) as note_amount, + n.M_UserUsername as note_user, + SupplierPaymentDetailIsActive as note_active, + 'xxx' as tests, + 'N' as show_detail, + SupplierPaymentNote as keterangan, + SupplierPaymentCoaID, + coaID, + coaDescription, + SupplierPaymentIsConfirm, + SupplierPaymentApprovedUserID, + SupplierPaymentApprovedDate, + SupplierInvoiceNumber, +SupplierName, +SupplierPaymentNumber, +CONCAT('Created by : ',n.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentCreated,'%d-%m-%Y %H:%i')) as d_created, +CONCAT('Confirmed by : ',c.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentConfirmDate,'%d-%m-%Y %H:%i')) as d_confirm, + CONCAT('Approved by : ',a.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentApprovedDate,'%d-%m-%Y %H:%i')) as d_approved + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID + LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID + JOIN purchase_order ON PurchaseOrderID = SupplierInvoicePurchaseOrderID + JOIN coa ON SupplierPaymentCoaID = coaID + LEFT JOIN m_user n ON SupplierPaymentUserID = n.M_UserID + LEFT JOIN m_user c ON SupplierPaymentConfirmUserID = c.M_UserID + LEFT JOIN m_user a ON SupplierPaymentApprovedUserID = a.M_UserID + WHERE + $where + GROUP BY SupplierPaymentID + ORDER BY SupplierPaymentID DESC + limit $number_limit offset $number_offset"; + //echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + $rows = $query->result_array(); + $result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_onedev->last_query()); + $this->sys_ok($result); + exit; + } + + function confirm_note() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $regionalid = $this->sys_user['S_RegionalID']; + $branchid = $this->sys_user['M_BranchID']; + $prm = $this->sys_input; + $prmnota = $prm['nota']; + $note = $prm['note']; + $sql = "UPDATE supplier_payment + SET SupplierPaymentIsFailed = 'Y', + SupplierPaymentFailedUserID = {$xuserid}, + SupplierPaymentFailedDate = now(), + SupplierPaymentFailedNote = '{$note}' + WHERE SupplierPaymentID = {$prmnota['SupplierPaymentID']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment delete"); + exit; + } + $headerid = $prmnota['SupplierPaymentID']; + $sql = "SELECT * FROM supplier_payment + JOIN m_user ON M_UserID = SupplierPaymentFailedUserID + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $row = $query->row_array(); + + + + $sqlbill = "UPDATE supplier_invoice SET + SupplierInvoiceIsLunas = 'N' + WHERE SupplierInvoiceID = {$prmnota['SupplierInvoiceID']}"; + $querybill = $this->db_onedev->query($sqlbill); + + + $sql = "SELECT * FROM supplier_payment_detail + WHERE SupplierPaymentDetailSupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $rows = $query->row_array(); + + $data = array("header" => $row, + "details" => $rows); + $message = "Nomor Pembayaran Faktur: " . $row["SupplierPaymentNumber"] ." telah dibatalkan oleh " . $row["M_UserUsername"]; + $this->insert_act_log("PF", "CONFIRM", $message, $headerid, $this->safeJsonEncode($data), $xuserid); + + $sqlData = "SELECT SupplierPaymentDetailID as id, + SupplierPaymentID, + SupplierPaymentNumber, + $branchid M_BranchID, + '' M_BranchCode, + '' M_BranchName, + M_BranchS_RegionalID, + M_BranchCompanyID, + M_BranchCompanyName, + CONCAT('Jurnal Payment Invoice Failed Nomor : SupplierPaymentNumber', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription, + IFNULL(periodeID,0) periodeid, + CONCAT('Jurnal Payment Invoice Failed Nomor : SupplierPaymentNumber', DATE_FORMAT(now(), '%d-%m-%Y'), ' regional ',S_RegionalName) title, + 22 typeid, + '' detailjurnal, + coaID, + coaAccountNo, + coaDescription, + 0 debit, + SupplierPaymentDetailAmount credit + + + + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID AND M_BranchID = {$branchid} + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ON coaID = SupplierPaymentCoaID + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + GROUP BY SupplierPaymentID"; + $newData = $this->db_onedev->query($sqlData)->result_array(); + // echo $this->db_onedev->last_query(); + if ($newData) { + foreach ($newData as $k => $v) { + $periodeid = $v["periodeid"]; + $branchcompanyid = $v["M_BranchCompanyID"]; + $date = date('Y-m-d'); + $description = $v["xdescription"]; + $regionalid = $v["M_BranchS_RegionalID"]; + $title = $v["title"]; + $typeid = $v["typeid"]; + $pvno = $v["SupplierPaymentNumber"]; + $detailjurnal = $this->db_onedev->query("SELECT SupplierPaymentDetailID as id, + coaID coaid, + coaDescription xdescription, + SupplierPaymentDetailAmount debit, + 0 credit + + + + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID AND M_BranchID = $branchid + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ON coaID = SupplierPaymentCoaID + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + + UNION SELECT jurnalTxID as id, + jurnalTxCoaID coaid, + jurnalTxDescription xdescription, + 0 debit, + SupplierPaymentDetailAmount credit + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID AND M_BranchID = $branchid + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + JOIN coa ON coaID = jurnalTxCoaID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + GROUP BY id")->result_array(); + //echo $this->db->last_query(); + $rows[$k]['detailjurnal'] = $detailjurnal; + + $this->savejurnal($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid); + } + + } + + + $result = array( + "total" => 1 , + "records" => array('prm'=>$prm) + ); + $this->sys_ok($result); + exit; + } + function savejurnal($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid) + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $sql_branch = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry_branch = $this->db_onedev->query($sql_branch, array($branchid)); + if ($qry_branch) { + $branchcodex = $qry_branch->row()->M_BranchCode; + } else { + $this->db_onedev->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_onedev->query($sql, array( + $branchcompanyid, + $regionalid, + $branchcodex, + $periodeid, + $title, + $description, + $date, + $typeid, + $userid + )); + $last_qry = $this->db_onedev->last_query(); + 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); + exit; + } + + $last_id = $this->db_onedev->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_onedev->query($sql_detail, array( + $last_id, + $value["coaid"], + $value["xdescription"], + $value["debit"], + $value["credit"], + $userid + )); + $last_qry = $this->db_onedev->last_query(); + if (!$qry_detail) { + $this->db_onedev->trans_rollback(); + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db); + exit; + } + + $tx_id = $this->db_onedev->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'JFA', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db_onedev->query($sql, array( + $last_id, + $tx_id, + $pvno, + $userid, + $userid + )); + $last_qry = $this->db_onedev->last_query(); + 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); + exit; + } + } + + + $this->db_onedev->trans_commit(); + // $result = array("total" => 1); + // $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function insert_act_log($code, $status, $description, $refId, $data, $userId) + { + $sql = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated) + VALUES (?,?,?,?,?,?,?)"; + $query = $this->db_onedev->query($sql, [$code, $status, $description, $refId, $data, $userId, date("Y-m-d H:i:s")]); + if (!$query) { + $this->sys_error_db("user activity", $this->db_onedev); + exit; + } + } + private function safeJsonEncode($data) { + // Coba encode data ke JSON + $jsonData = json_encode($data); + + // Cek apakah terjadi error saat encode + if (json_last_error() !== JSON_ERROR_NONE) { + $errorMsg = json_last_error_msg(); + error_log("JSON encode error: " . $errorMsg); + + // Lakukan sanitasi dan perbaikan data + $fixedData = $this->fixJsonEncodeIssues($data, $errorMsg); + + // Coba encode lagi setelah diperbaiki + $jsonData = json_encode($fixedData); + + // Jika masih error, log dan kembalikan objek kosong + if (json_last_error() !== JSON_ERROR_NONE) { + error_log("Failed to fix JSON encode issues: " . json_last_error_msg()); + // Kembalikan objek kosong jika masih gagal + return '{}'; + } + } + + return $jsonData; + } + + // Fungsi untuk memperbaiki masalah encoding JSON + private function fixJsonEncodeIssues($data, $errorMsg) { + // Buat salinan data untuk dimodifikasi + $fixedData = $data; + + // Tangani berbagai jenis error + if (strpos($errorMsg, 'Malformed UTF-8') !== false) { + // Perbaiki masalah karakter UTF-8 + $fixedData = $this->fixUTF8Issues($fixedData); + } else if (strpos($errorMsg, 'Inf and NaN cannot be JSON encoded') !== false) { + // Perbaiki masalah nilai Infinity atau NaN + $fixedData = $this->fixInfNanIssues($fixedData); + } else { + // Konversi semua nilai numerik menjadi string untuk menghindari masalah presisi + $fixedData = $this->convertNumericValuesToStrings($fixedData); + + // Perbaiki masalah referensi recursif + $fixedData = $this->fixRecursiveReferences($fixedData); + } + + return $fixedData; + } + + // Perbaiki masalah karakter UTF-8 + private function fixUTF8Issues($data) { + if (is_string($data)) { + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } else if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = $this->fixUTF8Issues($value); + } + } + return $data; + } + + // Perbaiki masalah nilai Infinity atau NaN + private function fixInfNanIssues($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_float($value) && (is_nan($value) || is_infinite($value))) { + $data[$key] = (string)$value; // Konversi ke string + } else if (is_array($value)) { + $data[$key] = $this->fixInfNanIssues($value); + } + } + } + return $data; + } + + // Perbaiki masalah referensi recursif + private function fixRecursiveReferences($data, $depth = 0) { + // Batasi kedalaman rekursi untuk menghindari infinite loop + if ($depth > 50) { + return "[MAX_DEPTH_REACHED]"; + } + + if (is_array($data)) { + $result = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $result[$key] = $this->fixRecursiveReferences($value, $depth + 1); + } else { + $result[$key] = $value; + } + } + return $result; + } + + return $data; + } + + // Cari dan konversi numerik ke string secara rekursif + private function convertNumericValuesToStrings($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->convertNumericValuesToStrings($value); + } else if (is_numeric($value)) { + $data[$key] = (string)$value; + } else if (is_bool($value)) { + $data[$key] = $value ? "true" : "false"; + } + } + } + return $data; + } +} diff --git a/application/controllers/mockup/supplierpaymentfailed/Payment.php b/application/controllers/mockup/supplierpaymentfailed/Payment.php new file mode 100644 index 0000000..f577654 --- /dev/null +++ b/application/controllers/mockup/supplierpaymentfailed/Payment.php @@ -0,0 +1,1024 @@ +db_onedev = $this->load->database("onedev", true); + } + + function lookup_type() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT M_PaymentTypeID as id, + M_PaymentTypeCode as code, + 'N' as chex, + M_PaymentTypeName as chexlabel, + 'Jumlah' as leftlabel, + '' as selected_card, + '' as selected_edc, + '' as selected_account, + CASE + WHEN M_PaymentTypeCode = 'CASH' THEN 'Kembali' + WHEN M_PaymentTypeCode = 'DEBIT' THEN 'Nomor Kartu' + WHEN M_PaymentTypeCode = 'CREDIT' THEN 'Nomor Kartu' + WHEN M_PaymentTypeCode = 'TRANSFER' THEN 'No. Rekening' + ELSE 'Nomor Voucher' + END as rightlabel, + 0 as leftvalue, + 0 as rightvalue + FROM m_paymenttype WHERE M_PaymentTypeIsActive = 'Y'"; + $rows = $this->db_onedev->query($query)->result_array(); + foreach($rows as $k => $v){ + $rows[$k]['selected_card'] = array('id'=>0,'name'=>''); + $rows[$k]['selected_edc'] = array('id'=>0,'name'=>''); + $rows[$k]['selected_account'] = array('id'=>0,'name'=>''); + if($v['chex'] == 'N') + $rows[$k]['chex'] = false; + else + $rows[$k]['chex'] = true; + } + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + function selectpaymenttype(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" SELECT * + FROM m_paymenttype + WHERE + M_PaymentTypeIsActive = 'Y' + "; + //echo $query; + $rows['paymenttypes'] = $this->db_onedev->query($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 selectbank(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" SELECT * + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankCode DESC + "; + //echo $query; + $rows['banks'] = $this->db_onedev->query($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 selectaccount(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" SELECT M_BankAccountID as M_BankAccountID, CONCAT(Nat_BankCode,' (',M_BankAccountNo,')') as M_BankAccountName + FROM m_bank_account + JOIN nat_bank ON M_BankAccountNat_BankID = Nat_BankID + WHERE + M_BankAccountIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + //echo $query; + $rows['accounts'] = $this->db_onedev->query($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 lookup_banks() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT Nat_BankID as id, Nat_BankCode as name + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + $rows = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + function lookup_accounts() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT M_BankAccountID as id, CONCAT(Nat_BankCode,' (',M_BankAccountNo,')') as name + FROM m_bank_account + JOIN nat_bank ON M_BankAccountNat_BankID = Nat_BankID + WHERE + M_BankAccountIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + $rows = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + + + function searchcard(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + if($prm['search'] != ''){ + $sql = " + SELECT count(*) as total + FROM nat_bank + WHERE + Nat_BankName like ? + AND Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + else{ + $sql = " + SELECT count(*) as total + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_city count",$this->db_onedev); + exit; + } + if($prm['search'] != ''){ + $sql = " + SELECT Nat_BankID as id, Nat_BankName as name + FROM nat_bank + WHERE + Nat_BankName like ? + AND Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + else{ + $sql = " + SELECT Nat_BankID as id, Nat_BankName as name + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_city rows",$this->db_onedev); + exit; + } + } + + + function pay() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $orderid = $prm['orderid']; + $payments = $prm['payments']; + //$xnumber = $this->db_onedev->query("SELECT `fn_numbering`('PAY') as numberx")->row()->numberx; + $sql = "INSERT INTO supplier_payment + (SupplierPaymentSupplierInvoiceID,SupplierPaymentDate,SupplierPaymentCreated,SupplierPaymentUserID) + VALUES (?,CURDATE(),NOW(),?)"; + $query = $this->db_onedev->query($sql, + array( + $orderid, $xuserid + ) + ); + + if (!$query) { + $this->sys_error_db("supplier_payment insert"); + exit; + } + $headerid = $this->db_onedev->insert_id(); + //echo $headerid; + + foreach($payments as $k => $v){ + if($v['chex']){ + $actual = 0; + $change = 0; + $amount = $v['leftvalue']; + if($v['code'] == 'CASH'){ + $actual = $v['leftvalue']; + $change = $v['rightvalue']; + if($actual > 0){ + $amount = intval($v['leftvalue']) - intval($v['rightvalue']); + } + else{ + $amount = $actual; + } + + $sql = "CALL `sp_bill_payment_add_cash`(".$orderid.",".$amount.",".$amount.",".$headerid.",".$v['id'].",".$xuserid.")"; + $query = $this->db_onedev->query($sql); + + if (!$query) { + $this->sys_error_db("supplier_payment_detail cash insert"); + exit; + } + + } + else{ + if(intval($v['leftvalue']) > 0){ + $actual = 0; + $change = 0; + $amount = $v['leftvalue']; + $selected_card = 0; + $selected_edc = 0; + $selected_account = 0; + if($v['code'] == 'DEBIT' || $v['code'] == 'CREDIT' || $v['code'] == 'TRANSFER'){ + $selected_card = $v['selected_card']['id']; + $selected_edc = $v['selected_edc']['id']; + $selected_account = $v['selected_account']['id']; + } + $sql = "CALL `sp_bill_payment_add_noncash`(".$orderid.",".$amount.",".$amount.",".$headerid.",".$v['id'].",".$xuserid.",".$selected_card.",".$selected_edc.",".$selected_account.")"; + //echo $sql; + + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if (!$query) { + $this->sys_error_db("supplier_payment_detail non cash insert"); + exit; + } + } + } + } + } + + $query = "SELECT M_PaymentTypeID as id, + M_PaymentTypeCode as code, + IF(M_PaymentTypeCode = 'CASH','Y','N') as chex, + M_PaymentTypeName as chexlabel, + 'Jumlah' as leftlabel, + CASE + WHEN M_PaymentTypeCode = 'CASH' THEN 'Kembali' + WHEN M_PaymentTypeCode = 'DEBIT' THEN 'Nomor Kartu' + WHEN M_PaymentTypeCode = 'CREDIT' THEN 'Nomor Kartu' + WHEN M_PaymentTypeCode = 'TRANSFER' THEN 'Nomor Rekening' + ELSE 'Nomor Voucher' + END as rightlabel, + 0 as leftvalue, + 0 as rightvalue + FROM m_paymenttype WHERE M_PaymentTypeIsActive = 'Y'"; + $rows = $this->db_onedev->query($query)->result_array(); + + foreach($rows as $k => $v){ + if($v['chex'] == 'N') + $rows[$k]['chex'] = false; + else + $rows[$k]['chex'] = true; + } + $xdata = $this->db_onedev->query("SELECT SupplierPaymentID as idx, SupplierPaymentNumber as numberx FROM supplier_payment WHERE SupplierPaymentID = {$headerid}")->row(); + $result = array( + "total" => count($rows) , + "records" => array('types'=>$rows,'data'=>$xdata) + ); + $this->sys_ok($result); + exit; + } + function paymanual() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $orderid = $prm['orderid']; + $amount = $prm['amount']; + $paymenttype = $prm['paymenttype']; + + $keterangan = $prm['keterangan']; + $bills = $prm['bills']; + $xnumber = $this->db_onedev->query("SELECT `fn_numbering`('PINV') as numberx")->row()->numberx; + $sql = "INSERT INTO supplier_payment + (SupplierPaymentSupplierInvoiceID, + SupplierPaymentNumber, + SupplierPaymentDate, + SupplierPaymentAmount, + SupplierPaymentM_PaymentTypeID, + SupplierPaymentNote, + SupplierPaymentCreated, + SupplierPaymentUserID) + VALUES (?, + ?, + CURDATE(), + ?, + ?, + ?, + NOW(), + ?)"; + $query = $this->db_onedev->query($sql, + array( + $orderid, + $xnumber, + $amount, + $paymenttype, + $keterangan, + $xuserid + ) + ); + $headerid = $this->db_onedev->insert_id(); + if (!$query) { + $this->sys_error_db("supplier_payment insert"); + exit; + } else{ + $sqlbill = "UPDATE supplier_invoice SET + SupplierInvoiceUnpaid = SupplierInvoiceUnpaid - $amount, + SupplierInvoiceIsLunas = IF(SupplierInvoiceUnpaid = 0,'Y','N') + WHERE SupplierInvoiceID = $orderid"; + $querybill = $this->db_onedev->query($sqlbill); + + } + + //echo $headerid; + + foreach($bills as $k => $v){ + if($v['tagihan_bayar'] > 0){ + $SupplierInvoiceDetailID = $v['SupplierInvoiceDetailID']; + $tagihan_bayar = $v['tagihan_bayar']; + $SupplierInvoiceDetailPurchaseOrderID = $v['SupplierInvoiceDetailPurchaseOrderID']; + $sql = "INSERT INTO supplier_payment_detail( + SupplierPaymentDetailSupplierPaymentID, + SupplierPaymentDetailSupplierInvoiceDetailID, + SupplierPaymentDetailAmount, + SupplierPaymentDetailUserID, + SupplierPaymentDetailCreated, + SupplierPaymentDetailLastUpdated) + VALUES( + $headerid, + $SupplierInvoiceDetailID, + $tagihan_bayar, + $xuserid, + now(), + now())"; + $query = $this->db_onedev->query($sql); + $billpaymentdetailid = $this->db_onedev->insert_id(); + if (!$query) { + $this->sys_error_db("supplier_payment_detail cash insert"); + exit; + }else{ + $sqlbilldetail = "UPDATE supplier_invoice_detail SET + SupplierInvoiceDetailUnpaid = SupplierInvoiceDetailUnpaid - $tagihan_bayar + WHERE SupplierInvoiceDetailID = $SupplierInvoiceDetailID"; + $querybilldetail = $this->db_onedev->query($sqlbilldetail); + + /* $sqlpayment = "INSERT INTO f_payment + (F_PaymentPurchaseOrderID, + F_PaymentDate, + F_PaymentTotal, + F_PaymentCreated, + F_PaymentLastUpdated, + F_PaymentM_UserID) + VALUES( + $SupplierInvoiceDetailPurchaseOrderID, + now(), + $tagihan_bayar, + now(), + now(), + $xuserid)"; + $querypayment = $this->db_onedev->query($sqlpayment); + $paymentid = $this->db_onedev->insert_id(); + $sqlpaymentdetail = "INSERT INTO f_paymentdetail + (F_PaymentDetailF_PaymentID, + F_PaymentDetailM_PaymentTypeID, + F_PaymentDetailAmount, + F_PaymentDetailActual, + F_PaymentDetailChange, + F_PaymentDetailEDCNat_BankID, + F_PaymentDetailCardNat_BankID, + F_PaymentDetailM_BankAccountID, + F_PaymentDetailCreated, + F_PaymentDetailLastUpdated, + F_PaymentDetailUserID) + VALUES( + $paymentid, + $paymenttype, + $tagihan_bayar, + $tagihan_bayar, + 0, + $edc, + $card, + $account, + now(), + now(), + $xuserid)"; + //echo $sqlpaymentdetail; + $querypaymentdetail = $this->db_onedev->query($sqlpaymentdetail); + + $sqleditbillpaymentdetail = "UPDATE supplier_payment_detail SET + SupplierPaymentDetailF_PaymentID = $paymentid + WHERE SupplierPaymentDetailID = $billpaymentdetailid"; + $queryeditbillpaymentdetail = $this->db_onedev->query($sqleditbillpaymentdetail); + + */ + } + + + } + } + + + $xdata = $this->db_onedev->query("SELECT SupplierPaymentID as idx, SupplierPaymentNumber as numberx FROM supplier_payment WHERE SupplierPaymentID = {$headerid}")->row(); + $result = array( + "total" => count($rows) , + "records" => array('data'=>$xdata) + ); + $this->sys_ok($result); + exit; + } + function delete_note() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $prmnota = $prm['nota']; + $catatan = $prm['catatan']; + $sql = "UPDATE supplier_payment SET SupplierPaymentIsActive = 'N', SupplierPaymentNote = '{$catatan}' WHERE SupplierPaymentID = {$prmnota['note_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment delete"); + exit; + } + + $sql = "UPDATE supplier_payment_detail SET SupplierPaymentDetailIsActive = 'N' WHERE SupplierPaymentDetailSupplierPaymentID = {$prmnota['note_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment_detail delete"); + exit; + } + + $result = array( + "total" => 1 , + "records" => array('prm'=>$prm) + ); + $this->sys_ok($result); + exit; + } + function confirm_note() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $regionalid = $this->sys_user['S_RegionalID']; + $prm = $this->sys_input; + $prmnota = $prm['nota']; + $sql = "UPDATE supplier_payment + SET SupplierPaymentIsConfirm = 'Y', + SupplierPaymentConfirmUserID = {$xuserid}, + SupplierPaymentConfirmDate = now() + WHERE SupplierPaymentID = {$prmnota['note_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment delete"); + exit; + } + + + + //echo $this->db_onedev->last_query(); + $headerid = $prmnota['note_id']; + + $sql = "SELECT * FROM supplier_payment + JOIN m_user ON M_UserID = SupplierPaymentUserID + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $row = $query->row_array(); + + $s_payment = $this->db_onedev->query("SELECT SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount + FROM supplier_payment + WHERE SupplierPaymentIsActive = 'Y' AND SupplierPaymentSupplierInvoiceID = {$prmnota['SupplierInvoiceID']}")->row(); + + + $s_jurnal = $this->db_onedev->query("SELECT SUM(jurnalTxCredit) totalbill + FROM supplier_invoice + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563 + WHERE SupplierInvoiceID = {$prmnota['SupplierInvoiceID']} + GROUP BY SupplierInvoiceID")->row(); + + + + $totalbill = $s_jurnal->totalbill; + $amount = $s_payment->SupplierPaymentAmount ? $s_payment->SupplierPaymentAmount : "0.00"; + + $x_total = $totalbill - $amount; + if($x_total == 0){ + $sqlbill = "UPDATE supplier_invoice SET + SupplierInvoiceIsLunas = 'Y' + WHERE SupplierInvoiceID = $orderid"; + $querybill = $this->db_onedev->query($sqlbill); + } + + $sql = "SELECT * FROM supplier_payment_detail + WHERE SupplierPaymentDetailSupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $rows = $query->row_array(); + + $data = array("header" => $row, + "details" => $rows); + $message = "Nomor Pembayaran Faktur: " . $row["SupplierPaymentNumber"] ." telah dikonfirmasi oleh " . $row["M_UserUsername"]; + $this->insert_act_log("PF", "CONFIRM", $message, $headerid, $this->safeJsonEncode($data), $xuserid); + + $sqlData = "SELECT SupplierPaymentDetailID as id, + SupplierPaymentID, + SupplierPaymentNumber, + 0 M_BranchID, + '' M_BranchCode, + '' M_BranchName, + M_BranchS_RegionalID, + M_BranchCompanyID, + M_BranchCompanyName, + CONCAT('Jurnal Payment Invoice Nomor : SupplierPaymentNumber', DATE_FORMAT(now(), '%d-%m-%Y')) xdescription, + IFNULL(periodeID,0) periodeid, + CONCAT('Jurnal Payment Invoice Nomor : SupplierPaymentNumber', DATE_FORMAT(now(), '%d-%m-%Y'), ' regional ',S_RegionalName) title, + 22 typeid, + '' detailjurnal, + coaID, + coaAccountNo, + coaDescription, + 0 debit, + SupplierPaymentDetailAmount credit + + + + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ON coaID = SupplierPaymentCoaID + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + GROUP BY SupplierPaymentID"; + $newData = $this->db_onedev->query($sqlData)->result_array(); + // echo $this->db_onedev->last_query(); + if ($newData) { + foreach ($newData as $k => $v) { + $branchid = $v["M_BranchID"]; + $periodeid = $v["periodeid"]; + $branchcompanyid = $v["M_BranchCompanyID"]; + $date = date('Y-m-d'); + $description = $v["xdescription"]; + $regionalid = $v["M_BranchS_RegionalID"]; + $title = $v["title"]; + $typeid = $v["typeid"]; + $pvno = $v["SupplierPaymentNumber"]; + $detailjurnal = $this->db_onedev->query("SELECT SupplierPaymentDetailID as id, + coaID coaid, + coaDescription xdescription, + 0 debit, + SupplierPaymentDetailAmount credit + + + + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + JOIN coa ON coaID = SupplierPaymentCoaID + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + + UNION SELECT jurnalTxID as id, + jurnalTxCoaID coaid, + jurnalTxDescription xdescription, + SupplierPaymentDetailAmount debit, + 0 credit + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + JOIN s_regional ON S_RegionalID = $regionalid + LEFT JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID + LEFT JOIN m_branch_companydetail ON M_BranchCompanyDetailM_BranchCode = M_BranchCode AND M_BranchCompanyDetailIsActive = 'Y' + LEFT JOIN m_branch_company ON M_BranchCompanyID = M_BranchCompanyDetailM_BranchCompanyID AND M_BranchCompanyIsActive = 'Y' + LEFT JOIN periode ON date(now()) BETWEEN periodeStartDate AND periodeEndDate AND periodeIsActive = 'Y' + JOIN jurnal_tx ON jurnalTxID = SupplierPaymentDetailSupplierInvoiceDetailID + JOIN coa ON coaID = jurnalTxCoaID + WHERE SupplierPaymentID = {$headerid} AND SupplierPaymentIsActive = 'Y' + GROUP BY id")->result_array(); + //echo $this->db->last_query(); + $rows[$k]['detailjurnal'] = $detailjurnal; + + $this->savejurnal($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid); + } + + } + + $result = array( + "total" => 1 , + "records" => array('prm'=>$prm) + ); + $this->sys_ok($result); + exit; + } + function savejurnal($branchid, $date, $description, $periodeid, $regionalid, $title, $typeid, $detailjurnal, $pvno, $branchcompanyid) + { + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $this->db_onedev->trans_begin(); + $userid = $this->sys_user['M_UserID']; + + $sql_branch = "SELECT + M_BranchID, + M_BranchCode, + M_BranchName + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchID = ?"; + $qry_branch = $this->db_onedev->query($sql_branch, array($branchid)); + if ($qry_branch) { + $branchcodex = $qry_branch->row()->M_BranchCode; + } else { + $this->db_onedev->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_onedev->query($sql, array( + $branchcompanyid, + $regionalid, + $branchcodex, + $periodeid, + $title, + $description, + $date, + $typeid, + $userid + )); + $last_qry = $this->db_onedev->last_query(); + 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); + exit; + } + + $last_id = $this->db_onedev->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_onedev->query($sql_detail, array( + $last_id, + $value["coaid"], + $value["xdescription"], + $value["debit"], + $value["credit"], + $userid + )); + $last_qry = $this->db_onedev->last_query(); + if (!$qry_detail) { + $this->db_onedev->trans_rollback(); + $error = array( + "message" => $this->db_onedev->error()["message"], + "sql" => $last_qry + ); + $this->sys_error_db($error, $this->db); + exit; + } + + $tx_id = $this->db_onedev->insert_id(); + + $sql = "INSERT INTO jurnal_addon + (jurnalAddOnJurnalID, + jurnalAddOnJurnalTxID, + jurnalAddOnCode, + jurnalAddOnValue, + jurnalAddOnCreated, + jurnalAddOnCreatedUserID, + jurnalAddOnLastUpdatedUserID, + jurnalAddOnLastUpdated) + VALUES + (?, + ?, + 'JFA', + ?, + now(), + ?, + ?, + now())"; + $qry = $this->db_onedev->query($sql, array( + $last_id, + $tx_id, + $pvno, + $userid, + $userid + )); + $last_qry = $this->db_onedev->last_query(); + 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); + exit; + } + } + + + $this->db_onedev->trans_commit(); + // $result = array("total" => 1); + // $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function insert_act_log($code, $status, $description, $refId, $data, $userId) + { + $sql = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated) + VALUES (?,?,?,?,?,?,?)"; + $query = $this->db_onedev->query($sql, [$code, $status, $description, $refId, $data, $userId, date("Y-m-d H:i:s")]); + if (!$query) { + $this->sys_error_db("user activity", $this->db_onedev); + exit; + } + } + private function safeJsonEncode($data) { + // Coba encode data ke JSON + $jsonData = json_encode($data); + + // Cek apakah terjadi error saat encode + if (json_last_error() !== JSON_ERROR_NONE) { + $errorMsg = json_last_error_msg(); + error_log("JSON encode error: " . $errorMsg); + + // Lakukan sanitasi dan perbaikan data + $fixedData = $this->fixJsonEncodeIssues($data, $errorMsg); + + // Coba encode lagi setelah diperbaiki + $jsonData = json_encode($fixedData); + + // Jika masih error, log dan kembalikan objek kosong + if (json_last_error() !== JSON_ERROR_NONE) { + error_log("Failed to fix JSON encode issues: " . json_last_error_msg()); + // Kembalikan objek kosong jika masih gagal + return '{}'; + } + } + + return $jsonData; + } + + // Fungsi untuk memperbaiki masalah encoding JSON + private function fixJsonEncodeIssues($data, $errorMsg) { + // Buat salinan data untuk dimodifikasi + $fixedData = $data; + + // Tangani berbagai jenis error + if (strpos($errorMsg, 'Malformed UTF-8') !== false) { + // Perbaiki masalah karakter UTF-8 + $fixedData = $this->fixUTF8Issues($fixedData); + } else if (strpos($errorMsg, 'Inf and NaN cannot be JSON encoded') !== false) { + // Perbaiki masalah nilai Infinity atau NaN + $fixedData = $this->fixInfNanIssues($fixedData); + } else { + // Konversi semua nilai numerik menjadi string untuk menghindari masalah presisi + $fixedData = $this->convertNumericValuesToStrings($fixedData); + + // Perbaiki masalah referensi recursif + $fixedData = $this->fixRecursiveReferences($fixedData); + } + + return $fixedData; + } + + // Perbaiki masalah karakter UTF-8 + private function fixUTF8Issues($data) { + if (is_string($data)) { + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } else if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = $this->fixUTF8Issues($value); + } + } + return $data; + } + + // Perbaiki masalah nilai Infinity atau NaN + private function fixInfNanIssues($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_float($value) && (is_nan($value) || is_infinite($value))) { + $data[$key] = (string)$value; // Konversi ke string + } else if (is_array($value)) { + $data[$key] = $this->fixInfNanIssues($value); + } + } + } + return $data; + } + + // Perbaiki masalah referensi recursif + private function fixRecursiveReferences($data, $depth = 0) { + // Batasi kedalaman rekursi untuk menghindari infinite loop + if ($depth > 50) { + return "[MAX_DEPTH_REACHED]"; + } + + if (is_array($data)) { + $result = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $result[$key] = $this->fixRecursiveReferences($value, $depth + 1); + } else { + $result[$key] = $value; + } + } + return $result; + } + + return $data; + } + + // Cari dan konversi numerik ke string secara rekursif + private function convertNumericValuesToStrings($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->convertNumericValuesToStrings($value); + } else if (is_numeric($value)) { + $data[$key] = (string)$value; + } else if (is_bool($value)) { + $data[$key] = $value ? "true" : "false"; + } + } + } + return $data; + } +} diff --git a/application/controllers/mockup/supplierpaymentv4/Bill.php b/application/controllers/mockup/supplierpaymentv4/Bill.php new file mode 100644 index 0000000..d00c9de --- /dev/null +++ b/application/controllers/mockup/supplierpaymentv4/Bill.php @@ -0,0 +1,257 @@ +db_onedev = $this->load->database("onedev", true); + } + + public function add_notes($orderid){ + $sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id, + SupplierPaymentID as note_id, + SupplierPaymentDetailSupplierInvoiceDetailID as detail_id, + SupplierPaymentDate as note_date, + SupplierPaymentNumber as note_number, + GROUP_CONCAT(DISTINCT coaDescription separator ' , ') as paymenttypes_name, + SUM(SupplierPaymentDetailAmount) as note_amount, + n.M_UserUsername as note_user, + SupplierPaymentDetailIsActive as note_active, + 'xxx' as tests, + 'N' as show_detail, + SupplierPaymentNote as keterangan, + SupplierPaymentCoaID, + coaID, + coaDescription, + SupplierPaymentIsConfirm, + CONCAT('Confirmed by : ',c.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentConfirmDate,'%d-%m-%Y %H:%i')) as d_confirm, + SupplierPaymentIsApproved, + CONCAT('Approved by : ',a.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentApprovedDate,'%d-%m-%Y %H:%i')) as d_approved, + CONCAT('Verified by : ',b.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentVerifDate,'%d-%m-%Y %H:%i')) as d_verif + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y' + LEFT JOIN coa ON SupplierPaymentCoaID = coaID + LEFT JOIN m_user n ON SupplierPaymentUserID = n.M_UserID + LEFT JOIN m_user c ON SupplierPaymentConfirmUserID = c.M_UserID + LEFT JOIN m_user a ON SupplierPaymentApprovedUserID = a.M_UserID + LEFT JOIN m_user b ON SupplierPaymentVerifUserID = b.M_UserID + WHERE + SupplierPaymentSupplierInvoiceID = {$orderid} + AND + SupplierPaymentIsActive = 'Y' + GROUP BY SupplierPaymentID"; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + if($rows){ + foreach($rows as $k => $v){ + $rows[$k]['tests'] = $this->add_tests($v['note_id']); + } + } + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } + } + public function add_tagihans($orderid){ + $sql = "SELECT SupplierInvoiceID as tagihan_id, + PurchaseOrderNumber as tagihan_number, + jurnalTxDescription as pasien, + jurnalTxCredit as tagihan_total, + IF(SupplierPaymentDetailID IS NULL , jurnalTxCredit, jurnalTxCredit - SUM(SupplierPaymentDetailAmount)) as tagihan_tagihan, + 0 as tagihan_bayar, + DATE_FORMAT(SupplierInvoiceDueDate,'%d-%m-%Y') as tagihan_duedate, + SupplierInvoiceIsActive as tagihan_active, + 'N' as show_detail, + jurnalTxID SupplierInvoiceDetailID, + PurchaseOrderID SupplierInvoiceDetailPurchaseOrderID + + FROM supplier_invoice + JOIN receive_order_po ON ReceiveOrderPoID = SupplierInvoiceReceiveOrderPoID + JOIN receive_order_po_detail ON ReceiveOrderPoDetailReceiveOrderPoID = ReceiveOrderPoID + JOIN purchase_order ON ReceiveOrderPoDetailPurchaseOrderID = PurchaseOrderID + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563 + LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierInvoiceIsActive = 'Y' + LEFT JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID AND SupplierPaymentDetailIsActive = 'Y' + WHERE + SupplierInvoiceID = {$orderid} + GROUP BY jurnalTxID + "; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } +} + public function add_tests($orderid){ + $sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id, + SupplierPaymentID as note_id, + SupplierPaymentDate as note_date, + SupplierPaymentNumber as note_number, + GROUP_CONCAT(coaDescription separator ' , ') as paymenttypes_name, + SUM(SupplierPaymentDetailAmount) as note_amount, + M_UserUsername as note_user, + SupplierPaymentDetailIsActive as note_active, + PurchaseOrderNumber, + SupplierInvoiceDetailTotal, + SupplierPaymentDetailAmount + FROM supplier_payment + JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID + LEFT JOIN supplier_invoice_detail ON SupplierPaymentDetailSupplierInvoiceDetailID = SupplierInvoiceDetailID + LEFT JOIN purchase_order ON SupplierInvoiceDetailPurchaseOrderID = PurchaseOrderID + LEFT JOIN coa ON SupplierPaymentCoaID = coaID + LEFT JOIN m_user ON SupplierPaymentDetailUserID = M_UserID + WHERE + SupplierPaymentID = {$orderid} + GROUP BY SupplierPaymentDetailID"; + $query = $this->db_onedev->query($sql); + if ($query) { + $rows = $query->result_array(); + if($rows){ + } + return $rows; + + } else { + $this->sys_error_db("get notes", $this->db_onedev); + exit; + } +} + public function search() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $supplier = $prm["supplier"]; + $search = $prm["search"]; + $status = $prm["status"]; + $startdate = $prm["startdate"]; + $enddate = $prm["enddate"]; + $regionalid = $this->sys_user['S_RegionalID']; + + $number_limit = 10; + $number_offset = ($prm['current_page'] - 1) * $number_limit ; + + $where = "SupplierInvoiceIsActive = 'Y' + AND SupplierInvoiceStatus = 'Approved' + AND SupplierInvoiceGrandTotal > 0 + AND IF(SupplierPaymentID IS NULL,'N','Y') = '{$status}' + AND (SupplierInvoiceNumber LIKE '%{$search}%' AND SupplierName LIKE '%{$supplier}%') + AND ReceiveOrderPoS_RegionalID = {$regionalid} + AND SupplierInvoiceDraftPaymentDate BETWEEN '{$startdate}' AND '{$enddate}'"; + + + + + $sql = " SELECT count(*) as total + FROM supplier_invoice + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + LEFT JOIN supplier_payment ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID AND SupplierPaymentIsActive = 'Y' + LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID + JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID + WHERE + $where + "; + // echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + + + $tot_count = 0; + $tot_page = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + $tot_page = ceil($tot_count/$number_limit); + } else { + $this->sys_error_db("supplier_invoice count", $this->db_onedev); + exit; + } + + + $sql = "SELECT supplier_invoice.*, + SupplierName, + '' M_MouName, + 0 as totalbill, + 0 as paid, + 0 as unpaid, + SupplierInvoiceIsLunas as flaglunas, + 0 as SupplierPaymentID, + '' as SupplierPaymentNumber, + 0 as SupplierPaymentAmount, + '' as SupplierPaymentDate, + '' as SupplierInvoiceIssueRefNumber, + '' as notes, + '' as tagihans, + 'N' as isbillterpusat, + DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar, + DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d%m%Y') as tanggalbayartext, + IF(SupplierPaymentID IS NULL,'N','Y') as status_invoice, + IFNULL(SupplierPaymentIsApproved,'N') as SupplierPaymentIsApproved, + IFNULL(SupplierPaymentIsVerif,'N') as SupplierPaymentIsVerif, + IFNULL(SupplierPaymentCashierNumber,'') SupplierPaymentCashierNumber + + FROM supplier_invoice + LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID + LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierPaymentIsActive = 'Y' + WHERE + $where + GROUP BY SupplierInvoiceID + ORDER BY SupplierInvoiceID ASC + limit $number_limit offset $number_offset"; + //echo $sql; + $query = $this->db_onedev->query($sql, $sql_param); + $rows = $query->result_array(); + if($rows){ + foreach($rows as $k => $v){ + $s_payment = $this->db_onedev->query("SELECT GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber, + SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount, + IFNULL(SupplierPaymentID,0) SupplierPaymentID, + GROUP_CONCAT(DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y') SEPARATOR ', ') as SupplierPaymentDate + FROM supplier_payment + WHERE SupplierPaymentIsActive = 'Y' AND SupplierPaymentSupplierInvoiceID = {$v['SupplierInvoiceID']}")->row(); + + $s_jurnal = $this->db_onedev->query("SELECT SUM(jurnalTxCredit) totalbill + FROM supplier_invoice + JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber + JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563 + WHERE SupplierInvoiceID = {$v['SupplierInvoiceID']} + GROUP BY SupplierInvoiceID")->row(); + $amount = $s_payment->SupplierPaymentAmount ? $s_payment->SupplierPaymentAmount : "0.00"; + $unpaid = (float)$s_jurnal->totalbill - (float)$amount; + $rows[$k]['SupplierPaymentID'] = $s_payment->SupplierPaymentID ? $s_payment->SupplierPaymentID : '0'; + $rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber ? $s_payment->SupplierPaymentNumber : ''; + $rows[$k]['SupplierPaymentAmount'] = $amount; + $rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate; + $rows[$k]['paid'] = $amount; + $rows[$k]['totalbill'] = $s_jurnal->totalbill ? $s_jurnal->totalbill : "0.00"; + $rows[$k]['unpaid'] = number_format($unpaid, 2, '.', ''); + + $rows[$k]['notes'] = $this->add_notes($v['SupplierInvoiceID']); + $rows[$k]['tagihans'] = $this->add_tagihans($v['SupplierInvoiceID']); + + } + } + + + $result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_onedev->last_query()); + $this->sys_ok($result); + exit; + } + + +} diff --git a/application/controllers/mockup/supplierpaymentv4/Payment.php b/application/controllers/mockup/supplierpaymentv4/Payment.php new file mode 100644 index 0000000..d9512dc --- /dev/null +++ b/application/controllers/mockup/supplierpaymentv4/Payment.php @@ -0,0 +1,982 @@ +db_onedev = $this->load->database("onedev", true); + } + + function lookup_type() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT coaID as id, + coaCode as code, + 'N' as chex, + coaDescription as chexlabel, + 'Jumlah' as leftlabel, + '' as selected_card, + '' as selected_edc, + '' as selected_account, + CASE + WHEN coaCode = 'CASH' THEN 'Kembali' + WHEN coaCode = 'DEBIT' THEN 'Nomor Kartu' + WHEN coaCode = 'CREDIT' THEN 'Nomor Kartu' + WHEN coaCode = 'TRANSFER' THEN 'No. Rekening' + ELSE 'Nomor Voucher' + END as rightlabel, + 0 as leftvalue, + 0 as rightvalue + FROM m_paymenttype WHERE coaIsActive = 'Y'"; + $rows = $this->db_onedev->query($query)->result_array(); + foreach($rows as $k => $v){ + $rows[$k]['selected_card'] = array('id'=>0,'name'=>''); + $rows[$k]['selected_edc'] = array('id'=>0,'name'=>''); + $rows[$k]['selected_account'] = array('id'=>0,'name'=>''); + if($v['chex'] == 'N') + $rows[$k]['chex'] = false; + else + $rows[$k]['chex'] = true; + } + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + function selectpaymenttypeold(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query ="SELECT * FROM m_paymenttype + WHERE + coaIsActive = 'Y'"; + //echo $query; + $rows['paymenttypes'] = $this->db_onedev->query($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 selectpaymenttype(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $regionalid = $this->sys_user['S_RegionalID']; + $prm = $this->sys_input; + $search = $prm["search"]; + $query ="SELECT coaID, +coaAccountNo, +coaDescription, +coaSubDescription +FROM coa +JOIN s_regional ON S_RegionalID = $regionalid +JOIN m_branch ON M_BranchS_RegionalID = S_RegionalID +JOIN map_bank_coa ON MapBank_CoaID = coaID AND MapBank_BranchCode = M_BranchCode +WHERE +coaIsActive = 'Y' AND +coaIsInput = 'Y' AND +coaAccountNo LIKE '111%' AND +coaAccountNo LIKE '11102%' AND +coaDescription LIKE '%{$search}%' + +UNION +SELECT coaID, +coaAccountNo, +coaDescription, +coaSubDescription +FROM coa +WHERE +coaIsActive = 'Y' AND +coaIsInput = 'Y' AND +coaAccountNo LIKE '111%' AND +coaAccountNo NOT LIKE '11102%' AND +coaDescription LIKE '%{$search}%' +ORDER BY coaAccountNo ASC"; + //echo $query; + $rows['paymenttypes'] = $this->db_onedev->query($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 selectbank(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" SELECT * + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankCode DESC + "; + //echo $query; + $rows['banks'] = $this->db_onedev->query($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 selectaccount(){ + + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" SELECT M_BankAccountID as M_BankAccountID, CONCAT(Nat_BankCode,' (',M_BankAccountNo,')') as M_BankAccountName + FROM m_bank_account + JOIN nat_bank ON M_BankAccountNat_BankID = Nat_BankID + WHERE + M_BankAccountIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + //echo $query; + $rows['accounts'] = $this->db_onedev->query($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 lookup_banks() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT Nat_BankID as id, Nat_BankCode as name + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + $rows = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + function lookup_accounts() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $query = "SELECT M_BankAccountID as id, CONCAT(Nat_BankCode,' (',M_BankAccountNo,')') as name + FROM m_bank_account + JOIN nat_bank ON M_BankAccountNat_BankID = Nat_BankID + WHERE + M_BankAccountIsActive = 'Y' + ORDER BY Nat_BankCode DESC"; + $rows = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + + + function searchcard(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + if($prm['search'] != ''){ + $sql = " + SELECT count(*) as total + FROM nat_bank + WHERE + Nat_BankName like ? + AND Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + else{ + $sql = " + SELECT count(*) as total + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_city count",$this->db_onedev); + exit; + } + if($prm['search'] != ''){ + $sql = " + SELECT Nat_BankID as id, Nat_BankName as name + FROM nat_bank + WHERE + Nat_BankName like ? + AND Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + else{ + $sql = " + SELECT Nat_BankID as id, Nat_BankName as name + FROM nat_bank + WHERE + Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName DESC + "; + } + + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_city rows",$this->db_onedev); + exit; + } + } + + + function pay() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $orderid = $prm['orderid']; + $payments = $prm['payments']; + //$xnumber = $this->db_onedev->query("SELECT `fn_numbering`('PAY') as numberx")->row()->numberx; + $sql = "INSERT INTO supplier_payment + (SupplierPaymentSupplierInvoiceID,SupplierPaymentDate,SupplierPaymentCreated,SupplierPaymentUserID) + VALUES (?,CURDATE(),NOW(),?)"; + $query = $this->db_onedev->query($sql, + array( + $orderid, $xuserid + ) + ); + + if (!$query) { + $this->sys_error_db("supplier_payment insert"); + exit; + } + $headerid = $this->db_onedev->insert_id(); + //echo $headerid; + + foreach($payments as $k => $v){ + if($v['chex']){ + $actual = 0; + $change = 0; + $amount = $v['leftvalue']; + if($v['code'] == 'CASH'){ + $actual = $v['leftvalue']; + $change = $v['rightvalue']; + if($actual > 0){ + $amount = intval($v['leftvalue']) - intval($v['rightvalue']); + } + else{ + $amount = $actual; + } + + $sql = "CALL `sp_bill_payment_add_cash`(".$orderid.",".$amount.",".$amount.",".$headerid.",".$v['id'].",".$xuserid.")"; + $query = $this->db_onedev->query($sql); + + if (!$query) { + $this->sys_error_db("supplier_payment_detail cash insert"); + exit; + } + + } + else{ + if(intval($v['leftvalue']) > 0){ + $actual = 0; + $change = 0; + $amount = $v['leftvalue']; + $selected_card = 0; + $selected_edc = 0; + $selected_account = 0; + if($v['code'] == 'DEBIT' || $v['code'] == 'CREDIT' || $v['code'] == 'TRANSFER'){ + $selected_card = $v['selected_card']['id']; + $selected_edc = $v['selected_edc']['id']; + $selected_account = $v['selected_account']['id']; + } + $sql = "CALL `sp_bill_payment_add_noncash`(".$orderid.",".$amount.",".$amount.",".$headerid.",".$v['id'].",".$xuserid.",".$selected_card.",".$selected_edc.",".$selected_account.")"; + //echo $sql; + + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if (!$query) { + $this->sys_error_db("supplier_payment_detail non cash insert"); + exit; + } + } + } + } + } + + $query = "SELECT coaID as id, + coaCode as code, + IF(coaCode = 'CASH','Y','N') as chex, + coaDescription as chexlabel, + 'Jumlah' as leftlabel, + CASE + WHEN coaCode = 'CASH' THEN 'Kembali' + WHEN coaCode = 'DEBIT' THEN 'Nomor Kartu' + WHEN coaCode = 'CREDIT' THEN 'Nomor Kartu' + WHEN coaCode = 'TRANSFER' THEN 'Nomor Rekening' + ELSE 'Nomor Voucher' + END as rightlabel, + 0 as leftvalue, + 0 as rightvalue + FROM m_paymenttype WHERE coaIsActive = 'Y'"; + $rows = $this->db_onedev->query($query)->result_array(); + + foreach($rows as $k => $v){ + if($v['chex'] == 'N') + $rows[$k]['chex'] = false; + else + $rows[$k]['chex'] = true; + } + $xdata = $this->db_onedev->query("SELECT SupplierPaymentID as idx, SupplierPaymentNumber as numberx FROM supplier_payment WHERE SupplierPaymentID = {$headerid}")->row(); + $result = array( + "total" => count($rows) , + "records" => array('types'=>$rows,'data'=>$xdata) + ); + $this->sys_ok($result); + exit; + } + function paymanual() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $orderid = $prm['orderid']; + $amount = $prm['amount']; + $paymenttype = $prm['paymenttype']; + $tanggalbayar = date('Y-m-d', strtotime($prm['tanggalbayar'])); + + $totalbill = $prm['totalbill']; + $paid = $prm['paid']; + + $keterangan = $prm['keterangan']; + $bills = $prm['bills']; + $xnumber = $this->db_onedev->query("SELECT `fn_numbering`('PINV') as numberx")->row()->numberx; + $sql = "INSERT INTO supplier_payment + (SupplierPaymentSupplierInvoiceID, + SupplierPaymentNumber, + SupplierPaymentDate, + SupplierPaymentAmount, + SupplierPaymentCoaID, + SupplierPaymentNote, + SupplierPaymentCreated, + SupplierPaymentUserID) + VALUES (?, + ?, + CURDATE(), + ?, + ?, + ?, + NOW(), + ?)"; + $query = $this->db_onedev->query($sql, + array( + $orderid, + $xnumber, + $amount, + $paymenttype, + $keterangan, + $xuserid + ) + ); + $headerid = $this->db_onedev->insert_id(); + if (!$query) { + $this->sys_error_db("supplier_payment insert"); + exit; + } else{ + $sqlbill = "UPDATE supplier_invoice SET + SupplierInvoiceDraftPaymentDate = '{$tanggalbayar}' + WHERE SupplierInvoiceID = $orderid"; + $querybill = $this->db_onedev->query($sqlbill); + + //echo $this->db_onedev->last_query(); + + } + + //echo $headerid; + + foreach($bills as $k => $v){ + if($v['tagihan_bayar'] > 0){ + $SupplierInvoiceDetailID = $v['SupplierInvoiceDetailID']; + $tagihan_bayar = $v['tagihan_bayar']; + $SupplierInvoiceDetailPurchaseOrderID = $v['SupplierInvoiceDetailPurchaseOrderID']; + $sql = "INSERT INTO supplier_payment_detail( + SupplierPaymentDetailSupplierPaymentID, + SupplierPaymentDetailSupplierInvoiceDetailID, + SupplierPaymentDetailAmount, + SupplierPaymentDetailUserID, + SupplierPaymentDetailCreated, + SupplierPaymentDetailLastUpdated) + VALUES( + $headerid, + $SupplierInvoiceDetailID, + $tagihan_bayar, + $xuserid, + now(), + now())"; + $query = $this->db_onedev->query($sql); + $billpaymentdetailid = $this->db_onedev->insert_id(); + if (!$query) { + $this->sys_error_db("supplier_payment_detail cash insert"); + exit; + }else{ + $sqlbilldetail = "UPDATE supplier_invoice_detail SET + SupplierInvoiceDetailUnpaid = SupplierInvoiceDetailUnpaid - $tagihan_bayar + WHERE SupplierInvoiceDetailID = $SupplierInvoiceDetailID"; + $querybilldetail = $this->db_onedev->query($sqlbilldetail); + + /* $sqlpayment = "INSERT INTO f_payment + (F_PaymentPurchaseOrderID, + F_PaymentDate, + F_PaymentTotal, + F_PaymentCreated, + F_PaymentLastUpdated, + F_PaymentM_UserID) + VALUES( + $SupplierInvoiceDetailPurchaseOrderID, + now(), + $tagihan_bayar, + now(), + now(), + $xuserid)"; + $querypayment = $this->db_onedev->query($sqlpayment); + $paymentid = $this->db_onedev->insert_id(); + $sqlpaymentdetail = "INSERT INTO f_paymentdetail + (F_PaymentDetailF_PaymentID, + F_PaymentDetailcoaID, + F_PaymentDetailAmount, + F_PaymentDetailActual, + F_PaymentDetailChange, + F_PaymentDetailEDCNat_BankID, + F_PaymentDetailCardNat_BankID, + F_PaymentDetailM_BankAccountID, + F_PaymentDetailCreated, + F_PaymentDetailLastUpdated, + F_PaymentDetailUserID) + VALUES( + $paymentid, + $paymenttype, + $tagihan_bayar, + $tagihan_bayar, + 0, + $edc, + $card, + $account, + now(), + now(), + $xuserid)"; + //echo $sqlpaymentdetail; + $querypaymentdetail = $this->db_onedev->query($sqlpaymentdetail); + + $sqleditbillpaymentdetail = "UPDATE supplier_payment_detail SET + SupplierPaymentDetailF_PaymentID = $paymentid + WHERE SupplierPaymentDetailID = $billpaymentdetailid"; + $queryeditbillpaymentdetail = $this->db_onedev->query($sqleditbillpaymentdetail); + + */ + } + + + } + } + $sql = "SELECT * FROM supplier_payment + JOIN m_user ON M_UserID = SupplierPaymentUserID + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $row = $query->row_array(); + + $sql = "SELECT * FROM supplier_payment_detail + WHERE SupplierPaymentDetailSupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $rows = $query->row_array(); + + $data = array("header" => $row, + "details" => $rows); + $message = "Nomor Pembayaran Faktur: " . $row["SupplierPaymentNumber"] ." berhasil dibuat oleh " . $row["M_UserUsername"]; + $this->insert_act_log("PF", "NEW", $message, $headerid, $this->safeJsonEncode($data), $xuserid); + + $xdata = $this->db_onedev->query("SELECT SupplierPaymentID as idx, SupplierPaymentNumber as numberx FROM supplier_payment WHERE SupplierPaymentID = {$headerid}")->row(); + $result = array( + "total" => count($rows) , + "records" => array('data'=>$xdata) + ); + $this->sys_ok($result); + exit; + } + function editpaymanual() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $orderid = $prm['orderid']; + $headerid = $prm['headerid']; + $tanggalbayar = date('Y-m-d', strtotime($prm['tanggalbayar'])); + $sqlbill = "UPDATE supplier_invoice SET + SupplierInvoiceDraftPaymentDate = '{$tanggalbayar}' + WHERE SupplierInvoiceID = $orderid"; + $querybill = $this->db_onedev->query($sqlbill); + + //echo $this->db_onedev->last_query(); + + + + $sql = "SELECT * FROM supplier_payment + JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID + JOIN m_user ON M_UserID = SupplierPaymentUserID + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $row = $query->row_array(); + + $sql = "SELECT * FROM supplier_payment_detail + WHERE SupplierPaymentDetailSupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $rows = $query->row_array(); + + $data = array("header" => $row, + "details" => $rows); + $message = "Nomor Pembayaran Faktur: " . $row["SupplierPaymentNumber"] ." berhasil diubah oleh " . $row["M_UserUsername"]; + $this->insert_act_log("PF", "NEW", $message, $headerid, $this->safeJsonEncode($data), $xuserid); + + $xdata = $this->db_onedev->query("SELECT SupplierPaymentID as idx, SupplierPaymentNumber as numberx FROM supplier_payment WHERE SupplierPaymentID = {$headerid}")->row(); + $result = array( + "total" => count($rows) , + "records" => array('data'=>$xdata) + ); + $this->sys_ok($result); + exit; + } + function delete_note() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $prmnota = $prm['nota']; + + $headerid = $prmnota['note_id']; + $sql = "SELECT * FROM supplier_payment + JOIN m_user ON M_UserID = SupplierPaymentUserID + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $row = $query->row_array(); + + $sql = "SELECT * FROM supplier_payment_detail + WHERE SupplierPaymentDetailSupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$headerid]); + $rows = $query->row_array(); + + $data = array("header" => $row, + "details" => $rows); + + $sql = "UPDATE supplier_payment + SET SupplierPaymentIsActive = 'N' + WHERE SupplierPaymentID = {$prmnota['note_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment delete"); + exit; + } + + $sql = "UPDATE supplier_payment_detail + SET SupplierPaymentDetailIsActive = 'N' + WHERE SupplierPaymentDetailSupplierPaymentID = {$prmnota['note_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment_detail delete"); + exit; + } + + $sql = "UPDATE supplier_invoice + SET SupplierInvoiceUnpaid = SupplierInvoiceUnpaid + CAST({$prmnota['note_amount']} AS UNSIGNED) + WHERE SupplierInvoiceID = {$prmnota['note_order_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_invoice delete"); + exit; + } + + $sql = "UPDATE supplier_invoice_detail + SET SupplierInvoiceDetailUnpaid = SupplierInvoiceDetailUnpaid + CAST({$prmnota['note_amount']} AS UNSIGNED) + WHERE SupplierInvoiceDetailID = {$prmnota['detail_id']}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_invoice_detail delete"); + exit; + } + + $message = "Nomor Pembayaran Faktur: " . $row["SupplierPaymentNumber"] ." telah dihapus oleh " . $row["M_UserUsername"]; + $this->insert_act_log("PF", "DELETE", $message, $headerid, $this->safeJsonEncode($data), $xuserid); + $result = array( + "total" => 1 , + "records" => array('prm'=>$prm) + ); + $this->sys_ok($result); + exit; + } + function edit_note() + { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $id = $prm['id']; + $inv_id = $prm['inv_id']; + $detail_id = $prm['detail_id']; + $paymenttype = $prm['paymenttype']; + $amount_old = $prm['amount_old']; + $amount_new = $prm['amount_new']; + $keterangan = $prm['keterangan']; + + $datas_log = []; + $messages_log = []; + + $sql = "SELECT * + FROM supplier_payment + WHERE SupplierPaymentID = ?"; + $query = $this->db_onedev->query($sql, [$id]); + if (!$query) { + $this->db_onedev->trans_rollback(); + $this->sys_error_db("supplier payment", $this->db_onedev); + exit; + } + $row = $query->row_array(); + + if($row["SupplierPaymentAmount"]!= $amount_new) { + $messages_log[] = "Perubahan pembayaran : " . $row["SupplierPaymentAmount"] . " menjadi " . $amount_new; + } + if($row["SupplierPaymentNote"]!= $keterangan) { + $messages_log[] = "Perubahan keterangan : " . $row["SupplierPaymentNote"] . " menjadi " . $keterangan; + } + if($row["SupplierPaymentCoaID"]!= $paymenttype) { + $messages_log[] = "Perubahan tipe pembayaran id : " . $row["SupplierPaymentCoaID"] . " menjadi " . $paymenttype; + } + + $datas_log['header'] = $row; + + $sql = "UPDATE supplier_payment SET + SupplierPaymentAmount = {$amount_new}, + SupplierPaymentNote = '{$keterangan}', + SupplierPaymentCoaID = {$paymenttype}, + SupplierPaymentUserID = {$xuserid} + WHERE SupplierPaymentID = {$id}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment edit"); + exit; + } + + $sql = "UPDATE supplier_payment_detail + SET SupplierPaymentDetailAmount = {$amount_new}, + SupplierPaymentDetailUserID = {$xuserid} + WHERE SupplierPaymentDetailSupplierPaymentID = {$id}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_payment_detail edit"); + exit; + } + + $sql = "UPDATE supplier_invoice + SET SupplierInvoiceUnpaid = (SupplierInvoiceUnpaid + $amount_old) - {$amount_new} + WHERE SupplierInvoiceID = {$inv_id}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_invoice edit"); + exit; + } + + $sql = "UPDATE supplier_invoice_detail + SET SupplierInvoiceDetailUnpaid = (SupplierInvoiceDetailUnpaid + $amount_old) - {$amount_new} + WHERE SupplierInvoiceDetailID = {$detail_id}"; + //echo $sql; + $query = $this->db_onedev->query($sql); + if (!$query) { + $this->sys_error_db("supplier_invoice_detail edit"); + exit; + } + if(count($messages_log) > 0) { + $message = "Perubahan Pembayaran Faktur: " . $row["SupplierPaymentNumber"] . "\n"; + $message .= implode("\n", $messages_log); + }else{ + $message = "Pembayaran Faktur: " . $row["SupplierPaymentNumber"] . " tanpa perubahan"; + } + + $datas_log = $this->convertNumericValuesToStrings($datas_log); + $this->insert_act_log("PF", "EDIT", $message, $id, $this->safeJsonEncode($datas_log), $xuserid); + $result = array( + "total" => 1 , + "records" => array('prm'=>$prm) + ); + $this->sys_ok($result); + exit; + } + function insert_act_log($code, $status, $description, $refId, $data, $userId) + { + $sql = "INSERT INTO user_activity( + UserActivityCode, + UserActivityStatus, + UserActivityDescription, + UserActivityRefID, + UserActivityData, + UserActivityUserID, + UserActivityCreated) + VALUES (?,?,?,?,?,?,?)"; + $query = $this->db_onedev->query($sql, [$code, $status, $description, $refId, $data, $userId, date("Y-m-d H:i:s")]); + if (!$query) { + $this->sys_error_db("user activity", $this->db_onedev); + exit; + } + } + private function safeJsonEncode($data) { + // Coba encode data ke JSON + $jsonData = json_encode($data); + + // Cek apakah terjadi error saat encode + if (json_last_error() !== JSON_ERROR_NONE) { + $errorMsg = json_last_error_msg(); + error_log("JSON encode error: " . $errorMsg); + + // Lakukan sanitasi dan perbaikan data + $fixedData = $this->fixJsonEncodeIssues($data, $errorMsg); + + // Coba encode lagi setelah diperbaiki + $jsonData = json_encode($fixedData); + + // Jika masih error, log dan kembalikan objek kosong + if (json_last_error() !== JSON_ERROR_NONE) { + error_log("Failed to fix JSON encode issues: " . json_last_error_msg()); + // Kembalikan objek kosong jika masih gagal + return '{}'; + } + } + + return $jsonData; + } + + // Fungsi untuk memperbaiki masalah encoding JSON + private function fixJsonEncodeIssues($data, $errorMsg) { + // Buat salinan data untuk dimodifikasi + $fixedData = $data; + + // Tangani berbagai jenis error + if (strpos($errorMsg, 'Malformed UTF-8') !== false) { + // Perbaiki masalah karakter UTF-8 + $fixedData = $this->fixUTF8Issues($fixedData); + } else if (strpos($errorMsg, 'Inf and NaN cannot be JSON encoded') !== false) { + // Perbaiki masalah nilai Infinity atau NaN + $fixedData = $this->fixInfNanIssues($fixedData); + } else { + // Konversi semua nilai numerik menjadi string untuk menghindari masalah presisi + $fixedData = $this->convertNumericValuesToStrings($fixedData); + + // Perbaiki masalah referensi recursif + $fixedData = $this->fixRecursiveReferences($fixedData); + } + + return $fixedData; + } + + // Perbaiki masalah karakter UTF-8 + private function fixUTF8Issues($data) { + if (is_string($data)) { + return mb_convert_encoding($data, 'UTF-8', 'UTF-8'); + } else if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = $this->fixUTF8Issues($value); + } + } + return $data; + } + + // Perbaiki masalah nilai Infinity atau NaN + private function fixInfNanIssues($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_float($value) && (is_nan($value) || is_infinite($value))) { + $data[$key] = (string)$value; // Konversi ke string + } else if (is_array($value)) { + $data[$key] = $this->fixInfNanIssues($value); + } + } + } + return $data; + } + + // Perbaiki masalah referensi recursif + private function fixRecursiveReferences($data, $depth = 0) { + // Batasi kedalaman rekursi untuk menghindari infinite loop + if ($depth > 50) { + return "[MAX_DEPTH_REACHED]"; + } + + if (is_array($data)) { + $result = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $result[$key] = $this->fixRecursiveReferences($value, $depth + 1); + } else { + $result[$key] = $value; + } + } + return $result; + } + + return $data; + } + + // Cari dan konversi numerik ke string secara rekursif + private function convertNumericValuesToStrings($data) { + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->convertNumericValuesToStrings($value); + } else if (is_numeric($value)) { + $data[$key] = (string)$value; + } else if (is_bool($value)) { + $data[$key] = $value ? "true" : "false"; + } + } + } + return $data; + } +} diff --git a/application/controllers/mockup/usergroup/Usergroupv6.php b/application/controllers/mockup/usergroup/Usergroupv6.php new file mode 100644 index 0000000..28cdf76 --- /dev/null +++ b/application/controllers/mockup/usergroup/Usergroupv6.php @@ -0,0 +1,1014 @@ +db_onedev = $this->load->database("onedev", true); + } + + + function lookupuser() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $sql = "select M_UserID as id, + M_UserM_UserGroupID as usergroupid, + + M_UserUsername as username, + IF(M_StaffIsActive = 'N','',M_StaffName) as staffname, + M_UserM_StaffID as xstaff, + M_UserS_RegionalID as xregional, + S_RegionalName, + M_UserM_ApproveLevelID as xapprovelevelid, + IFNULL(M_ApproveLevelName, '-') as xapprovelevelname, + M_UserDivisionID as xuserdivisonid, + DivisionID as xdivisonid, + IFNULL(DivisionCode, '-') as xuserdivisioncode, + IFNULL(DivisionName, '-') as xuserdivisionname, + M_UserM_BranchID as xbranch, + M_BranchName, + M_UserLocationFlag, + CASE + WHEN M_UserLocationFlag = 'R' THEN 'REGIONAL' + WHEN M_UserLocationFlag = 'B' THEN 'CABANG' + ELSE 'Unknown' + END as M_UserLocationFlagName, + M_UserDefaultT_SampleStationID as xsamplestation, + M_UserIsCoordinator as iscoordinator, + M_UserR_ReportGroupID as xreport, + R_ReportGroupName, + 'xxx' as action + from m_user + join m_staff oN M_UserM_StaffID = M_StaffID + AND M_UserIsActive = 'Y' + AND M_UserM_UserGroupID = {$id} + left join m_userlocation on M_UserLocationM_UserID = M_UserID + and M_UserLocationIsActive = 'Y' + left join r_reportgroup on M_UserR_ReportGroupID = R_ReportGroupID + left join s_regional on M_UserS_RegionalID = S_RegionalID + left join m_branch on M_UserM_BranchID = M_BranchID + left join m_approve_level ON M_UserM_ApproveLevelID = M_ApproveLevelID + AND M_ApproveLevelIsActive = 'Y' + left join m_userdivision ON M_UserID = M_UserDivisionM_UserID + AND M_UserDivisionIsActive = 'Y' + left join division on M_UserDivisionDivisionID = DivisionID + AND DivisionIsActive = 'Y' + "; + //echo $sql; + $rows = $this->db_onedev->query($sql)->result(); + + $result = array("total" => count($rows), "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function lookup() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm['search']; + $all = $prm['all']; + $limit = ''; + if ($all == 'N') { + $limit = ' LIMIT 10'; + } + $sql = "select COUNT(*) as total + from m_usergroup + where + M_UserGroupIsActive = 'Y'"; + $sql_param = array($search); + $total = $this->db_onedev->query($sql, $sql_param)->row()->total; + + + $sql = "select M_UserGroupID as id, M_UserGroupDashboard as dashboard, + M_UserGroupName as name, M_UserGroupIsClinic as clinic, M_UserGroupName as description , 'xxx' as usergrouptype + from m_usergroup + where + M_UserGroupName LIKE CONCAT('%','{$search}','%') AND + M_UserGroupIsActive = 'Y' $limit"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + } else { + $this->sys_error_db("m_usergroup select", $this->db_onedev); + exit; + } + + + $result = array("total" => $total, "total_filter" => count($rows), "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + public function getdashboards() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $group_id = $prm['group_id']; + + $sql = "select menu.S_MenuID as id, CONCAT(menu.S_MenuName,' [ ',menuparent.S_MenuName,' ]') as name, CONCAT('one-ui/',menu.S_MenuUrl) as url, menuparent.S_MenuName as group_name + FROM s_menu menu + LEFT JOIN s_menu menuparent ON menu.S_MenuParentS_MenuID = menuparent.S_MenuID + WHERE + menu.S_MenuUrl <> '#' AND menu.S_MenuIsActive = 'Y'"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + } else { + $this->sys_error_db("m_usergroup select", $this->db_onedev); + exit; + } + + + $result = array("total" => $total, "total_filter" => count($rows), "records" => $rows); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + public function addnewusergroup() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + + $name_usergroup = $prm['name']; + $dashboard_usergroup = $prm['dashboard']; + $clinic_usergroup = $prm['clinic']; + + + $query = "SELECT COUNT(*) as exist FROM m_usergroup WHERE M_UserGroupIsActive = 'Y' AND M_UserGroupName = '{$name_usergroup}'"; + $exist_name = $this->db_onedev->query($query)->row()->exist; + + + //echo $exist_name; + if ($exist_name == 0) { + $sql = "insert into m_usergroup( + M_UserGroupName, + M_UserGroupDashboard, + M_UserGroupIsClinic, + M_UserGroupCreated, + M_UserGroupLastUpdated + ) + values( ?, ?, ?,now(), now())"; + $query = $this->db_onedev->query( + $sql, + array( + $name_usergroup, + $dashboard_usergroup, + $clinic_usergroup + ) + ); + //echo $query; + if (!$query) { + $this->sys_error_db("m_usergroup insert"); + exit; + } + + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + + if ($exist_name != 0) { + array_push($errors, array('field' => 'name', 'msg' => 'Nama sudah ada yang pakai dong')); + } + + $result = array("total" => -1, "errors" => $errors, "records" => 0); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function editusergroup() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $id_usergroup = $prm['id']; + $name_usergroup = $prm['name']; + $dashboard_usergroup = $prm['dashboard']; + $clinic_usergroup = $prm['clinic']; + + $query = "SELECT COUNT(*) as exist FROM m_usergroup WHERE M_UserGroupIsActive = 'Y' AND M_UserGroupName = '{$name_usergroup}' + AND M_UserGroupID <> {$id_usergroup} "; + $exist_name = $this->db_onedev->query($query)->row()->exist; + + + if ($exist_name == 0) { + + $sql = "update m_usergroup SET + M_UserGroupName = ?, + M_UserGroupDashboard = ?, + M_UserGroupIsClinic = ?, + M_UserGroupLastUpdated = now() + where + M_UserGroupID = ? +"; + $query = $this->db_onedev->query( + $sql, + array( + $name_usergroup, + $dashboard_usergroup, + $clinic_usergroup, + $id_usergroup + ) + ); + //file_put_contents("/tmp/adi-update-user.sql",$this->db_onedev->last_query()); + //echo $query; + if (!$query) { + $this->sys_error_db("m_usergroup update"); + exit; + } + + $result = array("total" => 1, "records" => array("xid" => $id_usergroup)); + $this->sys_ok($result); + } else { + $errors = array(); + + + if ($exist_name != 0) { + array_push($errors, array('field' => 'name', 'msg' => 'Nama sudah ada yang pakai dong')); + } + + $result = array("total" => -1, "errors" => $errors, "records" => 0); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function getreportsample() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query = " SELECT * + FROM r_reportgroup + WHERE + R_ReportGroupIsActive = 'Y' +"; + //echo $query; + $rows['reports'] = $this->db_onedev->query($query)->result_array(); + + // $query =" SELECT * + // FROM t_samplestation + // WHERE + // T_SampleStationIsActive = 'Y' + // "; + // //echo $query; + // $rows['samplestations'] = $this->db_onedev->query($query)->result_array(); + $query = " SELECT * + FROM s_regional + WHERE + S_RegionalIsActive = 'Y' + "; + //echo $query; + $rows['regionals'] = $this->db_onedev->query($query)->result_array(); + + $query = " SELECT * + FROM m_branch + WHERE + M_BranchIsActive = 'Y' + "; + //echo $query; + $rows['branches'] = $this->db_onedev->query($query)->result_array(); + + + $query = " SELECT * + FROM m_usergroup + WHERE + M_UserGroupIsActive = 'Y' +"; + //echo $query; + $rows['usergroupnames'] = $this->db_onedev->query($query)->result_array(); + + $query = " SELECT * + FROM m_staff + WHERE + M_StaffIsActive = 'Y' +"; + //echo $query; + $rows['staffs'] = $this->db_onedev->query($query)->result_array(); + + + $result = array( + "total" => count($rows), + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + + public function edituser() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $xuserid = $this->sys_user['M_UserID']; + $userid = $prm['xid']; + $username = $prm['username']; + + $password = $prm['password']; + $md5_password = md5($this->one_salt . $prm["password"] . $this->one_salt); + $xstaff = $prm['xstaff']; + $xregional = $prm['xregional']; + $xuserdivision = isset($prm['xuserdivision']) ? (int) $prm['xuserdivision'] : 0; + $xdivision = isset($prm['xdivision']) ? (int) $prm['xdivision'] : 0; + $xbranch = isset($prm['xbranch']) ? (int) $prm['xbranch'] : 0; + $xapprovelevel = isset($prm['xapprovelevel']) ? (int) $prm['xapprovelevel'] : 0; + $xuserlocationflag = $prm['userlocationflag']; + $xsamplestation = $prm['xsamplestation']; + $xreport = $prm['xreport']; + $xusergroupname = $prm['xusergroupname']; + $iscoordinator = $prm['iscoordinator']; + + + $query = "SELECT COUNT(*) as exist FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserUsername = '{$username}' + and M_UserID <> $userid "; + $exist_username = $this->db_onedev->query($query)->row()->exist; + + if ($exist_username == 0) { + + $sql = "update m_user SET + M_UserUsername = ?, + M_UserM_BranchID = ?, + M_UserS_RegionalID = ?, + M_UserM_ApproveLevelID = ?, + + M_UserM_StaffID = ?, + M_UserDefaultT_SampleStationID = ?, + M_UserR_ReportGroupID = ?, + M_UserM_UserGroupID = ?, + M_UserIsCoordinator = ?, + M_UserLastUpdated = now() + where M_UserID = ? "; + + $query = $this->db_onedev->query( + $sql, + array( + $username, + + $xbranch, + $xregional, + $xapprovelevel, + + $xstaff["M_StaffID"], + $xsamplestation["T_SampleStationID"], + $xreport["R_ReportGroupID"], + $xusergroupname["M_UserGroupID"], + $iscoordinator, + $userid + ) + ); + if (!$query) { + $this->sys_error_db("m_user update", $this->db_onedev); + exit; + } + + $sql = "update m_userlocation SET + M_UserLocationFlag = ?, + M_UserLocationS_RegionalID = ?, + M_UserLocationM_BranchID = ?, + + M_UserLocationLastUpdatedUserID = now() + where M_UserLocationM_UserID = ?"; + + $query = $this->db_onedev->query( + $sql, + array( + $xuserlocationflag, + + $xregional, + $xbranch, + + $userid, + ) + ); + if (!$query) { + $this->sys_error_db("m_userlocation update", $this->db_onedev); + exit; + } + + $sql_searchdivision = "SELECT M_UserDivisionID FROM m_userdivision + WHERE M_UserDivisionM_UserID = ? + AND M_UserDivisionIsActive = 'Y'"; + $query = $this->db_onedev->query( + $sql_searchdivision, + array( + $userid, + ) + ); + if (!$query) { + $this->sys_error_db("m_userdivision search", $this->db_onedev); + exit; + } + + $row = $query->row(); + $M_UserDivisionID = $row->M_UserDivisionID ?? 0; + + if ($M_UserDivisionID == 0) { + $sql_insert = "INSERT INTO m_userdivision ( + M_UserDivisionM_UserID, + M_UserDivisionDivisionID, + M_UserDivisionCreatedUserID, + M_UserDivisionLastUpdatedUserID, + M_UserDivisionCreated, + M_UserDivisionLastUpdated + + ) + values( ?,?,?,?,now(),now())"; + + $query = $this->db_onedev->query( + $sql_insert, + array( + $userid, + $xdivision, + $xuserid, + $xuserid, + ) + ); + if (!$query) { + $this->sys_error_db("m_userdivision insert", $this->db_onedev); + exit; + } + // $last_inserted_id = $this->db_onedev->insert_id(); + }else{ + $sql = "update m_userdivision SET + M_UserDivisionDivisionID = ?, + M_UserDivisionLastUpdatedUserID = ?, + M_UserDivisionLastUpdated = now() + + where M_UserDivisionID = ? + and M_UserDivisionIsActive = 'Y'"; + + $query = $this->db_onedev->query( + $sql, + array( + $xdivision, + $xuserid, + $M_UserDivisionID + ) + ); + if (!$query) { + $this->sys_error_db("m_userdivision update", $this->db_onedev); + exit; + } + } + $result = array("total" => 1, "records" => array("xid" => $userid)); + $this->sys_ok($result); + } else { + $errors = array(); + + + $result = array("total" => -1, "errors" => $errors, "records" => 0); + $this->sys_ok($result); + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function addnewuser() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $xuserid = $this->sys_user['M_UserID']; + $prm = $this->sys_input; + $usergroupid = $prm['usergroupid']; + $username = $prm['username']; + + $password = $prm['password']; + $md5_password = md5($this->one_salt . $prm["password"] . $this->one_salt); + $xregional = $prm['xregional']; + $xbranch = 0; + if ($prm['xbranch']) { + $xbranch = $prm['xbranch']; + } + $xapprovelevel = 0; + if ($prm['xapprovelevel']) { + $xapprovelevel = $prm['xapprovelevel']; + } + ; + $xdivision = 0; + if ($prm['xdivision']) { + $xdivision = $prm['xdivision']; + } + ; + $userlocationflag = $prm['userlocationflag']; + $xstaff = $prm['xstaff']; + $xsamplestation = $prm['xsamplestation']; + $xreport = $prm['xreport']; + $iscoordinator = $prm['iscoordinator']; + + + if ($prm['xid'] == 0) { + $query = "SELECT COUNT(*) as exist FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserUsername = '{$username}'"; + $exist_username = $this->db_onedev->query($query)->row()->exist; + + if ($exist_username == 0) { + $sql = "insert into m_user( + M_UserM_UserGroupID, + M_UserUsername, + + M_UserS_RegionalID, + M_UserM_BranchID, + M_UserM_ApproveLevelID, + + M_UserPassword, + M_UserM_StaffID, + M_UserDefaultT_SampleStationID, + M_UserR_ReportGroupID, + M_UserIsCoordinator, + M_UserCreated, + M_UserLastUpdated + ) + values( ?,?,?,?,?,?,?,?,?,?,now(),now())"; + $query = $this->db_onedev->query( + $sql, + array( + $usergroupid, + $username, + + $xregional, + $xbranch, + $xapprovelevel, + + $md5_password, + $xstaff["M_StaffID"], + $xsamplestation["T_SampleStationID"], + $xreport["R_ReportGroupID"], + $iscoordinator + ) + ); + if (!$query) { + $this->sys_error_db("m_user insert", $this->db_onedev); + exit; + } + $last_inserted_id = $this->db_onedev->insert_id(); + + $sql = "insert into m_userlocation( + M_UserLocationM_UserID, + M_UserLocationFlag, + M_UserLocationS_RegionalID, + M_UserLocationM_BranchID, + M_UserLocationCreatedUserID, + M_UserLocationCreated, + M_UserLocationLastUpdated, + M_UserLocationLastUpdatedUserID + ) + values( ?,?,?,?,?,now(),now(),now())"; + $query = $this->db_onedev->query( + $sql, + array( + $last_inserted_id, + $userlocationflag, + $xregional, + $xbranch, + $xuserid + ) + ); + if (!$query) { + $this->sys_error_db("m_user insert", $this->db_onedev); + exit; + } + + $sql = "insert into m_userdivision( + M_UserDivisionM_UserID, + M_UserDivisionDivisionID, + M_UserDivisionCreatedUserID, + M_UserDivisionLastUpdatedUserID, + M_UserDivisionCreated, + M_UserDivisionLastUpdated + + ) + values( ?,?,?,?,now(),now())"; + $query = $this->db_onedev->query( + $sql, + array( + $last_inserted_id, + $xdivision, + $xuserid, + $xuserid, + ) + ); + if (!$query) { + $this->sys_error_db("m_userdivision insert", $this->db_onedev); + exit; + } + + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + if ($exist_username != 0) { + array_push($errors, array('field' => 'username', 'msg' => 'Nama User sudah ada yang pakai dong')); + } + + + $result = array("total" => -1, "errors" => $errors, "records" => 0); + $this->sys_ok($result); + } + } else { + $query = "SELECT COUNT(*) as exist FROM m_user WHERE M_UserIsActive = 'Y' AND M_UserUsername = '{$username}' AND M_UserID <> {$prm['xid']}"; + $exist_username = $this->db_onedev->query($query)->row()->exist; + //echo $query; + + //echo $query; + if ($exist_username == 0) { + $sql = "UPDATE m_user SET M_UserUsername = '{$username}', M_UserPassword = '{$password}', M_UserM_StaffID = '{$xstaff}', M_UserR_ReportGroupID = '{$xreport}', M_UserDefaultT_SampleStationID = '{$xsamplestation}', M_UserIsCoordinator = '{$iscoordinator}' WHERE M_UserID = '{$prm['xid']}'"; + //echo $sql; + $query = $this->db_onedev->query($sql); + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } else { + $errors = array(); + if ($exist_username != 0) { + array_push($errors, array('field' => 'username', 'msg' => 'Username sudah ada yang pakai dong')); + } + + $result = array("total" => -1, "errors" => $errors, "records" => 0); + $this->sys_ok($result); + } + } + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function generate_string($input, $strength = 4) + { + $input_length = strlen($input); + $random_string = ''; + for ($i = 0; $i < $strength; $i++) { + $random_character = $input[mt_rand(0, $input_length - 1)]; + $random_string .= $random_character; + } + + return $random_string; + } + + function reset_password() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $userid = $this->sys_user["M_UserID"]; + $permitted_chars = 'wertyuioplkjhgfdsazxcvbnm0123456789'; + $new_password = $this->generate_string($permitted_chars, 9); + $md5_password = md5($this->one_salt . $new_password . $this->one_salt); + //echo $new_password; + $sql = "UPDATE m_user SET M_UserPassword = '{$md5_password}', M_UserLastUpdated = NOW(), M_UserM_UserID = {$userid} WHERE M_UserID = {$id}"; + //echo $sql; + $rows = $this->db_onedev->query($sql); + + $sql = "SELECT * FROM m_user WHERE M_UserID = {$id}"; + $data_user = $this->db_onedev->query($sql)->row_array(); + $data_log = array( + "user_id" => $id, + "old_password" => $data_user['M_UserPassword'], + "new_password" => $md5_password, + "new_password_show" => $new_password, + "reason" => $prm['reason'] + ); + $data_log = json_encode($data_log); + $sql = "INSERT INTO log_user ( + Log_UserDatetime, + Log_UserCode, + Log_UserXID, + Log_UserJson, + Log_UserM_UserID + ) + VALUES( + NOW(), + 'RESETPWD', + {$id}, + '{$data_log}', + {$userid} + )"; + $this->db_onedev->query($sql); + $result = array("password" => $new_password); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + + + public function deleteuser() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $sql = "update m_user SET + M_UserUsername = CONCAT(M_UserUsername,'-DELETED'), + M_UserIsActive = 'N', + M_UserPassword = '1234567890XD3L3T3US312', + M_UserActiveToken = NULL, + M_UserIsLoggedIn = 'N', + M_UserLastUpdated = now() + WHERE + M_UserID = ? + +"; + + $query = $this->db_onedev->query( + $sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_user delete"); + exit; + } + + $sql = "update m_userdivision SET + M_UserDivisionIsActive = 'N', + M_UserDivisionDeletedUserID = ?, + M_UserDivisionDeleted = NOW(), + M_UserDivisionLastUpdated = NOW() + WHERE + M_UserDivisionM_UserID = ? + AND M_UserDivisionIsActive ='Y' + +"; + + $query = $this->db_onedev->query( + $sql, + array( + $userid, + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_userdivision delete"); + exit; + } + + + + + + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + public function deleteusergroup() + { + try { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + + $sql = "update m_usergroup SET + M_UserGroupIsActive = 'N', + M_UserGroupLastUpdated = now() + WHERE + M_UserGroupID = ? + +"; + + $query = $this->db_onedev->query( + $sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_usergroup delete"); + exit; + } + + $sql = "UPDATE m_user SET + M_UserIsActive = 'N', + M_UserLastUpdated = now() + WHERE + M_UserM_UserGroupID = ? +"; + + $query = $this->db_onedev->query( + $sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_user delete"); + exit; + } + + $result = array("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } catch (Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function search_regional() + { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $tot_count = 0; + $search = $prm['search']; + + $sql = " SELECT * + FROM s_regional + WHERE S_RegionalIsActive = 'Y' + AND S_RegionalName LIKE '%{$search}%'"; + + $query = $this->db_onedev->query($sql); + + if ($query) { + $rows = $query->result_array(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } else { + $this->sys_error_db("regional rows", $this->db_onedev); + exit; + } + } + + function search_branch() + { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $tot_count = 0; + $search = $prm['search']; + $regionalid = $prm['regionalid']; + + $sql = "SELECT * + FROM m_branch + WHERE M_BranchIsActive = 'Y' + AND M_BranchS_RegionalID = '{$regionalid}'"; + + $query = $this->db_onedev->query($sql); + + if ($query) { + $rows = $query->result_array(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } else { + $this->sys_error_db("branch rows", $this->db_onedev); + exit; + } + } + + function search_approvelevel() + { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT M_ApproveLevelID, M_ApproveLevelName + FROM m_approve_level + WHERE M_ApproveLevelIsActive = 'Y'"; + + $query = $this->db_onedev->query($sql); + + if ($query) { + $rows = $query->result_array(); + $result = array("total" => sizeof($rows), "records" => $rows); + $this->sys_ok($result); + } else { + $this->sys_error_db("aprrove level rows", $this->db_onedev); + exit; + } + } + function getdivision() + { + //# cek token valid + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $sql = "SELECT DivisionID, DivisionCode, DivisionName + FROM division + WHERE DivisionIsActive = 'Y'"; + + $query = $this->db_onedev->query($sql); + + if ($query) { + $rows = $query->result_array(); + $result = array("total" => sizeof($rows), "records" => $rows); + $this->sys_ok($result); + } else { + $this->sys_error_db("division rows", $this->db_onedev); + exit; + } + } +} diff --git a/application/controllers/v1/report-usergroup/Usergroup.php b/application/controllers/v1/report-usergroup/Usergroup.php new file mode 100644 index 0000000..d5428a8 --- /dev/null +++ b/application/controllers/v1/report-usergroup/Usergroup.php @@ -0,0 +1,650 @@ +db_onedev = $this->load->database("onedev", true); + } + + function lookupuserbyname(){ + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $groupname = $prm['groupname']; + $filter = ''; + if(isset($sexid)){ + $filter .= "AND ($sexid = 0 or ($sexid > 0 and Nat_SexID = $sexid)) "; + } + if(isset($flagid)){ + $filter .= "AND ($flagid = 0 or ($flagid > 0 and Nat_FlagID = $flagid))"; + } + $limit = ''; + if($all == 'N'){ + $limit = ' LIMIT 10'; + } + $number_limit = 10; + $number_offset = ($prm['current_page'] - 1) * $number_limit ; + $sql = "select COUNT(*) as total + FROM(SELECT * + from m_usergroup + WHERE + M_UserGroupIsActive = 'Y' AND + M_UserGroupName like '%{$groupname}%' + $filter GROUP BY M_UserGroupID) a"; + // $total = $this->db_onedev->query($sql,$sql_param)->row()->total; + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + $tot_count = 0; + $tot_page = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + $tot_page = ceil($tot_count/$number_limit); + } else { + $this->sys_error_db("m_usergroup count", $this->db_onedev); + exit; + } + + $sql = "SELECT m_usergroup.*, + M_UserGroupID as id, + M_UserGroupID, + M_UserGroupName +FROM m_usergroup +WHERE +M_UserGroupIsActive = 'Y' AND +M_UserGroupName like '%{$groupname}%' +$filter + GROUP BY M_UserGroupID + ORDER BY M_UserGroupName ASC + limit $number_limit offset $number_offset"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + // echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + + + } else { + $this->sys_error_db("m_usergroup select"); + exit; + } + + $result = array ("total" => $tot_page, "total_filter"=>count($rows),"records" => $rows); + $this->sys_ok($result); + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function lookupreportbyid(){ + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $id = $prm['id']; + $reportgroup = $prm['reportgroup']; + $reportcode = $prm['reportcode']; + $reportname = $prm['reportname']; + $status = $prm['status']; + $all = $prm['all']; + $filter = ''; + if($status != 'A'){ + $filter .= "AND status = '{$status}' "; + }else{ + $filter .= ""; + } + $limit = ''; + if($all == 'N'){ + $limit = ' LIMIT 10'; + } + $number_limit = 10; + $number_offset = ($prm['current_page'] - 1) * $number_limit ; + $sql = "select COUNT(*) as total + FROM(SELECT *, IF(IFNULL(UserGroupReportID,0) > 0 , 'Y', 'N') as status + from r_report + LEFT JOIN usergroup_report ON R_ReportID = UserGroupReportR_ReportID AND UserGroupReportM_UserGroupID = $id AND UserGroupReportIsActive = 'Y' + LEFT JOIN m_usergroup ON UserGroupReportM_UserGroupID = M_UserGroupID AND M_UserGroupIsActive = 'Y' + LEFT JOIN r_reportgroup ON R_ReportR_ReportGroupID = R_ReportGroupID + WHERE + R_ReportIsActive = 'Y') a + WHERE + R_ReportGroupName like '%{$reportgroup}%' AND + R_ReportCode like '%{$reportcode}%' AND + R_ReportName like '%{$reportname}%' $filter"; + // $total = $this->db_onedev->query($sql,$sql_param)->row()->total; + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + $tot_count = 0; + $tot_page = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + $tot_page = ceil($tot_count/$number_limit); + } else { + $this->sys_error_db("r_report count", $this->db_onedev); + exit; + } + + $sql = "SELECT * FROM(select R_ReportID as id, + R_ReportID, + R_ReportCode, + R_ReportName, + R_ReportGroupName, + UserGroupReportID, + UserGroupReportM_UserGroupID, + UserGroupReportR_ReportID, + IF(IFNULL(UserGroupReportID,0) > 0 , 'Y', 'N') as status + from r_report + LEFT JOIN usergroup_report ON R_ReportID = UserGroupReportR_ReportID AND UserGroupReportM_UserGroupID = $id AND UserGroupReportIsActive = 'Y' + LEFT JOIN m_usergroup ON UserGroupReportM_UserGroupID = M_UserGroupID AND M_UserGroupIsActive = 'Y' + LEFT JOIN r_reportgroup ON R_ReportR_ReportGroupID = R_ReportGroupID + WHERE + R_ReportIsActive = 'Y') a + WHERE + R_ReportGroupName like '%{$reportgroup}%' AND + R_ReportCode like '%{$reportcode}%' AND + R_ReportName like '%{$reportname}%' $filter + GROUP BY R_ReportID + ORDER BY R_ReportGroupName ASC, R_ReportName ASC + limit $number_limit offset $number_offset"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + + + } else { + $this->sys_error_db("r_report select"); + exit; + } + + $result = array ("total" => $tot_page, "total_filter"=>count($rows),"records" => $rows); + $this->sys_ok($result); + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function getsexreg(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + $query =" + SELECT 'A' as M_StatusID, 'Semua' as M_StatusName + UNION + SELECT 'Y' as M_StatusID, 'Terpilih' as M_StatusName + UNION + SELECT 'N' as M_StatusID, 'Belum Terpilih' as M_StatusName + "; + //echo $query; + $rows['f_statuss'] = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + function getstatus(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $rows = []; + + $query =" + SELECT 'A' as M_StatusID, 'Semua' as M_StatusName + UNION + SELECT 'Y' as M_StatusID, 'Terpilih' as M_StatusName + UNION + SELECT 'N' as M_StatusID, 'Belum Terpilih' as M_StatusName + "; + //echo $query; + $rows['f_statuss'] = $this->db_onedev->query($query)->result_array(); + + $result = array( + "total" => count($rows) , + "records" => $rows, + ); + $this->sys_ok($result); + exit; + } + public function addnewreport() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $userid = $prm['userid']; + $reportcode = $prm['reportcode']; + $reportname = $prm['reportname']; + $userid = $this->sys_user["M_UserID"]; + + $sql = "insert into r_report( + R_ReportCode, + R_ReportName, + R_ReportUserID, + R_ReportCreated, + R_ReportLastUpdated + ) + values(?,?,?,now(),now())"; + $query = $this->db_onedev->query($sql, + array( + $reportcode, + $reportname, + $userid + ) + ); + if (!$query) { + $this->sys_error_db("m_usergroup insert",$this->db_onedev); + exit; + } + $last_id = $this->db_onedev->insert_id(); + $result = array ("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + + + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function saveaddeditreport() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $usergroupid = $prm['userid']; + $reportid = $prm['R_ReportID']; + $reportuserid = $prm['UserGroupReportID']; + $status = $prm['status']; + $userid = $this->sys_user["M_UserID"]; + if($status == 'Y'){ + $sql = "insert into usergroup_report( + UserGroupReportM_UserGroupID, + UserGroupReportR_ReportID, + UserGroupUserID, + UserGroupReportCreated, + UserGroupReportLastUpdated + ) + values(?,?,?,now(),now())"; + $query = $this->db_onedev->query($sql, + array( + $usergroupid, + $reportid, + $userid + ) + ); + if (!$query) { + $this->sys_error_db("usergroup_report insert",$this->db_onedev); + exit; + } + $last_id = $this->db_onedev->insert_id(); + $result = array ("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + + }else{ + $sql = "UPDATE usergroup_report SET + UserGroupReportIsActive = 'N', + UserGroupUserID = ?, + UserGroupReportCreated = now(), + UserGroupReportLastUpdated = now() + WHERE UserGroupReportID = ?"; + $query = $this->db_onedev->query($sql, + array( + $userid, + $reportuserid + ) + ); + if (!$query) { + $this->sys_error_db("usergroup_report insert",$this->db_onedev); + exit; + } + $last_id = $this->db_onedev->insert_id(); + $result = array ("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + } + + + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function saveallreport(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $details = $prm['details']; + $userid = $this->sys_user["M_UserID"]; + foreach($details as $k => $v){ + $query = "UPDATE usergroup_report SET + UserGroupReportM_UserGroupID = '{$v['UserGroupReportM_UserGroupID']}', + UserGroupReportAdviceIna = '{$v['UserGroupReportAdviceIna']}', + UserGroupReportAdviceEng = '{$v['UserGroupReportAdviceEng']}', + UserGroupReportUserID = {$userid}, + UserGroupReportCreated = now(), + UserGroupReportLastUpdated = now() + WHERE UserGroupReportID = {$v['UserGroupReportID']}"; + + //echo $query; + $action = $this->db_onedev->query($query); + } + + + if($action){ + $result = array( + "total" => 1 , + "records" => array(), + ); + $this->sys_ok($result); + exit; + } + else{ + $this->sys_error_db($this->db_onedev->last_query(), $this->db_onedev); + exit; + } + +} + public function deleteuser() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $sql = "update nat_methode SET + Nat_MethodeIsActive = 'N' + WHERE + Nat_MethodeID = ? + + "; + + $query = $this->db_onedev->query($sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("nat_methode delete"); + exit; + } + $sql = "update m_usergroup SET + M_UserGroupIsActive = 'N' + WHERE + M_UserGroupNat_MethodeID = ? + + "; + + $query = $this->db_onedev->query($sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_usergroup delete"); + exit; + } + + + $result = array ("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function deletereport() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + //# ambil parameter input + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $sql = "update m_usergroup SET + M_UserGroupIsActive = 'N' + WHERE + M_UserGroupID = ? + + "; + + $query = $this->db_onedev->query($sql, + array( + $prm['id'] + ) + ); + // echo $query; + if (!$query) { + $this->sys_error_db("m_usergroup delete"); + exit; + } + + + $result = array ("total" => 1, "records" => array("xid" => 0)); + $this->sys_ok($result); + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + + function searchuser(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "SELECT count(*) as total + FROM nat_methode + WHERE + Nat_MethodeName like ? + AND Nat_MethodeIsActive = 'Y'"; + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("nat_methode count",$this->db_onedev); + exit; + } + + $sql = " + SELECT Nat_MethodeID, Nat_MethodeName + FROM nat_methode + WHERE + Nat_MethodeName like ? + AND Nat_MethodeIsActive = 'Y' + ORDER BY Nat_MethodeName ASC + "; + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("nat_methode rows",$this->db_onedev); + exit; + } + } + function searchuserbyname(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "SELECT count(*) as total + FROM nat_methode + WHERE + Nat_MethodeName like ? + AND Nat_MethodeIsActive = 'Y'"; + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("nat_methode count",$this->db_onedev); + exit; + } + + $sql = " + SELECT Nat_MethodeID, Nat_MethodeName + FROM nat_methode + WHERE + Nat_MethodeName like ? + AND Nat_MethodeIsActive = 'Y' + ORDER BY Nat_MethodeName ASC + "; + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("nat_methode rows",$this->db_onedev); + exit; + } + } + + +function searchtest(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "SELECT count(*) as total + FROM t_test + WHERE + T_TestName like ? + AND T_TestIsActive = 'Y' AND T_TestIsResult = 'Y'"; + $query = $this->db_onedev->query($sql,$q['search']); + //echo $query; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("t_test count",$this->db_onedev); + exit; + } + + $sql = " + SELECT * + FROM t_test + WHERE + T_TestName like ? + AND T_TestIsActive = 'Y' AND T_TestIsResult = 'Y' + ORDER BY T_TestName ASC + "; + $query = $this->db_onedev->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + //echo $this->db_onedev->last_query(); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("t_test rows",$this->db_onedev); + exit; + } +} +} \ No newline at end of file diff --git a/application/controllers/v1/report-v9/Lookup.php b/application/controllers/v1/report-v9/Lookup.php new file mode 100644 index 0000000..24ce2b1 --- /dev/null +++ b/application/controllers/v1/report-v9/Lookup.php @@ -0,0 +1,43 @@ +db_smartone = $this->load->database("onedev", true); + } + + function dropdown($sp) { + $sql = "call $sp"; + $qry = $this->db_smartone->query($sql); + if (! $qry) { + echo json_encode(array()); + } + $rows = $qry->result_array(); + if (count($rows) == 0 ) { + echo json_encode(array()); + } + echo json_encode($rows); + } + + function ac($sp) { + $prm = $this->sys_input; + $search = $prm['search']; + $sql = "call $sp(?)"; + if (isset($prm['dep'])) { + $sql = "call $sp(?,?)"; + $value = $prm['value']; + $qry = $this->db_smartone->query($sql,array($search,$value)); + } else { + $qry = $this->db_smartone->query($sql,array($search)); + } + if (! $qry) { + echo json_encode(array()); + } + $rows = $qry->result_array(); + if (count($rows) == 0 ) { + echo json_encode(array()); + exit; + } + echo json_encode($rows); + } +} diff --git a/application/controllers/v1/report-v9/Main.php b/application/controllers/v1/report-v9/Main.php new file mode 100644 index 0000000..20f263e --- /dev/null +++ b/application/controllers/v1/report-v9/Main.php @@ -0,0 +1,185 @@ +db_one= $this->load->database("onedev", true); + } + function detail(){ + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $id = $prm['id']; + $sql = "select * + from + r_reportdetail + join r_inputtype on R_ReportDetailR_InputTypeID = R_InputTypeID + and R_ReportDetailIsActive = 'Y' + where R_ReportDetailR_ReportID = ? + order by R_ReportDetailID, R_ReportDetailPriority desc"; + + // echo $sql; + $qry = $this->db_one->query($sql, array($id) ); + $last_q = $this->db_one->last_query(); + if ($qry) { + $rows = $qry->result_array(); + foreach($rows as $idx => $r) { + $rows[$idx]["model"] = ""; + $rows[$idx]["items"] = ""; + $rows[$idx]["tmp_date"] = false; + } + $result = array ("total" => count($rows), "records" => $rows); + $this->sys_ok($result); + } else { + $message = "Err Report Query"; + $this->sys_error($message,$this->db_one); + } + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + function list(){ + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm['search']; + $q_search = "where R_ReportIsActive = 'Y'"; + $q_param = array(); + if ($search !== "") { + $q_search = "where R_ReportIsActive = 'Y' and ( R_ReportCode like ? or R_ReportName like ? ) "; + $q_param[] = "%$search%"; + $q_param[] = "%$search%"; + } + $userid = $this->sys_user["M_UserID"]; + $sqlusergroup = $this->db_onedev->query("SELECT M_UserM_UserGroupID FROM m_user + WHERE M_UserID = $userid")->row(); + $usergroup = $sqlusergroup->M_UserM_UserGroupID; + $sql = "select + R_ReportGroupID, R_ReportGroupName, R_ReportGroupColor, + R_ReportID, R_ReportCode, R_ReportName, R_ReportUrl, R_ReportWithoutXls + from r_report + join r_reportgroup on R_ReportGroupID = R_ReportR_ReportGroupID + join usergroup_report on R_ReportID = UserGroupReportR_ReportID AND UserGroupReportM_UserGroupID = $usergroup + and UserGroupReportIsActive = 'Y' + $q_search ORDER BY R_ReportGroupName ASC, R_ReportCode ASC"; + // echo $sql; + if ($q_search == "" ) { + $qry = $this->db_one->query($sql); + } else { + $qry = $this->db_one->query($sql,$q_param); + } + $last_q = $this->db_one->last_query(); + if ($qry) { + $rows = $qry->result_array(); + $reports = array(); + $prev_group = 0; + $idx = -1; + foreach($rows as $r) { + if ($prev_group != $r["R_ReportGroupID"] ) { + $idx++; + $reports[] = array("id"=>$r["R_ReportGroupID"], "name" => $r["R_ReportGroupName"], + "color" => $r["R_ReportGroupColor"], + "reports" => array()); + } + $prev_group = $r["R_ReportGroupID"]; + $reports[$idx]["reports"][] = $r; + } + $result = array ("total" => count($reports), "records" => $reports); + $this->sys_ok($result); + } else { + $message = "Err Report Query"; + $this->sys_error($message,$this->db_one); + } + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } + public function lookupparam() + { + try { + //# cek token valid + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm['search']; + $limit = ''; + if($all == 'N'){ + $limit = ' LIMIT 10'; + } + $number_limit = 10; + $number_offset = ($prm['current_page'] - 1) * $number_limit ; + $sql = "select COUNT(*) as total + from r_reportparam + LEFT JOIN r_inputtype ON R_ReportParamR_InputTypeID = R_InputTypeID AND R_InputTypeIsActive = 'Y' + where + (R_ReportParamName LIKE CONCAT('%','{$search}','%') OR + IFNULL(R_InputTypeName,'') LIKE CONCAT('%','{$search}','%') OR + IFNULL(R_ReportParamLabel,'') LIKE CONCAT('%','{$search}','%')) AND + R_ReportParamIsActive = 'Y'"; + $sql_param = array($search); + // $total = $this->db_onedev->query($sql,$sql_param)->row()->total; + $query = $this->db_onedev->query($sql); + $tot_count = 0; + $tot_page = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + $tot_page = ceil($tot_count/$number_limit); + } else { + $this->sys_error_db("r_reportparam count", $this->db_onedev); + exit; + } + + $sql = "select R_ReportParamID as id, + R_InputTypeName, + r_reportparam.* + from r_reportparam + LEFT JOIN r_inputtype ON R_ReportParamR_InputTypeID = R_InputTypeID AND R_InputTypeIsActive = 'Y' + where + (R_ReportParamName LIKE CONCAT('%','{$search}','%') OR + IFNULL(R_InputTypeName,'') LIKE CONCAT('%','{$search}','%') OR + IFNULL(R_ReportParamLabel,'') LIKE CONCAT('%','{$search}','%')) AND + R_ReportParamIsActive = 'Y' + GROUP BY R_ReportParamID + ORDER BY R_ReportParamName ASC + limit $number_limit offset $number_offset"; + $sql_param = array($search); + $query = $this->db_onedev->query($sql); + //echo $this->db_onedev->last_query(); + if ($query) { + $rows = $query->result_array(); + + + } else { + $this->sys_error_db("r_reportparam select"); + exit; + } + + $result = array ("total" => $tot_page, "total_filter"=>count($rows),"records" => $rows); + $this->sys_ok($result); + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + } +}