debug = false; $this->SENDER_DOCTOR_ID = 0; $this->SENDER_ADDRESS_ID = 0; $this->PJ_DOCTOR_ID = 0; $this->KASIR_ONLINE_USER = 1500; $this->CONFIRM_USER_ID = 0; $this->SAMPLE_STATION_HS = 1; $this->apdTestID = 2858; $this->apdTestName = "Biaya APD"; $this->otherTestID = 3181; $this->minimalTestID = 3184; $this->otherTestName = "Biaya Lainnya (HS ke-2, APD)"; } function get_hs_test($transactionID, $debug = "") { $sql = "select t_transactionHSCost, t_transactionHSCostOther, t_transactionHSCostMinOrder from one_hs_lab.t_transactionHS where t_TransactionHST_TransactionID=?"; $qry = $this->db->query($sql, [$transactionID]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); $result = []; $otherCost = 0; $hsCost = 0; $minimalCost = 0; if (count($rows) > 0) { $otherCost = $rows[0]["t_transactionHSCostOther"]; $hsCost = $rows[0]["t_transactionHSCost"]; $minimalCost = $rows[0]["t_transactionHSCostMinOrder"]; } if ($otherCost > 0) { $result[] = [ "t_id" => $this->otherTestID, "t_cito" => "N", "t_price" => $otherCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } if ($minimalCost > 0) { $result[] = [ "t_id" => $this->minimalTestID, "t_cito" => "N", "t_price" => $minimalCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } if ($hsCost == 0) { return $result; } //get distance $sql = "select HS_ConfigLat,HS_ConfigLong from one_hs_lab.hs_config where HS_ConfigIsActive = 'Y' limit 0,1"; $qry = $this->db->query($sql); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("Error No Active HS Config"); $this->db->trans_rollback(); exit; } $branchLat = $rows[0]["HS_ConfigLat"]; $branchLong = $rows[0]["HS_ConfigLong"]; $sql = "select -- one_hs_lab.distance_v2(HS_AddressLat, HS_AddressLng, ?, ?) distance t_transactionHSDistance distance from one_hs_lab.t_transactionHS join one_hs_lab.hs_address on t_transactionHST_TransactionID = ? and t_transactionHSHS_AddressID = HS_AddressID "; $qry = $this->db->query($sql, [$branchLat, $branchLong, $transactionID]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("Error No HS Address"); $this->db->trans_rollback(); exit; } $distance_km = round($rows[0]["distance"], 0); // $distance_km = round($rows[0]["distance"]/1000,0); $sql = "select HS_PriceSekaliTestID, HS_PriceDuaKaliTestID from one_hs_lab.hs_price where HS_PriceIsActive = 'Y' and HS_PriceMinDistance <= ? and HS_PriceMaxDistance >= ? "; $this->log("distance : $distance_km km"); $qry = $this->db->query($sql, [$distance_km, $distance_km]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) > 0) { $result[] = [ "t_id" => $rows[0]["HS_PriceSekaliTestID"], "t_cito" => "N", "t_price" => $hsCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } if ($debug != "") { print_r($result); } return $result; } function get_hs_test_old($transactionID) { $sql = "select t_transactionHSCost, t_transactionHSCostOther from one_hs_lab.t_transactionHS where t_TransactionHST_TransactionID=?"; $qry = $this->db->query($sql, [$transactionID]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); $result = []; $apdCost = 0; $hsCost = 0; if (count($rows) > 0) { $apdCost = $rows[0]["t_transactionHSCostOther"]; $hsCost = $rows[0]["t_transactionHSCost"]; } if ($apdCost > 0) { $result[] = [ "t_id" => $this->apdTestID, "t_cito" => "N", "t_price" => $apdCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } if ($hsCost == 0) { return $result; } //get distance $sql = "select HS_ConfigLat,HS_ConfigLong from one_hs_lab.hs_config where HS_ConfigIsActive = 'Y' limit 0,1"; $qry = $this->db->query($sql); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("Error No Active HS Config"); $this->db->trans_rollback(); exit; } $branchLat = $rows[0]["HS_ConfigLat"]; $branchLong = $rows[0]["HS_ConfigLong"]; $sql = "select one_hs_lab.distance_v2(HS_AddressLat, HS_AddressLng, ?, ?) distance from one_hs_lab.t_transactionHS join one_hs_lab.hs_address on t_transactionHST_TransactionID = ? and t_transactionHSHS_AddressID = HS_AddressID "; $qry = $this->db->query($sql, [$branchLat, $branchLong, $transactionID]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("Error No HS Address"); $this->db->trans_rollback(); exit; } $distance = round($rows[0]["distance"], 0); $distance_km = round($rows[0]["distance"] / 1000, 0); $sql = "select T_OrderDetailT_TestID from one_hs_lab.t_orderdetail join one_hs_lab.t_order on T_OrderT_TransactionID = ? and T_OrderIsActive = 'Y' and T_OrderDetailT_OrderID = T_OrderID and T_OrderDetailIsActive = 'Y' join one_hs_lab.m_test_second_visit on T_OrderDetailT_TestID = M_TestSecondVisitT_TestID and M_TestSecondVisitIsActive = 'Y' "; $isSecondVisit = false; $qry = $this->db->query($sql, [$transactionID]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) > 0) { $isSecondVisit = true; } $sql = "select HS_PriceSekaliTestID, HS_PriceDuaKaliTestID from one_hs_lab.hs_price where HS_PriceIsActive = 'Y' and HS_PriceMinDistance <= ? and HS_PriceMaxDistance >= ? "; $this->log("distance : $distance | $distance_km km"); $qry = $this->db->query($sql, [$distance_km, $distance_km]); if (!$qry) { $this->log("Error {$this->db->error()["message"]}"); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); if (count($rows) > 0) { if ($isSecondVisit) { $result[] = [ "t_id" => $rows[0]["HS_PriceDuaKaliTestID"], "t_cito" => "N", "t_price" => $hsCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } else { $result[] = [ "t_id" => $rows[0]["HS_PriceSekaliTestID"], "t_cito" => "N", "t_price" => $hsCost, "t_disc" => 0, "t_discrp" => 0, "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => "N", "t_packettype" => "PX", "t_packetid" => 0, ]; } } return $result; } public function get_branch_default() { $sql = "select * from m_branch where M_BranchIsDefault = 'Y' and M_BranchIsActive = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Get Default Branch: {$this->db->error()["message"]}\n"; exit(); } $branchKelurahanID = $rows[0]["M_BranchM_KelurahanID"]; $this->SENDER_DOCTOR_ID = $rows[0]["M_BranchM_DoctorID"]; $this->SENDER_ADDRESS_ID = $rows[0]["M_BranchM_DoctorAddressID"]; $sql = "select * from m_doctorpj where M_DoctorPjIsActive = 'Y' and M_DoctorPjIsDefaultPJ='Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Get Default PJ: {$this->db->error()["message"]}\n"; exit(); } $this->PJ_DOCTOR_ID = $rows[0]["M_DoctorPjM_DoctorID"]; return [$branchKelurahanID]; } function now() { return Date("Y-m-d H:i:s"); } function log($msg) { file_put_contents("/xtmp/debug_hs_generate.log", "{$this->now()} $msg\n", FILE_APPEND); echo "{$this->now()} $msg\n"; } function getTestID($T_OrderHeaderID, $T_SampleTypeID) { $sql = "select T_OrderDetailT_TestID from t_orderdetail join t_test on T_OrderDetailT_OrderHeaderID = ? and T_OrderDetailT_TestID = T_TestID and T_TestT_SampleTypeID = ? and T_TestIsResult = 'Y'"; $qry = $this->db->query($sql, [$T_OrderHeaderID, $T_SampleTypeID]); if (!$qry) { $this->log( "Err get one_hs_lab.t_ordersample " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows = $qry->result_array(); if (count($rows) > 0) { return $rows[0]["T_OrderDetailT_TestID"]; } return 0; } function generate_sample( $orderID, $deliveryID, $T_OrderHeaderID, $order = [] ) { //Sample //join t_ordersample_receve $sql = "select t_ordersample.*, T_OrderSampleReceiveID from one_hs_lab.t_ordersample join one_hs_lab.t_ordersample_receive on T_OrderSampleT_OrderID=? and T_OrderSampleReceiveHs_DeliveryOrderID = ? and T_OrderSampleReceiveT_OrderID = T_OrderSampleT_OrderID and T_OrderSampleReceiveT_SampleTypeID = T_OrderSampleT_SampleTypeID and T_OrderSampleIsActive = 'Y' and T_OrderSampleReceiveIsActive = 'Y' and T_OrderSampleReceiveIsGenerate = 'N'"; $qry = $this->db->query($sql, [$orderID, $deliveryID]); if (!$qry) { $this->log( "Err get one_hs_lab.t_ordersample " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows_sample = $qry->result_array(); $s_ids = "-1"; foreach ($rows_sample as $s) { $s_ids .= "," . $s["T_OrderSampleT_SampleTypeID"]; } $is_nonlab = []; $arr_stationID = []; $is_agingOnHold = []; $arr_agingOnHoldTime = []; if (count($rows_sample) > 0) { $sql = "SELECT T_SampleTypeID,T_SampleStationIsNonLab, T_SampleStationID, T_SampleTypeAgingOnHold, T_SampleTypeAgingOnHoldTime FROM t_sampletype JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID WHERE T_SampleTypeID in ($s_ids) "; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err get is none lab" . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows_nl = $qry->result_array(); foreach ($rows_nl as $nl) { $is_nonlab[$nl["T_SampleTypeID"]] = $nl["T_SampleStationIsNonLab"]; $arr_stationID[$nl["T_SampleTypeID"]] = $nl["T_SampleStationID"]; $is_agingOnHold[$nl["T_SampleTypeID"]] = $nl["T_SampleTypeAgingOnHold"]; $arr_agingOnHoldTime[$nl["T_SampleTypeID"]] = $nl["T_SampleTypeAgingOnHoldTime"]; } //echo $this->db->last_query(); } $samplings = []; if (count($rows_sample) > 0) { $sampleTambahan = ""; $sr_ids = "0"; foreach ($rows_sample as $rs) { $sr_ids .= $rs["T_OrderSampleReceiveID"]; unset($rs["T_OrderSampleReceiveID"]); $sampleTypeID = $rs["T_OrderSampleT_SampleTypeID"]; $flagNonLab = "N"; if (isset($is_nonlab[$sampleTypeID])) { if (trim($is_nonlab[$sampleTypeID]) != "") { $flagNonLab = "Y"; } } $samplings[$sampleTypeID] = [ "userID" => $rs["T_OrderSampleUserID"], "date" => $rs["T_OrderSampleCreated"], "isNonLab" => $flagNonLab, "T_TestID" => $this->getTestID( $T_OrderHeaderID, $sampleTypeID ), "T_SampleStationID" => isset($arr_stationID[$sampleTypeID]) ? $arr_stationID[$sampleTypeID] : "0", ]; if ($sampleTambahan != "") { $sampleTambahan .= ", "; } $sampleTambahan .= $rs["T_OrderSampleT_SampleTypeName"]; } // echo "FO Verify : $T_OrderHeaderID
"; // print_r($samplings); $this->fo_verify($T_OrderHeaderID, $samplings, $is_agingOnHold, $arr_agingOnHoldTime); $this->log( $order["T_OrderQrCode"] . " Add Sample Tambahan $sampleTambahan " ); $sql = "update one_hs_lab.t_ordersample_receive set T_OrderSampleReceiveIsGenerate = 'Y' where T_OrderSampleReceiveID in ($sr_ids)"; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err update isGenerate one_hs_lab.t_ordersample " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } } } function process($transactionID, $deliveryID, $debug = "") { list($branchKelurahanID) = $this->get_branch_default(); $this->db->trans_begin(); $sql = "select distinct t_transaction.*, t_order.*, t_orderdetail.*, t_transactionHS.*, T_OrderHeaderLabNumber, T_OrderHeaderDate, m_patient.* from one_hs_lab.t_transaction join one_hs_lab.t_order on T_TransactionID = ? and T_TransactionID = T_OrderT_TransactionID and T_TransactionIsConfirmReceived = 'Y' -- and T_OrderIsGenerated = 'N' and T_TransactionIsActive = 'Y' and T_OrderIsActive = 'Y' join one_hs_lab.hs_deliveryorderdetail on HS_DeliveryOrderDetailHS_DeliveryOrderID = ? and T_TransactionID = HS_DeliveryOrderDetailT_TransactionID and HS_DeliveryOrderDetailIsActive = 'Y' join one_hs_lab.m_patient on T_OrderM_PatientID = M_PatientID join one_hs_lab.t_transactionHS on T_TransactionID = t_transactionHST_TransactionID and t_transactionHSIsActive = 'Y' join one_hs_lab.t_orderdetail on T_OrderDetailT_OrderID = T_OrderID and T_OrderDetailIsActive = 'Y' left join t_orderheader on T_OrderT_OrderHeaderID = T_OrderHeaderID -- where T_OrderT_OrderHeaderID is null order by t_transactionHSID, T_OrderID, T_OrderDetailT_OrderID "; $qry = $this->db->query($sql, [$transactionID, $deliveryID]); if (!$qry) { $this->log( "Error : " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No Pending Order for tranactionID $transactionID "); $this->db->trans_rollback(); if ($debug != "") { echo $this->db->last_query(); } exit(); } $arrTxID = []; $arrHsID = []; $arrOrderID = []; $idxOrder = 0; $transaction = []; //Populate HS Transacion -> Order -> OrderDetail foreach ($rows as $r) { $transactionID = $r["T_TransactionID"]; if (!in_array($transactionID, $arrTxID)) { $tmp_r = $r; foreach (array_keys($r) as $k) { if ( substr($k, 0, strlen("T_Transaction")) != "T_Transaction" ) { unset($tmp_r[$k]); } } $transaction = $tmp_r; $arrTxID[] = $transactionID; $transaction["order"] = []; $transaction["hs"] = []; } $hsID = $r["t_transactionHSID"]; if (!in_array($hsID, $arrHsID)) { $tmp_r = $r; foreach (array_keys($r) as $k) { if ( substr($k, 0, strlen("t_transactionHS")) != "t_transactionHS" ) { unset($tmp_r[$k]); } } $transaction["hs"] = $tmp_r; $arrHsID[] = $hsID; } $orderID = $r["T_OrderID"]; if (!in_array($orderID, $arrOrderID)) { $tmp_r = $r; foreach (array_keys($r) as $k) { if ( substr($k, 0, strlen("T_Order")) != "T_Order" && substr($k, 0, strlen("M_Patient")) != "M_Patient" ) { unset($tmp_r[$k]); } if ( substr($k, 0, strlen("T_OrderDetail")) == "T_OrderDetail" ) { unset($tmp_r[$k]); } } $transaction["order"][] = $tmp_r; $idxOrder = count($transaction["order"]) - 1; $transaction["order"][$idxOrder]["detail"] = []; $transaction["order"][$idxOrder]["sample"] = []; } $arrOrderID[] = $orderID; // order_detail $tmp_r = $r; foreach (array_keys($r) as $k) { if (substr($k, 0, strlen("T_OrderDetail")) != "T_OrderDetail") { unset($tmp_r[$k]); } } $transaction["order"][$idxOrder]["detail"][] = $tmp_r; } $this->CONFIRM_USER_ID = $transaction["T_TransactionConfirmReceiveM_UserID"]; $payment_used = 0; //Generate BizOne Order $is_first_order = true; $additional_hs_test = $this->get_hs_test($transactionID); if ($debug != "") { $this->log("Additional HS TEST : " . print_r($additional_hs_test, true)); } foreach ($transaction["order"] as $order) { $orderID = $order["T_OrderID"]; $T_OrderHeaderID = $order["T_OrderT_OrderHeaderID"]; if ($T_OrderHeaderID > 0) { $this->log( $order["T_OrderQrCode"] . " sudah ter-generate ke " . $order["T_OrderHeaderLabNumber"] . " pada " . $order["T_OrderHeaderDate"] ); $this->generate_sample( $orderID, $deliveryID, $T_OrderHeaderID, $order ); if ($debug != "") { echo "Debug Rollback"; $this->db->trans_rollback(); exit(); } $this->log("Sleep 1s\n"); sleep(1); $this->db->trans_commit(); $this->db->trans_begin(); continue; } //generate order //header //xdelivery //details $this->log("Create order from " . $order["T_OrderQrCode"]); list( $x_status, $msg, $x_orderheader, $M_PatientAddressID, ) = $this->generate_header( $transaction["T_TransactionM_MouID"], $order ); if ($x_status === false) { $this->log("Error Generate Header : " . $msg); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } //delivery $sql = "select * from one_hs_lab.t_orderdeliveries where T_OrderDeliveriesT_OrderID=? and T_OrderDeliveriesIsActive ='Y'"; $qry = $this->db->query($sql, [$order["T_OrderID"]]); if (!$qry) { $this->log( "Error : " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); exit(); } $delivery_rows = $qry->result_array(); $xdelivery = []; foreach ($delivery_rows as $d) { $xdel = [ "address_id" => $M_PatientAddressID, "delivery_id" => $d["T_OrderDeliveriesM_DeliveryID"], "delivery_type_id" => $d["T_OrderDeliveriesM_DeliveryTypeID"], "senderdoctorid" => $this->SENDER_DOCTOR_ID, "senderaddressid" => $this->SENDER_ADDRESS_ID, "note" => str_replace("\n", "\\n", $d["T_OrderDeliveriesDestination"]), "kelurahan" => intval($branchKelurahanID), ]; $xdelivery[] = $xdel; } $xdetails = $this->populate_test( $transaction["T_TransactionM_MouID"], $order["detail"] ); if (count($xdetails) == 0) { $this->log("Error Populate Test"); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $a_fix_pxr = []; foreach ($xdetails as $idx => $d) { if (isset($d["child_test"])) { $a_child_test = json_decode($d["child_test"], true); foreach ($a_child_test as $xt) { $a_fix_pxr[] = $xt; } unset($xdetails[$idx]["child_test"]); } } //Add Aditional HS Test if ($is_first_order) { $is_first_order = false; foreach ($additional_hs_test as $add_test) { $xdetails[] = $add_test; } } $xreq = [ "status" => "Y", "reqs" => [], ]; // Call mockup FO IBL order/save endpoint (menggantikan sp_fo_register_save_online) list($save_ok, $T_OrderHeaderID, $orderNo, $save_err) = $this->call_fo_register_save_online( $x_orderheader, $xdelivery, $xdetails, $xreq ); if (!$save_ok) { $this->log("| Order Creation : " . $save_err); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $this->log( " Order {$orderNo} from {$order["T_OrderNumber"]} " ); if ($debug != "") { $this->log("fo_register_save_online OK id={$T_OrderHeaderID} number={$orderNo}"); } if ($T_OrderHeaderID == 0) { $this->log("| Order Creation : " . $save_err); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } //fix pxr child price (order ada di onedev dari mockup order/save) $db_onedev = $this->load->database('onedev', true); foreach ($a_fix_pxr as $fix_t) { $priceAmount = $fix_t["T_PriceAmount"]; $priceDisc = $fix_t["T_PriceDisc"]; $priceDiscRp = $fix_t["T_PriceDiscRp"]; $testID = $fix_t["T_TestID"]; $discTotal = ($priceDisc / 100) * $priceAmount + $priceDiscRp; $priceTotal = $priceAmount - $discTotal; $sql = "update t_orderdetail set T_OrderDetailPrice = ?, T_OrderDetailPriceForDisc =?, T_OrderDetailDisc =?, T_OrderDetailDiscAmount =?, T_OrderDetailDiscTotal = ?, T_OrderDetailTotal = ? where T_OrderDetailT_OrderHeaderID = ? and T_OrderDetailT_TestID = ?"; $qry = $db_onedev->query($sql, [ $priceAmount, $priceAmount, $priceDisc, $priceDiscRp, $discTotal, $priceTotal, $T_OrderHeaderID, $testID, ]); if (!$qry) { $this->log( "Err fix pxr " . $db_onedev->error()["message"] . "|" . $db_onedev->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } } $this->do_order_log($T_OrderHeaderID, $delivery_json, true); $sql = "select * from order_log where OrderLogT_OrderHeaderID=$T_OrderHeaderID"; //update t_order $sql = "update one_hs_lab.t_order set T_OrderT_OrderHeaderID = ?, T_OrderIsGenerated='Y' where T_OrderID=?"; $qry = $this->db->query($sql, [ $T_OrderHeaderID, $order["T_OrderID"], ]); if (!$qry) { $this->log( "Err Update one_hs_lab.t_order " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } //Update payment $sql = "select * from one_hs_lab.f_payment where F_PaymentT_TransactionID=? and F_PaymentIsActive ='Y' order by F_PaymentID "; $qry = $this->db->query($sql, [$transaction["T_TransactionID"]]); if (!$qry) { $this->log( "Err get one_hs_lab.f_payment " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows_payment = $qry->result_array(); $payments = []; $tmp_used = $payment_used; $tot_payment_amount = 0; foreach ($rows_payment as $rp) { if ($rp["F_PaymentAmount"] < $tmp_used) { $tmp_used -= $rp["F_PaymentAmount"]; continue; } if ($tmp_used > 0) { $rp["F_PaymentAmount"] -= $tmp_used; $tmp_used = 0; } $payments[] = $rp; $tot_payment_amount += $rp["F_PaymentAmount"]; } if (count($payments) > 0) { $OrderTotal = $this->do_pelunasan($T_OrderHeaderID, $payments, true); $this->log(" Pelunasan $OrderTotal"); $payment_used = $payment_used + $OrderTotal; } if (count($payments) == 0) { //get pelunasan online $rows_payment = $this->get_duitku($transactionID); foreach ($rows_payment as $rp) { if ($rp["F_PaymentAmount"] < $tmp_used) { $tmp_used -= $rp["F_PaymentAmount"]; continue; } if ($tmp_used > 0) { $rp["F_PaymentAmount"] -= $tmp_used; $tmp_used = 0; } $payments[] = $rp; $tot_payment_amount += $rp["F_PaymentAmount"]; } if ($debug != "") { print_r($payments); } if (count($payments) > 0) { $OrderTotal = $this->do_pelunasan_online($T_OrderHeaderID, $payments, true); $this->log(" Pelunasan [Online] $OrderTotal"); $payment_used = $payment_used + $OrderTotal; } } //Nilai Normal $this->update_nilai_normal($T_OrderHeaderID); $this->generate_sample( $orderID, $deliveryID, $T_OrderHeaderID, $order ); // echo "Debug Rollback"; // $this->db->trans_rollback(); // exit(); $this->log("Sleep 1s\n"); sleep(1); } if ($debug != "") { $this->db->trans_rollback(); exit; } $this->db->trans_commit(); //debug } function do_order_log($orderHeaderID, $json_delivery, $use_onedev = false) { $db = $use_onedev ? $this->load->database('onedev', true) : $this->db; $sql = "SELECT * FROM t_orderheader JOIN m_patient ON M_PatientID = T_OrderHeaderM_PatientID join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID WHERE T_OrderHeaderID = {$orderHeaderID}"; //echo $sql; $qry = $db->query($sql); if (!$qry) { $this->log( "ERR : {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } $x_header = $qry->row_array(); $sql = "SELECT * FROM t_orderdetail WHERE T_OrderDetailT_OrderHeaderID = {$orderHeaderID} AND T_OrderDetailT_TestIsPrice = 'Y' AND T_OrderDetailIsActive = 'Y'"; $x_details = $db->query($sql)->result_array(); $x_details = json_encode($x_details); $x_deliveries = $json_delivery; $sql = "SELECT * FROM t_orderpromise WHERE T_OrderPromiseT_OrderHeaderID = {$orderHeaderID} AND T_OrderPromiseIsActive = 'Y'"; $qry = $db->query($sql); if (!$qry) { $this->log("ERR : {$db->error()["message"]}\n"); $this->db->trans_rollback(); exit(); } $x_promises = json_encode($qry->result_array()); $sql = "INSERT INTO order_log( OrderLogT_OrderHeaderID, OrderLogM_PatientDOB, OrderLogM_CompanyID, OrderLogM_MouID, OrderLogM_DoctorSenderID, OrderLogM_DoctorSenderAddressID, orderLogT_OrderHeaderAddOnAliasDoctorName, orderLogT_OrderHeaderAddOnAliasDoctorAddress, OrderLogAge, OrderLogFoNote, OrderLogSubtotal, OrderLogTotal, OrderLogUserID, OrderLogDetails, OrderLogDeliveries, OrderLogPromises ) VALUES( {$orderHeaderID}, '{$x_header["M_PatientDOB"]}', {$x_header["T_OrderHeaderM_CompanyID"]}, {$x_header["T_OrderHeaderM_MouID"]}, {$x_header["T_OrderHeaderSenderM_DoctorID"]}, {$x_header["T_OrderHeaderSenderM_DoctorAddressID"]}, '{$x_header["T_OrderHeaderAddOnAliasDoctorName"]}', '{$x_header["T_OrderHeaderAddOnAliasDoctorAddress"]}', '{$x_header["T_OrderHeaderM_PatientAge"]}', '{$x_header["T_OrderHeaderFoNote"]}', '{$x_header["T_OrderHeaderSubTotal"]}', '{$x_header["T_OrderHeaderTotal"]}', {$this->CONFIRM_USER_ID}, '{$x_details}', '{$x_deliveries}', '{$x_promises}' )"; $qry = $db->query($sql); if (!$qry) { $this->log("ERR : {$db->error()["message"]}\n"); $this->db->trans_rollback(); exit(); } } function fo_verify($orderID, $samplings, $is_agingOnHold, $arr_agingOnHoldTime) { $sql = "INSERT INTO fo_verificationsvalue ( Fo_VerificationsValueT_OrderHeaderID, Fo_VerificationsValueFo_VerificationsLabelID, Fo_VerificationsValueCheck, Fo_VerificationsValueNote, Fo_VerificationsValueUserID, Fo_VerificationsValueCreated ) SELECT {$orderID}, Fo_VerificationsLabelID, 'Y', '', {$this->CONFIRM_USER_ID}, NOW() FROM fo_verificationslabel WHERE Fo_VerificationsLabelIsActive = 'Y' "; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err insert fo_verificationsvalue " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $sql = "call sp_fo_barcode_generate({$orderID})"; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err insert call sp_fo_barcode_generate" . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $this->clean_mysqli_connection($this->db->conn_id); $sql = "call sp_fo_barcode_generate_again_not_exist({$orderID})"; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err insert call sp_fo_barcode_generate_again_not_exist " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $this->clean_mysqli_connection($this->db->conn_id); //updata fo status $sql = "update fo_status set Fo_StatusM_UserID = ? where Fo_StatusT_OrderHeaderID = ? "; $query = $this->db->query($sql, [$this->CONFIRM_USER_ID, $orderID]); if (!$query) { $this->log( "Err update fo_status " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $fostatusid = 3; $fologcode = "FO.VERIFICATION.CONFIRM"; $sql = "insert into fo_status( Fo_StatusDate, Fo_StatusT_OrderHeaderID, Fo_StatusM_StatusID, Fo_StatusM_UserID, Fo_StatusCreated, Fo_StatusUpdated) values( now(), ?, ?, ?, now(),now())"; $query = $this->db->query($sql, [ $orderID, $fostatusid, $this->CONFIRM_USER_ID, ]); if (!$query) { $this->log( "Err insert into fo_status " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $sql = "SELECT * FROM fo_verificationsvalue WHERE Fo_VerificationsValueT_OrderHeaderID = {$orderID}"; $data_log = []; $data_log["orderid"] = $orderID; $data_log["values"] = $this->db->query($sql)->result_array(); $data_log["note"] = ""; $json_dt_log = json_encode($data_log); $sql = "insert into one_log.log_fo( Log_FoDate, Log_FoCode, Log_FoJson, Log_FoUserID) values( now(), ?, ?, ?)"; $query = $this->db->query($sql, [ $fologcode, $json_dt_log, $this->CONFIRM_USER_ID, ]); if (!$query) { $this->log( "Err insert into fo_status " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } /* T_OrderSample */ //t_ordersample $samplingUserID = 0; $samplingDate = ""; // $sql = "select * from t_ordersample where T_OrderSampleT_OrderHeaderID=?"; // $qry = $this->db->query($sql, [$orderID]); // print_r($qry->result_array()); foreach ($samplings as $k => $s) { $sampleTypeID = $k; $userID = $s["userID"]; $sampleDate = $s["date"]; $samplingUserID = $userID; $samplingDate = $sampleDate; if ($s["isNonLab"] == "Y") { $arr_so = [ "T_SamplingSoT_SampleStationID" => $s["T_SampleStationID"], "T_SamplingSoT_TestID" => $s["T_TestID"], "T_SamplingSoT_OrderHeaderID" => $orderID, "T_SamplingSoProcessDate" => $samplingDate, "T_SamplingSoProcessTime" => $samplingDate, "T_SamplingSoProcessUserID" => $samplingUserID, "T_SamplingSoDoneDate" => $samplingDate, "T_SamplingSoDoneTime" => $samplingDate, "T_SamplingSoDoneUserID" => $samplingUserID, "T_SamplingSoFlag" => "D", ]; $qry = $this->db->insert("t_samplingso", $arr_so); if (!$qry) { $this->log( "Err insert t_samplingSo $orderID | $sampleTypeID \n" . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } } else { $set_aging_on_hold = ""; if ($is_agingOnHold[$sampleTypeID] == "Y") { if ($arr_agingOnHoldTime[$sampleTypeID] != "") { $set_aging_on_hold = ", T_OrderSampleReadyToProcessDateTime = now() + interval " . $arr_agingOnHoldTime[$sampleTypeID] . " minute "; } else { $set_aging_on_hold = ", T_OrderSampleReadyToProcessDateTime = now() "; } } else { $set_aging_on_hold = ", T_OrderSampleReadyToProcessDateTime = now() "; } $sql = "update t_ordersample set T_OrderSampleSampling='Y', T_OrderSampleSamplingDate = ?, T_OrderSampleSamplingTime = ?,T_OrderSampleSamplingUserID = ?, T_OrderSampleReceive='Y', T_OrderSampleReceiveDate = now() , T_OrderSampleReceiveTime = now(), T_OrderSampleReceiveUserID = ?, T_OrderSampleUserID=? $set_aging_on_hold where T_OrderSampleT_OrderHeaderID = ? and T_OrderSampleT_SampleTypeID =? "; $param = [ $sampleDate, $sampleDate, $userID, $this->CONFIRM_USER_ID, $this->CONFIRM_USER_ID, $orderID, $sampleTypeID, ]; $qry = $this->db->query($sql, $param); if (!$qry) { $this->log( "Err update t_ordersample (T_OrderHeaderID|T_SampleTypeID) $orderID | $sampleTypeID \n" . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } } } $sql = "INSERT INTO t_ordersamplereq( T_OrderSampleReqT_OrderHeaderID, T_OrderSampleReqT_SampleStationID, T_OrderSampleReqT_OrderSampleID, T_OrderSampleReqNat_PositionID, T_OrderSampleReqStatus, T_OrderSampleReqs, T_OrderSampleReqUserID, T_OrderSampleReqCreated ) select {$orderID}, {$this->SAMPLE_STATION_HS}, T_OrderSampleID, 2, 'Y', '[]', T_OrderSampleReceiveUserID, now() from t_ordersample where T_OrderSampleT_OrderHeaderID = {$orderID} and T_OrderSampleReceive = 'Y' and T_OrderSampleIsActive = 'Y' ON DUPLICATE KEY UPDATE T_OrderSampleReqStatus = 'Y', T_OrderSampleReqs = '[]', T_OrderSampleReqUserID = T_OrderSampleReceiveUserID"; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err insert into t_ordersamplereq " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } //t_sampling_queue_last_status $sql = "select count(*) total from t_ordersample where T_OrderSampleT_OrderHeaderID = ? and T_OrderSampleIsActive = 'Y' and T_OrderSampleReceive = 'N'"; $qry = $this->db->query($sql, [$orderID]); if (!$qry) { $this->log( "Err get status t_ordersamplereq " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows = $qry->result_array(); $status = 2; if (count($rows) == 0) { $status = 5; } $sql = "INSERT INTO t_sampling_queue_last_status ( T_SamplingQueueLastStatusT_SampleStationID, T_SamplingQueueLastStatusT_OrderHeaderID, T_SamplingQueueLastStatusT_SamplingQueueStatusID, T_SamplingQueueLastStatusUserID) VALUES( {$this->SAMPLE_STATION_HS}, {$orderID}, {$status}, {$samplingUserID}) ON DUPLICATE KEY UPDATE T_SamplingQueueLastStatusT_SamplingQueueStatusID = {$status}"; $qry = $this->db->query($sql); if (!$qry) { $this->log( "Err insert update t_sampling_queue_last_status " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } //sample_by_step $sql = "INSERT INTO sample_by_step( SampleByStepM_StatusSampleCode, SampleByStepT_OrderHeaderID, SampleByStepT_BarcodeLabID, SampleByStepRequirementStatus, SampleByStepRequirements, SampleByStepUserID, SampleByStepDateTime ) select 'SAMPLING.Sampling.Sampled', T_OrderSampleT_OrderHeaderID, T_OrderSampleT_BarcodeLabID, 'Y', '[]', T_OrderSampleSamplingUserID, concat(T_OrderSampleSamplingDate,' ', T_OrderSampleSamplingTime) from t_ordersample where T_OrderSampleT_OrderHeaderID = ? and T_OrderSampleIsActive = 'Y' and T_OrderSampleSampling = 'Y'"; $qry = $this->db->query($sql, [$orderID]); if (!$qry) { $this->log( "Err insert sample_by_step sampling " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $sql = "INSERT INTO sample_by_step( SampleByStepM_StatusSampleCode, SampleByStepT_OrderHeaderID, SampleByStepT_BarcodeLabID, SampleByStepRequirementStatus, SampleByStepRequirements, SampleByStepUserID, SampleByStepDateTime ) select 'SAMPLING.Sampling.Received', T_OrderSampleT_OrderHeaderID, T_OrderSampleT_BarcodeLabID, 'Y', '[]', T_OrderSampleSamplingUserID, concat(T_OrderSampleReceiveDate,' ', T_OrderSampleReceiveTime) from t_ordersample where T_OrderSampleT_OrderHeaderID = ? and T_OrderSampleIsActive = 'Y' and T_OrderSampleReceive= 'Y'"; $qry = $this->db->query($sql, [$orderID]); if (!$qry) { $this->log( "Err insert sample_by_step receive " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $this->log(" Update Sample [OK]"); } function update_nilai_normal($headerID) { // update nilai normal $sql = "select distinct T_OrderDetailT_OrderHeaderID id, T_TestT_SampleTypeID sid from t_orderdetail join t_test on T_OrderDetailT_OrderHeaderID = ? and T_OrderDetailIsActive = 'Y' and T_OrderDetailT_TestID = T_TestID and T_TestIsActive = 'Y' "; $qry = $this->db->query($sql, [$headerID]); if (!$qry) { $this->log( "Err get sampletype for update nilai normal " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } $rows = $qry->result_array(); foreach ($rows as $r) { $sql = "call sp_sampling_set_normal(?,?)"; $qry = $this->db->query($sql, [$r["id"], $r["sid"]]); if (!$qry) { $this->log( "Err update nilai normal sp_sampling_set_normal " . $this->db->error()["message"] . "|" . $this->db->last_query() ); $this->db->trans_rollback(); $this->db->trans_begin(); exit(); } } $this->log(" Update Nilai Normal [OK]"); } public function get_duitku($transactionID) { // get payment from duitku_cb $sql = "select duitku_cb.*, pgBankM_BankAccountID, pgBankM_PaymentTypeID from one_hs_lab.duitku_cb join one_hs_lab.t_transaction on duitkuCbMerchantOrderID = T_TransactionNumbering and T_TransactionID = ? join pg_bank on duitkuCbMerchantCode = pgBankMerchantCode and pgBankIsActive = 'Y'"; $qry = $this->db->query($sql, [$transactionID]); if (!$qry) { $this->log( "ERR Get Duitku CB : {$this->db->error()["message"]} | {$this->db->last_query()}\n" ); $this->db->trans_rollback(); exit; } $rows = $qry->result_array(); $payment = []; foreach ($rows as $r) { $payment[] = [ "F_PaymentCreated" => $r["duitkuCbCreated"], "F_PaymentAmount" => $r["duitkuCbAmount"], "note" => "Pg Ref # " . $r["duitkuCbReference"] . ", " . $r["pgPaymentMethodeName"], "F_PaymentM_PaymentTypeID" => $r["pgBankM_PaymentTypeID"], "F_PaymentM_BankAccountID" => $r["pgBankM_BankAccountID"], "F_PaymentCardNat_BankID" => 0, "F_PaymentEDCNat_BankID" => 0, ]; } return $payment; } public function do_pelunasan_online($headerID, $payment, $use_onedev = false) { $db = $use_onedev ? $this->load->database('onedev', true) : $this->db; $sql = "select T_OrderHeaderTotal from t_orderheader where T_OrderHeaderID = ?"; $qry = $db->query($sql, [$headerID]); if (!$qry) { $this->log( "ERR Get Total Order: {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("ERR Get Total Order: Not Found\n"); $this->db->trans_rollback(); exit(); } $orderTotal = $rows[0]["T_OrderHeaderTotal"]; $sumPayment = 0; foreach ($payment as $p) { if ($orderTotal == 0) { break; } $paymentDate = $p["F_PaymentCreated"]; $paymentNote = $p["note"]; $paymentAmount = $p["F_PaymentAmount"]; $currentPayment = $orderTotal; if ($paymentAmount < $orderTotal) { $orderTotal = $orderTotal - $paymentAmount; $sumPayment += $orderTotal; $currentPayment = $paymentAmount; } else { $sumPayment = $orderTotal; $orderTotal = 0; } if ($currentPayment == 0) { continue; } $arr = [ "F_PaymentT_OrderHeaderID" => $headerID, "F_PaymentDate" => $paymentDate, "F_PaymentNote" => $paymentNote, "F_PaymentTotal" => $currentPayment, "F_PaymentM_UserID" => $this->KASIR_ONLINE_USER, ]; $qry = $db->insert("f_payment", $arr); if (!$qry) { $this->log( "ERR Insert f_payment online : {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } $paymentID = $db->insert_id(); $paymentTypeID = $p["F_PaymentM_PaymentTypeID"]; $edcNat_BankID = $p["F_PaymentEDCNat_BankID"]; $cardNat_BankID = $p["F_PaymentCardNat_BankID"]; $bankAccountID = $p["F_PaymentM_BankAccountID"]; $arr = [ "F_PaymentDetailF_PaymentID" => $paymentID, "F_PaymentDetailM_PaymentTypeID" => $paymentTypeID, "F_PaymentDetailEDCNat_BankID" => $edcNat_BankID, "F_PaymentDetailCardNat_BankID" => $cardNat_BankID, "F_PaymentDetailM_BankAccountID" => $bankAccountID, "F_PaymentDetailNote" => "", "F_PaymentDetailAmount" => $currentPayment, "F_PaymentDetailActual" => $currentPayment, "F_PaymentDetailUserID" => $this->CONFIRM_USER_ID, "F_PaymentDetailChange" => 0, ]; $qry = $this->db->insert("f_paymentdetail", $arr); if (!$qry) { $this->log( "ERR Insert f_payment_detail : {$this->db->error()["message"]} | {$this->db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } } return $sumPayment; } public function do_pelunasan($headerID, $payment, $use_onedev = false) { $db = $use_onedev ? $this->load->database('onedev', true) : $this->db; $sql = "select T_OrderHeaderTotal from t_orderheader where T_OrderHeaderID = ?"; $qry = $db->query($sql, [$headerID]); if (!$qry) { $this->log( "ERR Get Total Order: {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("ERR Get Total Order: Not Found\n"); $this->db->trans_rollback(); exit(); } $orderTotal = $rows[0]["T_OrderHeaderTotal"]; $sumPayment = 0; foreach ($payment as $p) { if ($orderTotal == 0) { break; } $paymentDate = $p["F_PaymentCreated"]; $paymentNote = "-"; $paymentAmount = $p["F_PaymentAmount"]; $currentPayment = $orderTotal; if ($paymentAmount < $orderTotal) { $orderTotal = $orderTotal - $paymentAmount; $sumPayment += $orderTotal; $currentPayment = $paymentAmount; } else { $sumPayment = $orderTotal; $orderTotal = 0; } if ($currentPayment == 0) { continue; } $arr = [ "F_PaymentT_OrderHeaderID" => $headerID, "F_PaymentDate" => $paymentDate, "F_PaymentNote" => $paymentNote, "F_PaymentTotal" => $currentPayment, "F_PaymentM_UserID" => $this->CONFIRM_USER_ID, ]; $qry = $db->insert("f_payment", $arr); if (!$qry) { $this->log( "ERR Insert f_payment : {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } $paymentID = $db->insert_id(); $paymentTypeID = $p["F_PaymentM_PaymentTypeID"]; $edcNat_BankID = $p["F_PaymentEDCNat_BankID"]; $cardNat_BankID = $p["F_PaymentCardNat_BankID"]; $bankAccountID = $p["F_PaymentM_BankAccountID"]; $arr = [ "F_PaymentDetailF_PaymentID" => $paymentID, "F_PaymentDetailM_PaymentTypeID" => $paymentTypeID, "F_PaymentDetailEDCNat_BankID" => $edcNat_BankID, "F_PaymentDetailCardNat_BankID" => $cardNat_BankID, "F_PaymentDetailM_BankAccountID" => $bankAccountID, "F_PaymentDetailNote" => "", "F_PaymentDetailAmount" => $currentPayment, "F_PaymentDetailActual" => $currentPayment, "F_PaymentDetailUserID" => $this->CONFIRM_USER_ID, "F_PaymentDetailChange" => 0, ]; $qry = $db->insert("f_paymentdetail", $arr); if (!$qry) { $this->log( "ERR Insert f_payment_detail : {$db->error()["message"]} | {$db->last_query()}\n" ); $this->db->trans_rollback(); exit(); } } return $sumPayment; } public function populate_test($mouID, $details) { $a_test = []; foreach ($details as $d) { $packetID = $d["T_OrderDetailT_PacketID"]; $isCito = $d["T_OrderDetailIsCito"]; $isPacket = $packetID > 0 ? "Y" : "N"; $testID = $d["T_OrderDetailT_TestID"]; if ($isPacket == "Y") { $sql = "select * from ss_price_mou where Ss_PriceMouM_MouID = ? and packet_id = ? and is_packet = ? and T_PriceIsCito=?"; $qry = $this->db->query($sql, [ $mouID, $packetID, $isPacket, $isCito, ]); } else { $sql = "select * from ss_price_mou where Ss_PriceMouM_MouID = ? and T_TestID= ? and is_packet = ? and T_PriceIsCito=?"; $qry = $this->db->query($sql, [ $mouID, $testID, $isPacket, $isCito, ]); } if (!$qry) { echo "{$this->now()} ERR Populate Test : {$this->db->error()["message"]} | {$this->db->last_query()}\n"; $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); $check_test = []; foreach ($rows as $px) { if ($px["px_type"] == "PR") { $child_test = json_decode($px["child_test"], true); foreach ($child_test as $xt) { //check if already exists if (in_array($xt["T_TestID"], $check_test)) continue; $check_test[] = $xt["T_TestID"]; $a_test[] = [ "ss_price_id" => $xt["Ss_PriceMouID"] ?? null, "t_id" => $xt["T_TestID"], "t_cito" => $xt["T_PriceIsCito"], "t_price" => $xt["T_PriceAmount"], "t_disc" => $xt["T_PriceDisc"], "t_discrp" => $xt["T_PriceDiscRp"], "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => $xt["is_packet"], "t_packettype" => "PR", //$xt["px_type"], "t_packetid" => $xt["packet_id"], ]; } } elseif ($px["px_type"] == "PXR") { if (in_array($px["T_TestID"], $check_test)) continue; $check_test[] = $px["T_TestID"]; $a_test[] = [ "ss_price_id" => $px["Ss_PriceMouID"] ?? null, "t_id" => $px["T_TestID"], "t_cito" => $px["T_PriceIsCito"], "t_price" => $px["T_PriceAmount"], "t_disc" => $px["T_PriceDisc"], "t_discrp" => $px["T_PriceDiscRp"], "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => $px["is_packet"], "t_packettype" => "PR", "t_packetid" => $px["packet_id"], "child_test" => $px["child_test"], ]; // $child_test = json_decode($px["child_test"], true); // foreach ($child_test as $xt) { // $a_test[] = [ // "t_id" => $xt["T_TestID"], // "t_cito" => $xt["T_PriceIsCito"], // "t_price" => $xt["T_PriceAmount"], // "t_disc" => $xt["T_PriceDisc"], // "t_discrp" => $xt["T_PriceDiscRp"], // "t_req" => "Y", // "t_reqnote" => "", // "t_ispacket" => $xt["is_packet"], // "t_packettype" => "PX", //$xt["px_type"], // "t_packetid" => $xt["packet_id"], // ]; // } } else { if (in_array($px["T_TestID"], $check_test)) continue; $check_test[] = $px["T_TestID"]; $a_test[] = [ "ss_price_id" => $px["Ss_PriceMouID"] ?? null, "t_id" => $px["T_TestID"], "t_cito" => $px["T_PriceIsCito"], "t_price" => $px["T_PriceAmount"], "t_disc" => $px["T_PriceDisc"], "t_discrp" => $px["T_PriceDiscRp"], "t_req" => "Y", "t_reqnote" => "", "t_ispacket" => $px["is_packet"], "t_packettype" => $px["px_type"], "t_packetid" => $px["packet_id"], ]; } } } return $a_test; } /** * Memanggil controller mockup FO IBL Order->save() (menggantikan sp_fo_register_save_online). * Bukan HTTP online, hanya beda controller: mockup/fo/ibl_registration/Order. * fpp_id diisi 7, reference pakai Artikel (M_ReferenceID 3). * * @return array [ success: bool, T_OrderHeaderID: int, orderNo: string, error_message: string ] */ private function call_fo_register_save_online($x_orderheader, $xdelivery, $xdetails, $xreq) { $header = [ 'patient_id' => (string) $x_orderheader['patient_id'], 'age' => $x_orderheader['age'] ?? '', 'alias_doctor_name' => '', 'alias_doctor_address' => '', 'sender_doctor_id' => (string) $x_orderheader['sender_doctor_id'], 'sender_address_id' => (string) $x_orderheader['sender_address_id'], 'pj_doctor_id' => (string) $x_orderheader['pj_doctor_id'], 'lang_id' => $x_orderheader['lang_id'] ?? '1', 'lang_si' => $x_orderheader['lang_si'] ?? 'N', 'lang_id_2' => $x_orderheader['lang_id_2'] ?? 0, 'lang_si_2' => $x_orderheader['lang_si_2'] ?? 'N', 'doctor_note' => $x_orderheader['doctor_note'] ?? '', 'fo_note' => $x_orderheader['fo_note'] ?? '', 'patient_note' => '', 'company_id' => (string) $x_orderheader['company_id'], 'mou_id' => (int) $x_orderheader['mou_id'], 'received_sample' => ['flag' => 'N', 'time' => ''], 'queue' => $x_orderheader['queue'] ?? '', 'diagnose' => '', 'is_cito' => 'N', 'cito_id' => '2', 'mcu_pre_id' => -1, 'reference' => [ ['M_ReferenceID' => '3', 'M_ReferenceName' => 'Artikel', 'M_ReferenceIsActive' => 'Y'], ], 'fpp_id' => '7', 'preregister_promise' => '', 'pre_register_id' => 0, ]; $delivery_for_api = []; $delivery_ids = array_unique(array_column($xdelivery, 'delivery_id')); $delivery_codes = []; if (count($delivery_ids) > 0) { $db_onedev = $this->load->database('onedev', true); $ids_placeholders = implode(',', array_fill(0, count($delivery_ids), '?')); $q = $db_onedev->query( "SELECT d.M_DeliveryID, dt.M_DeliveryTypeCode FROM m_delivery d " . "JOIN m_deliverytype dt ON d.M_DeliveryM_DeliveryTypeID = dt.M_DeliveryTypeID " . "WHERE d.M_DeliveryID IN ({$ids_placeholders})", array_values($delivery_ids) ); if ($q) { foreach ($q->result_array() as $r) { $delivery_codes[(string) $r['M_DeliveryID']] = $r['M_DeliveryTypeCode']; } } } foreach ($xdelivery as $d) { $delivery_for_api[] = [ 'delivery_id' => (string) $d['delivery_id'], 'delivery_code' => $delivery_codes[(string) $d['delivery_id']] ?? '', 'delivery_type_id' => (string) ($d['delivery_type_id'] ?? ''), 'address_id' => (string) ($d['address_id'] ?? '0'), 'note' => $d['note'] ?? '', 'noteplus' => '', 'kelurahan' => (string) ($d['kelurahan'] ?? '0'), 'regional_cd' => (string) ($d['kelurahan'] ?? '0'), ]; } $detail_for_api = []; foreach ($xdetails as $d) { $row = [ 't_id' => (string) $d['t_id'], 't_price' => (string) $d['t_price'], 't_disc' => (string) ($d['t_disc'] ?? '0'), 't_discrp' => (string) ($d['t_discrp'] ?? '0'), 't_cito' => $d['t_cito'] ?? 'N', 't_req' => $d['t_req'] ?? 'N', 't_reqnote' => $d['t_reqnote'] ?? '', 't_ispacket' => $d['t_ispacket'] ?? 'N', 't_packetid' => (string) ($d['t_packetid'] ?? '0'), 't_packettype' => $d['t_packettype'] ?? 'PX', ]; if (!empty($d['ss_price_id'])) { $row['ss_price_id'] = (string) $d['ss_price_id']; } $detail_for_api[] = $row; } $req_for_api = [ 'status' => $xreq['status'] ?? 'Y', 'reqs' => is_array($xreq['reqs'] ?? []) ? $xreq['reqs'] : [], ]; if (is_string($xreq['reqs'] ?? null)) { $req_for_api['reqs'] = json_decode($xreq['reqs'], true) ?: []; } $body = [ '_internal' => true, 'mcuid' => null, 'preid' => null, 'order_id' => -1, 'header' => $header, 'delivery' => $delivery_for_api, 'delivery_note' => [], 'detail' => $detail_for_api, 'req' => $req_for_api, 'preregister_promise' => '', 'tests' => [], ]; // MY_Controller (parent Order) load library 'jwt' yang expect class CI_Jwt; library kita pakai class JWT if (!class_exists('CI_Jwt', false)) { if (!class_exists('JWT', false)) { require_once APPPATH . 'libraries/Jwt.php'; } if (class_exists('JWT', false)) { class_alias('JWT', 'CI_Jwt'); } } require_once APPPATH . 'controllers/mockup/fo/ibl_registration/Order.php'; $order_ctrl = new Order(); $order_ctrl->sys_input = $body; $order_ctrl->sys_user = ['M_UserID' => $this->CONFIRM_USER_ID, 'M_UserUsername' => 'hs_generate']; $order_ctrl->isLogin = true; $result = $order_ctrl->save(); if (!is_array($result)) { return [false, 0, '', 'Order->save() tidak mengembalikan array']; } if (isset($result['status']) && $result['status'] === 'ERR') { return [false, 0, '', $result['message'] ?? 'Order/save error']; } if (isset($result['status']) && $result['status'] === 'OK' && !empty($result['data']['data']['id']) && !empty($result['data']['data']['number'])) { return [true, (int) $result['data']['data']['id'], (string) $result['data']['data']['number'], '']; } return [false, 0, '', 'Order/save response tanpa data.id/number']; } function generate_header($txMouID, $order) { if ($order["M_PatientM_SexID"] == "" || $order["M_PatientM_SexID"] < 1) { $this->db->trans_rollback(); $this->log("Error M_PatientM_SexID null"); $this->log(print_r($order, true)); exit; } if ( $order["M_PatientIsLocal"] == "Y" && $order["M_PatientLocalM_PatientID"] > 0 ) { $M_PatientID = $order["M_PatientLocalM_PatientID"]; $sql = "select M_PatientAddressID from m_patientaddress where M_PatientAddressM_PatientID = ? and M_PatientAddressIsActive = 'Y' limit 0,1"; $qry = $this->db->query($sql, [$M_PatientID]); if (!$qry) { $this->log("{$this->now()} ERR get pasien address : {$this->db->error()["message"]}"); return [false, "Error Get Pasien Address M_PatientID $M_PatientID", [], 0]; } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("{$this->now()} ERR No pasien address"); return [false, "Error M_PatientID : $M_PatientID not found", [], 0]; } $M_PatientAddressID = $rows[0]["M_PatientAddressID"]; $this->log( " Update Bizone M_Patient one_hs_lab.M_PatientID {$order["M_PatientID"]}" ); $this->update_pasien($order["M_PatientID"]); } else { $this->log( " New Bizone M_Patient one_hs_lab.M_PatientID {$order["M_PatientID"]}" ); list($M_PatientID, $M_PatientAddressID) = $this->get_patient_by_id( $order["M_PatientM_IdTypeID"], $order["M_PatientIDNumber"] ); if ($M_PatientID == 0) { list( $M_PatientID, $M_PatientAddressID, $msg, ) = $this->add_pasien($order["M_PatientID"]); } } // force return false for DEBUG // return [ // false, // "debug generae patient " . // $order["M_PatientIDNumber"] . // " Not Found : " . // $msg, // [], // 0, // ]; if ($M_PatientID == 0) { return [ false, "Patient with ID : " . $order["M_PatientIDNumber"] . " Not Found : " . $msg, [], 0, ]; } $fo_note = "HS : " . $order["T_OrderQrCode"]; $xheader = [ "date" => date("Y-m-d H:i:s"), "patient_id" => $M_PatientID, "age" => $this->get_age( $order["M_PatientDOB"], date("Y-m-d H:i:s") ), "sender_doctor_id" => $this->SENDER_DOCTOR_ID, "sender_address_id" => $this->SENDER_ADDRESS_ID, "pj_doctor_id" => $this->PJ_DOCTOR_ID, "company_id" => $this->get_company_id($txMouID), "mou_id" => $txMouID, "lang_id" => "1", "lang_si" => "N", "doctor_note" => "", "fo_note" => $fo_note, "queue" => "", "received_sample" => "N", "lang_id_2" => "0", "lang_si_2" => "N", ]; return [true, "", $xheader, $M_PatientAddressID]; } public function update_pasien($hsPatientID) { $sql = "select * from one_hs_lab.m_patient where M_PatientID=?"; $qry = $this->db->query($sql, [$hsPatientID]); if (!$qry) { $this->log($this->db->error()["message"]); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No one_hs M_Patient record"); $this->db->trans_rollback(); exit(); } $pasien = $rows[0]; //print_r($pasien); $arr = [ "M_PatientM_TitleID" => $pasien["M_PatientM_TitleID"], "M_PatientName" => $pasien["M_PatientName"], "M_PatientDOB" => $pasien["M_PatientDOB"], "M_PatientM_SexID" => $pasien["M_PatientM_SexID"], "M_PatientJob" => $pasien["M_PatientJob"], "M_PatientM_IdTypeID" => $pasien["M_PatientM_IdTypeID"], "M_PatientIDNumber" => $pasien["M_PatientIDNumber"], "M_PatientUserID" => $this->CONFIRM_USER_ID, ]; $M_PatientID = $pasien["M_PatientLocalM_PatientID"]; $this->db->where("M_PatientID", $M_PatientID); $qry = $this->db->update("m_patient", $arr); //echo $this->db->last_query(); if (!$qry) { $this->log( "Erro Update Bizone M_Patient " . $this->db->error()["message"] ); $this->db->trans_rollback(); exit(); } $sql = "select M_PatientAddressID from m_patientaddress where M_PatientAddressM_PatientID = ? and M_PatientAddressIsActive = 'Y' order by M_PatientAddressID limit 0,1"; $qry = $this->db->query($sql, [$M_PatientID]); if (!$qry) { $this->log( "Erro Get Bizone First Active M_PatientAddress " . $this->db->error()["message"] ); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No BizOne First M_PatientAddress record"); return; } $M_PatientAddressID = $rows[0]["M_PatientAddressID"]; $sql = "select * from one_hs_lab.m_patientaddress where M_PatientAddressM_PatientID=? and M_PatientAddressIsActive='Y'"; $qry = $this->db->query($sql, [$hsPatientID]); if (!$qry) { $this->log($this->db->error()["message"]); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No one_hs M_PatientAddress record"); return; } $address = $rows[0]; $arr = [ "M_PatientAddressNote" => $address["M_PatientAddressNote"], "M_PatientAddressDescription" => $address["M_PatientAddressDescription"], "M_PatientAddressM_KelurahanID" => $address["M_PatientAddressM_KelurahanID"], "M_PatientAddressLastUpdated" => date("Y-m-d H:i:s"), "M_PatientAddressUserID" => $this->CONFIRM_USER_ID, ]; $this->db->where("M_PatientAddressID", $M_PatientAddressID); $qry = $this->db->update("m_patientaddress", $arr); if (!$qry) { $this->log( "Erro Update Bizone M_PatientAddress " . $this->db->error()["message"] ); $this->db->trans_rollback(); exit(); } } public function add_pasien($hsPatientID) { $sql = "select * from one_hs_lab.m_patient where M_PatientID=?"; $qry = $this->db->query($sql, [$hsPatientID]); if (!$qry) { $this->log($this->db->error()["message"]); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No one_hs M_Patient record"); $this->db->trans_rollback(); exit(); } $pasien = $rows[0]; if ( $pasien["M_PatientM_SexID"] == "" || $pasien["M_PatientM_SexID"] < 1 ) { $this->log("Sex ID Error one_hs M_Patient"); $this->db->trans_rollback(); exit(); } if ( $pasien["M_PatientM_TitleID"] == "" || $pasien["M_PatientM_TitleID"] < 1 ) { $this->log("M_TitleID Error one_hs M_Patient"); $this->db->trans_rollback(); exit(); } $arr = [ "M_PatientM_TitleID" => $pasien["M_PatientM_TitleID"], "M_PatientName" => $pasien["M_PatientName"], "M_PatientDOB" => $pasien["M_PatientDOB"], "M_PatientM_SexID" => $pasien["M_PatientM_SexID"], "M_PatientJob" => $pasien["M_PatientJob"], "M_PatientM_IdTypeID" => $pasien["M_PatientM_IdTypeID"], "M_PatientIDNumber" => $pasien["M_PatientIDNumber"], "M_PatientUserID" => $this->CONFIRM_USER_ID, ]; $qry = $this->db->insert("m_patient", $arr); $M_PatientID = $this->db->insert_id(); if (!$qry) { return [ 0, 0, "Add Patient " . $this->db->error()["message"] . " | " . $this->db->last_query(), ]; } $sql = "select * from one_hs_lab.m_patientaddress where M_PatientAddressM_PatientID = ? and M_PatientAddressIsActive = 'Y' order by M_PatientAddressID limit 0,1"; $qry = $this->db->query($sql, [$hsPatientID]); if (!$qry) { $this->log($this->db->error()["message"]); $this->db->trans_rollback(); exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { $this->log("No one_hs M_PatientAddress record"); $this->db->trans_rollback(); exit(); } $M_PatientAddressID = 0; foreach ($rows as $d) { $arr = [ "M_PatientAddressM_PatientID" => $M_PatientID, "M_PatientAddressNote" => $d["M_PatientAddressNote"], "M_PatientAddressDescription" => $d["M_PatientAddressDescription"], "M_PatientAddressM_KelurahanID" => $d["M_PatientAddressM_KelurahanID"], "M_PatientAddressUserID" => $this->CONFIRM_USER_ID, ]; $qry = $this->db->insert("m_patientaddress", $arr); if (!$qry) { return [$M_PatientID, 0, $this->db->error()["message"]]; } $M_PatientAddressID = $this->db->insert_id(); } return [$M_PatientID, $M_PatientAddressID, ""]; } public function get_patient_by_id($idType, $idNo, $noreg = "") { $sql = "select * from m_patient where ( ( M_PatientM_IdTypeID=? and M_PatientIDNumber=? ) ) and M_PatientIsActive='Y'"; $qry = $this->db->query($sql, [$idType, $idNo]); if (!$qry) { echo "{$this->now()} ERR get pasien : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { return [0, 0]; } $patientID = $rows[0]["M_PatientID"]; $sql = "select M_PatientAddressID from m_patientaddress where M_PatientAddressM_PatientID = ? and M_PatientAddressIsActive = 'Y' limit 0,1"; $qry = $this->db->query($sql, [$patientID]); if (!$qry) { echo "{$this->now()} ERR get pasien address : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { return [$patientID, 0]; } return [$patientID, $rows[0]["M_PatientAddressID"]]; } public function get_company_id($mouID) { $sql = "select * from m_mou where M_MouID=?"; $qry = $this->db->query($sql, [$mouID]); if (!$qry) { echo "{$this->now()} ERR get Company : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { return 0; } return $rows[0]["M_MouM_CompanyID"]; } public function get_age($dob, $order_date) { $sql = "select fn_global_age_count(?,?) xage"; $qry = $this->db->query($sql, [$dob, $order_date]); if (!$qry) { echo "{$this->now()} ERR get Age : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { return ""; } return $rows[0]["xage"]; } }