db_smartone = $this->load->database("onedev", true); $this->db_log = $this->load->database("one_lab_log", true); $this->load->library('ibl_encryptor'); $this->load->helper("uuid"); } function xxxget_time_start() { $prm = $this->sys_input; $s_menu_preregister = $this->db_smartone->query("SELECT S_MenuUrl FROM s_menu WHERE S_MenuName = 'Pre-Register' AND S_MenuIsActive = 'Y' LIMIT 1")->row(); $s_menu_register = $this->db_smartone->query("SELECT S_MenuUrl FROM s_menu WHERE S_MenuName = 'Registration' AND S_MenuIsActive = 'Y' LIMIT 1")->row(); if ($prm['pre_id'] != -1 && $prm['pre_id'] != 0 && $prm['pre_id'] != null) { $sql = $this->db_smartone->query("SELECT IF(Mgm_McuM_BranchID = 100,0,Mcu_PreregisterPatientsT_OrderHeaderID) as t_orderid FROM mcu_preregister_patients JOIN mgm_mcu ON Mgm_McuID = Mcu_PreregisterPatientsMgm_McuID WHERE Mcu_PreregisterPatientsID = {$prm['pre_id']}")->row(); $t_orderid = $sql->t_orderid; } $rows = date("Y-m-d H:i:s"); $this->sys_ok(["records" => $rows, "total" => 1, "q" => $this->db_smartone->last_query(), "orderid" => $t_orderid, "url_preregister" => $s_menu_preregister->S_MenuUrl, "url_register" => $s_menu_register->S_MenuUrl]); } function get_time_start() { if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $rows = date("Y-m-d H:i:s"); $this->sys_ok(["records" => $rows, "total" => 1, "q" => $this->db_smartone->last_query()]); } function check_exist_details($details, $detail) { $rst = false; foreach ($details as $key => $value) { if ($value['t_id'] == $detail['t_id']) $rst = true; } return $rst; } function convert_to_normal_text($text) { $normal_characters = "a-zA-Z0-9\s`~!@#$%^&*()_+-={}|:;<>?,.\/\"\'\\\[\]"; $normal_text = preg_replace("/[^$normal_characters]/", '', $text); return $normal_text; } function genqrcode($nomorlab, $id) { $this->load->library('ciqrcode'); //pemanggilan library QR CODE $home_dir = "/home/one/project/one/"; $target_dir = $home_dir . "one-media/one-qrcontrolcard/"; $config['cacheable'] = false; //boolean, the default is true //$config['cachedir'] = './assets/'; //string, the default is application/cache/ //$config['errorlog'] = './assets/'; //string, the default is application/logs/ $config['imagedir'] = $target_dir; //direktori penyimpanan qr code $config['quality'] = true; //boolean, the default is true $config['size'] = '1024'; //interger, the default is 1024 $config['black'] = array(224, 255, 255); // array, default is array(255,255,255) $config['white'] = array(70, 130, 180); // array, default is array(0,0,0) $this->ciqrcode->initialize($config); $image_name = "qrcode_" . $nomorlab . ".png"; //buat name dari qr code sesuai dengan nim $params['data'] = $_SERVER['HTTP_HOST'] . "/one-ui-lab/test/vuex/cpone-control-card/?noreg=" . $nomorlab . "&id=" . $id; //data yang akan di jadikan QR CODE $params['level'] = 'H'; //H=High $params['size'] = 10; $params['savename'] = $config['imagedir'] . $image_name; //simpan image QR CODE ke folder assets/images/ $this->ciqrcode->generate($params); // fungsi untuk generate QR CODE return $_SERVER['HTTP_HOST'] . "/one-api-lab/assets/images/" . $image_name; } function genpatientqrcode($nomorlab) { $this->load->library('ciqrcode'); //pemanggilan library QR CODE $home_dir = "/home/one/project/one/"; $target_dir = $home_dir . "one-media/one-qrpatient/"; $config['cacheable'] = false; //boolean, the default is true //$config['cachedir'] = './assets/'; //string, the default is application/cache/ //$config['errorlog'] = './assets/'; //string, the default is application/logs/ $config['imagedir'] = $target_dir; //direktori penyimpanan qr code $config['quality'] = true; //boolean, the default is true $config['size'] = '1024'; //interger, the default is 1024 $config['black'] = array(224, 255, 255); // array, default is array(255,255,255) $config['white'] = array(70, 130, 180); // array, default is array(0,0,0) $init = $this->ciqrcode->initialize($config); //print_r($init); $image_name = "patient_qr_" . $nomorlab . ".png"; //buat name dari qr code sesuai dengan nim $params['data'] = $nomorlab; //data yang akan di jadikan QR CODE $params['level'] = 'H'; //H=High $params['size'] = 10; $params['savename'] = $config['imagedir'] . $image_name; //simpan image QR CODE ke folder assets/images/ $save = $this->ciqrcode->generate($params); // fungsi untuk generate QR CODE //print_r($save); // exit; return $_SERVER['HTTP_HOST'] . "/one-media/one-qrpatient/" . $image_name; //echo "selesai"; } function genformqrcode($uuid) { $this->load->library('ciqrcode'); //pemanggilan library QR CODE $home_dir = "/home/one/project/one/"; $target_dir = $home_dir . "one-media/one-qrpatient/"; $config['cacheable'] = false; //boolean, the default is true //$config['cachedir'] = './assets/'; //string, the default is application/cache/ //$config['errorlog'] = './assets/'; //string, the default is application/logs/ $config['imagedir'] = $target_dir; //direktori penyimpanan qr code $config['quality'] = true; //boolean, the default is true $config['size'] = '1024'; //interger, the default is 1024 $config['black'] = array(224, 255, 255); // array, default is array(255,255,255) $config['white'] = array(70, 130, 180); // array, default is array(0,0,0) $this->ciqrcode->initialize($config); $image_name = "form_qr_" . $uuid . ".png"; //buat name dari qr code sesuai dengan nim $params['data'] = $_SERVER['HTTP_HOST'] . "/one-ui-lab/test/vuex/cpone-riwayat-form-v2/?id=" . $uuid; //data yang akan di jadikan QR CODE $params['level'] = 'H'; //H=High $params['size'] = 10; $params['savename'] = $config['imagedir'] . $image_name; //simpan image QR CODE ke folder assets/images/ $this->ciqrcode->generate($params); // fungsi untuk generate QR CODE return array('image' => $_SERVER['HTTP_HOST'] . "/one-media/one-qrpatient/" . $image_name, 'url' => $params['data']); //echo "selesai"; } function generate_code_string() { $length = 5; $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $code = ''; for ($i = 0; $i < $length; $i++) { $code .= $characters[rand(0, strlen($characters) - 1)]; } return $code; } function generate_uuid() { return lab_uuid_v4(); } function generate_code_form($preid, $orderid) { $userid = $this->sys_user["M_UserID"]; $sql = "SELECT FormRiwayatPasienID, FormRiwayatPasienCode, FormRiwayatPasienUUID, FormRiwayatPasienT_OrderHeaderID FROM form_riwayat_pasien WHERE FormRiwayatPasienPreregisterID = ? AND FormRiwayatPasienIsActive = 'Y' ORDER BY FormRiwayatPasienID DESC LIMIT 1"; $qry = $this->db_onedev->query($sql, [$preid]); if (!$qry) { return ''; } $exist = $qry->row_array(); if ($exist) { if ((int) $exist['FormRiwayatPasienT_OrderHeaderID'] !== (int) $orderid) { $sql = "UPDATE form_riwayat_pasien SET FormRiwayatPasienT_OrderHeaderID = ?, FormRiwayatPasienLasUpdated = NOW(), FormRiwayatPasienLasUpdatedUserID = ? WHERE FormRiwayatPasienID = ?"; $qry = $this->db_onedev->query($sql, [$orderid, $userid, $exist['FormRiwayatPasienID']]); if (!$qry) { return ''; } } return array('uuid' => $exist['FormRiwayatPasienUUID'], 'code' => $exist['FormRiwayatPasienCode']); } $sql = "SELECT COUNT(*) as total FROM form_riwayat_pasien WHERE FormRiwayatPasienT_OrderHeaderID = ? AND FormRiwayatPasienIsActive = 'Y' "; $qry = $this->db_onedev->query($sql, [$orderid]); if ($qry) { $total = $qry->result_array()[0]['total']; if ($total == 0) { $code = $this->generate_code_string(); $uuid = $this->generate_uuid(); $sql = "INSERT INTO form_riwayat_pasien ( FormRiwayatPasienPreregisterID, FormRiwayatPasienCode, FormRiwayatPasienUUID, FormRiwayatPasienT_OrderHeaderID, FormRiwayatPasienCreated, FormRiwayatPasienCreatedUserID) VALUES (?, ?, ?, ?, NOW(), ?)"; $qry = $this->db_onedev->query($sql, [$preid, $code, $uuid, $orderid, $userid]); //echo $this->db_onedev->last_query(); //exit; if (!$qry) { return ''; } return array('uuid' => $uuid, 'code' => $code); } } return ''; } function check_duplicate_nat_tests($data) { // Array untuk menyimpan nat_tests ID yang sudah ditemui beserta detail tesnya $encountered_nat_tests = []; // Array untuk menyimpan informasi duplikat $duplicate_pairs = []; // Flag untuk menandakan ada duplikat atau tidak $has_duplicates = false; // Iterasi melalui setiap item dalam data foreach ($data as $index => $item) { if (isset($item['t_id'])) { $sql = "SELECT * FROM t_test WHERE T_TestID = {$item['t_id']}"; $query = $this->db_smartone->query($sql); //echo $this->db_smartone->last_query(); if (!$query) { $this->sys_error_db(["status" => "ERR", "message" => "select t_test | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } $dt_test = $query->row_array(); $nat_test_id = $dt_test['T_TestNat_TestID']; $test_name = $dt_test['T_TestName']; if (isset($encountered_nat_tests[$nat_test_id])) { $has_duplicates = true; // Buat pasangan nama tes yang berisi duplikat $existing_test = $encountered_nat_tests[$nat_test_id]; $pair_key = ($existing_test < $test_name) ? $existing_test . '|' . $test_name : $test_name . '|' . $existing_test; if (!isset($duplicate_pairs[$pair_key])) { $duplicate_pairs[$pair_key] = [ 'test1' => $existing_test, 'test2' => $test_name ]; } } else { // Jika belum ada, tambahkan ke array encountered_nat_tests $encountered_nat_tests[$nat_test_id] = $test_name; } } else { $test_name = isset($item['T_TestName']) ? $item['T_TestName'] : 'Unknown Test'; // Periksa jika nat_tests ada dan dalam bentuk string JSON if (isset($item['nat_tests']) && is_string($item['nat_tests'])) { // Decode string JSON menjadi array $nat_tests_array = json_decode($item['nat_tests'], true); // Jika decode berhasil dan hasilnya array if (is_array($nat_tests_array)) { // Iterasi melalui setiap nat_tests ID dalam item saat ini foreach ($nat_tests_array as $nat_test_id) { // Jika nat_tests ID sudah ada di array encountered_nat_tests, berarti duplikat if (isset($encountered_nat_tests[$nat_test_id])) { $has_duplicates = true; // Buat pasangan nama tes yang berisi duplikat $existing_test = $encountered_nat_tests[$nat_test_id]; $pair_key = ($existing_test < $test_name) ? $existing_test . '|' . $test_name : $test_name . '|' . $existing_test; if (!isset($duplicate_pairs[$pair_key])) { $duplicate_pairs[$pair_key] = [ 'test1' => $existing_test, 'test2' => $test_name ]; } } else { // Jika belum ada, tambahkan ke array encountered_nat_tests $encountered_nat_tests[$nat_test_id] = $test_name; } } } } } } // Mengembalikan hasil pengecekan return [ 'is_duplicate' => $has_duplicates, 'duplicate_pairs' => array_values($duplicate_pairs) // Convert to indexed array ]; } /** * Simpan order. Bisa dipanggil dari HTTP (sys_input dari request) atau internal * dari controller lain (mis. Generate_order) dengan sys_input berisi _internal => true. * Jika _internal => true, tidak cek token dan mengembalikan array [status, data/message] tanpa exit. */ function save() { $internal = !empty($this->sys_input['_internal']); if (!$internal && !$this->isLogin) { $this->sys_error("Invalid Token"); exit; } // Sanitize semua string dalam data_log agar newline tidak merusak JSON di SQL $sanitize_for_json = function ($data) use (&$sanitize_for_json) { if (is_array($data)) { return array_map($sanitize_for_json, $data); } if (is_string($data)) { return str_replace(["\r\n", "\r", "\n"], ' ', $data); } return $data; }; /* CREATE TABLE `order_payload` ( `OrderPayloadID` int(11) NOT NULL AUTO_INCREMENT, `OrderPayloadM_PatientID` int(11) NOT NULL DEFAULT 0, `OrderPayloadDate` date NOT NULL DEFAULT '0000-00-00', `OrderPayloadJSON` mediumtext NOT NULL DEFAULT '', `OrderPayloadMD5` varchar(150) NOT NULL DEFAULT '', `OrderPayloadIsActive` char(1) NOT NULL DEFAULT 'Y', `OrderPayloadCreated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `OrderPayloadUserID` int(11) NOT NULL DEFAULT 0, PRIMARY KEY (`OrderPayloadID`), KEY `OrderPayloadM_PatientID` (`OrderPayloadM_PatientID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; */ $prm = $this->sys_input; if ($internal) { unset($prm['_internal']); } $userid = $this->sys_user["M_UserID"]; $username = $this->sys_user["M_UserUsername"]; $pre_registerid = isset($prm['preid']) ? $prm['preid'] : 0; $header = $prm['header']; $header['pre_register_id'] = $pre_registerid; $details = $prm['detail']; $mgm_mcuid = isset($prm['mcuid']) ? $prm['mcuid'] : 0; $order_payload = $prm; $md5_payload = md5(json_encode($order_payload)); $patient_id = $header['patient_id']; $sql = "SELECT * FROM order_payload WHERE OrderPayloadM_PatientID = ? AND OrderPayloadMD5 = ? AND OrderPayloadIsActive = 'Y'"; $query = $this->db_log->query($sql, [$patient_id, $md5_payload]); if (!$query) { $msg = "select order_payload | " . $this->db_log->error()["message"]; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg, "debug" => $this->db_log->last_query()]); exit; } $dt_order_payload = $query->row_array(); if (count($dt_order_payload) > 0) { $msg = "Order sudah pernah dibuat"; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error($msg); exit; } $sql = "INSERT INTO order_payload (OrderPayloadM_PatientID, OrderPayloadJSON, OrderPayloadMD5, OrderPayloadIsActive, OrderPayloadCreated, OrderPayloadUserID) VALUES (?, ?, ?, ?, ?, ?)"; $query = $this->db_log->query($sql, [ $patient_id, json_encode($order_payload), $md5_payload, 'Y', date('Y-m-d H:i:s'), $userid ]); if (!$query) { $msg = "insert order_payload | " . $this->db_log->error()["message"]; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg, "debug" => $this->db_log->last_query()]); exit; } $tests = []; foreach ($details as $k => $v) { $dt_test_price = $v; if (isset($v['ss_price_id'])) { $sql = "SELECT * FROM ss_price_mou WHERE Ss_PriceMouID = {$v['ss_price_id']}"; $query = $this->db_smartone->query($sql); if (!$query) { $msg = "select ss_price_mou | " . $this->db_smartone->error()["message"]; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg, "debug" => $this->db_smartone->last_query()]); exit; } $dt_test_price = $query->row_array(); } $tests[] = $dt_test_price; } $check_test = $this->check_duplicate_nat_tests($tests); if ($check_test['is_duplicate']) { $msg = "duplicate test | " . json_encode($check_test['duplicate_pairs']); if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg]); exit; } $this->db_smartone->trans_begin(); $fn_save_order_header = $this->save_order_header($header, $userid, ['skip_patient_note' => $internal]); if (!$fn_save_order_header['status']) { $this->db_smartone->trans_rollback(); $message = $fn_save_order_header['message'] ?? 'Terjadi kesalahan saat menyimpan data header'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } $header_id = $fn_save_order_header['data']['header_id']; $fn_save_order_detail = $this->save_order_detail($details, $header_id, $userid); //print_r($fn_save_order_detail); if (!$fn_save_order_detail['status']) { $this->db_smartone->trans_rollback(); $message = $fn_save_order_detail['message'] ?? 'Terjadi kesalahan saat menyimpan data detail'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } $fn_generate_sample_lab = $this->generate_sample_lab($header_id, $userid); if (!$fn_generate_sample_lab['status']) { $this->db_smartone->trans_rollback(); $message = $fn_generate_sample_lab['message'] ?? 'Terjadi kesalahan saat membuat sample lab'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } $fn_generate_req = $this->generate_req($header_id, $prm['req'], $userid); if (!$fn_generate_req['status']) { $this->db_smartone->trans_rollback(); $message = $fn_generate_req['message'] ?? 'Terjadi kesalahan saat membuat req'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } $fn_update_preregister_promise = $this->update_preregister_promise($header_id, $prm['preregister_promise'], $prm['preid']); if (!$fn_update_preregister_promise['status']) { $this->db_smartone->trans_rollback(); $message = $fn_update_preregister_promise['message'] ?? 'Terjadi kesalahan saat memperbarui promise'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } $fn_order_delivery = $this->save_delivery($header_id, $prm['delivery'], $userid); if (!$fn_order_delivery['status']) { $this->db_smartone->trans_rollback(); $message = $fn_order_delivery['message'] ?? 'Terjadi kesalahan saat membuat delivery'; if ($internal) return ['status' => 'ERR', 'message' => $message]; $this->sys_error($message); exit; } if ($pre_registerid != 0) { $sql_preregister = "UPDATE mcu_preregister_patients SET Mcu_PreregisterPatientsIsRegistered = 'Y', Mcu_PreregisterPatientsT_OrderHeaderID = ? WHERE Mcu_PreregisterPatientsID = ?"; $prm_preregister = [ $header_id, $prm['preid'] ]; $query_preregister = $this->db_smartone->query($sql_preregister, $prm_preregister); if (!$query_preregister) { $message = 'Terjadi kesalahan saat menyimpan data preregister'; if ($internal) { $this->db_smartone->trans_rollback(); return ['status' => 'ERR', 'message' => $message]; } $prm_log = ['UPDATE_MCU_PREREGISTER_PATIENTS', 'order/save', json_encode($query_preregister)]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); $this->sys_error($message); exit; } } // Link ke order klinik jika klinik_number dikirim $klinik_number = trim($header['klinik_number'] ?? ''); if ($klinik_number !== '') { $this->db_smartone->query( "UPDATE one_klinik.`order` SET orderT_OrderHeaderID = ? WHERE OrderNumber = ?", [$header_id, $klinik_number] ); } $sql = "SELECT t_orderheader.* FROM t_orderheader WHERE T_OrderHeaderID = ? LIMIT 1"; $query_orderheader = $this->db_smartone->query($sql, [$header_id]); //echo $this->db_smartone->last_query(); if (!$query_orderheader) { $message = 'Terjadi kesalahan saat mengambil data order header'; if ($internal) { $this->db_smartone->trans_rollback(); return ['status' => 'ERR', 'message' => $message]; } $prm_log = ['SELECT_T_ORDERHEADER', 'order/save', $header_id]; $this->db_smartone->trans_rollback(); $insert_log_error = $this->insert_log_error($this->db_smartone->last_query(), $prm_log); $this->sys_error($message); exit; } //echo $this->db_smartone->last_query(); $x_data_array = $query_orderheader->row_array(); $lab_number = $x_data_array['T_OrderHeaderLabNumber']; $x_data = json_encode($x_data_array); /*$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_fo_status = $this->db_smartone->query($sql, [$header_id, 1, $userid]); if (!$query_fo_status) { $prm_log = ['INSERT_FO_STATUS', 'order/save' ]; $insert_log_error = $this->insert_log_error($this->db_log->last_query(), $prm_log); $this->db_smartone->trans_rollback(); $message = 'Terjadi kesalahan saat menyimpan data fo_status'; $this->sys_error($message); exit; }*/ $genqrcode = $this->genqrcode($lab_number, $header_id); $genpatientqrcode = $this->genpatientqrcode($lab_number); $sql = "SELECT COUNT(DISTINCT FisikTemplateID) as jumlah_fisik_template FROM t_orderheader JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID AND T_OrderDetailIsActive = 'Y' JOIN nat_test ON Nat_TestCode = T_OrderDetailT_TestCode AND Nat_TestIsActive = 'Y' JOIN fisik_map_test_template ON Fisik_MapTestTemplateNat_TestID = Nat_TestID AND Fisik_MapTestTemplateIsActive = 'Y' JOIN fisik_template_mapping ON Fisik_MapTestTemplateFisikTemplateMappingID = FisikTemplateMappingID AND FisikTemplateMappingIsActive = 'Y' JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND FisikTemplateMappingDetailIsActive = 'Y' JOIN fisik_template ON FisikTemplateID = FisikTemplateMappingDetailFisikTemplateID AND FisikTemplateIsActive = 'Y' AND ( FisikTemplateType = 'Riwayat' OR FisikTemplateType = 'K3' ) WHERE T_OrderHeaderID = ?"; $query_orderheader = $this->db_smartone->query($sql, [$header_id]); if (!$query_orderheader) { $msg = "select t_orderheader | " . $this->db_smartone->error()["message"]; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg, "debug" => $this->db_smartone->last_query()]); exit; } $dt_jumlah_fisik_template = $query_orderheader->row_array(); $jumlah_fisik_template = $dt_jumlah_fisik_template['jumlah_fisik_template']; if ($jumlah_fisik_template > 0) { $genformqrcode = ''; $uuid = ''; $get_uuid = $this->generate_code_form($pre_registerid, $header_id); if ($get_uuid && $get_uuid['uuid'] != '') { $uuid = $get_uuid['uuid']; $genformqrcode = $this->genformqrcode($uuid); } } $this->db_smartone->trans_commit(); $fn_generate_location = $this->generate_location($header_id, $userid); $location_warning = null; if ($fn_generate_location['has_failure']) { $failed_parts = array_map(function ($f) { return $f['name'] . ' (ID:' . $f['id'] . ')'; }, $fn_generate_location['failed']); $failed_str = implode(', ', $failed_parts); $location_warning = [ 'has_error' => true, 'message' => "Order tersimpan sebagian. Gagal membuat lokasi: {$failed_str} belum punya mapping m_location aktif. Tindakan: tambahkan mapping lokasi aktif untuk station tersebut lalu retry generate location. OrderID: {$header_id}.", 'failed_stations' => $fn_generate_location['failed'], ]; } $sql = "SELECT * FROM `s_menu` WHERE `S_MenuName` = 'Pre-Register' AND `S_MenuIsActive` = 'Y' LIMIT 1"; $query_menu = $this->db_smartone->query($sql); if (!$query_menu) { $msg = "select s_menu | " . $this->db_smartone->error()["message"]; if ($internal) return ['status' => 'ERR', 'message' => $msg]; $this->sys_error_db(["status" => "ERR", "message" => $msg, "debug" => $this->db_smartone->last_query()]); exit; } $dt_menu = $query_menu->row_array(); //print_r($dt_menu); $xurl = $dt_menu['S_MenuUrl']; $get_order_header = $this->get_order_header($header_id); if (!$get_order_header['status']) { if ($internal) return ['status' => 'ERR', 'message' => $get_order_header['message']]; $this->sys_error($get_order_header['message']); exit; } $order_header = $get_order_header['data']; $get_order_detail = $this->get_order_detail($header_id); if (!$get_order_detail['status']) { if ($internal) return ['status' => 'ERR', 'message' => $get_order_detail['message']]; $this->sys_error($get_order_detail['message']); exit; } $order_detail = $get_order_detail['data']; $get_deliveries = $this->get_deliveries_by_order($header_id); if (!$get_deliveries['status']) { if ($internal) return ['status' => 'ERR', 'message' => $get_deliveries['message']]; $this->sys_error($get_deliveries['message']); exit; } $order_delivery = $get_deliveries['data']; $get_order_promises = $this->get_order_promises($header_id); if (!$get_order_promises['status']) { if ($internal) return ['status' => 'ERR', 'message' => $get_order_promises['message']]; $this->sys_error($get_order_promises['message']); exit; } $order_promise = $get_order_promises['data']; $get_details = $this->get_details($header_id); if (!$get_details['status']) { if ($internal) return ['status' => 'ERR', 'message' => $get_details['message']]; $this->sys_error($get_details['message']); exit; } $order_details = $get_details['data']; $base_params = [ 'PUsername' => $username, 'PT_OrderHeaderID' => $header_id, 'TS' => '#TS' ]; $reports = [ 'invoice_ina_v1' => ['FO-INV-P-INA-01', []], 'invoice_en_v1' => ['FO-INV-P-EN-01', []], 'invoice_ina_v2' => ['FO-INV-P-INA-02', []], 'bp_ina_v1' => ['FO-BP-P-INA-01', ['PAn' => '#ATAS_NAMA']], 'bp_ina_v2' => ['FO-BP-P-INA-02', ['PAn' => '#ATAS_NAMA']], 'kw_ina_v1' => ['FO-KW-P-INA-01', ['PAn' => '#ATAS_NAMA']], 'kw_ina_v2' => ['FO-KW-P-INA-02', ['PAn' => '#ATAS_NAMA']], 'kw_en_v1' => ['FO-KW-P-EN-01', ['PAn' => '#ATAS_NAMA']], 'kw_en_v2' => ['FO-KW-P-EN-02', ['PAn' => '#ATAS_NAMA']], 'ic_ina_v1' => ['FO-IC-P-INA-01', []], 'ic_ina_v2' => ['FO-IC-P-INA-02', []], 'nota_ina_r' => ['FO-NR-P-INA-01', [ 'PPaymentID' => '#PPaymentID' ]], 'nota_ina_b' => ['FO-NB-P-INA-01', [ 'PPaymentID' => '#PPaymentID' ]] ]; foreach ($reports as $key => $config) { $report_url[$key] = $this->get_report_url( $config[0], array_merge($base_params, $config[1]) ); } // Strip PII dari header sebelum masuk log (identitas pasien di m_patient, sudah terenkripsi) $header_for_log = is_array($order_header) ? $order_header : (array)$order_header; foreach (['patient_name','patient_address','patient_phone','patient_email','patient_hp'] as $_pii) { unset($header_for_log[$_pii]); } $data_log = $sanitize_for_json(array( 'header' => $header_for_log, 'detail_order' => $order_detail, 'delivery' => $order_delivery, 'promise' => $order_promise, 'details' => $order_details )); $data_before = []; $sqllog = "INSERT INTO order_log( orderLogType, orderLogT_OrderHeaderID, orderLogJSONBefore, orderLogJSONAfter, orderLogCreated, orderLogUserID) VALUES ('REGISTER',?,'',?,now(),?)"; $querylog = $this->db_log->query($sqllog, [ $header_id, json_encode($data_log), $userid ]); //echo $this->db_log->last_query(); if (!$querylog) { $message = 'Terjadi kesalahan saat menyimpan data log'; if ($internal) { $this->db_smartone->trans_rollback(); return ['status' => 'ERR', 'message' => $message]; } $prm_log = ['INSERT_ORDER_LOG', 'order/save']; $insert_log_error = $this->insert_log_error($this->db_log->last_query(), $prm_log); $this->db_smartone->trans_rollback(); $this->sys_error($message); exit; } $insert_group_order = $this->insert_group_order($header_id); if (!$insert_group_order['status']) { if ($internal) { $this->db_smartone->trans_rollback(); return ['status' => 'ERR', 'message' => $insert_group_order['message']]; } $this->db_smartone->trans_rollback(); $this->sys_error($insert_group_order['message']); exit; } $group_order = $insert_group_order['data']; $url_preregister = $this->get_url_preregister($userid); if (!$url_preregister['status']) { if ($internal) return ['status' => 'ERR', 'message' => $url_preregister['message']]; $this->sys_error($url_preregister['message']); exit; } $url_preregister = $url_preregister['data']; $dt_order = [ 'status' => 'OK', 'order_id' => $x_data_array['T_OrderHeaderID'], 'order_date' => $x_data_array['T_OrderHeaderDate'], 'noreg' => $lab_number, 'qrcode' => $genqrcode, 'patient_qrcode' => $genpatientqrcode, 'form_qrcode' => $genformqrcode, 'uuid' => isset($uuid) ? $uuid : '', 'tipe' => 'new', 'url' => $xurl, 'url_preregister' => $url_preregister, 'data' => array('id' => $header_id, 'number' => $lab_number), 'order_delivery' => isset($prm['delivery']) ? $prm['delivery'] : $order_delivery, 'order_detail' => $order_detail, 'order_header' => $order_header, 'inform_consent' => isset($order_header['inform_consent']) ? $order_header['inform_consent'] : [], 'order_promise' => $order_promise, 'order_details' => $order_details, 'report_url' => $report_url, 'location_warning' => $location_warning, ]; if ($internal) return ['status' => 'OK', 'data' => $dt_order]; $this->sys_ok($dt_order); exit; } function get_url_preregister($userid) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT S_MenuUrl FROM s_menu JOIN s_privilege ON S_PrivilegeS_MenuID = S_MenuID AND S_PrivilegeIsActive = 'Y' JOIN m_usergroup ON S_PrivilegeM_UserGroupID = M_UserGroupID AND M_UserGroupIsActive = 'Y' JOIN m_user ON M_UserID = ? AND M_UserIsActive = 'Y' AND M_UserM_UserGroupID = M_UserGroupID WHERE S_MenuName = 'Pre-Register' AND S_MenuIsActive = 'Y' LIMIT 1"; $query = $this->db_smartone->query($sql, [$userid]); if (!$query) { $this->sys_error_db(["status" => "ERR", "message" => "select s_menu | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } $dt_menu = $query->result_array(); if (count($dt_menu) > 0) { $return['data'] = $dt_menu[0]['S_MenuUrl']; } else { $return['data'] = ''; } return $return; } function get_order_promises($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT *, DATE_FORMAT(T_OrderPromiseDateTime,'%d-%m-%Y %H:%i') as T_OrderPromiseDateTime_ina FROM t_orderpromise WHERE T_OrderPromiseT_OrderHeaderID = ? AND T_OrderPromiseIsActive = 'Y'"; $query = $this->db_smartone->query($sql, [$order_id]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERPROMISE', 'order/get_order_promises']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data promise", "data" => [] ]; return $return; } $data = $query->result_array(); $return['data'] = $data; return $return; } function insert_group_order($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT DISTINCT Group_ResultID, Group_ResultName, Group_Concat(T_OrderDetailID) as T_OrderDetailIDs, 0 as T_TestID FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsResult = 'Y' AND T_TestIsActive = 'Y' JOIN group_resultdetail ON Group_ResultDetailT_TestID = T_TestID AND Group_ResultDetailIsActive = 'Y' JOIN group_result ON Group_ResultDetailGroup_ResultID = Group_ResultID AND Group_ResultIsActive = 'Y' AND Group_ResultFlagPerTest = 'N' WHERE T_OrderDetailT_OrderHeaderID = ? AND T_OrderDetailIsActive = 'Y' GROUP BY Group_ResultID, Group_ResultName HAVING Group_ResultID IS NOT NULL AND Group_Concat(T_OrderDetailID) IS NOT NULL UNION SELECT DISTINCT Group_ResultID as Group_ResultID, T_TestName as Group_ResultName, Group_Concat(T_OrderDetailID) as T_OrderDetailIDs, T_TestID as T_TestID FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsResult = 'Y' AND T_TestIsActive = 'Y' JOIN group_resultdetail ON Group_ResultDetailT_TestID = T_TestID AND Group_ResultDetailIsActive = 'Y' JOIN group_result ON Group_ResultDetailGroup_ResultID = Group_ResultID AND Group_ResultIsActive = 'Y' AND Group_ResultFlagPerTest = 'Y' WHERE T_OrderDetailT_OrderHeaderID = ? AND T_OrderDetailIsActive = 'Y' GROUP BY T_TEstID, T_TestName HAVING T_TEstID IS NOT NULL AND Group_Concat(T_OrderDetailID) IS NOT NULL"; $query = $this->db_smartone->query($sql, [$order_id, $order_id]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERGROUP', 'order/insert_group_order']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data group order", "data" => [] ]; return $return; } $data_group = $query->result_array(); $debug_query_get = $this->db_smartone->last_query(); foreach ($data_group as $key => $value) { $sql = "INSERT INTO t_orderheader_group_result ( T_OrderHeaderGroupResultT_OrderHeaderID, T_OrderHeaderGroupResultGroup_ResultID, T_OrderHeaderGroupResultGroup_ResultName, T_OrderHeaderGroupResultT_TestID, T_OrderHeaderGroupResultDetails, T_OrderHeaderGroupResultCreated ) VALUES (?, ?, ?, ?, ?, NOW())"; $query = $this->db_smartone->query($sql, [ $order_id, $value['Group_ResultID'], $value['Group_ResultName'], $value['T_TestID'], $value['T_OrderDetailIDs'] ]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error(), 'debug' => $debug_query_get]; $prm_log = ['INSERT_T_ORDERHEADER_GROUP_RESULT', 'order/insert_group_order']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data group order", "data" => [] ]; return $return; } } $return['data'] = $data_group; return $return; } function get_deliveries_by_order($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT M_DeliveryTypeCode as xtype, M_DeliverySource as source, M_DeliveryName as label, T_OrderDeliveryDestination_enc, IFNULL(T_OrderDeliveryNoteValue, T_OrderDeliveryDestination) as xdesc_fallback FROM t_orderdelivery JOIN m_deliverytype ON T_OrderDeliveryM_DeliveryTypeID = M_DeliveryTypeID JOIN m_delivery ON T_OrderDeliveryM_DeliveryID = M_DeliveryID LEFT JOIN t_orderdeliverynote ON T_OrderDeliveryNoteT_OrderDeliveryID = T_OrderDeliveryID AND T_OrderDeliveryNoteIsActive = 'Y' WHERE T_OrderDeliveryT_OrderHeaderID = ? AND T_OrderDeliveryIsActive = 'Y'"; $query = $this->db_smartone->query($sql, [$order_id]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERDELIVERY', 'order/get_deliveries_by_order']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data delivery", "data" => [] ]; return $return; } $data = $query->result_array(); $rst = []; foreach ($data as $key => $value) { $dest_enc = $value['T_OrderDeliveryDestination_enc'] ?? ''; $dest = $dest_enc ? ($this->ibl_encryptor->decrypt($dest_enc) ?: $value['xdesc_fallback']) : $value['xdesc_fallback']; $rst[] = array( 'type' => $value['xtype'], 'source' => $value['source'], 'label' => $value['label'], 'desc' => $dest ); } $return['data'] = $rst; return $return; } function get_order_header($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT 'N' as M_CompanyIsAgingOnHold, '' as M_CompanyIsAgingOnHoldNote, M_CompanyIsBill, M_CompanyMinDP, pj1.M_DoctorName as doctor_pj1, pj2.M_DoctorName as doctor_pj2, sender.M_DoctorName as doctor_sender, M_DoctorAddressDescription as doctor_sender_address, M_CompanyName as order_company, T_OrderHeaderDate as order_date, T_OrderHeaderID as order_id, T_OrderHeaderLabNumber as order_no, M_MouName as order_mou, T_OrderHeaderRounding as order_rounding, T_OrderHeaderSubTotal as order_subtotal, T_OrderHeaderTotal as order_total, M_PatientNoReg as patient_mr, M_PatientName_enc, M_PatientAddressDescription_enc, M_PatientPhone_enc, M_PatientEmail_enc, t_orderheader.*, IFNULL(Nat_CitoName,'') as cito_name, IFNULL(Mgm_McuNumber,'') as mcu_number, IFNULL(Mgm_McuLabel,'') as mcu_label, IFNULL(latest_sig.Patient_SignatureUrl,'') as image_signature FROM `t_orderheader` JOIN `t_orderheaderaddon` ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderAddOnIsActive = 'Y' JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID LEFT JOIN m_patientaddress ON M_PatientAddressID = ( SELECT pa.M_PatientAddressID FROM m_patientaddress pa WHERE pa.M_PatientAddressM_PatientID = M_PatientID AND pa.M_PatientAddressIsActive = 'Y' ORDER BY (pa.M_PatientAddressNote = 'Utama') DESC, pa.M_PatientAddressID DESC LIMIT 1 ) JOIN m_company ON T_OrderHeaderM_CompanyID = M_CompanyID JOIN m_mou ON T_OrderHeaderM_MouID = M_MouID JOIN m_doctor pj1 ON T_OrderHeaderPjM_DoctorID = pj1.M_DoctorID LEFT JOIN m_doctor pj2 ON T_OrderHeaderPj2M_DoctorID = pj2.M_DoctorID JOIN m_doctor sender ON T_OrderHeaderSenderM_DoctorID = sender.M_DoctorID LEFT JOIN m_doctoraddress sender_address ON T_OrderHeaderSenderM_DoctorAddressID = M_DoctorAddressID LEFT JOIN nat_cito ON T_OrderHeaderNat_CitoID = Nat_CitoID LEFT JOIN mgm_mcu ON T_OrderHeaderMgm_McuID = Mgm_McuID LEFT JOIN ( SELECT ps.Patient_SignatureM_PatientID, ps.Patient_SignatureUrl FROM patient_signature ps JOIN ( SELECT Patient_SignatureM_PatientID, MAX(Patient_SignatureID) as Patient_SignatureID FROM patient_signature WHERE Patient_SignatureIsActive = 'Y' GROUP BY Patient_SignatureM_PatientID ) latest_sig_id ON latest_sig_id.Patient_SignatureID = ps.Patient_SignatureID ) latest_sig ON latest_sig.Patient_SignatureM_PatientID = M_PatientID AND latest_sig.Patient_SignatureM_PatientID = T_OrderHeaderM_PatientID WHERE `T_OrderHeaderID` = ? GROUP BY T_OrderHeaderID"; $query = $this->db_smartone->query($sql, [$order_id]); // echo $this->db_smartone->last_query(); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERHEADER', 'order/get_order_header']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data header", "data" => [] ]; return $return; } $data = $query->row_array(); if (is_array($data) && count($data) > 0) { $enc = $this->ibl_encryptor; $addr_raw = $enc->decrypt($data['M_PatientAddressDescription_enc'] ?? ''); $data['patient_name'] = $enc->decrypt($data['M_PatientName_enc'] ?? ''); $data['patient_address'] = implode('
', array_filter([ $addr_raw, $data['M_PatientAddressVillage'] ?? '', $data['M_PatientAddressDistrict'] ?? '', $data['M_PatientAddressCity'] ?? '', ])); $data['patient_phone'] = $enc->decrypt($data['M_PatientPhone_enc'] ?? ''); $data['patient_email'] = $enc->decrypt($data['M_PatientEmail_enc'] ?? ''); foreach (array_keys($data) as $col) { if (substr($col, -4) === '_enc') unset($data[$col]); } $data['inform_consent'] = $this->get_inform_consent_by_order($order_id); } $return['data'] = $data; return $return; } function get_inform_consent_by_order($order_id) { $fallback = $this->get_inform_consent_template('umum'); $fallback['company_type_group_name'] = ''; $fallback['company_type_group_id'] = 0; $sql_group = "SELECT IFNULL(c.M_CompanyM_CompanyGroupTypeID, 0) as company_type_group_id, IFNULL(g.M_CompanyTypeGroupName, '') as company_type_group_name FROM t_orderheader h JOIN m_company c ON h.T_OrderHeaderM_CompanyID = c.M_CompanyID LEFT JOIN m_companytypegroup g ON c.M_CompanyM_CompanyGroupTypeID = g.M_CompanyTypeGroupID WHERE h.T_OrderHeaderID = ? LIMIT 1"; $query_group = $this->db_smartone->query($sql_group, [$order_id]); if (!$query_group) { return $fallback; } $dt_group = $query_group->row_array(); if (!$dt_group) { return $fallback; } $group_type_id = intval($dt_group['company_type_group_id']); $template_type = ($group_type_id === 8) ? 'cpmi' : 'umum'; $sql_template = "SELECT M_InformConsentType as type, M_InformConsentTitle as title, M_InformConsentContent as content FROM m_informconsent WHERE M_InformConsentType = ? AND M_InformConsentIsActive = 'Y' LIMIT 1"; $query_template = $this->db_smartone->query($sql_template, [$template_type]); if (!$query_template) { $fallback = $this->get_inform_consent_template($template_type); $fallback['company_type_group_name'] = $dt_group['company_type_group_name']; $fallback['company_type_group_id'] = intval($dt_group['company_type_group_id']); return $fallback; } $dt_template = $query_template->row_array(); if (!$dt_template) { $fallback = $this->get_inform_consent_template($template_type); $fallback['company_type_group_name'] = $dt_group['company_type_group_name']; $fallback['company_type_group_id'] = intval($dt_group['company_type_group_id']); return $fallback; } $dt_template['company_type_group_name'] = $dt_group['company_type_group_name']; $dt_template['company_type_group_id'] = intval($dt_group['company_type_group_id']); return $dt_template; } function get_inform_consent_template($template_type) { $fallback = [ 'type' => $template_type, 'title' => '', 'content' => '' ]; $sql_template = "SELECT M_InformConsentType as type, M_InformConsentTitle as title, M_InformConsentContent as content FROM m_informconsent WHERE M_InformConsentType = ? AND M_InformConsentIsActive = 'Y' LIMIT 1"; $query_template = $this->db_smartone->query($sql_template, [$template_type]); if (!$query_template) { return $fallback; } $dt_template = $query_template->row_array(); if (!$dt_template) { return $fallback; } return $dt_template; } function get_details($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT * FROM `t_orderdetail` JOIN `t_orderdetailaddon` ON T_OrderDetailAddOnT_OrderDetailID = T_OrderDetailID AND T_OrderDetailAddOnIsActive = 'Y' WHERE `T_OrderDetailT_OrderHeaderID` = ? AND `T_OrderDetailIsActive` = 'Y'"; $query = $this->db_smartone->query($sql, [$order_id]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERDETAIL', 'order/get_details']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data details", "data" => [] ]; return $return; } $data = $query->result_array(); $rst = []; foreach ($data as $key => $value) { $rst[] = $value; } $return['data'] = $rst; return $return; } function get_order_detail($order_id) { $return = [ "status" => true, "message" => "", "data" => [] ]; $sql = "SELECT T_OrderDetailOrderID as d_id, T_OrderDetailOrderT_TestID as t_id, IF(T_OrderDetailOrderIsPacket = 'Y',T_OrderDetailOrderT_PacketName,T_OrderDetailOrderT_TestName) as t_name, T_OrderDetailOrderT_PriceAmount as t_price, ((T_OrderDetailOrderT_PriceDisc/100) * T_OrderDetailOrderT_PriceAmount) + T_OrderDetailOrderT_PriceDiscRp as t_disctotal, T_OrderDetailOrderT_PriceTotal as t_total FROM `t_orderdetailorder` WHERE `T_OrderDetailOrderT_OrderHeaderID` = ? AND `T_OrderDetailOrderIsActive` = 'Y'"; $query = $this->db_smartone->query($sql, [$order_id]); if (!$query) { $dt_log = ['data' => $order_id, 'error' => $this->db_smartone->error()]; $prm_log = ['SELECT_T_ORDERDETAILORDER', 'order/get_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $return = [ "status" => false, "message" => "Terjadi kesalahan saat mengambil data detail order", "data" => [] ]; return $return; } $data = $query->result_array(); $rst = []; foreach ($data as $key => $value) { $rst[] = $value; } $return['data'] = $rst; return $return; } function insert_log_error($log_sql, $params, $data = '') { // Membersihkan SQL dari \r\n dan whitespace berlebih //$clean_log_sql = trim(str_replace(["\r\n", "\r", "\n"], ' ', $log_sql)); $sql = "INSERT INTO error_log_order( ErrorLogOrderCode, ErrorLogOrderFnName, ErrorLogOrderDescription, ErrorLogOrderData, ErrorLogOrderCreated ) VALUES( ?,?,?,?,NOW() )"; $query = $this->db_log->query($sql, [$params[0], $params[1], $log_sql, json_encode($data)]); //echo $this->db_log->last_query(); if (!$query) { return false; } return true; } function save_order_header($header, $userid, $options = []) { $skip_patient_note = !empty($options['skip_patient_note']); $return = [ "status" => true, "message" => "", "data" => [] ]; $this->db_smartone->trans_begin(); $sql = "SELECT fn_numbering('L') xnumber"; $query = $this->db_smartone->query($sql); if (!$query) { $prm_log = ['SELECT_FN_NUMBERING_CPONE_TRANSACTION', 'order/save']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $return['status'] = false; $return['message'] = 'Terjadi kesalahan saat membuat nomor transaksi'; $this->db_smartone->trans_rollback(); return $return; } $rows_no_trans = $query->result_array(); //get no trans $no_trans = $rows_no_trans[0]['xnumber']; $queue = isset($header['queue']) ? $header['queue'] : ''; //insert header $sql_header = "INSERT INTO t_orderheader ( T_OrderHeaderQueue, T_OrderHeaderDate, T_OrderHeaderLabNumber, T_OrderHeaderM_PatientID, T_OrderHeaderM_CompanyID, T_OrderHeaderMgm_McuID, T_OrderHeaderM_MouID, T_OrderHeaderM_PatientAge, T_OrderHeaderSenderM_DoctorID, T_OrderHeaderSenderM_DoctorAddressID, T_OrderHeaderPjM_DoctorID, T_OrderHeaderPj2M_DoctorID, T_OrderHeaderM_LangID, T_OrderHeaderLangIsSI, T_OrderHeaderIsCito, T_OrderHeaderNat_CitoID, T_OrderHeaderDiagnose, T_OrderHeaderFoNote, T_OrderHeaderFoNoteM_UserID, T_OrderHeaderCreated, T_OrderHeaderCreatedUserID ) VALUES ( ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ? ) "; $prm_header = [ $queue, $no_trans, $header['patient_id'], $header['company_id'], isset($prm['mcuid']) ? $prm['mcuid'] : 0, $header['mou_id'], $header['age'], $header['sender_doctor_id'], $header['sender_address_id'], $header['pj_doctor_id'], 0, $header['lang_id'], $header['lang_si'], $header['is_cito'], $header['is_cito'] == 'N' ? 0 : $header['cito_id'], $header['diagnose'], $header['fo_note'], $header['fo_note'] != '' ? $userid : 0, $userid ]; $query_header = $this->db_smartone->query($sql_header, $prm_header); if (!$query_header) { $dt_log = ['data' => $prm_header, 'error' => $this->db_smartone->error()]; $prm_log = ['INSERT_T_ORDERHEADER', 'order/save_order_header']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data header", "data" => [] ]; return $return; } //get header id $header_id = $this->db_smartone->insert_id(); $sql = "SELECT M_PatientName_enc, IFNULL(M_TitleName,'') M_TitleName, IFNULL(M_PatientPrefix,'') M_PatientPrefix, IFNULL(M_PatientSuffix,'') M_PatientSuffix FROM m_patient LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID WHERE M_PatientID = ? LIMIT 1"; $query_patient = $this->db_smartone->query($sql, [$header['patient_id']]); if (!$query_patient) { $prm_log = ['SELECT_M_PATIENT', 'order/save_order_header']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); } $rows_patient = $query_patient->row_array(); $pname = $this->ibl_encryptor->decrypt($rows_patient['M_PatientName_enc'] ?? ''); $rows_patient['full_patient_name'] = trim(implode(' ', array_filter([ $rows_patient['M_TitleName'], $rows_patient['M_PatientPrefix'], $pname, $rows_patient['M_PatientSuffix'] ]))); $full_patient_name = $rows_patient['full_patient_name']; $sql = "INSERT INTO t_orderheaderaddon ( T_OrderHeaderAddOnT_OrderHeaderID, T_OrderHeaderAddOnSecondM_LangID, T_OrderHeaderAddOnSecondLangIsSI, T_OrderHeaderAddOnAliasDoctorName, T_OrderHeaderAddOnAliasDoctorAddress, T_OrderHeaderAddOnOnlySampleTime, T_OrderHeaderAddOnPatientMcu, T_OrderHeaderAddOnFullPatientName, T_OrderHeaderAddOnCreated, T_OrderHeaderAddOnCreatedUserID ) VALUES( ?,?,?,?,?,?,?,?,NOW(),? )"; $prm_addon = [ $header_id, $header['lang_id_2'], $header['lang_si_2'], $header['alias_doctor_name'], $header['alias_doctor_address'], $header['received_sample']['flag'] == 'Y' ? $header['received_sample']['time'] : null, intval($header['pre_register_id']) > 0 ? 'Y' : 'N', $full_patient_name, $userid ]; $query_addon = $this->db_smartone->query($sql, $prm_addon); if (!$query_addon) { $prm_log = ['INSERT_T_ORDERHEADERADDON', 'order/save_order_header']; $xsql = $this->db_smartone->last_query(); $dt_log = ['data' => $prm_addon, 'error' => $this->db_smartone->error()]; $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data header addon", "data" => [] ]; return $return; } $sqlheaderlang = "INSERT INTO t_orderheaderlang (T_OrderHeaderLangT_OrderHeaderID, T_OrderHeaderLangM_LangID, T_OrderHeaderLangCreated, T_OrderHeaderLangCreatedUserID, T_OrderHeaderLangLastUpdated, T_OrderHeaderLangLastUpdatedUserID) VALUES(?,?,NOW(),?,NOW(),?)"; $prm_header_lang = [ $header_id, $header['lang_id_2'] != 0 ? $header['lang_id_2'] : $header['lang_id'], $userid, $userid ]; $query_header_lang = $this->db_smartone->query($sqlheaderlang, $prm_header_lang); if (!$query_header_lang) { $prm_log = ['INSERT_T_ORDERHEADER_LANG', 'order/save']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data header lang", "data" => [] ]; return $return; } if (isset($header['code_icd10']) && $header['code_icd10'] != '') { // add icd10 $sql_icd10 = "INSERT INTO t_order_icd10( T_OrderIcd10T_OrderheaderID, T_OrderIcd10Code, T_OrderIcd10Name, T_OrderIcd10IsActive, T_OrderIcd10UserID, T_OrderIcd10Created ) VALUES( ?, ?, ?, 'Y', ?, NOW() )"; $qry_icd10 = $this->db_smartone->query($sql_icd10, [$header_id, $header['code_icd10'], $header['name_icd10'], $userid]); if (!$qry_icd10) { $prm_log = ['INSERT_T_ORDER_ICD10', 'order/save']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data icd10", "data" => [] ]; return $return; } } // add reference $reference = isset($header['reference']) ? $header['reference'] : []; if (count($reference) > 0) { foreach ($reference as $key => $value) { $sql_ref = "INSERT INTO t_orderreference( T_OrderreferenceT_OrderheaderID, T_OrderreferenceM_ReferenceID, T_OrderreferenceIsActive, T_OrderreferenceCreated, T_OrderreferenceUserID) VALUES( ?, ?, 'Y', NOW(), ? )"; $qry_ref = $this->db_smartone->query($sql_ref, [$header_id, $value['M_ReferenceID'], $userid]); if (!$qry_ref) { $prm_log = ['INSERT_T_ORDER_REFERENCE', 'order/save']; $xsql = $this->db_smartone->last_query(); $dt_log = ['data' => $value, 'error' => $this->db_smartone->error(), 'header_id' => $header_id]; $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data reference", "data" => [] ]; return $return; } } } // add FPP TYPE $sql_fpp = "INSERT INTO t_orderaddon( T_OrderAddonT_OrderHeaderID, T_OrderAddonM_FppTypeID, T_OrderAddonUserID ) VALUES( ?, ?, ? )"; $qry_fpp = $this->db_smartone->query($sql_fpp, [$header_id, $header['fpp_id'], $userid]); if (!$qry_fpp) { $prm_log = ['INSERT_T_ORDER_FPP', 'order/save']; $xsql = $this->db_smartone->last_query(); $dt_log = ['data' => $header, 'error' => $this->db_smartone->error()]; $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data fpp", "data" => [] ]; return $return; } $this->db_smartone->trans_commit(); $return['data'] = [ "header_id" => $header_id ]; // Update patient note SETELAH commit agar tidak ikut dalam transaksi order (hindari lock wait timeout di m_patient) if (!$skip_patient_note) { $patient_note_value = isset($header['patient_note']) && is_scalar($header['patient_note']) ? (string)$header['patient_note'] : ''; $userid_patient_note = (int)$userid; if ($userid_patient_note === 0) { $userid_patient_note = 1; } $q_patient = $this->db_smartone->query( "SELECT M_PatientID, M_PatientCreated FROM m_patient WHERE M_PatientID = ? ORDER BY M_PatientCreated DESC LIMIT 1", [$header['patient_id']] ); $row_patient = $q_patient ? $q_patient->row_array() : null; if ($row_patient) { $sql = "UPDATE m_patient SET M_PatientNote = ?, M_PatientLastUpdatedUserID = ?, M_PatientLastUpdated = NOW() WHERE M_PatientID = ? AND M_PatientCreated = ?"; $query_patient_note = $this->db_smartone->query($sql, [ $patient_note_value, $userid_patient_note, $header['patient_id'], $row_patient['M_PatientCreated'] ]); if (!$query_patient_note) { $db_err = $this->db_smartone->error(); $last_sql = $this->db_smartone->last_query(); $dt_log = ['data' => $patient_note_value, 'patient_id' => $header['patient_id'], 'M_PatientCreated' => $row_patient['M_PatientCreated'], 'error' => $db_err, 'last_query' => $last_sql]; $this->insert_log_error($last_sql, ['UPDATE_M_PATIENT', 'order/save_order_header'], $dt_log); // Tidak gagalkan order; order sudah tersimpan. Hanya log error (mis. lock wait timeout). } } } return $return; } function save_order_detail($details, $header_id, $userid) { $return = [ "status" => true, "message" => "", "data" => [] ]; $this->db_smartone->trans_begin(); $tests = []; foreach ($details as $k => $v) { if (isset($v['ss_price_id'])) { $sql = "SELECT * FROM ss_price_mou WHERE Ss_PriceMouID = {$v['ss_price_id']}"; $query = $this->db_smartone->query($sql); if (!$query) { $message = "Terjadi kesalahan saat memilih data test price"; $prm_log = ['SELECT_SS_PRICE_MOU', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $v); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => $message, "data" => [] ]; return $return; } $dt_test_price = $query->row_array(); $dt_test_price['child_test'] = json_decode($dt_test_price['child_test'], true); //print_r($dt_test_price); $tests[] = $dt_test_price; } else { $sql = "SELECT * FROM t_test WHERE T_TestID = {$v['t_id']}"; $query = $this->db_smartone->query($sql); if (!$query) { $message = "Terjadi kesalahan saat memilih data test"; $prm_log = ['SELECT_T_TEST', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $v); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => $message, "data" => [] ]; return $return; } $dt_test = $query->row_array(); $dt_test_price = $v; $dt_test_price['child_test'] = []; $dt_test_price['T_TestID'] = $dt_test['T_TestID']; $dt_test_price['T_TestName'] = $dt_test['T_TestName']; $dt_test_price['px_type'] = $v['t_packettype']; $dt_test_price['T_PriceAmount'] = $v['t_price']; $dt_test_price['T_PriceDisc'] = $v['t_disc']; $dt_test_price['T_PriceDiscRp'] = $v['t_discrp']; $dt_test_price['T_PriceSubTotal'] = $v['t_price'] - (($v['t_price'] * $v['t_disc'] / 100) + $v['t_disc_rp']); $dt_test_price['T_PriceTotal'] = $dt_test_price['T_PriceSubTotal']; $tests[] = $dt_test_price; } } //print_r($tests); foreach ($tests as $k => $detail) { $sql_orderdetailorder = "INSERT INTO t_orderdetailorder( T_OrderDetailOrderT_OrderHeaderID, T_OrderDetailOrderT_TestID, T_OrderDetailOrderT_TestName, T_OrderDetailOrderIsPacket, T_OrderDetailOrderPacketType, T_OrderDetailOrderT_PacketID, T_OrderDetailOrderT_PacketName, T_OrderDetailOrderT_PriceAmount, T_OrderDetailOrderT_PriceDisc, T_OrderDetailOrderT_PriceDiscRp, T_OrderDetailOrderT_PriceSubTotal, T_OrderDetailOrderT_PriceTotal, T_OrderDetailOrderCreated, T_OrderDetailOrderCreatedUserID, T_OrderDetailOrderJsonChildren ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?)"; $prm_detail_order = [ $header_id, $detail['px_type'] == 'PX' ? $detail['T_TestID'] : '', $detail['px_type'] == 'PX' ? $detail['T_TestName'] : '', $detail['px_type'] != 'PX' ? 'Y' : 'N', $detail['px_type'] != 'PX' ? $detail['px_type'] : 'PX', $detail['px_type'] != 'PX' ? $detail['T_TestID'] : '0', $detail['px_type'] != 'PX' ? $detail['T_TestName'] : '', $detail['T_PriceAmount'], $detail['T_PriceDisc'], $detail['T_PriceDiscRp'], $detail['T_PriceSubTotal'], $detail['T_PriceTotal'], $userid, json_encode($detail['child_test']) ]; $query_detail_order = $this->db_smartone->query($sql_orderdetailorder, $prm_detail_order); if (!$query_detail_order) { $prm_log = ['INSERT_T_ORDERDETAILORDER', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $dt_log = ['data' => $detail, 'error' => $this->db_smartone->error()]; $log_error = $this->insert_log_error($xsql, $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => "Terjadi kesalahan saat menyimpan data detail order", "data" => [] ]; return $return; } $detail_order_id = $this->db_smartone->insert_id(); if ($detail['px_type'] != 'PX') { if (count($detail['child_test']) == 0) { $message = "Detail packet tidak boleh kosong"; $prm_log = ['INSERT_T_ORDERDETAILORDER', 'order/save_order_detail']; $dt_log = json_encode($detail); $log_error = $this->insert_log_error($dt_log, $prm_log, $detail); $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => $message, "data" => [] ]; return $return; } foreach ($detail['child_test'] as $k => $child_test_packet) { $child_test_packet['test_id'] = $child_test_packet['T_TestID']; $child_test_packet['test_name'] = $child_test_packet['T_TestName']; $detail_insert = $this->insert_order_detail($header_id, $detail_order_id, $child_test_packet, $userid); if ($detail_insert['status'] == 'N') { $message = $detail_insert['message']; $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => $message, "data" => [] ]; return $return; } } } else { $detail_insert = $this->insert_order_detail($header_id, $detail_order_id, $detail, $userid); if ($detail_insert['status'] == 'N') { $message = "Terjadi kesalahan saat menyimpan data detail order " . $detail['test_name']; $this->db_smartone->trans_rollback(); $return = [ "status" => false, "message" => $message, "data" => [] ]; return $return; } } } $this->db_smartone->trans_commit(); return $return; } function insert_order_detail($header_id, $detail_order_id, $detail, $userid) { $this->db_smartone->trans_begin(); // Buat array untuk informasi error/success $result = [ 'status' => 'Y', 'message' => 'Success', 'test_name' => isset($detail['T_TestName']) ? $detail['T_TestName'] : '', 'test_id' => isset($detail['T_TestID']) ? $detail['T_TestID'] : '', 'test_code' => '', 'error_type' => '', 'error_detail' => [] ]; // Cek data test $sql = "SELECT * FROM t_test WHERE T_TestID = ?"; $query = $this->db_smartone->query($sql, $detail['T_TestID']); if (!$query) { $result['status'] = 'N'; $result['message'] = 'Terjadi kesalahan saat mengambil data test'; $result['error_type'] = 'DB_QUERY_ERROR'; $prm_log = ['SELECT_T_TEST', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; return $result; } $rows_test = $query->result_array(); if (count($rows_test) == 0) { $result['status'] = 'N'; $result['message'] = 'Test tidak ditemukan'; $result['error_type'] = 'TEST_NOT_FOUND'; $prm_log = ['SELECT_T_TEST', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); return $result; } $dt_test = $rows_test[0]; //print_r($dt_test); //return false; // Update dengan data test yang benar dari database $result['test_name'] = $dt_test['T_TestName']; $result['test_code'] = $dt_test['T_TestCode']; $result['test_sas_code'] = $dt_test['T_TestSasCode']; $price = isset($detail['T_PriceAmount']) ? $detail['T_PriceAmount'] : $detail['price']; $disc = isset($detail['T_PriceDisc']) ? $detail['T_PriceDisc'] : $detail['disc']; $disc_rp = isset($detail['T_PriceDiscRp']) ? $detail['T_PriceDiscRp'] : $detail['disc_rp']; $subtotal = isset($detail['T_PriceSubTotal']) ? $detail['T_PriceSubTotal'] : $detail['subtotal']; $total = isset($detail['T_PriceTotal']) ? $detail['T_PriceTotal'] : $detail['total']; $sql = "SELECT Nat_UnitID, Nat_UnitName FROM t_test JOIN nat_test ON T_TestNat_TestID = Nat_TestID JOIN nat_unit ON Nat_TestNat_UnitID = Nat_UnitID WHERE T_TestID = 2 LIMIT 1"; $dt_unit = $this->db_smartone->query($sql, $detail['T_TestID'])->row_array(); // Query insert order detail $sql_orderdetail = "INSERT INTO t_orderdetail( T_OrderDetailT_OrderHeaderID, T_OrderDetailT_OrderDetailOrderID, T_OrderDetailT_TestID, T_OrderDetailT_TestCode, T_OrderDetailT_TestSasCode, T_OrderDetailT_TestName, T_OrderDetailT_TestIsResult, T_OrderDetailT_TestIsPanel, T_OrderDetailT_TestIsPanelChildren, T_OrderDetailT_TestIsPanelChildrenPrintNota, T_OrderDetailT_TestIsPrice, T_OrderDetailIsCito, T_OrderDetailPrice, T_OrderDetailPriceForDisc, T_OrderDetailDisc, T_OrderDetailDiscAmount, T_OrderDetailDiscTotal, T_OrderDetailTotal, T_OrderDetailReq, T_OrderDetailReqNote, T_OrderDetailNat_UnitID, T_OrderDetailNat_UnitName, T_OrderDetailCreatedUserID, T_OrderDetailCreated ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'N','',?,?,?,NOW())"; $prm_orderdetail = [ $header_id, $detail_order_id, $dt_test['T_TestID'], $dt_test['T_TestCode'], $dt_test['T_TestSasCode'], $dt_test['T_TestName'], $dt_test['T_TestIsResult'], 'N', 'N', 'N', $dt_test['T_TestIsPrice'], 'N', $dt_test['T_TestIsPrice'] == 'N' ? 0 : $price, $dt_test['T_TestIsPrice'] == 'N' ? 0 : $price, $dt_test['T_TestIsPrice'] == 'N' ? 0 : $disc, $dt_test['T_TestIsPrice'] == 'N' ? 0 : $disc_rp, $dt_test['T_TestIsPrice'] == 'N' ? 0 : $subtotal, $dt_test['T_TestIsPrice'] == 'N' ? 0 : $total, $dt_unit['Nat_UnitID'], $dt_unit['Nat_UnitName'], $userid ]; $query_orderdetail = $this->db_smartone->query($sql_orderdetail, $prm_orderdetail); //echo $this->db_smartone->last_query(); if (!$query_orderdetail) { $result['status'] = 'N'; $result['message'] = 'Terjadi kesalahan saat menyimpan data detail order'; $result['error_type'] = 'INSERT_DETAIL_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_ORDERDETAIL', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $dt_test); $this->db_smartone->trans_rollback(); return $result; } // Ambil child test $sql = "SELECT * FROM t_test WHERE T_TestSasCode LIKE ? AND T_TestIsActive = 'Y' AND T_TestSasCode != ?"; $query = $this->db_smartone->query($sql, [$dt_test['T_TestSasCode'] . '%', $dt_test['T_TestSasCode']]); if (!$query) { $result['status'] = 'N'; $result['message'] = 'Terjadi kesalahan saat mengambil data child test'; $result['error_type'] = 'CHILD_TEST_QUERY_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query(), 'parent_test' => [ 'id' => $dt_test['T_TestID'], 'name' => $dt_test['T_TestName'], 'code' => $dt_test['T_TestCode'], 'sas_code' => $dt_test['T_TestSasCode'] ] ]; $prm_log = ['SELECT_CHILD_TEST', 'order/save_order_detail']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log, $result['error_detail']); $this->db_smartone->trans_rollback(); return $result; } $rows_test_child = $query->result_array(); if (count($rows_test_child) > 0) { // Tambahkan informasi jumlah child test yang ditemukan $result['child_tests_count'] = count($rows_test_child); foreach ($rows_test_child as $k_child => $test_child) { $sql = "SELECT Nat_UnitID, Nat_UnitName FROM t_test JOIN nat_test ON T_TestNat_TestID = Nat_TestID JOIN nat_unit ON Nat_TestNat_UnitID = Nat_UnitID WHERE T_TestID = ? LIMIT 1"; $dt_child_unit = $this->db_smartone->query($sql, $test_child['T_TestID'])->row_array(); $sql_orderdetail = "INSERT INTO t_orderdetail( T_OrderDetailT_OrderHeaderID, T_OrderDetailT_OrderDetailOrderID, T_OrderDetailT_TestID, T_OrderDetailT_TestCode, T_OrderDetailT_TestSasCode, T_OrderDetailT_TestName, T_OrderDetailT_TestIsResult, T_OrderDetailT_TestIsPanel, T_OrderDetailT_TestIsPanelChildren, T_OrderDetailT_TestIsPanelChildrenPrintNota, T_OrderDetailT_TestIsPrice, T_OrderDetailIsCito, T_OrderDetailPrice, T_OrderDetailPriceForDisc, T_OrderDetailDisc, T_OrderDetailDiscAmount, T_OrderDetailDiscTotal, T_OrderDetailTotal, T_OrderDetailReq, T_OrderDetailReqNote, T_OrderDetailCreated, T_OrderDetailNat_UnitID, T_OrderDetailNat_UnitName, T_OrderDetailCreatedUserID ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'N','',NOW(),?,?,?)"; $prm_orderdetail = [ $header_id, $detail_order_id, $test_child['T_TestID'], $test_child['T_TestCode'], $test_child['T_TestSasCode'], $test_child['T_TestName'], $test_child['T_TestIsResult'], 'N', 'N', 'N', $test_child['T_TestIsPrice'], 'N', 0, 0, 0, 0, 0, 0, $dt_child_unit['Nat_UnitID'], $dt_child_unit['Nat_UnitName'], $userid ]; // echo $this->db_smartone->last_query(); $query_child = $this->db_smartone->query($sql_orderdetail, $prm_orderdetail); if (!$query_child) { $result['status'] = 'N'; $xsql = $this->db_smartone->last_query(); $result['message'] = 'Terjadi kesalahan saat menyimpan data child test ' . $test_child['T_TestName']; $result['error_type'] = 'INSERT_CHILD_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $xsql, 'child_index' => $k_child + 1, 'total_children' => count($rows_test_child), 'child_test' => [ 'id' => $test_child['T_TestID'], 'name' => $test_child['T_TestName'], 'code' => $test_child['T_TestCode'], 'sas_code' => $test_child['T_TestSasCode'] ], 'parent_test' => [ 'id' => $dt_test['T_TestID'], 'name' => $dt_test['T_TestName'], 'code' => $dt_test['T_TestCode'], 'sas_code' => $dt_test['T_TestSasCode'] ] ]; $prm_log = ['INSERT_T_ORDERDETAIL_CHILD', 'order/save_order_detail']; $log_error = $this->insert_log_error($xsql, $prm_log, $result['error_detail']); $this->db_smartone->trans_rollback(); return $result; } } } $this->db_smartone->trans_commit(); // Jika semua proses berhasil if (count($rows_test_child) > 0) { $result['message'] = 'Berhasil menyimpan data test utama dan ' . count($rows_test_child) . ' child test'; } else { $result['message'] = 'Berhasil menyimpan data test'; } return $result; } function generate_sample_lab($header_id, $userid) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; //$this->db_smartone->trans_begin(); $counter_barcode = 1; $sql = "SELECT T_OrderHeaderLabNumber, T_TestID, T_SampleTypeID , T_SampleTypeSuffix, T_SampleStationIsNonLab, T_SampleStationID FROM t_orderheader JOIN t_orderdetail ON t_orderheaderid = t_orderdetailt_orderheaderid AND t_orderdetailIsActive = 'Y' JOIN t_test ON t_orderdetailt_testid = t_testid AND T_TestIsResult = 'Y' JOIN t_sampletype ON T_TestT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID JOIN group_resultdetail ON Group_ResultDetailT_TestID = T_TestID AND Group_ResultDetailIsActive = 'Y' JOIN group_result ON Group_ResultID = Group_ResultDetailGroup_ResultID AND Group_ResultIsActive = 'Y' AND Group_ResultFlagNonLab = 'N' WHERE T_OrderHeaderID = ? GROUP BY T_SampleTypeID"; $qry = $this->db_smartone->query($sql, $header_id); if (!$qry) { $err = $this->db_smartone->error(); $prm_log = ['SELECT_SAMPLE', 'order/generate_sample_lab', $err]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data sample'; $result['error_type'] = 'SAMPLE_QUERY_ERROR'; $result['error_detail'] = [ 'sql_error' => $err, 'last_query' => $xsql ]; $prm_log = ['SELECT_SAMPLE', 'order/generate_sample_lab']; $this->db_smartone->trans_rollback(); return $result; } $data_samples = $qry->result_array(); if (count($data_samples) > 0) { foreach ($data_samples as $k => $v) { $counter_barcode = 1; $lab_no = $v['T_OrderHeaderLabNumber']; $test_id = $v['T_TestID']; $sample_id = $v['T_SampleTypeID']; $sample_code = $v['T_SampleTypeSuffix']; $barcode = $lab_no . $sample_code; $isnonlab = $v['T_SampleStationIsNonLab']; $samplestation_id = $v['T_SampleStationID']; if ($counter_barcode == 1) { $barcode = $barcode . $counter_barcode; $sql = "INSERT INTO t_barcodelab( T_BarcodeLabT_OrderHeaderID, T_BarcodeLabBarcode, T_BarcodeLabT_SampleTypeID, T_BarcodeLabCounter) VALUES (?,?,?,?)"; $prm_barcode = [ $header_id, $barcode, $sample_id, $counter_barcode ]; $qry = $this->db_smartone->query($sql, $prm_barcode); //echo $this->db_smartone->last_query(); if (!$qry) { //echo $this->db_smartone->last_query(); $err = $this->db_smartone->error(); $prm_log = ['INSERT_T_BARCODELAB', 'order/generate_sample_lab', $err]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data barcode lab'; $result['error_type'] = 'BARCODE_LAB_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $log_error, 'last_query' => $xsql ]; return $result; } $last_id_barcode = $this->db_smartone->insert_id(); /*if ($isnonlab == "") { $sql = "INSERT INTO t_ordersample( T_OrderSampleT_OrderHeaderID, T_OrderSampleT_SampleTypeID, T_OrderSampleT_BarcodeLabID, T_OrderSampleBarcode, T_OrderSampleT_SampleStationID, T_OrderSampleCreated) VALUES (?,?,?,?,?,NOW())"; $prm_ordersample = [ $header_id, $sample_id, $last_id_barcode, $barcode, $samplestation_id ]; $qry = $this->db_smartone->query($sql, $prm_ordersample); if (!$qry) { echo $this->db_smartone->last_query(); $err = $this->db_smartone->error(); $prm_log = ['INSERT_T_ORDERSAMPLE', 'order/generate_sample_lab', $err]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data sample ' . $sample_code; $result['error_type'] = 'SAMPLE_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $log_error, 'last_query' => $xsql ]; $this->db_smartone->trans_rollback(); return $result; } }*/ } $sql = "SELECT MAX(T_BarcodeLabCounter) as ctr FROM t_barcodelab WHERE T_BarcodeLabT_OrderHeaderID = ? AND T_BarcodeLabBarcode LIKE CONCAT(?, '%') AND T_BarcodeLabIsActive = 'Y'"; $qry = $this->db_smartone->query($sql, [$header_id, $barcode]); if ($qry) { $ctr = $qry->row()->ctr; $counter_barcode = $ctr + 1; } else { $err = $this->db_smartone->error(); $prm_log = ['SELECT_COUNTER_BARCODE', 'order/generate_sample_lab', $err]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data counter barcode'; $result['error_type'] = 'COUNTER_BARCODE_QUERY_ERROR'; $result['error_detail'] = [ 'sql_error' => $log_error, 'last_query' => $xsql ]; $this->db_smartone->trans_rollback(); return $result; } } } $this->db_smartone->trans_commit(); return $result; } function generate_location($header_id, $userid) { $sql = "SELECT T_SampleStationID, T_SampleStationName FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsActive = 'Y' JOIN t_sampletype ON T_TestT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID WHERE T_OrderDetailT_OrderHeaderID = ? GROUP BY T_SampleStationID"; $qry = $this->db_smartone->query($sql, $header_id); if (!$qry) { $this->insert_log_error( $this->db_smartone->last_query(), ['LOCATION_STATIONS_QUERY_ERROR', 'order/generate_location'], ['order_id' => $header_id] ); return [ 'has_failure' => true, 'succeeded' => [], 'failed' => [['id' => 0, 'name' => 'unknown', 'reason' => 'STATIONS_QUERY_ERROR']], ]; } $stations = $qry->result_array(); return $this->_do_generate_location_for_stations($stations, $header_id, $userid); } private function _do_generate_location_for_stations(array $stations, $header_id, $userid) { $succeeded = []; $failed = []; foreach ($stations as $v) { $sample_id = $v['T_SampleStationID']; $sample_name = $v['T_SampleStationName']; $sql = "SELECT M_LocationID as loc_id FROM m_location WHERE M_LocationT_SampleStationID = ? AND M_LocationIsActive = 'Y' ORDER BY M_LocationPriority DESC, M_LocationID ASC LIMIT 1"; $qry = $this->db_smartone->query($sql, $sample_id); if (!$qry) { $failed[] = ['id' => $sample_id, 'name' => $sample_name, 'reason' => 'QUERY_ERROR']; $this->insert_log_error( $this->db_smartone->last_query(), ['LOCATION_QUERY_ERROR', 'order/generate_location'], ['order_id' => $header_id, 'station_id' => $sample_id, 'station_name' => $sample_name] ); continue; } $row = $qry->row(); if (!$row) { $failed[] = ['id' => $sample_id, 'name' => $sample_name, 'reason' => 'NO_MAPPING']; $this->insert_log_error( 'no active m_location for station ' . $sample_id, ['LOCATION_NO_MAPPING', 'order/generate_location'], ['order_id' => $header_id, 'station_id' => $sample_id, 'station_name' => $sample_name] ); continue; } $loc_id = $row->loc_id; $sql = "INSERT INTO t_order_location( T_OrderLocationT_OrderHeaderID, T_OrderLocationM_LocationID, T_OrderLocationT_SampleStationID, T_OrderLocationCreated, T_OrderLocationLastUpdated, T_OrderLocationUserID) VALUES (?,?,?,NOW(),NOW(),?)"; $qry = $this->db_smartone->query($sql, [$header_id, $loc_id, $sample_id, $userid]); if (!$qry) { $failed[] = ['id' => $sample_id, 'name' => $sample_name, 'reason' => 'INSERT_ERROR']; $this->insert_log_error( $this->db_smartone->last_query(), ['LOCATION_INSERT_ERROR', 'order/generate_location'], ['order_id' => $header_id, 'station_id' => $sample_id, 'station_name' => $sample_name] ); continue; } $succeeded[] = ['id' => $sample_id, 'name' => $sample_name]; } return [ 'has_failure' => count($failed) > 0, 'succeeded' => $succeeded, 'failed' => $failed, ]; } function generate_req($header_id, $req, $userid) { $this->db_smartone->trans_begin(); $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; $sql = $this->db_smartone->query("SELECT Nat_PositionID as req_id FROM nat_position WHERE Nat_PositionCode = 'FO'")->row(); $req_id = $sql->req_id; $req_status = $req['status']; $req_tmp = "0"; $req['reqs'] = json_decode($req['reqs'], true); if (count($req['reqs']) > 0) { foreach ($req['reqs'] as $value) { $req_tmp .= "," . $value; } } $reqid = "[" . $req_tmp . "]"; $sql = "INSERT INTO t_orderreq( T_OrderReqT_OrderHeaderID, T_OrderReqNat_PositionID, T_OrderReqStatus, T_OrderReqT_TestID, T_OrderReqs) VALUES (?,?,?,?,?)"; $prm_orderreq = [ $header_id, $req_id, $req_status, '[]', $reqid ]; $qry = $this->db_smartone->query($sql, $prm_orderreq); if (!$qry) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data request'; $result['error_type'] = 'ORDER_REQ_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_ORDERREQ', 'order/generate_req']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); //$this->db_smartone->trans_rollback(); return $result; } $this->db_smartone->trans_commit(); return $result; } function save_delivery($header_id, $deliveries, $userid) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; $this->db_smartone->trans_begin(); if (count($deliveries) > 0) { foreach ($deliveries as $key => $delivery) { $destination = $delivery['note']; if (($delivery['delivery_code'] == 'EMAIL' || $delivery['delivery_code'] == 'WHATSAPP' || $delivery['delivery_code'] == 'TELEGRAM') && $delivery['noteplus'] != '') { $destination = $delivery['noteplus']; } $sql = "INSERT INTO t_orderdelivery( T_OrderDeliveryT_OrderHeaderID, T_OrderDeliveryM_DeliveryID, T_OrderDeliveryM_DeliveryTypeID, T_OrderDeliveryDestination, T_OrderDeliveryDestination_enc, T_OrderDeliveryAddressID, T_OrderDeliveryRegionalCd, T_OrderDeliveryCreated, T_OrderDeliveryCreatedUserID ) VALUES (?,?,?,?,?,?,?,NOW(),?)"; $prm_orderdelivery = [ $header_id, $delivery['delivery_id'], $delivery['delivery_type_id'], $destination, $this->ibl_encryptor->encrypt($destination), $delivery['address_id'], $delivery['regional_cd'], $userid ]; $qry = $this->db_smartone->query($sql, $prm_orderdelivery); if (!$qry) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data delivery'; $result['error_type'] = 'ORDER_DELIVERY_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_ORDERDELIVERY', 'order/save_delivery', $delivery]; $log_error = $this->insert_log_error($this->db_smartone->last_query(), $prm_log); //$this->db_smartone->trans_rollback(); return $result; } $xdel_id = $this->db_smartone->insert_id(); if ($delivery['delivery_code'] != 'EMAIL' && $delivery['delivery_code'] != 'WHATSAPP' && $delivery['delivery_code'] != 'TELEGRAM' && $delivery['noteplus'] != '') { $sql = "INSERT INTO t_orderdeliverynote( T_OrderDeliveryNoteT_OrderDeliveryID, T_OrderDeliveryNoteValue, T_OrderDeliveryNoteCreated, T_OrderDeliveryNoteCreatedUserID ) VALUES( ?, ?, NOW(), ? )"; $prm_orderdeliverynote = [ $xdel_id, $delivery['noteplus'], $userid ]; $qry = $this->db_smartone->query($sql, $prm_orderdeliverynote); if (!$qry) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data delivery note'; $result['error_type'] = 'ORDER_DELIVERY_NOTE_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_ORDERDELIVERYNOTE', 'order/save_delivery', $xdel_id]; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); //$this->db_smartone->trans_rollback(); return $result; } } // Jika $delivery['delivery_type_id'] == 3 // START if ($delivery['delivery_type_id'] == 3) { $sql_header_info = "SELECT M_PatientName_enc, IFNULL(M_TitleName,'') M_TitleName, IFNULL(M_PatientPrefix,'') M_PatientPrefix, IFNULL(M_PatientSuffix,'') M_PatientSuffix, M_CompanyName as corporate_name, CONCAT(IFNULL(M_DoctorPrefix,''),IFNULL(M_DoctorPrefix2,''),' ',M_DoctorName,IFNULL(M_DoctorSufix,''),IFNULL(M_DoctorSufix2,''),IFNULL(M_DoctorSufix3,'')) as doctor_fullname FROM t_orderheader JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID JOIN m_company ON T_OrderHeaderM_CompanyID = M_CompanyID JOIN m_doctor ON T_OrderHeaderSenderM_DoctorID = M_DoctorID WHERE T_OrderHeaderID = ?"; $q_h = $this->db_smartone->query($sql_header_info, [$header_id]); $d_h = $q_h->row_array(); $pname_del = $this->ibl_encryptor->decrypt($d_h['M_PatientName_enc'] ?? ''); $d_h['patient_fullname'] = trim(implode(' ', array_filter([ $d_h['M_TitleName'], $d_h['M_PatientPrefix'], $pname_del, $d_h['M_PatientSuffix'] ]))); $sql_del_source = "SELECT M_DeliverySource FROM m_delivery WHERE M_DeliveryID = ?"; $q_d = $this->db_smartone->query($sql_del_source, [$delivery['delivery_id']]); $d_d = $q_d->row_array(); $recepient_type = $d_d ? strtoupper($d_d['M_DeliverySource']) : ''; if ($recepient_type == 'MOU') $recepient_type = 'COMPANY'; $type_email = 'S'; if ($recepient_type != 'PATIENT') $type_email = 'M'; $email_addresses = explode(',', $destination); foreach ($email_addresses as $email) { $email = trim($email); if ($email == '') continue; $sql_insert_email = "INSERT INTO t_send_email ( T_SendEmailT_OrderHeaderID, T_SendEmailT_OrderDeliveryID, T_SendEmailRecepient, T_SendEmailRecepientType, T_SendEmailPatientName, T_SendEmailCorporateName, T_SendEmailDoctorName, T_SendEmailType, T_SendEmailReports, T_SendEmailNarratives, T_SendEmailResponse, T_SendEmailStatus, T_SendEmailCount, T_SendEmailReceived, T_SendEmailIsActive, T_SendEmailCreated, T_SendEmailCreatedUserID, T_SendEmailLastUpdated, T_SendEmailLastUpdatedUserID ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '[]', '', '', 'D', 0, '0000-00-00 00:00:00', 'Y', NOW(), ?, '0000-00-00 00:00:00', 0)"; $qry_email = $this->db_smartone->query($sql_insert_email, [ $header_id, $xdel_id, $email, $recepient_type, $d_h['patient_fullname'], $d_h['corporate_name'], $d_h['doctor_fullname'], $type_email, $userid ]); if (!$qry_email) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data send email draft'; $result['error_type'] = 'INSERT_SEND_EMAIL_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_SEND_EMAIL', 'order/save_delivery']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } } // END $sql = "INSERT INTO order_log_deliveries ( Order_LogDeliveriesT_OrderHeaderID, Order_LogDeliveriesM_DeliveryID, Order_LogDeliveriesM_DeliveryTypeID, Order_LogDeliveriesDestination, Order_LogDeliveriesAddressID, Order_LogDeliveriesRegionalCd, Order_LogDeliveriesNote, Order_LogDeliveriesCreated, Order_LogDeliveriesCreatedUserID ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?)"; $prm_orderlogdeliveries = [ $header_id, $xdel_id, $delivery['delivery_type_id'], $destination, $delivery['address_id'], $delivery['regional_cd'], $delivery['noteplus'], $userid ]; $qry = $this->db_smartone->query($sql, $prm_orderlogdeliveries); if (!$qry) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data delivery log'; $result['error_type'] = 'ORDER_LOG_DELIVERY_INSERT_ERROR'; $prm_log = ['INSERT_ORDER_LOG_DELIVERIES', 'order/save_delivery']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; } } } $this->db_smartone->trans_commit(); return $result; } function not_active_promise($header_id) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; $sql = "SELECT T_OrderPromiseID FROM t_orderpromise WHERE T_OrderPromiseT_OrderHeaderID = ? AND T_OrderPromiseIsActive = 'Y'"; $query = $this->db_smartone->query($sql, [$header_id]); if (!$query) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data promise'; $result['error_type'] = 'SELECT_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['SELECT_PROMISE_ERROR', 'order/update_preregister_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); //$this->db_smartone->trans_rollback(); return $result; } $promise_ids = $query->result_array(); if (count($promise_ids) > 0) { foreach ($promise_ids as $promise_id) { $log_promise = $this->insert_log_promise('not_active', $header_id, $promise_id['T_OrderPromiseID'], $userid); if (!$log_promise['status']) { $result['status'] = false; $result['message'] = $log_promise['message']; $result['error_type'] = $log_promise['error_type']; $result['error_detail'] = $log_promise['error_detail']; $prm_log = ['INSERT_ORDER_LOG_PROMISE', 'order/not_active_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } $sql = "UPDATE t_orderpromise SET T_OrderPromiseIsActive = 'N' WHERE T_OrderPromiseID = ?"; $query = $this->db_smartone->query($sql, [$promise_id['T_OrderPromiseID']]); if (!$query) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update promise'; $result['error_type'] = 'UPDATE_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_T_ORDERPROMISE', 'order/not_active_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } } return $result; } function insert_log_promise($type, $header_id, $promise_id, $userid) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; $sql = "SELECT T_OrderDetailID as xid, T_OrderDetailT_TestID as test_id, T_OrderDetailT_TestName as test_name, T_OrderDetailT_TestSasCode as test_sas_code FROM t_orderdetail WHERE T_OrderDetailT_OrderPromiseID = ? AND T_OrderDetailIsActive = 'Y'"; $query = $this->db_smartone->query($sql, [$promise_id['T_OrderPromiseID']]); if (!$query) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data detail order'; $result['error_type'] = 'SELECT_ORDER_DETAIL_NOT_ACTIVE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['SELECT_ORDER_DETAIL_NOT_ACTIVE_ERROR', 'order/insert_log_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } $detail_ids = $query->result_array(); if (count($detail_ids) > 0) { $sql = "INSERT INTO order_log_promise( Order_LogPromiseType, Order_LogPromiseT_OrderHeaderID, Order_LogPromiseT_OrderPromiseID, Order_LogPromiseDetails, Order_LogPromiseCreatedUserID, Order_LogPromiseCreated ) VALUES ( ?, ?, ?, ?, NOW() )"; $prm_orderlogpromise = [ $type, $header_id, $promise_id, json_encode($detail_ids), $userid ]; $qry = $this->db_smartone->query($sql, $prm_orderlogpromise); if (!$qry) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data promise log'; $result['error_type'] = 'ORDER_LOG_PROMISE_INSERT_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_ORDER_LOG_PROMISE', 'order/insert_log_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } return $result; } function update_preregister_promise($header_id, $preregister_promise, $pre_registerid) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; //$this->db_smartone->trans_begin(); if (intval($preregister_id) == 0) { // generate promise baru untuk yang dari order $set_order_promise = $this->generate_order_promise($header_id); if (!$set_order_promise['status']) { $result['status'] = false; $result['message'] = $set_order_promise['message']; $result['error_type'] = $set_order_promise['error_type']; $result['error_detail'] = $set_order_promise['error_detail']; //$this->db_smartone->trans_rollback(); return $result; } } else { // hapus promise yang aktif $not_active_promise = $this->not_active_promise($header_id); // generate promise baru untuk yang dari preregister $sql = "INSERT INTO t_orderpromise(T_OrderPromiseT_OrderHeaderID, T_OrderPromiseDateTime) VALUES (?, ?)"; $query = $this->db_smartone->query($sql, [$header_id, $preregister_promise]); if (!$query) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data promise'; $result['error_type'] = 'INSERT_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_T_ORDERPROMISE', 'order/update_preregister_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); return $result; } $order_promise_id = $this->db_smartone->insert_id(); $sql = "UPDATE t_orderdetail SET T_OrderDetailT_OrderPromiseID = ? WHERE T_OrderDetailT_OrderHeaderID = ?"; $query = $this->db_smartone->query($sql, [$order_promise_id, $header_id]); if (!$query) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update detail order'; $result['error_type'] = 'UPDATE_ORDER_DETAIL_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_T_ORDERDETAIL_PROMISE', 'order/update_preregister_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); $this->db_smartone->trans_rollback(); return $result; } $log_promise = $this->insert_log_promise('active', $header_id, $order_promise_id, $userid); if (!$log_promise['status']) { $result['status'] = false; $result['message'] = $log_promise['message']; $result['error_type'] = $log_promise['error_type']; $result['error_detail'] = $log_promise['error_detail']; } } return $result; } function generate_order_promise($orderid) { $result = [ 'status' => true, 'message' => 'Success', 'error_type' => '', 'error_detail' => [] ]; /// $this->db_smartone->trans_begin(); try { // Update existing promises to inactive $not_active_promise = $this->not_active_promise($orderid); if (!$not_active_promise['status']) { $result['status'] = false; $result['message'] = $not_active_promise['message']; $result['error_type'] = $not_active_promise['error_type']; $result['error_detail'] = $not_active_promise['error_detail']; $prm_log = ['NOT_ACTIVE_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } // Get order details with cito information $sql_details = "SELECT b.T_OrderDetailID, b.T_OrderDetailT_TestID, b.T_OrderDetailIsCito, T_OrderHeaderIsCito, IFNULL(Nat_CitoID, 0) as Nat_CitoID, IFNULL(Nat_CitoDuration, 0) as Nat_CitoDuration FROM t_orderdetail a JOIN t_orderdetail b on b.T_OrderdetailT_OrderHeaderID = ? AND b.T_OrderDetailIsActive = 'Y' AND b.T_OrderDetailT_TestSasCode LIKE CONCAT(a.T_OrderDetailT_TestSasCode, '%') JOIN t_orderheader ON b.T_OrderDetailT_OrderHeaderID = T_OrderHeaderID LEFT JOIN nat_cito ON T_OrderHeaderIsCito = 'Y' AND T_OrderHeaderNat_CitoID = Nat_CitoID WHERE a.T_OrderDetailT_OrderHeaderID = ? AND a.T_OrderDetailIsActive = 'Y' AND a.T_OrderDetailT_TestIsPrice = 'Y'"; $query_details = $this->db_smartone->query($sql_details, [$orderid, $orderid]); if (!$query_details) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data detail order'; $result['error_type'] = 'SELECT_ORDER_DETAIL_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['SELECT_ORDER_DETAIL_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); //$this->db_smartone->trans_rollback(); return $result; } $details = $query_details->result_array(); // Initialize variables $c_search = []; // Array to store dates $c_dt = []; // Array to store datetime values $c_data = []; // Array to store promise IDs $cito_tmp = null; $cito_tmp_id = null; $order_promise_ids = []; foreach ($details as $detail) { $detail_id = $detail['T_OrderDetailID']; $test_id = $detail['T_OrderDetailT_TestID']; $is_cito_d = $detail['T_OrderDetailIsCito']; $is_cito_h = $detail['T_OrderHeaderIsCito']; $cito_id = $detail['Nat_CitoID']; $cito_dur = $detail['Nat_CitoDuration']; // Handle CITO logic if ($is_cito_d == 'Y' && $is_cito_h == 'Y' && $cito_id != 0) { if ($cito_tmp === null) { $dur_hour = floor($cito_dur / 60); $dur_min = $cito_dur % 60; $tmp = date('Y-m-d H:i:s', strtotime("+{$dur_hour} hours +{$dur_min} minutes")); $cito_tmp = $tmp; // Insert CITO promise $sql_insert_cito = "INSERT INTO t_orderpromise(T_OrderPromiseT_OrderHeaderID, T_OrderPromiseDateTime) VALUES (?, ?)"; $query_insert_cito = $this->db_smartone->query($sql_insert_cito, [$orderid, $cito_tmp]); if (!$query_insert_cito) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data promise CITO'; $result['error_type'] = 'INSERT_CITO_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $this->db_smartone->trans_rollback(); return $result; } $cito_tmp_id = $this->db_smartone->insert_id(); $order_promise_ids[] = $cito_tmp_id; } // Update detail with CITO promise ID $sql_update_detail = "UPDATE t_orderdetail SET T_OrderDetailT_OrderPromiseID = ? WHERE T_OrderDetailID = ?"; $query_update_detail = $this->db_smartone->query($sql_update_detail, [$cito_tmp_id, $detail_id]); if (!$query_update_detail) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update detail dengan promise CITO'; $result['error_type'] = 'UPDATE_DETAIL_CITO_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; //$this->db_smartone->trans_rollback(); return $result; } $log_promise = $this->insert_log_promise('active', $orderid, $cito_tmp_id, $userid); if (!$log_promise['status']) { $result['status'] = false; $result['message'] = $log_promise['message']; $result['error_type'] = $log_promise['error_type']; $result['error_detail'] = $log_promise['error_detail']; } continue; // Skip to next iteration } // Get promise for non-CITO tests $sql_promise = "SELECT fn_fo_find_promise_per_px_v2(?, ?) as promise_date"; $query_promise = $this->db_smartone->query($sql_promise, [$test_id, $orderid]); if (!$query_promise) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat mengambil data promise'; $result['error_type'] = 'SELECT_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['SELECT_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } $promise_row = $query_promise->row(); $tmp = $promise_row->promise_date; // Handle null or invalid date if ($tmp == '0000-00-00 00:00:00' || $tmp == null) { $tmp = null; } if ($tmp !== null) { $tmp_d = date('Y-m-d', strtotime($tmp)); $tmp_t = date('H:i:s', strtotime($tmp)); $ln = count($c_search); if ($ln < 1) { // First entry $c_search[] = $tmp_d; $c_dt[] = $tmp; // Insert promise $sql_insert = "INSERT INTO t_orderpromise(T_OrderPromiseT_OrderHeaderID, T_OrderPromiseDateTime) VALUES (?, ?)"; $query_insert = $this->db_smartone->query($sql_insert, [$orderid, $tmp]); if (!$query_insert) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data promise'; $result['error_type'] = 'INSERT_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } $lid = $this->db_smartone->insert_id(); $order_promise_ids[] = $lid; $c_data[] = $lid; // Update detail $sql_update_detail = "UPDATE t_orderdetail SET T_OrderDetailT_OrderPromiseID = ? WHERE T_OrderDetailID = ? AND T_OrderDetailIsActive = 'Y'"; $query_update_detail = $this->db_smartone->query($sql_update_detail, [$lid, $detail_id]); if (!$query_update_detail) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update detail dengan promise'; $result['error_type'] = 'UPDATE_DETAIL_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_DETAIL_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } else { // Check if date already exists $c_idx = array_search($tmp_d, $c_search); if ($c_idx !== false) { // Date exists, check time $c_t = date('H:i:s', strtotime($c_dt[$c_idx])); $c_data_tmp = $c_data[$c_idx]; if ($tmp_t > $c_t) { // Update with later time $c_dt[$c_idx] = $tmp; $sql_update_promise = "UPDATE t_orderpromise SET T_OrderPromiseDateTime = ? WHERE T_OrderPromiseID = ?"; $query_update_promise = $this->db_smartone->query($sql_update_promise, [$tmp, $c_data_tmp]); if (!$query_update_promise) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update promise datetime'; $result['error_type'] = 'UPDATE_PROMISE_DATETIME_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_PROMISE_DATETIME_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } // Update detail with existing promise ID $sql_update_detail = "UPDATE t_orderdetail SET T_OrderDetailT_OrderPromiseID = ? WHERE T_OrderDetailID = ? AND T_OrderDetailIsActive = 'Y'"; $query_update_detail = $this->db_smartone->query($sql_update_detail, [$c_data_tmp, $detail_id]); if (!$query_update_detail) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update detail dengan promise existing'; $result['error_type'] = 'UPDATE_DETAIL_EXISTING_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_DETAIL_EXISTING_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } else { // New date, add to arrays $c_search[] = $tmp_d; $c_dt[] = $tmp; // Insert new promise $sql_insert = "INSERT INTO t_orderpromise(T_OrderPromiseT_OrderHeaderID, T_OrderPromiseDateTime) VALUES (?, ?)"; $query_insert = $this->db_smartone->query($sql_insert, [$orderid, $tmp]); if (!$query_insert) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat menyimpan data promise baru'; $result['error_type'] = 'INSERT_NEW_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['INSERT_NEW_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } $lid = $this->db_smartone->insert_id(); $c_data[] = $lid; // Update detail $sql_update_detail = "UPDATE t_orderdetail SET T_OrderDetailT_OrderPromiseID = ? WHERE T_OrderDetailID = ? AND T_OrderDetailIsActive = 'Y'"; $query_update_detail = $this->db_smartone->query($sql_update_detail, [$lid, $detail_id]); if (!$query_update_detail) { $result['status'] = false; $result['message'] = 'Terjadi kesalahan saat update detail dengan promise baru'; $result['error_type'] = 'UPDATE_DETAIL_NEW_PROMISE_ERROR'; $result['error_detail'] = [ 'sql_error' => $this->db_smartone->error(), 'last_query' => $this->db_smartone->last_query() ]; $prm_log = ['UPDATE_DETAIL_NEW_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); return $result; } } } } } if (count($c_data) > 0) { foreach ($c_data as $c_data_id) { $log_promise = $this->insert_log_promise('active', $orderid, $c_data_id, $userid); if (!$log_promise['status']) { $result['status'] = false; $result['message'] = $log_promise['message']; $result['error_type'] = $log_promise['error_type']; $result['error_detail'] = $log_promise['error_detail']; $prm_log = ['INSERT_LOG_PROMISE_ERROR', 'order/generate_order_promise']; $xsql = $this->db_smartone->last_query(); $log_error = $this->insert_log_error($xsql, $prm_log); } } } //$this->db_smartone->trans_commit(); return $result; } catch (Exception $e) { //$this->db_smartone->trans_rollback(); $result['status'] = false; $result['message'] = 'Terjadi kesalahan: ' . $e->getMessage(); $result['error_type'] = 'EXCEPTION'; $result['error_detail'] = [ 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ]; return $result; } } function broadcastAntrian($orderID) { // 20450 $sql = "SELECT T_OrderHeaderID, T_OrderHeaderMgm_McuID, T_OrderHeaderM_BranchID, T_OrderLocationT_SampleStationID FROM t_orderheader JOIN t_order_location ON T_OrderHeaderID = T_OrderLocationT_OrderHeaderID AND T_OrderLocationIsActive = 'Y' WHERE T_OrderHeaderID = $orderID"; $query = $this->db_smartone->query($sql); if (!$query) { $message = $this->db_smartone->error(); $message['qry'] = $this->db_smartone->last_query(); $this->sys_error($message); exit; } $rows = $query->result_array(); foreach ($rows as $key => $value) { file_get_contents("http://127.0.0.1:9088/broadcast/sm.new." . $value['T_OrderLocationT_SampleStationID'] . "." . $value['T_OrderHeaderMgm_McuID'] . "." . $value['T_OrderHeaderM_BranchID']); } } function lookup_barcodes() { try { $prm = $this->sys_input; //# cek token valid if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $sql = "SELECT T_BarcodeLabID as id, 'barcode' as type, T_SampleTypeID, T_BarcodeLabID, T_BarcodeLabBarcode, T_BarcodeLabT_OrderHeaderID as orderid, T_BarcodeLabCounter, T_SampleTypeName, 'N' as chex FROM t_barcodelab JOIN t_sampletype ON T_BarcodeLabT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID AND T_SampleStationIsNonLab = '' WHERE T_BarcodeLabT_OrderHeaderID = {$prm['id']} AND T_BarcodeLabIsActive = 'Y' UNION SELECT T_TestID as id, 'nonlab' as type, T_OrderDetailID as T_SampleTypeID, '' as T_BarcodeLabID, '-' as T_BarcodeLabBarcode, T_OrderHeaderID as order_id, 0 as T_BarcodeLabCounter, T_TestName as T_SampleTypeName, 'N' as chex FROM t_orderheader JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID AND T_OrderDetailIsActive = 'Y' JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsResult = 'Y' JOIN group_resultdetail ON Group_ResultDetailT_TestID = T_TestID JOIN group_result ON Group_ResultDetailGroup_ResultID = Group_ResultID AND ( Group_ResultName <> 'lab' AND Group_ResultName <> 'Papsmear') WHERE T_OrderHeaderID = {$prm['id']} GROUP BY T_TestID UNION SELECT T_TestID as id, 'nonlab' as type, T_OrderDetailID as T_SampleTypeID, '' as T_BarcodeLabID, '-' as T_BarcodeLabBarcode, T_OrderHeaderID as order_id, 0 as T_BarcodeLabCounter, T_TestName as T_SampleTypeName, 'N' as chex FROM t_orderheader JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID AND T_OrderDetailIsActive = 'Y' JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsResult = 'Y' JOIN group_resultdetail ON Group_ResultDetailT_TestID = T_TestID JOIN group_result ON Group_ResultDetailGroup_ResultID = Group_ResultID AND ( Group_ResultName = 'Papsmear') WHERE T_OrderHeaderID = {$prm['id']} GROUP BY Group_ResultID "; //echo $sql; $query = $this->db_smartone->query($sql); if (!$query) { $message = $this->db_smartone->error(); $message['qry'] = $this->db_smartone->last_query(); $this->sys_error($message); exit; } $rows = $query->result_array(); if ($rows) { foreach ($rows as $k => $v) { if ($v['chex'] == 'N') $rows[$k]['chex'] = false; else $rows[$k]['chex'] = true; } } $result = array("total" => 0, "records" => $rows); $this->sys_ok($result); } catch (Exception $exc) { $message = $exc->getMessage(); $this->sys_error($message); } } function generate_sample($id) { $userid = $this->sys_user["M_UserID"]; $counter_barcode = 1; $sql = "SELECT T_OrderHeaderLabNumber, T_TestID, T_SampleTypeID , T_SampleTypeSuffix, T_SampleStationIsNonLab, T_SampleStationID from t_orderheader JOIN t_orderdetail ON t_orderheaderid = t_orderdetailt_orderheaderid AND t_orderdetailIsActive = 'Y' JOIN t_test ON t_orderdetailt_testid = t_testid AND T_TestIsResult = 'Y' JOIN t_sampletype ON T_TestT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID where T_OrderHeaderID = '{$id}' group by T_SampleTypeID"; $qry = $this->db_smartone->query($sql); if (!$qry) { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "select barcode | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } $data_samples = $qry->result_array(); foreach ($data_samples as $k => $v) { $lab_no = $v['T_OrderHeaderLabNumber']; $test_id = $v['T_TestID']; $sample_id = $v['T_SampleTypeID']; $sample_code = $v['T_SampleTypeSuffix']; $barcode = $lab_no . $sample_code; $isnonlab = $v['T_SampleStationIsNonLab']; $samplestation_id = $v['T_SampleStationID']; if ($counter_barcode == 1) { $barcode = $barcode . $counter_barcode; $sql = "INSERT INTO t_barcodelab( T_BarcodeLabT_OrderHeaderID, T_BarcodeLabBarcode, T_BarcodeLabT_SampleTypeID, T_BarcodeLabCounter) VALUES ('{$id}','{$barcode}','{$sample_id}','{$counter_barcode}')"; $qry = $this->db_smartone->query($sql); //echo $this->db_smartone->last_query(); if (!$qry) { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert t_barcodelab | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } $last_id_barcode = $this->db_smartone->insert_id(); if ($isnonlab == "") { $sql = "INSERT INTO t_ordersample( T_OrderSampleT_OrderHeaderID, T_OrderSampleT_SampleTypeID, T_OrderSampleT_BarcodeLabID, T_OrderSampleBarcode, T_OrderSampleT_SampleStationID) VALUES ('{$id}','{$sample_id}','{$last_id_barcode}','{$barcode}','{$samplestation_id}')"; $qry = $this->db_smartone->query($sql); if (!$qry) { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert t_ordersample | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } } } $sql = "SELECT MAX(T_BarcodeLabCounter) as ctr FROM t_barcodelab WHERE T_BarcodeLabT_OrderHeaderID = '{$v['T_OrderHeaderID']}' AND T_BarcodeLabBarcode LIKE CONCAT('{$barcode}', '%') AND T_BarcodeLabIsActive = 'Y'"; $qry = $this->db_smartone->query($sql); if ($qry) { $ctr = $qry->row()->ctr; $counter_barcode = $ctr + 1; } else { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "conter barcode | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } } } function generate_location_xxx($id, $mcuid, $branch_id) { $userid = $this->sys_user["M_UserID"]; $sql = "SELECT T_SampleStationID,T_SampleStationName FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsActive = 'Y' JOIN t_sampletype ON T_TestT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID WHERE T_OrderDetailT_OrderHeaderID = {$id} GROUP BY T_SampleStationID "; $qry = $this->db_smartone->query($sql); $data_samples = $qry->result_array(); foreach ($data_samples as $k => $v) { $sample_id = $v['T_SampleStationID']; $sql = $this->db_smartone->query("SELECT M_LocationID as loc_id FROM m_location WHERE M_LocationT_SampleStationID = $sample_id ORDER BY M_LocationPriority DESC, M_LocationID ASC LIMIT 1")->row(); $loc_id = $sql->loc_id; $sql = "INSERT INTO t_order_location( T_OrderLocationT_OrderHeaderID, T_OrderLocationM_LocationID, T_OrderLocationT_SampleStationID, T_OrderLocationCreated, T_OrderLocationLastUpdated, T_OrderLocationUserID) VALUES ('{$id}','{$loc_id}','{$sample_id}',now(),now(),$userid)"; $qry = $this->db_smartone->query($sql); file_get_contents("http://127.0.0.1:9088/broadcast/sm.new." . $sample_id . "." . $mcuid . "." . $branch_id); } if (!$qry) { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert t_order_location | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } } function generate_req_xxx($id, $req) { $userid = $this->sys_user["M_UserID"]; $sql = $this->db_smartone->query("SELECT Nat_PositionID as req_id FROM nat_position WHERE Nat_PositionCode = 'FO'")->row(); $req_id = $sql->req_id; $req_status = $req['status']; $req_tmp = "0"; foreach ($req['reqs'] as $value) { $req_tmp .= "," . $value; } $reqid = "[" . $req_tmp . "]"; $sql = "INSERT INTO t_orderreq( T_OrderReqT_OrderHeaderID, T_OrderReqNat_PositionID, T_OrderReqStatus, T_OrderReqT_TestID, T_OrderReqs) VALUES ('{$id}','{$req_id}','{$req_status}','[]','{$reqid}')"; $qry = $this->db_smartone->query($sql); if (!$qry) { //$this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderreq | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); exit; } } function endshowtime() { $prm = $this->sys_input; $userid = $this->sys_user["M_UserID"]; $this->db_log->trans_begin(); $sql = "UPDATE t_orderheaderaddon SET T_OrderHeaderAddonFoTimeStart = '{$prm['time_start']}', T_OrderHeaderAddonFoTimeEnd = NOW() WHERE T_OrderHeaderAddonT_OrderHeaderID = '{$prm['order_id']}'"; $qry = $this->db_smartone->query($sql); if (!$qry) { $dt_log = ['data' => $prm, 'error' => $this->db_log->error(), 'last_query' => $this->db_log->last_query()]; $prm_log = ['UPDATE_T_ORDERHEADERADDON', 'order/endshowtime']; $log_error = $this->insert_log_error($this->db_log->last_query(), $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "update t_orderheaderaddon | " . $this->db_log->error()["message"], "debug" => $this->db_log->last_query()]); exit; } $sql = "INSERT INTO log_action( LogActionType, LogActionT_OrderHeaderID, LogActionCreated, LogActionUserID) VALUES ('FO_START','{$prm['order_id']}','{$prm['time_start']}','{$userid}')"; $qry = $this->db_log->query($sql); if (!$qry) { $dt_log = ['data' => $prm, 'error' => $this->db_log->error(), 'last_query' => $this->db_log->last_query()]; $prm_log = ['INSERT_LOG_ACTION_START', 'order/endshowtime']; $log_error = $this->insert_log_error($this->db_log->last_query(), $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert log_action start| " . $this->db_log->error()["message"], "debug" => $this->db_log->last_query()]); exit; } $sql = "INSERT INTO log_action( LogActionType, LogActionT_OrderHeaderID, LogActionCreated, LogActionUserID) VALUES ('FO_END','{$prm['order_id']}',now(),'{$userid}')"; $qry = $this->db_log->query($sql); if (!$qry) { $dt_log = ['data' => $prm, 'error' => $this->db_log->error(), 'last_query' => $this->db_log->last_query()]; $prm_log = ['INSERT_LOG_ACTION_END', 'order/endshowtime']; $log_error = $this->insert_log_error($this->db_log->last_query(), $prm_log, $dt_log); $this->db_smartone->trans_rollback(); $this->sys_error_db(["status" => "ERR", "message" => "insert log_action end| " . $this->db_log->error()["message"], "debug" => $this->db_log->last_query()]); exit; } $this->db_log->trans_commit(); $result = array( "total" => 1, "records" => array() ); $this->sys_ok($result); exit; } function get_header($id) { $sql = " SELECT T_OrderHeaderID as order_id, T_OrderHeaderLabNumber as order_no, T_OrderHeaderDate as order_date, T_OrderHeaderSubTotal as order_subtotal, T_OrderHeaderRounding as order_rounding, T_OrderHeaderTotal as order_total, M_PatientName_enc, IFNULL(M_TitleName,'') M_TitleName, IFNULL(M_PatientPrefix,'') M_PatientPrefix, IFNULL(M_PatientSuffix,'') M_PatientSuffix, M_PatientNoReg as patient_mr, M_MouName as order_mou, CorporateName as order_company, fn_global_doctor_name(da.M_DoctorID) doctor_sender, fn_global_doctor_name(db.M_DoctorID) doctor_pj, fn_global_doctor_address(aa.M_DoctorAddressID, 1) doctor_sender_address, M_MouIsBill CorporateIsBill, M_MouMinDP CorporateMinDP, M_MouIsAgingOnHold CorporateIsAgingOnHold, M_MouIsAgingOnHoldNote CorporateIsAgingOnHoldNote from t_orderheader join m_patient on T_OrderHeaderM_PatientID = M_PatientID join corporate on T_OrderHeaderCorporateID = CorporateID join m_mou on T_OrderHeaderM_MouID = M_MouID join m_doctor da on T_OrderHeaderSenderM_DoctorID = da.M_DoctorID join m_doctoraddress aa on T_OrderHeaderSenderM_DoctorAddressID = aa.M_DoctorAddressID join m_doctor db on T_OrderHeaderSenderM_DoctorID = db.M_DoctorID left join m_title on m_patientm_titleid = m_titleid where T_OrderHeaderID = {$id}"; //echo $sql; $query = $this->db_smartone->query($sql); $rows = $query->row_array(); $pname = $this->ibl_encryptor->decrypt($rows['M_PatientName_enc'] ?? ''); $rows['patient_name'] = trim(implode(' ', array_filter([ $rows['M_TitleName'], $rows['M_PatientPrefix'], $pname, $rows['M_PatientSuffix'] ]))); unset($rows['M_PatientName_enc'], $rows['M_TitleName'], $rows['M_PatientPrefix'], $rows['M_PatientSuffix']); return (object) $rows; } function get_delivery($id) { $sql = "CALL sp_fo_payment_get_delivery('{$id}')"; $rows = $this->db_smartone->query($sql)->row(); $this->clean_mysqli_connection($this->db_smartone->conn_id); return json_decode($rows->delivery); } function old_get_details($id) { $sql = " select T_OrderDetailID as d_id, T_OrderDetailT_TestID as t_id, IFNULL(T_OrderDetailT_TestName, T_PacketName) as t_name, T_OrderDetailPrice as t_price, T_OrderDetailDiscTotal as t_disctotal, T_OrderDetailTotal as t_total from t_orderdetail join t_orderdetailaddon on T_OrderDetailAddOnT_OrderDetailID = T_OrderDetailID left join t_test on t_orderdetailt_testid = t_testid left join t_packet on t_orderdetailaddonispacket = 'Y' and t_orderdetailaddont_packetid = t_packetid where T_OrderDetailT_OrderHeaderID = {$id} and T_ORderDetailIsActive = 'Y' and ((T_ORderDetailAddOnIsPacket = 'N' AND T_TestIsPrintNota = 'Y' AND T_OrderDetailT_TestIsPanelChildren = 'N') OR (T_OrderDetailT_TestIsPanelChildren = 'Y' AND T_OrderDetailT_TestIsPanelChildrenPrintNota = 'Y') OR (T_ORderDetailAddOnIsPacket = 'Y' AND T_PacketIsNOta = 'Y'))"; $query = $this->db_smartone->query($sql); //echo $this->db_smartone->last_query(); $rows = $query->result_array(); return $rows; } function load_from_clinic() { $prm = $this->sys_input; $sql = "CALL sp_fo_clinic_load('{$prm['queue']}');"; $query = $this->db_smartone->query($sql); if ($query) { $rst = $query->row(); if ($rst->status == "OK") { $rst->data = json_decode($rst->data); $rst->data->doctor->address = $rst->data->doctor_address; unset($rst->data->doctor_address); $rst->data->company->mou = [$rst->data->mou]; unset($rst->data->mou); } else { $this->sys_error("Tidak ada order"); exit; } echo json_encode($rst); } else { $this->sys_error_db("save order", $this->db_smartone); exit; } } function load() { $prm = $this->sys_input; $sql = "CALL sp_fo_register_load('{$prm['id']}');"; $query = $this->db_smartone->query($sql); if ($query) { $rst = $query->row(); if ($rst->status == "OK") { $rst->data = json_decode($rst->data); $rst->data->doctor->address = $rst->data->doctor_address; unset($rst->data->doctor_address); $rst->data->company->mou = [$rst->data->mou]; unset($rst->data->mou); $this->clean_mysqli_connection($this->db_smartone->conn_id); $ic = $this->get_inform_consent_by_order(intval($prm['id'])); $rst->data->inform_consent = (!empty($ic['title'])) ? $ic : null; } else { $this->sys_error("Tidak ada order"); exit; } echo json_encode($rst); } else { $this->sys_error_db("save order", $this->db_smartone); exit; } } function search_deliveries($prm) { $type = $prm['type']; $id = $prm['id']; if ($type == 'patient') { $prow = $this->db_smartone->query( "SELECT M_PatientEmail_enc, M_PatientHP_enc FROM m_patient WHERE M_PatientID = ? LIMIT 1", [$id] )->row_array(); $patient_email = $this->db_smartone->escape( $this->ibl_encryptor->decrypt($prow['M_PatientEmail_enc'] ?? '') ?: 'Belum ada email' ); $patient_hp = $this->db_smartone->escape( $this->ibl_encryptor->decrypt($prow['M_PatientHP_enc'] ?? '') ?: 'Belum ada WA pasien' ); } if ($type == 'patient') { $sql = "SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, '' as description, 'N' as chex, '' as note, 'origin' as typeform, 'patient' as type, M_DeliveryTypeCode as delivery_code FROM m_delivery JOIN m_deliverytype ON M_DeliveryTypeCode = 'PICKUP' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_DeliverySource = 'patient' AND M_DeliveryIsActive = 'Y' UNION SELECT 0 as kelurahan, m_patientaddress.M_PatientAddressRegionalCd as regional_cd, M_PatientAddressID as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, CONCAT(M_PatientAddressDescription,' ',m_patientaddress.M_PatientAddressVillage,', ',m_patientaddress.M_PatientAddressDistrict,', ',m_patientaddress.M_PatientAddressCity) as description, 'N' as chex, '' as note, 'origin' as typeform, 'patient' as type, M_DeliveryTypeCode as delivery_code FROM m_patient JOIN m_patientaddress ON M_PatientAddressM_PatientID = M_PatientID AND M_PatientAddressIsActive = 'Y' JOIN m_delivery ON M_DeliverySource = 'patient' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'ADDRESS' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_PatientID = {$id} GROUP BY M_PatientAddressID UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IFNULL({$patient_email},'Belum ada email') as description, 'N' as chex, '' as note, 'origin' as typeform, 'patient' as type, M_DeliveryTypeCode as delivery_code FROM m_patient JOIN m_delivery ON M_DeliverySource = 'patient' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'EMAIL' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_PatientID = {$id} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IFNULL({$patient_email},'Belum ada email') as description, 'N' as chex, '' as note, 'origin' as typeform, 'patient' as type, M_DeliveryTypeCode as delivery_code FROM m_patient JOIN m_delivery ON M_DeliverySource = 'patient' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'EMAIL' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_PatientID = {$id} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IFNULL({$patient_hp},'Belum ada WA pasien') as description, 'N' as chex, '' as note, 'origin' as typeform, 'patient' as type, M_DeliveryTypeCode as delivery_code FROM m_patient JOIN m_delivery ON M_DeliverySource = 'patient' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'WHATSAPP' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_PatientID = {$id}"; // echo $sql; } if ($type == 'mou') { //echo $id; $sql = "SELECT * FROM m_mou WHERE M_MouID = {$id}"; //echo $sql; $query = $this->db_smartone->query($sql); if (!$query) { echo $type; echo $this->db_smartone->last_query(); exit; } $data_mou = $query->row_array(); //print_r($data_mou); $sql = "SELECT 0 as kelurahan, M_CompanyM_KelurahanID as regional_cd, M_CompanyID as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, CONCAT(M_CompanyAddress,' ',M_CompanyAddressVillage,', ',M_CompanyAddressDistrict,', ',M_CompanyAddressCity) as description, 'N' as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_company JOIN m_delivery ON M_DeliverySource = 'COMPANY' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'ADDRESS' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_CompanyID = {$data_mou['M_MouM_CompanyID']} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IF(ISNULL(M_CompanyEmail) OR M_CompanyEmail = '', 'Belum ada email', M_CompanyEmail) as description, 'N' as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_company JOIN m_delivery ON M_DeliverySource = 'COMPANY' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'EMAIL' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_CompanyID = {$data_mou['M_MouM_CompanyID']} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IF(ISNULL(M_MouEmail) OR M_MouEmail = '', 'Belum ada email', M_MouEmail) as description, IF(M_MouEmailIsDefault = '','N',IFNULL(M_MouEmailIsDefault,'N')) as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_mou JOIN m_delivery ON M_DeliverySource = '{$type}' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'EMAIL' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_MouID = {$id}"; //echo $sql; } if ($type == 'doctor') { $sql = "SELECT 0 as kelurahan, M_DoctorAddressRegionalCd as regional_cd, M_DoctorAddressID as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, CONCAT(M_DoctorAddressDescription,' ',M_DoctorAddressVillage,', ',M_DoctorAddressDistrict,', ',M_DoctorAddressCity) as description, M_DoctorAddressDeliveryDefault as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_doctor JOIN m_doctoraddress ON M_DoctorAddressM_DoctorID = M_DoctorID AND M_DoctorAddressIsActive = 'Y' JOIN m_kelurahan ON M_DoctorAddressM_KelurahanID = M_KelurahanID JOIN m_district ON M_KelurahanM_DistrictID = M_DistrictID JOIN m_city ON M_DistrictM_CityID = M_CityID JOIN m_delivery ON M_DeliverySource = '{$type}' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'ADDRESS' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_DoctorID = {$id} GROUP BY M_DoctorAddressID UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IF(ISNULL(M_DoctorEmail) OR M_DoctorEmail = '','Belum ada email',M_DoctorEmail) as description, IF(M_DoctorEmailIsDefault = '','N',IFNULL(M_DoctorEmailIsDefault,'N')) as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_doctor JOIN m_delivery ON M_DeliverySource = '{$type}' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'EMAIL' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_DoctorID = {$id} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IF(ISNULL(M_DoctorHP) OR M_DoctorHP = '','Belum ada WA pengirim',M_DoctorHP) as description, IF(M_DoctorEmailIsDefault = '','N',IFNULL(M_DoctorEmailIsDefault,'N')) as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_doctor JOIN m_delivery ON M_DeliverySource = '{$type}' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'WHATSAPP' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_DoctorID = {$id} UNION SELECT 0 as kelurahan, '' as regional_cd, 0 as address_id, M_DeliveryM_DeliveryTypeID as delivery_type, M_DeliveryID as delivery_id, M_DeliveryName as delivery_name, IF(ISNULL(M_DoctorHP) OR M_DoctorHP = '','Belum ada telegram pengirim',M_DoctorHP) as description, IF(M_DoctorEmailIsDefault = '','N',IFNULL(M_DoctorEmailIsDefault,'N')) as chex, '' as note, 'origin' as typeform, '{$type}' as type, M_DeliveryTypeCode as delivery_code FROM m_doctor JOIN m_delivery ON M_DeliverySource = '{$type}' AND M_DeliveryIsActive = 'Y' JOIN m_deliverytype ON M_DeliveryTypeCode = 'TELEGRAM' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID WHERE M_DoctorID = {$id}"; } //echo $sql; $query = $this->db_smartone->query($sql); if ($query) { $rows = $query->result_array(); //$data = json_decode($rows->x); if ($rows) { foreach ($rows as $k => $v) { $xval = $v['chex'] === 'N' ? false : true; //$rows[$k]['chex'] = $xval; } } return $rows; } else { return array(); } } function post($url) { //$data = $data; $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); //echo "RST : $result "; return $result; } function load_preregister() { if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $prm = $this->sys_input; $tests = []; if ($prm['id'] != -1) { $sql = "SELECT * FROM mcu_preregister_patients JOIN mgm_mcu ON Mcu_PreregisterPatientsMgm_McuID = Mgm_McuID WHERE Mcu_PreregisterPatientsID = {$prm['id']}"; } // echo $sql; $row_header = $this->db_onedev->query($sql)->row_array(); $patient = array(); $sql = "SELECT 'N' divider,M_PatientID, M_PatientNoReg,M_PatientEmail,M_PatientPrefix,M_PatientSuffix, concat(IFNULL(M_TitleName,''),' ',IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) M_PatientName, M_PatientName M_PatientRealName, M_TitleID, M_TitleName, M_SexID, M_SexName, M_PatientHP, M_PatientPOB, M_PatientDOB, DATE_FORMAT(M_PatientDOB,'%d-%m-%Y') as dob_ina, m_patientaddress.M_PatientAddressDescription, M_PatientM_IdTypeID, M_PatientIDNumber, CONCAT(m_patientaddress.M_PatientAddressDescription, '\n\n', m_patientaddress.M_PatientAddressVillage, '\n', m_patientaddress.M_PatientAddressDistrict, '\n', m_patientaddress.M_PatientAddressCity) as full_address, IFNULL(M_PatientNote, '') M_PatientNote, M_PatientPhoto, IF(M_PatientPhone IS NULL OR M_PatientPhone = '', M_PatientHP, M_PatientPhone) hp, '' info, 0 M_KelurahanID, 0 M_DistrictID, 0 M_CityID, 0 M_ProvinceID, religion.code as M_PatientReligionCode, IFNULL(display, '-') M_ReligionName, M_PatientNIP as M_PatientNIK, M_PatientJabatan, M_PatientKedudukan, M_PatientPJ, M_PatientLocation, M_PatientJob FROM m_patient LEFT JOIN m_title on M_PatientM_TitleID = M_TitleID JOIN m_sex on M_PatientM_SexID = M_SexID LEFT JOIN m_patientaddress on M_PatientAddressM_PatientID = M_PatientID and M_PatientAddressIsActive = 'Y' AND M_PatientAddressNote = 'Utama' LEFT JOIN terminology religion ON M_PatientReligionCode = religion.code AND religion.attribute_path = 'Person.religion.code' where M_PatientID = {$row_header['Mcu_PreregisterPatientsM_PatientID']}"; //echo $sql; $query = $this->db_onedev->query($sql); if ($query && $prm['id'] != -1) { $patient = $query->row_array(); $patient['M_PatientName'] = stripslashes($patient['M_PatientName']); $patient['M_PatientAddress'] = stripslashes($patient['full_address']); $info = $this->db_onedev->query("SELECT fn_fo_patient_visit(?) info", [$patient['M_PatientID']])->row(); $patient['info'] = json_decode($info->info); $rst['patient'] = $patient; } else { $rst['patient'] = array(); } $sql = "SELECT M_MouStatus,M_MouEmail, M_MouEmailIsDefault, M_MouEndDate, M_MouID, M_MouIsBill, M_MouIsDefault, M_MouName, M_MouNote, M_MouStartDate, '' delivery_email_code FROM m_mou WHERE M_MouID = {$row_header['Mgm_McuM_MouID']} "; //echo $sql; $row_mou = $this->db_onedev->query($sql)->row_array(); $rst['data_deliveries'] = array(); $new_delivery = array(); $new_delivery = $this->search_deliveries(array('id' => $row_header['Mcu_PreregisterPatientsM_PatientID'], 'type' => 'patient')); if (count($new_delivery) > 0) { foreach ($new_delivery as $knd => $vnd) { array_push($rst['data_deliveries'], $vnd); } } /*data doctor*/ $sql = "SELECT M_DoctorID, M_DoctorIsDefault, 'N' M_DoctorIsPJ, CONCAT('[ ',M_DoctorCode,' ] ',M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ',M_DoctorSufix, M_DoctorSufix2, M_DoctorSufix3) as M_DoctorName, fn_fo_delivery_code('DOCTOR', 'EMAIL', 0) as delivery_email_code, IF(M_DoctorEmail IS NULL OR M_DoctorEmail = '', 'N', M_DoctorEmailIsDefault) email_default, IFNULL( concat('[', group_concat(JSON_OBJECT('description',M_DoctorAddressNote,'M_DoctorAddressDescription', M_DoctorAddressDescription, 'M_DoctorAddressID', M_DoctorAddressID, 'delivery_default', M_DoctorAddressDeliveryDefault, 'delivery_code', fn_fo_delivery_code('DOCTOR', 'ADDRESS', M_DoctorAddressID)) SEPARATOR ','), ']'), '[]') as address, M_DoctorNote FROM m_doctor JOIN m_doctoraddress ON M_DoctorAddressM_DoctorID = M_DoctorID AND M_DoctorAddressIsActive = 'Y' JOIN m_doctorpj ON M_DoctorPjM_DoctorID = M_DoctorID AND M_DoctorPjIsActive = 'Y' group by M_DoctorID"; //echo $sql; $v = $this->db_onedev->query($sql)->row_array(); if ($v) { $v['address'] = json_decode($v['address']); $rst['selected_doctor'] = $v; /*$sql = "SELECT M_DoctorAddressDescription, M_DoctorAddressID, M_DoctorAddressDeliveryDefault delivery_default, fn_fo_delivery_code('DOCTOR', 'ADDRESS', M_DoctorAddressID) delivery_code FROM m_doctoraddress WHERE M_DoctorAddressM_DoctorID = {$v['M_DoctorID']}"; $raddr = $this->db_onedev->query($sql)->row_array();*/ foreach ($v['address'] as $kaddr => $vaddr) { $v['address'][$kaddr]->description = $v['address'][$kaddr]->M_DoctorAddressNote . " : " . $v['address'][$kaddr]->M_DoctorAddressDescription; } $rst['selected_address'] = $v['address'][0]; //$rst['selected_address'] = $vaddr; } $new_delivery = array(); $new_delivery = $this->search_deliveries(array('id' => $rst['selected_doctor']['M_DoctorID'], 'type' => 'doctor')); if (count($new_delivery) > 0) { foreach ($new_delivery as $knd => $vnd) { array_push($rst['data_deliveries'], $vnd); } } /*data company mou*/ $sql = "SELECT m_company.*, '' mou FROM m_company WHERE M_CompanyID = {$row_header['Mgm_McuM_CompanyID']}"; //echo $sql; $row_company = $this->db_onedev->query($sql)->row_array(); $sql = "SELECT M_MouStatus,M_MouEmail, M_MouEmailIsDefault, M_MouEndDate, M_MouID, M_MouIsBill, M_MouIsDefault, M_MouName, M_MouNote, M_MouStartDate, '' delivery_email_code FROM m_mou WHERE M_MouM_CompanyID = {$row_company['M_CompanyID']} AND M_MouStatus = 'R' AND M_MouIsActive = 'Y'"; //echo $sql; $row_company['mou'] = $this->db_onedev->query($sql)->result_array(); $rst['selected_company'] = $row_company; $sql = "SELECT M_MouStatus, M_CompanyEmail as M_MouEmail, M_MouEndDate, M_MouID, M_MouIsBill, M_MouIsDefault, M_MouName, M_MouNote, M_MouStartDate, '' delivery_email_code FROM m_mou JOIN m_company ON M_CompanyID = M_MouM_CompanyID WHERE M_MouNumber = '{$row_header['Mcu_PreregisterPatientsM_MouNumber']}' AND M_MouStatus = 'R' AND M_MouIsActive = 'Y'"; $row_mou = $this->db_onedev->query($sql)->row_array(); //echo $this->db_onedev->last_query(); $rst['selected_mou'] = $row_mou; // print_r($rst['selected_mou']); $rst['companies'] = array(); array_push($rst['companies'], $rst['selected_company']); $new_delivery = array(); //echo $rst['selected_mou']['M_MouID']; $new_delivery = $this->search_deliveries(array('id' => $row_mou['M_MouID'], 'type' => 'mou')); if (count($new_delivery) > 0) { foreach ($new_delivery as $knd => $vnd) { array_push($rst['data_deliveries'], $vnd); } } //echo 'dsada'; $sql = "SELECT * FROM mgm_mcuemailresult WHERE Mgm_McuEmailResultMgm_McuID = ? AND Mgm_McuEmailResultIsActive = 'Y'"; $rst_email_result = $this->db_smartone->query($sql, [$row_header['Mgm_McuID']])->result_array(); if (count($rst_email_result) > 0) { $rst['email_result'] = $rst_email_result[0]; } $email_patient = false; $email_company = false; if ($rst['email_result'] == 'P') { $email_patient = true; } else if ($rst['email_result'] == 'C') { $email_company = true; } else { $email_patient = true; $email_company = true; } foreach ($rst['data_deliveries'] as $k_ordev => $v_ordev) { if ($email_patient && intval($v_ordev['delivery_id'] == 3)) { $rst['data_deliveries'][$k_ordev]['chex'] = 'Y'; } else if ($email_company && intval($v_ordev['delivery_id'] == 14)) { $rst['data_deliveries'][$k_ordev]['chex'] = 'Y'; } else { $rst['data_deliveries'][$k_ordev]['chex'] = 'N'; } } $rst['tests'] = array(); $explode_tests = explode(',', $row_header['Mcu_PreregisterPatientsOrders']); if (!empty($explode_tests)) { //print_r($explode_tests); foreach ($explode_tests as $ktest => $vtest) { $r_test = $this->search_test_by_code(trim($vtest), $row_mou['M_MouID']); if ($r_test) { array_push($rst['tests'], $r_test); } } } $rst['selected_reference'] = []; $sql = "SELECT * FROM m_reference WHERE M_ReferenceIsActive = 'Y'"; $rst_reference = $this->db_smartone->query($sql)->result_array(); if (count($rst_reference) > 0) { $rst['selected_reference'] = $rst_reference[0]; } $rst['result_promise'] = ''; $sql = "SELECT * FROM mgm_mcuresultpromise WHERE Mgm_McuResultPromiseMgm_McuID = ? AND Mgm_McuResultPromiseIsActive = 'Y' LIMIT 1"; $rst_result_promise = $this->db_smartone->query($sql, [$row_header['Mgm_McuID']])->row_array(); //echo $this->db_smartone->last_query(); if ($rst_result_promise) { $result_promise = 'Janji hasil belum disetting'; if ($rst_result_promise['Mgm_McuResultPromiseType'] == 'D') { $promise_days = $rst_result_promise['Mgm_McuResultPromiseValue']; $result_promise = date('d-m-Y H:i:s', strtotime('+' . $promise_days . ' days 23:59:59')); } if ($rst_result_promise['Mgm_McuResultPromiseType'] == 'T') { $result_promise = date('d-m-Y H:i:s', strtotime($rst_result_promise['Mgm_McuResultPromiseDate'] . ' ' . $rst_result_promise['Mgm_McuResultPromiseTime'])); } $rst['result_promise'] = $result_promise; } $sql = "SELECT * FROM s_menu WHERE `S_MenuName` = 'Pre-Register' AND S_MenuIsActive = 'Y'"; $row_returnurl = $this->db_onedev->query($sql)->row_array(); $rst['url_return'] = $row_returnurl['S_MenuUrl']; $xrst = array('status' => $status, 'data' => $rst); $result = array("records" => $rst); $this->sys_ok($result); exit; } function load_preregister_xxx() { if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $prm = $this->sys_input; //$tests = $row_header['Mcu_PreregisterPatientsTests']; if ($prm['id'] != -1) { $sql = "SELECT * FROM mcu_preregister_patients JOIN mgm_mcu ON Mgm_McuID = Mcu_PreregisterPatientsMgm_McuID WHERE Mcu_PreregisterPatientsID = {$prm['id']}"; } $row_header = $this->db_smartone->query($sql)->row_array(); $patient = array(); $sql = "SELECT 'N' divider,M_PatientID, M_PatientNoReg,M_PatientEmail,M_PatientPrefix,M_PatientSuffix, concat(IFNULL(M_TitleName,''),' ',IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) M_PatientName, M_PatientName M_PatientRealName, M_TitleID, M_TitleName, 0 M_SexID, '{$row_header['Mcu_PreregisterPatientsGender']}' M_SexName, M_PatientHP, '' M_PatientPOB, M_PatientDOB, DATE_FORMAT(M_PatientDOB,'%d-%m-%Y') as dob_ina, M_PatientAddress, M_PatientAddress M_PatientAddressDescription, 0 M_PatientM_IdTypeID, M_PatientIdentifierValue M_PatientIDNumber, '' M_PatientNote, M_PatientPhoto, M_PatientHp hp, '' info, M_PatientAddressRegionalCd, M_PatientAddressCity, M_PatientAddressRT, M_PatientAddressRW, M_PatientAddressVillage, M_PatientAddressDistrict, M_PatientAddressState, M_PatientAddressCountry, 0 M_KelurahanID, 0 M_DistrictID, 0 M_CityID, 0 M_ProvinceID, 0 M_PatientM_ReligionID, M_PatientReligionCode M_ReligionName, '{$row_header['Mgm_McuM_BranchID']}' branch_id, M_BranchName branch_name from m_patient left join m_title on M_PatientM_TitleID = M_TitleID left join m_branch on M_BranchID = '{$row_header['Mgm_McuM_BranchID']}' where M_PatientID = {$row_header['Mcu_PreregisterPatientsM_PatientID']} group by M_PatientID"; //echo $sql; $query = $this->db_smartone->query($sql); if ($query && $prm['id'] != -1) { $patient = $query->row_array(); $patient['M_PatientName'] = stripslashes($patient['M_PatientName']); $rst['patient'] = $patient; } else { $rst['patient'] = array(); } $rst['data_deliveries'] = array(); $new_delivery = array(); $new_delivery = $this->search_deliveries(array('id' => $rst['patient']['M_PatientID'], 'type' => 'patient')); if (count($new_delivery) > 0) { foreach ($new_delivery as $knd => $vnd) { array_push($rst['data_deliveries'], $vnd); } } /*data doctor*/ $sql = "SELECT M_DoctorID, 'N' M_DoctorIsPJ, CONCAT('[ ',M_DoctorCode,' ] ',M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ',M_DoctorSufix,M_DoctorSufix2) as M_DoctorName, '' as delivery_email_code, IFNULL(M_DoctorEmail,'') email_default, -- M_DoctorAddress as address, '' M_DoctorNote FROM m_doctorpj JOIN m_doctor ON M_DoctorPjM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' WHERE M_DoctorPjIsActive = 'Y' ORDER BY M_DoctorPjID DESC LIMIT 1"; //echo $sql; $row_doctor = $this->db_smartone->query($sql)->row_array(); $rst['selected_doctor'] = $row_doctor; $new_delivery = array(); $new_delivery = $this->search_deliveries(array('id' => $rst['selected_doctor']['M_DoctorID'], 'type' => 'doctor')); if (count($new_delivery) > 0) { foreach ($new_delivery as $knd => $vnd) { array_push($rst['data_deliveries'], $vnd); } } /*data company mou*/ $sql = "SELECT m_company.*, '' mou FROM m_company WHERE M_CompanyID = {$row_header['Mgm_McuM_CompanyID']}"; $row_company = $this->db_smartone->query($sql)->row_array(); //print_r($row_company); $rst['selected_company'] = $row_company; $rst['companies'] = array(); array_push($rst['companies'], $rst['selected_company']); /* $new_delivery = array(); //echo $rst['selected_mou']['M_MouID']; $new_delivery = $this->search_deliveries(array('id'=>$row_mou['M_MouID'],'type'=>'mou')); if(count($new_delivery) > 0){ foreach($new_delivery as $knd => $vnd){ array_push($rst['data_deliveries'],$vnd); } } //echo 'dsada'; foreach($rst['data_deliveries'] as $k_ordev => $v_ordev){ //echo $row_header['McuOfflinePrepareDeliveries']; $check_centang_dev = $this->checked_delivery($row_header['McuOfflinePrepareDeliveries'],$v_ordev); if($check_centang_dev){ $rst['data_deliveries'][$k_ordev] = $check_centang_dev ; } } */ $tests = $row_header['Mcu_PreregisterPatientsOrders']; $rst['tests'] = array(); $explode_tests = explode(',', $row_header['Mcu_PreregisterPatientsOrders']); if (!empty($explode_tests)) { //print_r($explode_tests); foreach ($explode_tests as $ktest => $vtest) { $r_test = $this->search_test_by_code(trim($vtest), $row_header['Mgm_McuT_PriceHeaderID']); if ($r_test) { array_push($rst['tests'], $r_test); } } } $xrst = array('status' => $status, 'data' => $rst); //sleep(30); $result = array("records" => $rst); $this->sys_ok($result); exit; } function checked_delivery($prepare_deliveries, $delivery) { $rtn = false; //print_r($delivery); //print_r($prepare_deliveries); $prepare_deliveries = preg_replace("/\\n/", "___n___", $prepare_deliveries); $deliveries = json_decode($prepare_deliveries); //print_r($deliveries); foreach ($deliveries as $k => $v) { if ((intval($v->kelurahan) == intval($delivery['kelurahan'])) && (intval($v->address_id) == intval($delivery['address_id'])) && ($v->delivery_type == $delivery['delivery_type']) && (intval($v->delivery_id) == intval($delivery['delivery_id'])) && $v->chex == 'Y') { $rtn = $v; } } return $rtn; } function search_test_by_code($xcode, $mouid) { $is_packet = 'N'; $px_type = 'PX'; $pxtype = ''; if (substr($xcode, 0, 2) == 'PN' || substr($xcode, 0, 2) == 'PR') { $is_packet = 'Y'; $px_type = substr($xcode, 0, 2); $sql = "SELECT T_PacketID as T_TestID FROM t_packet WHERE T_PacketSasCode = '{$xcode}' AND T_PacketIsActive = 'Y'"; $pxtype = "px_type = '{$px_type}' AND"; } else { $sql = "SELECT T_TestID FROM t_test WHERE T_TestSasCode = '{$xcode}' AND T_TestIsActive = 'Y'"; } //echo $sql; $xrow_test = $this->db_smartone->query($sql)->row_array(); $sql = "select * from ss_price_mou where Ss_PriceMouM_MouID = {$mouid} AND T_TestID = {$xrow_test['T_TestID']} AND $pxtype is_packet = '{$is_packet}' AND T_PriceIsCito <> 'Y';"; //echo $sql; $query = $this->db_smartone->query($sql); if ($query) { $row = $query->row_array(); $id_to_remove = []; // var_dump($rows); $row['requirement'] = []; if ($row['px_type'] == "PX") { $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$row['T_TestID']}') x") ->row(); if ($x->x != null) $row['requirement'] = json_decode($x->x); } //print_r($row); // Janji Hasil per PX //$x = $this->db_smartone->query("SELECT fn_fo_find_promise_by_one_px('{$row['T_TestID']}') x")->row(); if ($row['is_packet'] == 'N') { $tests = $row['T_PriceT_TestID']; $panels = ''; } else { $tests = ''; $panels = $row['T_PriceT_TestID']; } $sql_param = array($tests, $panels); // $sql = "select fn_fo_find_promise_by_px(?, ?) as x"; // $x = $this->db_smartone->query($sql, $sql_param)->row(); // if ($x->x != null) // $row['promise'] = $x->x; $row['nat_test'] = json_decode($row['nat_test']); $row['child_test'] = json_decode($row['child_test']); //print_r($row['child_test'] ); // IF PROFILE if ($row['px_type'] == "PN" || $row['px_type'] == "PR" || $row['px_type'] == "PXR") { foreach ($row['child_test'] as $l => $w) { $row['child_test'][$l]->requirement = []; $row['child_test'][$l]->nat_test = json_decode($w->nat_test); $row['child_test'][$l]->promise = null; //echo "SELECT fn_fo_requirement_get('{$w->T_TestID}')"; $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$w->T_TestID}') x")->row(); if ($x->x != null) $row['child_test'][$l]->requirement = json_decode($x->x); // Janji Hasil per PX //$x = $this->db_smartone->query("SELECT fn_fo_find_promise_by_one_px('{$w->T_TestID}') x") // ->row(); //if ($x->x != null) $row['child_test'][$l]->promise = null; } } return $row; } } function get_report_url($code_report, $params) { $this->load->library("Reporturl"); $report_url = $this->reporturl->get_report_url_by_code($code_report, $params); if ($report_url[0]) { return $report_url[1]; } else { return null; } } // ============================================================ // MIRROR SCREEN: Ambil daftar pemeriksaan berdasarkan order_id // ============================================================ function get_tests_by_order() { $prm = $this->sys_input; $order_id = isset($prm['order_id']) ? intval($prm['order_id']) : 0; if ($order_id <= 0) { $this->sys_error("order_id tidak valid"); exit; } $sql = "SELECT T_OrderDetailID, T_TestName as test_name, T_TestCode as test_code, CASE WHEN M_MouIsBill = 'Y' THEN '-' ELSE CAST(T_OrderDetailPrice AS CHAR) END as price, CASE WHEN M_MouIsBill = 'Y' THEN '-' ELSE CAST(T_OrderHeaderTotal AS CHAR) END as order_total FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsPrice = 'Y' JOIN t_orderheader ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID JOIN m_mou ON T_OrderHeaderM_MouID = M_MouID WHERE T_OrderDetailT_OrderHeaderID = ? AND T_OrderDetailIsActive = 'Y' ORDER BY T_TestName ASC"; $query = $this->db_smartone->query($sql, [$order_id]); if (!$query) { $this->sys_error("Gagal mengambil data pemeriksaan"); exit; } $data = $query->result_array(); $this->sys_ok($data); exit; } // ============================================================ // MIRROR SCREEN: Simpan tanda tangan digital pasien // ============================================================ function save_signature() { $prm = $this->sys_input; $order_id = isset($prm['order_id']) ? intval($prm['order_id']) : 0; $noreg = isset($prm['noreg']) ? $prm['noreg'] : ''; $uuid = isset($prm['uuid']) ? $prm['uuid'] : ''; $signature = isset($prm['signature']) ? $prm['signature'] : ''; if ($order_id <= 0 || empty($signature)) { $this->sys_error("Parameter tidak lengkap"); exit; } // Ambil M_PatientID dari t_orderheader $row_order = $this->db_smartone->query( "SELECT T_OrderHeaderM_PatientID FROM t_orderheader WHERE T_OrderHeaderID = ? LIMIT 1", [$order_id] )->row(); if (!$row_order) { $this->sys_error("Order tidak ditemukan"); exit; } $patient_id = intval($row_order->T_OrderHeaderM_PatientID); // Decode base64 dan simpan sebagai file PNG $sig_data = $signature; if (strpos($sig_data, ',') !== false) { $sig_data = explode(',', $sig_data, 2)[1]; } $sig_decoded = base64_decode($sig_data); $home_dir = "/home/one/project/one/"; $target_dir = $home_dir . "one-media/one-signature/" . date("Y") . "/"; if (!is_dir($target_dir)) { @mkdir($target_dir, 0775, true); } $filename = "signature_" . $order_id . "_" . date('YmdHis') . ".png"; $filepath = $target_dir . $filename; $public_url = "/" . str_replace($home_dir, "", $filepath); $saved = file_put_contents($filepath, $sig_decoded); // Update field tanda tangan di t_orderheader $sql_update = "UPDATE t_orderheader SET T_OrderHeaderSignature = ?, T_OrderHeaderSignatureDate = NOW() WHERE T_OrderHeaderID = ?"; @$this->db_smartone->query($sql_update, [$public_url, $order_id]); // Nonaktifkan TTD lama pasien (jika ada) $sql_deactivate = "UPDATE patient_signature SET Patient_SignatureIsActive = 'N', Patient_SignatureLastUpdated = NOW(), Patient_SignatureLastUpdatedUserID = 0 WHERE Patient_SignatureM_PatientID = ? AND Patient_SignatureIsActive = 'Y'"; $this->db_smartone->query($sql_deactivate, [$patient_id]); // Simpan TTD baru ke patient_signature $sql_insert = "INSERT INTO patient_signature ( Patient_SignatureM_PatientID, Patient_SignatureUrl, Patient_SignatureIsActive, Patient_SignatureCreated, Patient_SignatureCreatedUserID ) VALUES (?, ?, 'Y', NOW(), 0)"; $insert_ok = $this->db_smartone->query($sql_insert, [$patient_id, $public_url]); if (!$insert_ok) { $this->sys_error_db("INSERT PATIENT SIGNATURE", $this->db_smartone); exit; } // Catat ke order_log $sqllog = "INSERT INTO order_log( orderLogType, orderLogT_OrderHeaderID, orderLogJSONBefore, orderLogJSONAfter, orderLogCreated, orderLogUserID) VALUES ('SIGNATURE', ?, '', ?, NOW(), 0)"; $log_data = json_encode(['signature_url' => $public_url, 'patient_id' => $patient_id, 'noreg' => $noreg, 'uuid' => $uuid]); @$this->db_log->query($sqllog, [$order_id, $log_data]); $this->sys_ok([ 'order_id' => $order_id, 'patient_id' => $patient_id, 'noreg' => $noreg, 'signature_url' => $public_url, 'saved' => ($saved !== false) ]); exit; } function retry_location() { if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $prm = $this->sys_input; $header_id = isset($prm['order_id']) ? (int) $prm['order_id'] : 0; $userid = $this->sys_user["M_UserID"]; if (!$header_id) { $this->sys_error("order_id tidak boleh kosong"); exit; } // Ambil semua station terkait order $sql = "SELECT T_SampleStationID, T_SampleStationName FROM t_orderdetail JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsActive = 'Y' JOIN t_sampletype ON T_TestT_SampleTypeID = T_SampleTypeID JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID WHERE T_OrderDetailT_OrderHeaderID = ? GROUP BY T_SampleStationID"; $qry = $this->db_smartone->query($sql, $header_id); if (!$qry) { $this->sys_error("Gagal mengambil data station untuk order " . $header_id); exit; } $all_stations = $qry->result_array(); // Ambil station yang sudah punya lokasi $sql = "SELECT T_OrderLocationT_SampleStationID as station_id FROM t_order_location WHERE T_OrderLocationT_OrderHeaderID = ?"; $qry = $this->db_smartone->query($sql, $header_id); if (!$qry) { $this->sys_error("Gagal mengambil data lokasi existing untuk order " . $header_id); exit; } $existing_ids = array_column($qry->result_array(), 'station_id'); // Hanya proses station yang belum punya lokasi $pending = array_values(array_filter($all_stations, function ($s) use ($existing_ids) { return !in_array($s['T_SampleStationID'], $existing_ids); })); if (empty($pending)) { $this->sys_ok([ 'order_id' => $header_id, 'succeeded' => [], 'failed' => [], 'message' => 'Semua lokasi sudah terbentuk untuk order ini.', ]); exit; } $result = $this->_do_generate_location_for_stations($pending, $header_id, $userid); $succeeded_count = count($result['succeeded']); $failed_count = count($result['failed']); $this->sys_ok([ 'order_id' => $header_id, 'succeeded' => $result['succeeded'], 'failed' => $result['failed'], 'message' => "Retry selesai. {$succeeded_count} berhasil, {$failed_count} gagal.", ]); exit; } function load_klinik() { if (!$this->isLogin) { $this->sys_error("Invalid Token"); exit; } $prm = $this->sys_input; $klinik_number = trim($prm['klinik_number'] ?? ''); if (!$klinik_number) { $this->sys_error("klinik_number required"); exit; } // Ambil header order klinik $row_header = $this->db_onedev->query( "SELECT o.*, s.*, od.orderDoctorDiagnosePrimer FROM one_klinik.`order` o JOIN one_klinik.setting s ON s.settingIsActive = 'Y' LEFT JOIN one_klinik.order_doctor od ON od.orderDoctorOrderID = o.orderID AND od.orderDoctorIsActive = 'Y' AND od.orderDoctorType = 'TEXT' WHERE o.OrderNumber = ? LIMIT 1", [$klinik_number] )->row_array(); if (!$row_header) { $this->sys_error("Order tidak ditemukan"); exit; } $rst = []; $rst['klinik'] = $row_header; $enc = $this->ibl_encryptor; // Patient $patient_row = $this->db_onedev->query( "SELECT m_patient.*, M_TitleID, M_TitleName, M_SexID, M_SexName, M_PatientAddressM_KelurahanID as M_KelurahanID, M_PatientAddressDescription, IFNULL(M_ReligionName,'-') as M_ReligionName FROM m_patient LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID JOIN m_sex ON M_PatientM_SexID = M_SexID LEFT JOIN m_patientaddress ON M_PatientAddressM_PatientID = M_PatientID AND M_PatientAddressIsActive = 'Y' LEFT JOIN m_religion ON M_PatientM_ReligionID = M_ReligionID WHERE M_PatientID = ? GROUP BY M_PatientID LIMIT 1", [$row_header['orderM_PatientID']] )->row_array(); if ($patient_row) { $p_name = $enc->decrypt($patient_row['M_PatientName_enc'] ?? '') ?: $patient_row['M_PatientName']; $p_hp = $enc->decrypt($patient_row['M_PatientHP_enc'] ?? '') ?: $patient_row['M_PatientHP']; $p_email = $enc->decrypt($patient_row['M_PatientEmail_enc'] ?? '') ?: $patient_row['M_PatientEmail']; $p_idnum = $enc->decrypt($patient_row['M_PatientIDNumber_enc']?? '') ?: $patient_row['M_PatientIDNumber']; $p_dob_raw = $enc->decrypt($patient_row['M_PatientDOB_enc'] ?? ''); // p_dob_raw is d-m-Y; convert to Y-m-d for M_PatientDOB, keep d-m-Y for dob_ina $p_dob_ina = $p_dob_raw ?: $patient_row['M_PatientDOB']; $p_dob_sql = ''; if ($p_dob_raw) { $parts = explode('-', $p_dob_raw); $p_dob_sql = count($parts) === 3 ? "{$parts[2]}-{$parts[1]}-{$parts[0]}" : ''; } $title = $patient_row['M_TitleName'] ? $patient_row['M_TitleName'] . ' ' : ''; $prefix = $patient_row['M_PatientPrefix'] ? $patient_row['M_PatientPrefix'] . ' ': ''; $suffix = $patient_row['M_PatientSuffix'] ? ' ' . $patient_row['M_PatientSuffix']: ''; $patient_row['M_PatientName'] = trim($title . $prefix . $p_name . $suffix); $patient_row['M_PatientRealName'] = $p_name; $patient_row['M_PatientHP'] = $p_hp; $patient_row['M_PatientEmail'] = $p_email; $patient_row['M_PatientIDNumber'] = $p_idnum; $patient_row['M_PatientDOB'] = $p_dob_sql ?: $patient_row['M_PatientDOB']; $patient_row['dob_ina'] = $p_dob_ina; $patient_row['divider'] = 'N'; $patient_row['hp'] = $p_hp; $patient_row['M_PatientAddress'] = ''; $patient_row['M_DistrictID'] = 0; $patient_row['M_CityID'] = 0; $patient_row['M_ProvinceID'] = 0; if ($patient_row['M_KelurahanID']) { $addr = $this->db_onedev->query( "SELECT *, CONCAT(IFNULL(?,''),'\n\n',M_KelurahanName,', ',M_DistrictName,'\n',M_CityName,', ',M_ProvinceName) as xaddress FROM m_kelurahan JOIN m_district ON M_KelurahanM_DistrictID = M_DistrictID JOIN m_city ON M_DistrictM_CityID = M_CityID JOIN m_province ON M_CityM_ProvinceID = M_ProvinceID WHERE M_KelurahanID = ?", [$patient_row['M_PatientAddressDescription'], $patient_row['M_KelurahanID']] )->row_array(); if ($addr) { $patient_row['M_PatientAddress'] = stripslashes($addr['xaddress']); $patient_row['M_DistrictID'] = $addr['M_DistrictID']; $patient_row['M_CityID'] = $addr['M_CityID']; $patient_row['M_ProvinceID'] = $addr['M_ProvinceID']; } } $info = $this->db_onedev->query("SELECT fn_fo_patient_visit(?) info", [$patient_row['M_PatientID']])->row(); $patient_row['info'] = $info ? json_decode($info->info) : null; // Hapus kolom enc sebelum return foreach (['M_PatientName_enc','M_PatientName_bidx','M_PatientHP_enc','M_PatientHP_bidx', 'M_PatientEmail_enc','M_PatientIDNumber_enc','M_PatientNIK_bidx', 'M_PatientDOB_enc','M_PatientDOB_bidx'] as $col) { unset($patient_row[$col]); } $rst['patient'] = $patient_row; } else { $rst['patient'] = []; } // MOU & Company dari order $mou_id = intval($row_header['orderM_MouID'] ?? 0); $row_mou = $this->db_onedev->query( "SELECT M_MouM_CompanyID, M_MouStatus, M_MouEmail, M_MouEmailIsDefault, M_MouEndDate, M_MouID, M_MouIsBill, M_MouIsDefault, M_MouName, M_MouNote, M_MouStartDate FROM m_mou WHERE M_MouID = ?", [$mou_id] )->row_array(); $row_company = []; if ($row_mou) { $row_company = $this->db_onedev->query( "SELECT * FROM m_company WHERE M_CompanyID = ?", [$row_mou['M_MouM_CompanyID']] )->row_array(); $row_company['mou'] = $this->db_onedev->query( "SELECT M_MouStatus, M_MouEmail, M_MouEmailIsDefault, M_MouEndDate, M_MouID, M_MouIsBill, M_MouIsDefault, M_MouName, M_MouNote, M_MouStartDate FROM m_mou WHERE M_MouM_CompanyID = ? AND M_MouStatus = 'R' AND M_MouIsActive = 'Y'", [$row_company['M_CompanyID']] )->result_array(); } $rst['selected_mou'] = $row_mou ?: []; $rst['selected_company'] = $row_company ?: []; $rst['companies'] = $row_company ? [$row_company] : []; $rst['tests'] = []; $sql = "SELECT ss_price_mou.* FROM one_klinik.order_penunjang JOIN t_test ON orderPenunjangT_TestID = t_test.T_TestID AND t_test.T_TestIsActive = 'Y' JOIN ss_price_mou ON Ss_PriceMouM_MouID = ? AND t_test.T_TestID = ss_price_mou.T_TestID AND is_packet = 'N' WHERE orderPenunjangOrderID = ? AND orderPenunjangIsActive = 'Y' GROUP BY ss_price_mou.T_TestID"; $qry_tests = $this->db_onedev->query($sql, [ $row_header['settingM_MouID'], $row_header['orderID'] ]); if (!$qry_tests) { $this->sys_error_db("tests query: " . $this->db_onedev->error()['message'], $this->db_onedev); exit; } $get_tests_from_detail = $qry_tests->result_array(); if ($get_tests_from_detail) { foreach ($get_tests_from_detail as $value) { $data_ss_price = $value; $data_ss_price['requirement'] = []; if ($data_ss_price['px_type'] == "PX") { $x = $this->db_smartone->query( "SELECT fn_fo_requirement_get(?) x", [$data_ss_price['T_TestID']] )->row(); if ($x && $x->x != null) { $data_ss_price['requirement'] = json_decode($x->x); } } if ($data_ss_price['is_packet'] == 'N') { $tests = $data_ss_price['T_PriceT_TestID']; $panels = ''; } else { $tests = ''; $panels = $data_ss_price['T_PriceT_TestID']; } $x = $this->db_smartone->query( "SELECT fn_fo_find_promise_by_px(?, ?) as x", [$tests, $panels] )->row(); if ($x && $x->x != null) { $data_ss_price['promise'] = $x->x; } $data_ss_price['nat_test'] = json_decode($data_ss_price['nat_test']); $data_ss_price['child_test'] = json_decode($data_ss_price['child_test']); $rst['tests'][] = $data_ss_price; } } $rst['diagnose'] = $row_header['orderDoctorDiagnosePrimer'] ?? ''; $this->sys_ok(['records' => $rst]); exit; } }