Files
BE_IBL/application/controllers/mockup/fo/resultemailv7/Done.php
2026-05-24 22:15:13 +07:00

447 lines
12 KiB
PHP

<?php
class Done extends MY_Controller
{
var $db_onedev;
var $db_log;
public function index()
{
echo "SampleStorage API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
$this->db_log = $this->load->database("one_lab_log", true);
}
public function search()
{
$prm = $this->sys_input;
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$nolab = $prm["nolab"];
$groupid = $prm["groupid"];
//$subgroupid = $prm["subgroupid"];
$join_group = '';
if($groupid != '0'){
$join_group = "JOIN nat_group ON T_TestNat_GroupID = Nat_GroupID AND Nat_GroupID = {$groupid}";
}
/*$join_subgroup = '';
if($subgroupid != 0){
$join_group = "JOIN nat_subgroup ON T_TestNat_SubgroupID = Nat_SubgroupID AND Nat_SubgroupID = {$subgroupid}";
}*/
if(!isset($prm['current_page']))
$prm['current_page'] = 1;
$sql_where = "WHERE Result_FrontOfficeStatus = 'S' AND JSON_CONTAINS(Result_FrontOfficeIds,T_OrderDetailID)";
$number_limit = 10;
$number_offset = ($prm['current_page'] - 1) * $number_limit ;
//$sql_param = array();
if ($nolab != "" ) {
if ($sql_where != "") {
$sql_where .=" and ";
}
$sql_where .= " ( T_OrderHeaderLabNumber like '%$nolab%' OR M_PatientName like '%$nolab%' )";
}
/*if ($nama != "") {
if ($sql_where != "") {
$sql_where .=" and ";
}
$sql_where .= " M_PatientName like '%$nama%' ";
}*/
$sql = "SELECT Result_FrontOfficeID as xid,
T_OrderHeaderID as orderid,
T_OrderHeaderLabNumber as ordernumber,
UPPER(CONCAT(M_TitleName,' ',M_PatientName)) as patient_fullname,
Result_FrontOfficeTestName as test_name,
'N' as chex
FROM result_frontoffice
join t_orderheader ON Result_FrontOfficeT_OrderHeaderID = T_OrderHeaderID
JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID
JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND JSON_CONTAINS(Result_FrontOfficeIds, T_OrderDetailID)
$join_group
JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN m_sex ON M_PatientM_SexID = M_SexID
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
$sql_where
GROUP BY Result_FrontOfficeID
";
$query = $this->db_onedev->query($sql);
$rows = $query->result_array();
foreach($rows as $k => $v){
if($v['chex'] == 'N')
$rows[$k]['chex'] = false;
else
$rows[$k]['chex'] = true;
}
$result = array("total" => count($rst), "records" => $rows, "sql"=> '');
$this->sys_ok($result);
exit;
}
function getkerajaan(){
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
//$rst = array(array('id'=>0,'name'=>'Semua'));
$sql = "SELECT 0 as id, 'Semua' as name UNION SELECT Nat_GroupID as id, Nat_GroupName as name FROM nat_group WHERE Nat_GroupIsActive = 'Y'";
$rst_db = $this->db_onedev->query($sql)->result_array();
//$c = array_combine($rst,$rst_db);
$result = array(
"total" => 1 ,
"records" => $rst_db
);
$this->sys_ok($result);
exit;
}
function dosend(){
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$userid = $this->sys_user['M_UserID'];
$selected = $prm['selected'];
foreach($selected as $k => $v){
$sql = "UPDATE result_frontoffice SET Result_FrontOfficeStatus = 'R' WHERE Result_FrontOfficeID = {$v['xid']}";
$this->db_onedev->query($sql);
}
$result = array(
"total" => 1 ,
"records" => array('status'=>'OK'),
);
$this->sys_ok($result);
exit;
}
function sendemail(){
try {
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$userid = $this->sys_user['M_UserID'];
$rows = array();
$sql = "INSERT INTO result_handoveremail (
Result_HandOverEmailSendDateTime,
Result_HandOverEmailT_OrderHeaderID,
Result_HandOverEmailT_OrderPromiseID,
Result_HandOverEmailT_OrderDeliveryID,
Result_HandOverEmailOfficer,
Result_HandOverEmailCreated,
Result_HandOverEmailUserID
)VALUES(
NOW(),
{$prm['order_id']},
{$prm['order_promise_id']},
{$prm['delivery_id']},
{$userid},
NOW(),
{$userid}
)
";
//echo $sql;
$this->db_onedev->query($sql);
$result = array ("total" => 0, "records" => $rows);
$this->sys_ok($result);
} catch(Exception $exc) {
$message = $exc->getMessage();
$this->sys_error($message);
}
}
function resendemail(){
try {
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$userid = $this->sys_user['M_UserID'];
$rows = array();
$sql = "UPDATE result_handoveremail SET
Result_HandOverEmailSendDateTime = NOW(),
Result_HandOverEmailOfficer = {$userid},
Result_HandOverEmailStatus = 'S',
Result_HandOverEmailRetry = 0,
Result_HandOverEmailUserID = {$userid}
WHERE
Result_HandOverEmailID = {$prm['xid']}
";
//echo $sql;
$this->db_onedev->query($sql);
$result = array ("total" => 0, "records" => $rows);
$this->sys_ok($result);
} catch(Exception $exc) {
$message = $exc->getMessage();
$this->sys_error($message);
}
}
function updateemail(){
try {
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$userid = $this->sys_user['M_UserID'];
$rows = array();
$id = $prm['id'];
$sql = "UPDATE t_orderdelivery SET T_OrderDeliveryDestination = '{$prm['edited_email']}', T_OrderDeliveryUserID = {$userid} WHERE T_OrderDeliveryID = {$id}";
//echo $sql;
$this->db_onedev->query($sql);
$result = array ("total" => 0, "records" => array());
$this->sys_ok($result);
} catch(Exception $exc) {
$message = $exc->getMessage();
$this->sys_error($message);
}
}
function send_email_v2()
{
try {
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
return;
}
$prm = $this->sys_input;
$userid = isset($this->sys_user['M_UserID']) ? $this->sys_user['M_UserID'] : 0;
$order_header_id = isset($prm['T_OrderHeaderID']) ? $prm['T_OrderHeaderID'] : 0;
$recepient_email = isset($prm['T_SendEmailRecepient'])
? $prm['T_SendEmailRecepient']
: '';
if ($order_header_id == 0 || $recepient_email == '') {
$this->sys_error("Order ID dan Email wajib diisi");
return;
}
$type = isset($prm['type']) ? $prm['type'] : 'S';
$email_config = isset($prm['email_config']) ? $prm['email_config'] : [];
if (is_string($email_config)) {
$email_config = json_decode($email_config, true);
}
// Ambil value 'format' saja untuk disimpan sebagai string
$narratives = isset($email_config['format']) ? $email_config['format'] : '';
$status = isset($prm['status']) ? $prm['status'] : 'S';
// Build reports dari qr_printout: [{"id":"1","url":"...","result":"LAB"}, ...]
$sql_qr = "SELECT
QR_PrintOutID AS id,
QR_PrintOutReportURLElectronic AS url,
QR_PrintOutGroup_ResultName AS result
FROM qr_printout
WHERE QR_PrintOutT_OrderHeaderID = ?
AND QR_PrintOutIsActive = 1
ORDER BY QR_PrintOutID ASC";
$qr_rows = $this->db_onedev->query($sql_qr, [$order_header_id]);
$reports_arr = [];
if ($qr_rows && $qr_rows->num_rows() > 0) {
foreach ($qr_rows->result_array() as $idx => $qr) {
$reports_arr[] = [
'id' => (string)($idx + 1),
'url' => $qr['url'],
'result' => $qr['result'],
];
}
}
$reports = json_encode($reports_arr);
// Extract result names for log
$group_result_names = array_column($reports_arr, 'result');
$group_result_name_str = implode(', ', $group_result_names);
$payload_json = json_encode($prm);
// ================= UPDATE (DB ONE_LAB) =================
$this->db_onedev->trans_begin();
$sql_update = "UPDATE t_send_email
SET
T_SendEmailType = ?,
T_SendEmailReports = ?,
T_SendEmailNarratives = ?,
T_SendEmailStatus = ?,
T_SendEmailLastUpdated = NOW(),
T_SendEmailLastUpdatedUserID = ?
WHERE
T_SendEmailT_OrderHeaderID = ?
AND
T_SendEmailRecepient = ?
AND
T_SendEmailIsActive = 'Y'";
$this->db_onedev->query($sql_update, array(
$type,
$reports,
$narratives,
$status,
$userid,
$order_header_id,
$recepient_email
));
if ($this->db_onedev->affected_rows() == 0) {
throw new Exception("Update gagal / data tidak ditemukan");
}
$this->db_onedev->trans_commit();
// ================= INSERT LOG (DB ONE_LAB_LOG) =================
$sql_log = "INSERT INTO t_send_email_log (
T_SendEmailLogT_OrderHeaderID,
T_SendEmailLogRecepient,
T_SendEmailLogStatus,
T_SendEmailLogResponse,
T_SendEmailLogGroup_ResultName,
T_SendEmailLogJson,
T_SendEmailLogCreated,
T_SendEmailLogCreatedUserID
) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)";
$this->db_log->query($sql_log, array(
$order_header_id,
$recepient_email,
$status,
'',
$group_result_name_str,
$payload_json,
$userid
));
if ($this->db_log->affected_rows() == 0) {
throw new Exception("Insert log gagal");
}
$result = array(
"status" => "OK",
"message" => "Update berhasil & log tersimpan"
);
$this->sys_ok($result);
} catch (Exception $e) {
if ($this->db_onedev->trans_status() === FALSE) {
$this->db_onedev->trans_rollback();
}
$this->sys_error($e->getMessage());
}
}
function cancel_email()
{
try {
if (!$this->isLogin) {
$this->sys_error("Invalid Token");
return;
}
$prm = $this->sys_input;
$userid = isset($this->sys_user['M_UserID']) ? $this->sys_user['M_UserID'] : 0;
$order_header_id = isset($prm['T_OrderHeaderID']) ? (int) $prm['T_OrderHeaderID'] : 0;
$recepient_email = isset($prm['T_SendEmailRecepient']) ? trim($prm['T_SendEmailRecepient']) : '';
if ($order_header_id == 0 || $recepient_email == '') {
$this->sys_error("Order ID dan Email wajib diisi");
return;
}
// Hanya boleh cancel jika status masih S (Sending/queued)
$check = $this->db_onedev->query("
SELECT T_SendEmailID, T_SendEmailStatus
FROM t_send_email
WHERE T_SendEmailT_OrderHeaderID = ?
AND T_SendEmailRecepient = ?
AND T_SendEmailIsActive = 'Y'
LIMIT 1
", [$order_header_id, $recepient_email])->row_array();
if (!$check) {
$this->sys_error("Data email tidak ditemukan");
return;
}
if ($check['T_SendEmailStatus'] !== 'S') {
$this->sys_error("Tidak bisa dicancel, status saat ini: " . $check['T_SendEmailStatus']);
return;
}
$this->db_onedev->query("
UPDATE t_send_email
SET T_SendEmailStatus = 'C',
T_SendEmailLastUpdated = NOW(),
T_SendEmailLastUpdatedUserID = ?
WHERE T_SendEmailID = ?
", [$userid, $check['T_SendEmailID']]);
$this->db_log->query("
INSERT INTO t_send_email_log
(T_SendEmailLogT_OrderHeaderID, T_SendEmailLogRecepient,
T_SendEmailLogStatus, T_SendEmailLogResponse,
T_SendEmailLogGroup_ResultName, T_SendEmailLogJson,
T_SendEmailLogCreated, T_SendEmailLogCreatedUserID)
VALUES (?, ?, 'C', NULL, '', ?, NOW(), ?)
", [
$order_header_id,
$recepient_email,
json_encode($prm),
$userid,
]);
$this->sys_ok([
"status" => "OK",
"message" => "Email berhasil dicancel"
]);
} catch (Exception $e) {
$this->sys_error($e->getMessage());
}
}
}