Files

770 lines
29 KiB
PHP

<?php
class Bill extends MY_Controller
{
var $db_onedev;
public function index()
{
echo "Bill API";
}
public function __construct()
{
parent::__construct();
$this->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;
}
}