diff --git a/.gitignore b/.gitignore index a787c9a..5582c47 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ vendor/ .vscode/ +.cursor/ .DS_Store composer.phar diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Bank.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Bank.php new file mode 100644 index 0000000..96430c0 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Bank.php @@ -0,0 +1,81 @@ +db_smartone = $this->load->database("onedev", true); + } + + + public function search() + { + $prm = $this->sys_input; + + if (isset($prm['card'])) + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank WHERE Nat_BankIsCard = 'Y' AND Nat_BankIsActive = 'Y' ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + else if (isset($prm['edc'])) + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank WHERE Nat_BankIsEDC = 'Y' AND Nat_BankIsActive = 'Y' ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + else + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank WHERE Nat_BankIsActive = 'Y' ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + + // $sql = "select Nat_BankID, Nat_BankName + // from nat_bank + // where Nat_BankIsActive = 'Y' + // ORDER BY Nat_BankName"; + $query = $this->db_smartone->query($sql); + + if ($query) { + $rows = $query->result_array(); + + $result = array("total" => 0, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("BANK rows",$this->db_smartone); + exit; + } + } + + public function search_account() + { + $prm = $this->sys_input; + + $sql = "select M_BankAccountID, CONCAT(Nat_BankCode, ' no ', M_BankAccountNo) M_BankAccountNo + from nat_bank + JOIN m_bank_account ON M_BankAccountNat_BankID = Nat_BankID AND M_BankAccountIsActive = 'Y' + where Nat_BankIsActive = 'Y' + ORDER BY Nat_BankName"; + $query = $this->db_smartone->query($sql); + + if ($query) { + $rows = $query->result_array(); + + $result = array("total" => 0, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("BANK rows",$this->db_smartone); + exit; + } + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Company.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Company.php new file mode 100644 index 0000000..3a74d5d --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Company.php @@ -0,0 +1,282 @@ +db_smartone = $this->load->database("onedev", true); + } + function _add_mou(&$companies) { + if (count($companies) == 0) { + return; + } + $company_list= "-1"; + foreach($companies as $idx => $c) { + $company_list .= ", " . $c["M_PatientTypeID"]; + if (! isset($companies[$idx]["mou"])) $companies[$idx]["mou"] = array(); + } + $sql = "select * + from + m_moucompany + where M_MouCompanyM_PatientTypeID in ( $company_list ) + and ( M_MouCompanyStartDate <= now() and M_MouCompanyEndDate >= now() ) + and M_MouCompanyIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + if ($query) { + $rows= $query->result_array(); + foreach($rows as $r) { + $patientTypeID= $r["M_MouCompanyM_PatientTypeID"]; + foreach($companies as $idx => $c) { + if($c["M_PatientTypeID"] == $patientTypeID) { + $companies[$idx]["mou"][] = $r; + } + } + } + } else { + $this->sys_error_db("m_moucompany mou",$this->db_smartone); + exit; + } + } + + public function search() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $rows = $this->_search_company($prm['search']); + + $tot_count = count($rows); + $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows)); + $this->sys_ok($result); + exit; + } + + private function _search_company($search){ + $rows = array(); + $q = array(); + $q['search'] = "%{$search}%"; + + $sql = "SELECT CorporateID, CorporateName, '' as corporate_prices + FROM corporate + JOIN corporate_price on CorporatePriceCorporateID = CorporateID and CorporatePriceIsActive = 'Y' + and CorporatePriceStartDate <= date(now()) and CorporatePriceEndDate >= date(now()) + JOIN t_priceheader on CorporatePriceT_PriceHeaderID = T_PriceHeaderID and T_PriceHeaderValidasi = 'Y' AND T_PriceHeaderIsActive = 'Y' + WHERE + CorporateIsActive = 'Y' and CorporateName like ? + GROUP BY CorporateID"; + $query = $this->db_smartone->query($sql, array($q['search'])); + //echo $this->db_smartone->last_query(); + + if ($query) { + $rows = $query->result_array(); + foreach ($rows as $k => $v){ + $sql = " SELECT + CorporatePriceCorporateID as corporate_id, + T_PriceHeaderID as price_header_id, + T_PriceHeaderName as price_header_name, + T_PriceHeaderCode as price_header_code, + DATE_FORMAT(CorporatePriceStartDate, '%d-%m-%Y') as corporate_price_start_date, + DATE_FORMAT(CorporatePriceEndDate, '%d-%m-%Y') as corporate_price_end_date, + CorporatePriceNote as note, + CorporatePriceIsDefault as is_default + FROM corporate_price + JOIN t_priceheader on CorporatePriceT_PriceHeaderID = T_PriceHeaderID and T_PriceHeaderValidasi = 'Y' AND T_PriceHeaderIsActive = 'Y' + WHERE + CorporatePriceCorporateID = ? AND + CorporatePriceIsActive = 'Y' AND + T_PriceHeaderValidasi = 'Y' AND + CorporatePriceStartDate <= date(now()) AND + CorporatePriceEndDate >= date(now()) + ORDER BY T_PriceHeaderName ASC + "; + $query = $this->db_smartone->query($sql, array($v['CorporateID'])); + //echo $this->db_smartone->last_query(); + $rowsDetail = $query->result_array(); + if(count($rowsDetail) > 0){ + $rows[$k]['corporate_prices'] = $rowsDetail; + }else{ + $rows[$k]['corporate_prices'] = array(); + } + } + } else { + $this->sys_error_db("corporate rows", $this->db_smartone); + exit; + } + return $rows; + } + + public function _search_default() + { + $prm = $this->sys_input; + + $sql = "SELECT M_MouID, M_MouM_CompanyID + FROM m_mou + JOIN m_company ON M_CompanyID = M_MouM_CompanyID ANd M_CompanyIsDefault = 'Y' ANd M_CompanyIsActive = 'Y' + WHERE M_MouIsActive = 'Y' ANd M_MouIsDefault = 'Y' AND M_MouIsApproved = 'Y' AND M_MouIsReleased = 'Y' + AND M_MouStartDate <= date(now()) AND M_MouEndDate >= date(now())"; + $query = $this->db_smartone->query($sql); + + if ($query) + { + $rows = $query->row(); + $sql = "select M_CompanyID, M_CompanyName, + IFNULL( concat('[', group_concat( json_object('M_MouID', M_MouID, 'M_MouName', M_MouName, 'M_MouStartDate', M_MouStartDate, 'M_MouEndDate', M_MouEndDate, 'M_MouNote', M_MouNote, 'M_MouIsBill', M_MouIsBill, 'M_MouEmail', M_MouEmail, 'M_MouIsDefault', M_MouIsDefault, 'M_MouEmailIsDefault', M_MouEmailIsDefault, 'delivery_email_code', `fn_fo_delivery_code`('MOU', 'EMAIL', '0')) ), ']'), '[]') as mou + from m_company + join m_mou on M_MouM_CompanyID = M_CompanyID and M_MouIsActive = 'Y' + and M_MouIsApproved = 'Y' and M_MouStartDate <= date(now()) and M_MouEndDate >= date(now()) AND M_MouIsReleased = 'Y' + where M_CompanyID = ? + group by m_companyid"; + $query = $this->db_smartone->query($sql, array($rows->M_MouM_CompanyID)); + $rows2 = $query->result_array(); + + foreach ($rows2 as $k => $v) + $rows2[$k]['mou'] = json_decode($v['mou']); + + $result = array("total" => 1, "records" => $rows2, "total_display" => sizeof($rows)); + $this->sys_ok($result); + } + else + { + $this->sys_error_db("m_company rows", $this->db_smartone); + exit; + } + } + + public function search_() + { + $prm = $this->sys_input; + $search = $prm["search"]; + $sql_param = array("%$search%"); + $sql = "select count(*) total + from + m_patienttype + where + M_PatientTypeName like ? and + M_PatientTypeIsActive = 'Y'"; + $query = $this->db_smartone->query($sql, $sql_param); + $tot_count =0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } else { + $this->sys_error_db("m_patienttype count", $this->db_smartone); + exit; + } + $sql = "select M_PatientTypeID, M_PatientTypeName + from + m_patienttype + where + M_PatientTypeName like ? and + M_PatientTypeIsActive = 'Y' + limit 0,10"; + $query = $this->db_smartone->query($sql,$sql_param); + $rows = $query->result_array(); + $this->_add_mou($rows); + $result = array("total" => $tot_count, "records" => $rows ); + $this->sys_ok($result); + exit; + } + + public function search_project() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm["search"]; + $expl_search = explode(" - ", $search); + if(count($expl_search) == 2){ + $code = $expl_search[0]; + $label = $expl_search[1]; + }else{ + $code = $expl_search[0]; + $label = $expl_search[0]; + } + + $sql_param = array("%$label%", "%$code%"); + $sql = "SELECT Mgm_McuID as id, + Mgm_McuLabel as label, + Mgm_McuNumber as code, + FisikTemplateMappingID as fisik_mapping_id, + FisikTemplateMappingName as fisik_mapping_label, + Mgm_McuNote as note, + 'Y' as is_default, + CorporateID, + CorporateName, + JSON_ARRAY(JSON_OBJECT( + 'price_header_id', T_PriceHeaderID, + 'price_header_name', T_PriceHeaderName, + 'price_header_code', T_PriceHeaderCode, + 'corporate_price_start_date', DATE_FORMAT(Mgm_McuStartDate, '%d-%m-%Y'), + 'corporate_price_end_date', DATE_FORMAT(Mgm_McuEndDate, '%d-%m-%Y'), + 'corporate_id', CorporateID, + 'corporate_name', CorporateName, + 'note', Mgm_McuNote, + 'is_default', 'Y')) as corporate_prices + FROM mgm_mcu + JOIN mgm_mcutemplate ON Mgm_McuTemplateMgm_McuID = Mgm_McuID AND Mgm_McuTemplateIsActive = 'Y' + JOIN corporate ON Mgm_McuCorporateID = CorporateID AND CorporateIsActive = 'Y' + JOIN t_priceheader ON Mgm_McuT_PriceHeaderID = T_PriceHeaderID and T_PriceHeaderValidasi = 'Y' AND T_PriceHeaderIsActive = 'Y' + JOIN fisik_template_mapping ON Mgm_McuTemplateFisikTemplateMappingID = FisikTemplateMappingID AND FisikTemplateMappingIsActive = 'Y' + WHERE Mgm_McuIsActive = 'Y' AND ( Mgm_McuLabel LIKE ? OR Mgm_McuNumber LIKE ? ) AND + Mgm_McuStartDate <= date(now()) AND Mgm_McuEndDate >= date(now()) + ORDER BY Mgm_McuLabel ASC + LIMIT 30"; + $query = $this->db_smartone->query($sql, $sql_param); + if(!$query){ + $this->sys_error_db("m_mcu rows", $this->db_smartone); + exit; + } + $rows = $query->result_array(); + if(count($rows) > 0){ + foreach($rows as $k => $v){ + $obj_encoded = json_decode($v['corporate_prices']); + $rows[$k]['corporate_prices'] = $obj_encoded; + } + } + $result = array("total" => $query->num_rows, "records" => $rows ); + $this->sys_ok($result); + exit; + } + + function search_fisik_template() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm["search"]; + $sql_param = array("%$search%"); + $sql = "SELECT FisikTemplateMappingID as fisik_template_id, FisikTemplateMappingName as fisik_template_label + FROM fisik_template_mapping WHERE + FisikTemplateMappingName like ? AND + FisikTemplateMappingIsActive = 'Y' + ORDER BY FisikTemplateMappingName ASC" + ; + $query = $this->db_smartone->query($sql, $sql_param); + if(!$query){ + $this->sys_error_db("fisik_template_mapping rows", $this->db_smartone); + exit; + } + $rows = $query->result_array(); + $result = array("total" => $query->num_rows, "records" => $rows ); + $this->sys_ok($result); + exit; + } + +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Delivery.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Delivery.php new file mode 100644 index 0000000..8c80b0d --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Delivery.php @@ -0,0 +1,248 @@ +db_smartone = $this->load->database("onedev", true); + } + public function search() + { + $prm = $this->sys_input; + $q = [ + "patient_id" => 0, + "doctor_id" => 0, + "mou_id" => 0, + "company_id" => 0 + ]; + + if (isset($prm['patient_id'])) + $q["patient_id"] = $prm['patient_id']; + if (isset($prm['doctor_id'])) + $q["doctor_id"] = $prm['doctor_id']; + if (isset($prm['mou_id'])) + $q["mou_id"] = $prm['mou_id']; + if (isset($prm['c_id'])) + $q["company_id"] = $prm['c_id']; + + $sql = "CALL sp_fo_delivery_address_v3_bandung('', '{$q['patient_id']}', '{$q['doctor_id']}', '{$q['mou_id']}','{$q["company_id"]}')"; + $query = $this->db_smartone->query($sql); + if ($query) { + $rows= $query->row(); + $data = json_decode($rows->x); + + $result = array("records" => $data); + $this->sys_ok($result); + exit; + } else { + $this->sys_error_db("delivery address",$this->db_smartone); + exit; + } + + // $rows = array(); + // $rows[] = array("id" =>1, "name" => "Ambil Sendiri", "selected" => false, "note" => ""); + // $rows[] = array("id" =>2, "name" => "Kirim ke dokter", "selected" => false, "note" => ""); + // $rows[] = array("id" =>3, "name" => "Kirim ke email pasien", "selected" => false, "note" => ""); + // $rows[] = array("id" =>4, "name" => "Kirim ke email dokter", "selected" => false, "note" => ""); + // $rows[] = array("id" =>5, "name" => "Kirim ke alamat utama pasien", "selected" => false, "note" => ""); + // $rows[] = array("id" =>6, "name" => "Kirim ke alamat utama dokter", "selected" => false, "note" => ""); + // $rows[] = array("id" =>7, "name" => "Kirim ke rekanan"); + + + } + + public function search_deliveries() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $type = $prm['type']; + $id = $prm['id']; + if($type == 'patient'){ + $sql = " SELECT 0 as kelurahan, + 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, + '{$type}' 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 = '{$type}' AND M_DeliveryIsActive = 'Y' + UNION + SELECT M_PatientAddressVillage as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + CONCAT(M_PatientAddress,' ',M_PatientAddressVillage,', ',M_PatientAddressDistrict,', ',M_PatientAddressState) as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientEmail,'Belum ada email pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} AND M_PatientEmail IS NOT NULL AND M_PatientEmail != '' + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientHP,'Belum ada WA pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} AND M_PatientHP IS NOT NULL AND M_PatientHP != '' + "; + } + if($type == 'company'){ + + $sql = "SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + CONCAT(CorporateAddress,' ',CorporateAddressVillage,', ',CorporateAddressDistrict,', ',CorporateAddressCity) as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM corporate + 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 + CorporateID = {$id} AND CorporateAddress IS NOT NULL AND CorporateAddress != '' + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(CorporateEmail,'Belum ada email perusahaan') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM corporate + 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 + CorporateID = {$id} AND CorporateEmail IS NOT NULL AND CorporateEmail != ''"; + } + if($type == 'doctor'){ + $sql = "SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + CONCAT(M_DoctorAddress,' ',M_DoctorAddressVillage,', ',M_DoctorAddressDistrict,', ',M_DoctorAddressCity) as description, + '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 = 'ADDRESS' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID + WHERE + M_DoctorID = {$id} AND M_DoctorAddress IS NOT NULL AND M_DoctorAddress != '' + UNION + SELECT 0 as kelurahan, + 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 pengirim',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} AND M_DoctorEmail IS NOT NULL AND M_DoctorEmail != '' + UNION + SELECT 0 as kelurahan, + 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_DoctorWAIsDefault = '','N',IFNULL(M_DoctorWAIsDefault,'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} AND M_DoctorHP IS NOT NULL AND M_DoctorHP != '' + "; + } + + $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; + } + } + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } else { + $this->sys_error_db("delivery address",$this->db_smartone); + exit; + } + + + + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Doctor.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Doctor.php new file mode 100644 index 0000000..44e3c99 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Doctor.php @@ -0,0 +1,283 @@ +db_smartone = $this->load->database("onedev", true); + } + function _add_address(&$doc) + { + if (count($doc) == "0") { + return; + } + $doc_ids = "-1"; + foreach ($doc as $idx => $d) { + $doc_ids .= "," . $d["M_DoctorID"]; + $doc[$idx]["address"] = array(); + } + $sql = "select M_DoctorAddressID,M_DoctorAddressM_DoctorID, + M_DoctorAddressDesc + from + m_doctoraddress + where + M_DoctorAddressM_DoctorID in ( $doc_ids ) + and M_DoctorAddressIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + if ($query) { + $rows = $query->result_array(); + foreach ($rows as $r) { + $doctorID = $r["M_DoctorAddressM_DoctorID"]; + foreach ($doc as $idx => $d) { + if ($d["M_DoctorID"] == $doctorID) { + $doc[$idx]["address"][] = $r; + } + } + } + } else { + $this->sys_error_db("m_doctoraddress ", $this->db_smartone); + exit; + } + } + + public function search_fpptype() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') { + $q['search'] = "%{$prm['search']}%"; + } + + $sql = "select *, M_FppTypeID id, M_FppTypeName name FROM m_fpp_type WHERE M_FppTypeIsActive = 'Y' AND M_FppTypeName LIKE ?"; + $query = $this->db_smartone->query($sql, array($q['search'])); + $rows = $query->result_array(); + + $sqlselected = "SELECT *, M_FppTypeID id, M_FppTypeName name FROM m_fpp_type WHERE M_FppTypeIsActive = 'Y' AND M_FppTypeIsDefault = 'Y'"; + $queryselected = $this->db_smartone->query($sqlselected); + $selected = $queryselected->row_array(); + $result = array("total" => count($rows), "records" => $rows, "selected" => $selected); + $this->sys_ok($result); + exit; + } + + public function search_pj() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + //sipe : M_DoctorPjIsDefault diganti ke M_DoctorPjIsDefaultPJ + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + + $sql = "SELECT M_DoctorID, + CONCAT(M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ',M_DoctorSuffix, M_DoctorSuffix2) M_DoctorName, + M_DoctorPjIsDefaultPj + FROM m_doctor + JOIN m_doctorpj on M_DoctorPJM_DoctorID = M_DoctorID and M_DoctorPjIsactive = 'Y' + JOIN m_user ON M_DoctorPjM_BranchID = M_UserLoginM_BranchID + AND M_UserID = ? + WHERE + M_DoctorIsActive = 'Y' AND + ( M_DoctorPJID IS NOT NULL ) "; + $query = $this->db_smartone->query($sql, array($userid)); + if(!$query){ + $this->sys_error_db("m_doctorpj rows", $this->db_smartone); + exit; + } + $rows = $query->result_array(); + if(count($rows) == 0){ + $sql = "SELECT M_DoctorID, + CONCAT(M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ',M_DoctorSuffix, M_DoctorSuffix2) M_DoctorName, + M_DoctorPjIsDefaultPj + FROM `m_doctorpj` + WHERE + `M_DoctorPjIsDefaultPJ` = 'Y' AND `M_DoctorPjIsActive` = 'Y'"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->sys_error_db("m_doctorpj rows", $this->db_smartone); + exit; + } + $rows = $query->result_array(); + } + $result = array("total" => count($rows), "records" => $rows); + $this->sys_ok($result); + exit; + } + + public function search() + { + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count = 0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + + $sql = "SELECT + M_DoctorID, + M_DoctorCode, + M_DoctorPrefix, + M_DoctorPrefix2, + M_DoctorSuffix, + M_DoctorSuffix2, + M_DoctorName, + M_DoctorNote, + IFNULL(M_DoctorAddress, '') as address + from m_doctor + where M_DoctorIsActive = 'Y' + and CONCAT(M_DoctorCode, ' - ', M_DoctorName) like ? + group by M_DoctorID + limit 25"; + + $query = $this->db_smartone->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + $result = array("total" => count($rows), "records" => $rows); + $this->sys_ok($result); + } else { + $this->sys_error_db("m_doctor rows", $this->db_smartone); + exit; + } + } + + public function search_() + { + $prm = $this->sys_input; + $search = $prm["search"]; + + $sql = "select count(*) total + from + m_doctor + join ( + select distinct M_DoctorAddressM_DoctorID + from m_doctoraddress + where M_DoctorAddressIsActive = 'Y' + ) ma on M_DoctorID = M_DoctorAddressM_DoctorID + where M_DoctorIsActive = 'Y' and M_DoctorName like ? "; + $query = $this->db_smartone->query($sql, array("%$search%")); + $tot_count = 0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } else { + $this->sys_error_db("m_patient count", $this->db_smartone); + exit; + } + $sql = "select M_DoctorID,CONCAT(IF(M_DoctorPrefix IS NOT NULL, CONCAT(M_DoctorPrefix, '. '), ''), IF(M_DoctorPrefix2 IS NOT NULL, CONCAT(CONCAT(M_DoctorPrefix2, '. '), ' '), ''),' ',M_DoctorName,' ',IF(M_DoctorSuffix IS NOT NULL, CONCAT(', ',M_DoctorSuffix), ''), IF(M_DoctorSuffix2 IS NOT NULL, CONCAT(', ',M_DoctorSuffix2), '')) M_DoctorName + from + m_doctor + join ( + select distinct M_DoctorAddressM_DoctorID + from m_doctoraddress + where M_DoctorAddressIsActive = 'Y' + ) ma on M_DoctorID = M_DoctorAddressM_DoctorID + where M_DoctorIsActive = 'Y' and CONCAT(IF(M_DoctorPrefix IS NOT NULL, CONCAT(M_DoctorPrefix, '. '), ''), IF(M_DoctorPrefix2 IS NOT NULL, CONCAT(CONCAT(M_DoctorPrefix2, '. '), ' '), ''),' ',M_DoctorName,' ',IF(M_DoctorSuffix IS NOT NULL, CONCAT(', ',M_DoctorSuffix), ''), IF(M_DoctorSuffix2 IS NOT NULL, CONCAT(', ',M_DoctorSuffix2), '')) like ? + limit 0,10"; + $query = $this->db_smartone->query($sql, array("%$search%")); + echo $this->db_smartone->last_query(); + exit; + $rows = $query->result_array(); + $this->_add_address($rows); + $result = array("total" => $tot_count, "records" => $rows); + $this->sys_ok($result); + exit; + } + + public function save() + { + $prm = $this->sys_input; + $prm = $prm['data']; + + $q = [ + 'name' => isset($prm['name']) ? $prm['name'] : '', + 'prefix1' => isset($prm['prefix1']) ? $prm['prefix1'] : '', + 'prefix2' => isset($prm['prefix2']) ? $prm['prefix2'] : '', + 'sufix1' => isset($prm['sufix1']) ? $prm['sufix1'] : '', + 'sufix2' => isset($prm['sufix2']) ? $prm['sufix2'] : '', + 'sufix3' => isset($prm['sufix3']) ? $prm['sufix3'] : '', + 'sex' => isset($prm['sex']) ? $prm['sex'] : '0', + 'hp' => isset($prm['hp']) ? $prm['hp'] : '', + 'note' => isset($prm['note']) ? $prm['note'] : '', + 'address' => isset($prm['address']) ? $prm['address'] : '', + 'province' => isset($prm['province']) ? $prm['province'] : '', + 'city' => isset($prm['city']) ? $prm['city'] : '', + 'district' => isset($prm['district']) ? $prm['district'] : '', + 'village' => isset($prm['village']) ? $prm['village'] : '' + ]; + + $sql = "INSERT INTO m_doctor(M_DoctorPrefix, + M_DoctorPrefix2, + M_DoctorName, + M_DoctorSufix, + M_DoctorSufix2, + M_DoctorSufix3, + M_DoctorM_SexID, + M_DoctorHP, + M_DoctorNote) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"; + $query = $this->db_smartone->query($sql, [$q['prefix1'], $q['prefix2'], $q['name'], $q['sufix1'], $q['sufix2'], $q['sufix3'], $q['sex'], $q['hp'], $q['note']]); + + if ($query) { + $id = $this->db_smartone->insert_id(); + + $sql = "INSERT INTO m_doctoraddress(M_DoctorAddressM_DoctorID, + M_DoctorAddressNote, + M_DoctorAddressDescription, + M_DoctorAddressM_KelurahanID) + VALUES(?, 'Utama', ?, ?)"; + $query = $this->db_smartone->query($sql, [$id, $q['address'], $q['village']]); + + if ($query) { + $result = $this->get_one($id); + $this->sys_ok($result); + exit; + } + } + + $this->sys_error_db("DOCTOR SAVE", $this->db_smartone); + } + + private function get_one($id) + { + $sql = "SELECT M_DoctorID, M_DoctorIsDefault, 'N' M_DoctorIsPJ, + fn_global_doctor_name(M_DoctorID) as M_DoctorName, M_DoctorName M_DoctorRealName, + IFNULL( concat('[', group_concat(JSON_OBJECT('M_DoctorAddressNote',M_DoctorAddressNote,'M_DoctorAddressDescription', M_DoctorAddressDescription, 'M_DoctorAddressID', M_DoctorAddressID) SEPARATOR ','), ']'), '[]') as address + FROM m_doctor + LEFT JOIN m_doctoraddress ON M_DoctorAddressM_DoctorID = M_DoctorID AND M_DoctorAddressIsActive = 'Y' + WHERE M_DoctorID = ?"; + $query = $this->db_smartone->query($sql, $id); + + if ($query) { + $row = $query->result_array(); + foreach ($row as $k => $v) + $row[$k]['address'] = json_decode($v['address']); + + $result = array("total" => 1, "records" => $row, "total_display" => 1); + return $result; + } + + return false; + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/History.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/History.php new file mode 100644 index 0000000..34db792 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/History.php @@ -0,0 +1,583 @@ +db_onedev = $this->load->database("onedev", true); + } + + public function search() + { + $prm = $this->sys_input; + + $sql = "SELECT + T_OrderHeaderID, + M_DoctorIsDefaultPJ, + M_DoctorIsPJ, + M_DoctorNote, + T_OrderHeaderSenderM_DoctorID as M_DoctorID, + CONCAT( M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ', M_DoctorSufix, M_DoctorSufix2, M_DoctorSufix3) realdoctor, + CONCAT( M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ', M_DoctorSufix, M_DoctorSufix2, M_DoctorSufix3) M_DoctorName, + DATE_FORMAT(T_OrderHeaderDate,'%d-%m-%Y') xdate, + T_OrderHeaderLabNumber, + T_OrderHeaderLabNumberExt labnumber_ext, + T_OrderHeaderSubTotal, + 0 total_disc, + 'N' xshow, + T_OrderHeaderTotal, + IF(ISNULL(T_OrderHeaderDiagnose) OR T_OrderHeaderDiagnose = '','-',T_OrderHeaderDiagnose) T_OrderHeaderDiagnose, + IF(ISNULL(T_OrderHeaderFoNote) OR T_OrderHeaderFoNote = '','-',T_OrderHeaderFoNote) T_OrderHeaderFoNote, + IF(ISNULL(M_PatientNote) OR M_PatientNote = '','-',M_PatientNote) M_PatientNote, + M_CompanyID, + M_CompanyName, + M_MouID, + M_MouName, + M_DoctorAddressID, + M_DoctorAddressDescription + FROM t_orderheader + JOIN m_company ON T_OrderHeaderM_CompanyID = M_CompanyID + JOIN m_mou ON T_OrderHeaderM_MouID = M_MouID + JOIN m_doctor ON T_OrderHeaderSenderM_DoctorID = M_DoctorID + JOIN m_doctoraddress ON T_OrderHeaderSenderM_DoctorAddressID = M_DoctorAddressID + JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID + JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID + AND T_OrderDetailIsActive = 'Y' + WHERE T_OrderHeaderM_PatientID = ? + AND T_OrderHeaderIsActive = 'Y' + GROUP BY T_OrderHeaderID + ORDER BY T_OrderHeaderDate DESC + LIMIT 5"; + //echo $sql; + $query = $this->db_onedev->query($sql, [$prm['patient_id']]); + if ($query) + { + //echo $this->db_onedev->last_query(); + $rows = $query->result_array(); + if($rows){ + foreach($rows as $k => $v){ + $doctor_name = $v['M_DoctorName']; + $doctor_name_len = strlen($v['M_DoctorName']); + if($doctor_name_len > 45) + $doctor_name = substr($doctor_name,0,45).'...'; + + $rows[$k]['M_DoctorName'] = $doctor_name; + $sql = "SELECT + T_OrderDetailT_TestName as test_name, + T_OrderDetailPrice as price, + T_OrderDetailPrice as str_price, + T_OrderDetailDisc as disc_persen, + T_OrderDetailDiscAmount as disc_rp, + T_OrderDetailDiscAmount as str_disc_rp, + T_OrderDetailDiscTotal as disc, + T_OrderDetailDiscTotal as str_disc, + T_OrderDetailTotal as total, + T_OrderDetailTotal as str_total + FROM t_orderdetail + WHERE + T_OrderDetailT_OrderHeaderID = {$v['T_OrderHeaderID']} AND + T_OrderDetailIsActive = 'Y' AND + T_OrderDetailT_TestIsPrice = 'Y'"; + //echo $sql; + $rows[$k]['details'] = $this->db_onedev->query($sql)->result_array(); + $total_diskon = 0; + $total_bruto = 0; + foreach($rows[$k]['details'] as $kx => $vx){ + $total_diskon = $total_diskon + $vx['disc']; + $total_bruto = $total_bruto + $vx['price']; + $str_price = number_format($vx['price'],0,',','.'); + $rows[$k]['details'][$kx]['str_price'] = $str_price; + $str_disc_rp = number_format($vx['disc_rp'],0,',','.'); + $rows[$k]['details'][$kx]['str_disc_rp'] = $str_disc_rp; + $str_disc = number_format($vx['str_disc'],0,',','.'); + $rows[$k]['details'][$kx]['str_disc'] = $str_disc; + $str_total = number_format($vx['total'],0,',','.'); + $rows[$k]['details'][$kx]['str_total'] = $str_total; + } + $rows[$k]['total_disc'] = number_format($total_diskon,0,',','.'); + $rows[$k]['T_OrderHeaderSubTotal'] = number_format($total_bruto,0,',','.'); + $rows[$k]['T_OrderHeaderTotal'] = number_format($v['T_OrderHeaderTotal'],0,',','.'); + + $sql = "SELECT * , IFNULL(T_OrderDeliveryNoteValue,'-') xnote + FROM t_orderdelivery + JOIN m_delivery ON T_OrderDeliveryM_DeliveryID = M_DeliveryID + LEFT JOIN t_orderdeliverynote ON T_OrderDeliveryNoteT_OrderDeliveryID = T_OrderDeliveryID + WHERE + T_OrderDeliveryT_OrderHeaderID = {$v['T_OrderHeaderID']} AND + T_OrderDeliveryIsActive = 'Y'"; + $rows[$k]['deliveries'] = $this->db_onedev->query($sql)->result_array(); + + /* + $rows[$k]['selected_doctor'] = array( + 'M_DoctorID'=>$v['M_DoctorID'], + 'M_DoctorIsDefault'=>$v['M_DoctorIsDefault'], + 'M_DoctorIsPJ'=>$v['M_DoctorIsPJ'], + 'M_DoctorName'=>$v['M_DoctorName'], + 'M_DoctorNote'=>$v['M_DoctorNote'] + ); + $rows[$k]['selected_address'] = array( + 'M_DoctorAddressID'=>$v['M_DoctorAddressID'], + 'M_DoctorAddressDescription'=>$v['M_DoctorAddressDescription'] + ); + $sql = "SELECT M_DoctorAddressID, M_DoctorAddressDescription + FROM m_doctoraddress + WHERE M_DoctorAddressM_DoctorID = {$v['M_DoctorID']} AND M_DoctorAddressIsActive = 'Y'"; + $rows[$k]['doctor_address'] = $this->db_onedev->query($sql)->result_array(); + $sql = "SELECT 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 + "; + $rows[$k]['selected_company'] = array('M_CompanyID'=>$v['M_CompanyID'],'M_CompanyName'=>$v['M_CompanyName']); + $deliveries = array(); + */ + } + } + $this->sys_ok(["records"=>$rows]); + } + else + { + $this->sys_error_db("Patient History count", $this->db_onedev); + } + } + + function get_databyorder_id(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $sql = "SELECT * + FROM t_orderheader + WHERE + T_OrderHeaderID = {$prm['order_id']}"; + $row_header = $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_MouID = {$row_header['T_OrderHeaderM_MouID']}"; + $row_mou = $this->db_onedev->query($sql)->row_array(); + $status = "Y"; + //print_r($row_mou); + $rst = array(); + if($row_mou['M_MouStatus'] != 'R' || date('Y-m-d', strtotime($row_mou['M_MouEndDate'])) < date('Y-m-d')){ + $status = "N"; + $xrst = array('status'=>$status,'data'=>array()); + } + if($status == 'Y'){ + $rst['data_deliveries'] = array(); + $new_delivery = array(); + $new_delivery = $this->search_deliveries(array('id'=>$row_header['T_OrderHeaderM_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_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('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 t_orderheader + JOIN m_doctor ON T_OrderHeaderSenderM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' + JOIN m_doctoraddress ON M_DoctorAddressM_DoctorID = M_DoctorID AND M_DoctorAddressIsActive = 'Y' + WHERE + T_OrderHeaderID = {$prm['order_id']} + 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 t_orderheader + JOIN m_doctor ON T_OrderHeaderSenderM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' + JOIN m_doctoraddress ON T_OrderHeaderSenderM_DoctorAddressID = M_DoctorAddressID AND M_DoctorAddressIsActive = 'Y' + WHERE + T_OrderHeaderID = {$prm['order_id']}"; + $raddr = $this->db_onedev->query($sql)->row_array(); + foreach($v['address'] as $kaddr => $vaddr){ + if(intval($vaddr->M_DoctorAddressID) == intval($raddr['M_DoctorAddressID'])) + $rst['selected_address'] = $v['address'][$kaddr]; + } + //$rst['selected_address'] = $vaddr; + } + else{ + $sql = "SELECT M_DoctorID, M_DoctorIsDefault, 'N' M_DoctorIsPJ, + CONCAT(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('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' + WHERE M_DoctorName = '-' AND M_DoctorIsActive = 'Y' group by M_DoctorID"; + $rst['selected_doctor'] = $this->db_onedev->query($sql)->result_array(); + foreach ($rst['selected_doctor'] as $xxk => $xxv) + $rst['selected_doctor'][$k]['address'] = json_decode($xxv['address']); + } + + + if(!$rst['selected_address']){ + $rst['selected_address'] = $rst['address_doctor'][0]; + } + $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['T_OrderHeaderM_CompanyID']}"; + $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(); + //print_r($row_company); + $rst['selected_company'] = $row_company; + $rst['selected_mou'] = $row_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'=>$rst['selected_mou']['M_MouID'],'type'=>'mou')); + if(count($new_delivery) > 0){ + foreach($new_delivery as $knd => $vnd){ + array_push($rst['data_deliveries'],$vnd); + } + } + + /*data deliveries*/ + $sql = "SELECT * + FROM t_orderdelivery + JOIN m_deliverytype ON T_OrderDeliveryM_DeliveryTypeID = M_DeliveryTypeID + JOIN m_delivery ON T_OrderDeliveryM_DeliveryID = M_DeliveryID + WHERE + T_OrderDeliveryT_OrderHeaderID = {$row_header['T_OrderHeaderID']} AND T_OrderDeliveryIsActive = 'Y'"; + $order_deliveries = $this->db_onedev->query($sql)->result_array(); + + foreach($rst['data_deliveries'] as $kd => $vd){ + $check_exist = $this->exist_delivery($order_deliveries,$vd); + //print_r($check_exist); + if($check_exist['idx'] != -1){ + $rst['data_deliveries'][$kd]['chex'] = 'Y'; + $idx = $check_exist['idx']; + if($vd['delivery_code'] == 'PICKUP' || $vd['delivery_code'] == 'ADDRESS'){ + $sql = "SELECT * + FROM t_orderdeliverynote + WHERE + T_OrderDeliveryNoteT_OrderDeliveryID = {$order_deliveries[$idx]['T_OrderDeliveryID']} AND + T_OrderDeliveryNoteIsActive = 'Y'"; + //echo $sql; + $dt_note = $this->db_onedev->query($sql)->row_array(); + if($dt_note){ + $rst['data_deliveries'][$kd]['note'] = $dt_note['T_OrderDeliveryNoteValue']; + } + } + if($vd['delivery_code'] !== 'PICKUP' && $vd['delivery_code'] != 'ADDRESS'){ + if($vd['description'] != $order_deliveries[$idx]['T_OrderDeliveryDestination']){ + //echo 'YYYYYYYYY'; + $rst['data_deliveries'][$kd]['note'] = $order_deliveries[$idx]['T_OrderDeliveryDestination']; + } + + + } + } + } + $xrst = array('status'=>$status,'data'=>$rst); + } + + $result = array("records" => $xrst); + $this->sys_ok($result); + exit; + } + + function exist_delivery($arr,$row){ + $rtn = array('status'=>false,'idx'=>-1); + foreach($arr as $k => $v){ + if($v['M_DeliveryID'] == $row['delivery_id'] && $v['T_OrderDeliveryAddressID'] == $row['address_id']){ + $rtn = array('status'=>false,'idx'=>$k); + } + } + return $rtn; + } + + function search_deliveries($prm) + { + + $type = $prm['type']; + $id = $prm['id']; + if($type == 'patient'){ + $sql = " + SELECT 0 as kelurahan, + 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, + '{$type}' 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 = '{$type}' AND M_DeliveryIsActive = 'Y' + UNION + SELECT M_PatientAddressM_KelurahanID as kelurahan, + 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_KelurahanName,', ',M_DistrictName,', ',M_CityName) as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' 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_kelurahan ON M_PatientAddressM_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_PatientID = {$id} + GROUP BY M_PatientAddressID + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientEmail,'Belum ada email pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientEmail,'Belum ada email pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientHP,'Belum ada WA pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientHP,'Belum ada telegram pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id}"; + } + if($type == 'mou'){ + //echo $id; + $sql = "SELECT * FROM m_mou WHERE M_MouID = {$id}"; + //echo $sql; + $data_mou = $this->db_onedev->query($sql)->row_array(); + //print_r($data_mou); + $sql = " + SELECT M_CompanyM_KelurahanID as kelurahan, + 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_KelurahanName,', ',M_DistrictName,', ',M_CityName) 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 + JOIN m_kelurahan ON M_CompanyM_KelurahanID = M_KelurahanID + JOIN m_district ON M_KelurahanM_DistrictID = M_DistrictID + JOIN m_city ON M_DistrictM_CityID = M_CityID + WHERE + M_CompanyID = {$data_mou['M_MouM_CompanyID']} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_MouEmail,'Belum ada email agreement') as description, + 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 M_DoctorAddressM_KelurahanID as kelurahan, + 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_KelurahanName,', ',M_DistrictName,', ',M_CityName) 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, + 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 pengirim',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, + 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, + 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_onedev->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(); + } + + + + } +} +?> \ No newline at end of file diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Language.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Language.php new file mode 100644 index 0000000..78af343 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Language.php @@ -0,0 +1,87 @@ +db_smartone = $this->load->database("onedev", true); + } + + public function search() + { + $prm = $this->sys_input; + + $max_rst = 12; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "select count(*) total + from + m_lang + where M_LangIsActive = 'Y' + and M_LangName like ?"; + $query = $this->db_smartone->query($sql, array($q['search'])); + + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_lang count",$this->db_smartone); + exit; + } + + $sql = "select M_LangID as id, M_LangName as name + from m_lang + where M_LangIsActive = 'Y' + and M_LangName like ?"; + $query = $this->db_smartone->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + $rows_ = []; + $si = [["is_si" => "N", "si_text" => ""], ["is_si" => "Y", "si_text" => "(SI)"]]; + foreach ($rows as $k => $v) + { + foreach ($si as $l => $w) + { + $v['is_si'] = $w['is_si']; + $v['name'] .= $w['si_text'] == '' ? '' : ' ' . $w['si_text']; + $v['key'] = $v['id'] . '-' . $v['is_si']; + $rows_[] = $v; + } + } + + $result = array("total" => $tot_count, "records" => $rows_, "total_display" => sizeof($rows_)); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_doctor rows",$this->db_smartone); + exit; + } + } + + public function search_() + { + $rows = array(); + $rows[] = array("id" =>"ID", "name" => "Bahasa Indonesia"); + $rows[] = array("id" =>"EN", "name" => "Bahasa Inggris"); + $rows[] = array("id" =>"CH", "name" => "Bahasa Mandarin"); +$result = array("records" => $rows); +$this->sys_ok($result); +exit; + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Order copy.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Order copy.php new file mode 100644 index 0000000..59b2de6 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Order copy.php @@ -0,0 +1,1374 @@ +db_smartone = $this->load->database("onedev", true); + } + + function get_time_start(){ + $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 save() + { + $prm = $this->sys_input; + $preid = $prm['preid']; + $hdr = $prm['header']; + $req = $prm['req']; + $details_now = array(); + foreach ($prm['detail'] as $k_det => $v_det) { + if(!$this->check_exist_details($details_now,$v_det)) + array_push($details_now,$v_det); + } + $prm['detail'] = $details_now; + $tests = $prm['tests']; + $userid = $this->sys_user["M_UserID"]; + $this->db_smartone->trans_begin(); + $sqlheader = "INSERT INTO t_orderheader + (T_OrderHeaderM_StatusCode, + T_OrderHeaderM_BranchID, + T_OrderHeaderDate, + T_OrderHeaderLabNumber, + T_OrderHeaderM_PatientID, + T_OrderHeaderCorporateID, + T_OrderHeaderMgm_McuID, + T_OrderHeaderM_PatientAge, + T_OrderHeaderPjM_DoctorID, + T_OrderHeaderDiagnose, + T_OrderHeaderFoNote, + T_OrderHeaderSamplingNote, + T_OrderHeaderResultNote, + T_OrderHeaderFoNoteM_UserID, + T_OrderHeaderSamplingNoteM_UserID, + T_OrderHeaderResultNoteM_UserID, + T_OrderHeaderCreated, + T_OrderHeaderLastUpdated, + T_OrderHeaderCreatedUserID, + T_OrderHeaderLastUpdatedUserID) + VALUES( + 'RG', + '{$hdr['branch_id']}', + now(), + fn_numbering('T'), + '{$hdr['patient_id']}', + '{$hdr['company_id']}', + '{$prm['mcuid']}', + '{$hdr['age']}', + '{$hdr['sender_doctor_id']}', + '{$hdr['diagnose']}', + '{$hdr['fo_note']}', + '', + '', + $userid, + 0, + 0, + now(), + now(), + $userid, + $userid)"; + + $queryheader = $this->db_smartone->query($sqlheader); + + + if($queryheader) + { + + $header_id = $this->db_smartone->insert_id(); + $sqlheaderlang = "INSERT INTO t_orderheaderlang + (T_OrderHeaderLangT_OrderHeaderID, + T_OrderHeaderLangM_LangID, + T_OrderHeaderLangCreated, + T_OrderHeaderLangCreatedUserID, + T_OrderHeaderLangLastUpdated, + T_OrderHeaderLangLastUpdatedUserID) + VALUES( + '{$header_id}', + 1, + now(), + $userid, + now(), + $userid)"; + $queryheaderlang = $this->db_smartone->query($sqlheaderlang); + if(!$queryheaderlang){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderheaderlang | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + + foreach($tests as $k => $v){ + if($v['is_packet'] == 'Y'){ + $sqlt_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_OrderDetailOrderCreated, + T_OrderDetailOrderCreatedUserID, + T_OrderDetailOrderLastUpdated, + T_OrderDetailOrderLastUpdatedUserID, + T_OrderDetailOrderJsonChildren) + VALUES( + $header_id, + 0, + '', + '{$v['is_packet']}', + '{$v['px_type']}', + '{$v['packet_id']}', + '{$v['T_TestName']}', + now(), + $userid, + now(), + now(), + '')"; + //echo $sqlorder; + $queryt_orderdetailorder = $this->db_smartone->query($sqlt_orderdetailorder); + if(!$queryt_orderdetailorder){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + $detail_id = $this->db_smartone->insert_id(); + }else{ + $sqlt_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_OrderDetailOrderCreated, + T_OrderDetailOrderCreatedUserID, + T_OrderDetailOrderLastUpdated, + T_OrderDetailOrderLastUpdatedUserID, + T_OrderDetailOrderJsonChildren) + VALUES( + $header_id, + '{$v['T_TestID']}', + '{$v['T_TestName']}', + '{$v['is_packet']}', + '', + 0, + '', + now(), + $userid, + now(), + now(), + '')"; + //echo $sqlorder; + $queryt_orderdetailorder = $this->db_smartone->query($sqlt_orderdetailorder); + if(!$queryt_orderdetailorder){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + $detail_id = $this->db_smartone->insert_id(); + } + + if($v['px_type'] == 'PX'){ + $sql = $this->db_smartone->query("SELECT T_TestIsParent as isparent FROM t_test WHERE T_TestID = '{$v['T_TestID']}'")->row(); + $isparent = $sql->isparent; +//echo $isparent; +$sqlt_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_OrderDetailUserID, + T_OrderDetailCreated, + T_OrderDetailLastUpdated) + SELECT + $header_id, + $detail_id, + '{$v['T_TestID']}', + T_TestCode, + T_TestSasCode, + '{$v['T_TestName']}', + T_TestIsResult, + 'N', + 'N', + 'N', + T_TestIsPrice, + 'N', + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceDisc']}'), + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceDiscRp']}'), + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceSubTotal']}'), + IF(T_TestIsPrice = 'N',0,'{$v['T_PriceTotal']}'), + 'N', + '', + $userid, + now(), + now() + from t_test + where T_TestID = '{$v['T_TestID']}' AND '{$v['is_packet']}' = 'N' + "; + +$queryt_orderdetail = $this->db_smartone->query($sqlt_orderdetail); +//echo $this->db_smartone->last_query(); +if(!$queryt_orderdetail){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; +} +$this->db_smartone->trans_commit(); + if($isparent == 'Y') + { + $sqlt_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_OrderDetailUserID, + T_OrderDetailCreated, + T_OrderDetailLastUpdated) + SELECT + $header_id, + $detail_id, + T_TestID, + T_TestCode, + T_TestSasCode, + T_TestName, + T_TestIsResult, + 'N', + 'N', + 'N', + T_TestIsPrice, + 'N', + 0, + 0, + 0, + 0, + 0, + 0, + 'N', + '', + $userid, + now(), + now() + FROM + (SELECT * FROM t_test WHERE T_TestIsActive = 'Y' ORDER BY T_TestParentT_TestID, T_TestID ASC) as a, + (SELECT @pv := '{$v['T_TestID']}') initialisation + WHERE find_in_set(T_TestParentT_TestID, @pv) > 0 AND @pv := CONCAT(@pv, ',', T_TestID)"; + + $queryt_orderdetail = $this->db_smartone->query($sqlt_orderdetail); +//echo $this->db_smartone->last_query(); + if(!$queryt_orderdetail){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + } + }else{ + foreach($v['child_test'] as $k => $p){ + $sql = $this->db_smartone->query("SELECT T_TestIsParent as isparent FROM t_test WHERE T_TestID = '{$p['T_TestID']}'")->row(); + $isparent = $sql->isparent; + //echo $isparent; + $sqlt_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_OrderDetailUserID, + T_OrderDetailCreated, + T_OrderDetailLastUpdated) + SELECT + $header_id, + $detail_id, + '{$p['T_TestID']}', + T_TestCode, + '{$p['T_TestSasCode']}', + '{$p['T_TestName']}', + T_TestIsResult, + 'N', + 'N', + 'N', + T_TestIsPrice, + 'N', + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceDisc']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceDiscRp']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceSubTotal']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceTotal']}'), + 'N', + '', + $userid, + now(), + now() + from t_test + where T_TestID = '{$p['T_TestID']}' AND '{$p['is_packet']}' = 'N' + "; + + $queryt_orderdetail = $this->db_smartone->query($sqlt_orderdetail); +//echo $this->db_smartone->last_query(); + if(!$queryt_orderdetail){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + if($isparent == 'Y') + { + $sqlt_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_OrderDetailUserID, + T_OrderDetailCreated, + T_OrderDetailLastUpdated) + SELECT + $header_id, + $detail_id, + T_TestID, + T_TestCode, + T_TestSasCode, + T_TestName, + T_TestIsResult, + 'N', + 'N', + 'N', + T_TestIsPrice, + 'N', + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceAmount']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceDisc']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceDiscRp']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceSubTotal']}'), + IF(T_TestIsPrice = 'N',0,'{$p['T_PriceTotal']}'), + 'N', + '', + $userid, + now(), + now() + FROM + (SELECT * FROM t_test WHERE T_TestIsActive = 'Y' ORDER BY T_TestParentT_TestID, T_TestID ASC) as a, + (SELECT @pv := '{$p['T_TestID']}') initialisation + WHERE find_in_set(T_TestParentT_TestID, @pv) > 0 AND @pv := CONCAT(@pv, ',', T_TestID)"; + + $queryt_orderdetail = $this->db_smartone->query($sqlt_orderdetail); + //echo $this->db_smartone->last_query(); + if(!$queryt_orderdetail){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert t_orderdetailorder | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + } + + + } + } + + } + $query_generate_sample = $this->generate_sample($header_id); + $query_generate_location = $this->generate_location($header_id); + $query_generate_req = $this->generate_req($header_id,$req); + + $sqlpreregister = "UPDATE mcu_preregister_patients + SET Mcu_PreregisterPatientsIsRegistered = 'Y', + Mcu_PreregisterPatientsT_OrderHeaderID = '{$header_id}' + WHERE + Mcu_PreregisterPatientsID = {$preid}"; + $querypreregister = $this->db_smartone->query($sqlpreregister); + if(!$querypreregister){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "update mcu_preregister_patients | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + + //$query_generate_log = $this->generate_log($header_id); + $sql = "SELECT * + FROM t_orderheader + JOIN t_orderdetail ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID + WHERE + T_OrderHeaderID = {$header_id}"; + $x_data = $this->db_smartone->query($sql)->result_array(); + $x_data = json_encode($x_data); + + $sqllog= "INSERT INTO order_log( + orderLogType, + orderLogT_OrderHeaderID, + orderLogJSONBefore, + orderLogJSONAfter, + orderLogCreated, + orderLogUserID) + VALUES ('REGISTER','{$header_id}','','{$x_data}',now(),'{$userid}')"; + $querylog= $this->db_smartone->query($sqllog); + if(!$querylog){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "update mcu_preregister_patients | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + + $r = $this->db_smartone->where('T_OrderHeaderID', $header_id) + ->get('t_orderheader') + ->row(); + + $nomorreg = $r->T_OrderHeaderLabNumber; + + $url = "https://devcpone.aplikasi.web.id/one-api/v1/su/test/genqrcode/".$nomorreg."/".$header_id; + $post_rst = $this->post($url); + // echo "to $url \nresponse : $post_rst\n"; + $j_rst = json_decode($post_rst,true); + + $urlpat = "https://devcpone.aplikasi.web.id/one-api/v1/su/test/genpatientqrcode/".$nomorreg; + $post_rstpat = $this->post($urlpat); + // echo "to $urlpat \nresponse : $post_rstpat\n"; + $j_rstpat = json_decode($post_rstpat,true); + +$rst->data = array("id" => $header_id, 'noreg'=>$r->T_OrderHeaderLabNumber); + + $this->broadcast("fo-register"); + echo json_encode($rst); + }else + { + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "save | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $this->db_smartone->trans_commit(); + + } + 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($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); +} +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($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"]; + $sql = "INSERT INTO log_action( + LogActionType, + LogActionT_OrderHeaderID, + LogActionCreated, + LogActionUserID) + VALUES ('FO_START','{$prm['order_id']}','{$prm['time_start']}','{$userid}')"; + $qry = $this->db_smartone->query($sql); + + if (!$qry) { + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert log_action start| " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $sql = "INSERT INTO log_action( + LogActionType, + LogActionT_OrderHeaderID, + LogActionCreated, + LogActionUserID) + VALUES ('FO_END','{$prm['order_id']}',now(),'{$userid}')"; + $qry = $this->db_smartone->query($sql); + if ($qry) + { + $result = array( + "total" => 1, + "records" => array() + ); + $this->sys_ok($result); + exit; + } + else + { + $this->db_smartone->trans_rollback(); + $this->sys_error_db(["status" => "ERR", "message" => "insert log_action end| " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + 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, + concat(if(M_TitleID is null, '', concat(M_TitleName, ' ')),IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) as patient_name, + 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(); + //echo $this->db_smartone->last_query(); + return $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 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); + } + 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'){ + $sql = " + SELECT 0 as kelurahan, + 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, + '{$type}' 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 = '{$type}' AND M_DeliveryIsActive = 'Y' + UNION + SELECT M_PatientAddressM_KelurahanID as kelurahan, + 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_KelurahanName,', ',M_DistrictName,', ',M_CityName) as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' 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_kelurahan ON M_PatientAddressM_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_PatientID = {$id} + GROUP BY M_PatientAddressID + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientEmail,'Belum ada email pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientEmail,'Belum ada email pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientHP,'Belum ada WA pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_PatientHP,'Belum ada telegram pasien') as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM m_patient + 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_PatientID = {$id}"; + } + if($type == 'mou'){ + //echo $id; + $sql = "SELECT * FROM m_mou WHERE M_MouID = {$id}"; + //echo $sql; + $data_mou = $this->db_smartone->query($sql)->row_array(); + //print_r($data_mou); + $sql = " + SELECT CorporateM_KelurahanID as kelurahan, + CorporateID as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + CONCAT(CorporateAddress,' ',M_KelurahanName,', ',M_DistrictName,', ',M_CityName) as description, + 'N' as chex, + '' as note, + 'origin' as typeform, + '{$type}' as type, + M_DeliveryTypeCode as delivery_code + FROM corporate + JOIN m_delivery ON M_DeliverySource = 'COMPANY' AND M_DeliveryIsActive = 'Y' + JOIN m_deliverytype ON M_DeliveryTypeCode = 'ADDRESS' AND M_DeliveryM_DeliveryTypeID = M_DeliveryTypeID + JOIN m_kelurahan ON CorporateM_KelurahanID = M_KelurahanID + JOIN m_district ON M_KelurahanM_DistrictID = M_DistrictID + JOIN m_city ON M_DistrictM_CityID = M_CityID + WHERE + CorporateID = {$data_mou['M_MouCorporateID']} + UNION + SELECT 0 as kelurahan, + 0 as address_id, + M_DeliveryM_DeliveryTypeID as delivery_type, + M_DeliveryID as delivery_id, + M_DeliveryName as delivery_name, + IFNULL(M_MouEmail,'Belum ada email agreement') as description, + 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 M_DoctorAddressM_KelurahanID as kelurahan, + 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_KelurahanName,', ',M_DistrictName,', ',M_CityName) 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, + 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 pengirim',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, + 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, + 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 = $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() ; + } + + + /*data doctor*/ + $sql = "SELECT M_DoctorID, +'N' M_DoctorIsPJ, +CONCAT('[ ',M_DoctorCode,' ] ',M_DoctorPrefix, M_DoctorPrefix2,' ',M_DoctorName,' ',M_DoctorSuffix,M_DoctorSuffix2) 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(); + + /*data company mou*/ + $sql = "SELECT corporate.*, '' mou + FROM corporate + WHERE + CorporateID = {$row_header['Mgm_McuCorporateID']}"; + $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); + + + $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,$mcuid) + { + + $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 "; + + $sql = "select * + from + ss_price_mou + where + T_PriceT_PriceHeaderID = {$mcuid} 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']); + + // IF PROFILE + if ($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; + } + + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Order.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Order.php new file mode 100644 index 0000000..15a5179 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Order.php @@ -0,0 +1,3617 @@ +db_smartone = $this->load->database("onedev", true); + $this->db_log = $this->load->database("cpone_log", true); + } + + 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'] = "https://devcpone.aplikasi.web.id/one-ui/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 "https://devcpone.aplikasi.web.id/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 "https://devcpone.aplikasi.web.id/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'] = "https://devcpone.aplikasi.web.id/one-ui/test/vuex/cpone-riwayat-form/?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' => "https://devcpone.aplikasi.web.id/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() + { + // Generate 16 bytes (128 bits) of random data + $data = random_bytes(16); + + // Set version to 0100 + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + // Set bits 6-7 to 10 + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + + // Output the 36 character UUID + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); + } + + function generate_code_form($preid = 0, $orderid) + { + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT COUNT(*) as total + FROM form_riwayat_pasien + WHERE FormRiwayatPasienT_OrderHeaderID = ? AND + FormRiwayatPasienIsActive = 'Y' + "; + $qry = $this->db_onedev->query($sql, [$orderid]); + //echo $this->db_onedev->last_query(); + //exit; + 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); + } + } else { + return ''; + } + } + + function check_duplicate_nat_tests($data) + { + $has_duplicates = false; + $duplicate_pairs = []; + $nat_tests = isset($data['nat_test']) ? $data['nat_test'] : []; + foreach ($data as $key => $value) { + if (isset($value['nat_test']) && is_array($value['nat_test'])) { + foreach ($value['nat_test'] as $nat_test) { + if (in_array($nat_test, $nat_tests)) { + $has_duplicates = true; + $duplicate_pairs[] = $nat_test; + } + } + } + } + + // Mengembalikan hasil pengecekan + return [ + 'is_duplicate' => $has_duplicates, + 'duplicate_pairs' => array_values($duplicate_pairs) // Convert to indexed array + ]; + } + + function save() + { + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + + $check_duplicate_nat_tests = $this->check_duplicate_nat_tests($prm['detail']); + if($check_duplicate_nat_tests['is_duplicate']){ + $this->sys_error_db(["status" => "ERR", "message" => "duplicate test | " . json_encode($check_duplicate_nat_tests['duplicate_pairs'])]); + exit; + } + + $userid = $this->sys_user["M_UserID"]; + $sql = "SELECT M_UserLoginM_BranchID as branch_id, M_BranchCodeLab as branch_code_lab, M_BranchCodeBridging as branch_code_bridging + FROM m_user + JOIN m_branch ON M_UserLoginM_BranchID = M_BranchID AND M_BranchIsActive = 'Y' + WHERE M_UserID = $userid"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "select m_user | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $dt_branch = $query->row_array(); + $branch_id = $dt_branch['branch_id']; + $branch_code_lab = $dt_branch['branch_code_lab']; + $branch_code_bridging = $dt_branch['branch_code_bridging']; + $pre_registerid = isset($prm['preid']) ? $prm['preid'] : 0; + $header = $prm['header']; + $header['pre_register_id'] = $pre_registerid; + $details = $prm['detail']; + $mgm_mcuid = isset($prm['selected_project']) ? $prm['selected_project']['id'] : 0; + + $test_orders = []; + foreach($details as $k => $v){ + if($v['t_ispacket'] == 'Y'){ + // Check if packet with same packetid already exists + $packet_exists = false; + foreach($test_orders as $test_order){ + if($test_order['packet_id'] == $v['t_packetid']){ + $packet_exists = true; + break; + } + } + if(!$packet_exists){ + $test_orders[] = array( + 't_testid' => '0', + 't_testname' => '', + 'is_packet' => 'Y', + 'packet_id' => $v['t_packetid'], + 'packet_type' => $v['packet_type'], + 'packet_name' => $v['packet_name'] + ); + } + }else{ + $test_exists = false; + foreach($test_orders as $test_order){ + if($test_order['t_testid'] == $v['t_id']){ + $test_exists = true; + break; + } + } + if(!$test_exists){ + $test_orders[] = array( + 't_testid' => $v['t_id'], + 't_testname' => $v['t_name'], + 'is_packet' => 'N', + 'packet_id' => '0', + 'packet_type' => '', + 'packet_name' => '' + ); + } + } + } + + $this->db_smartone->trans_begin(); + + $sql = "SELECT M_DoctorID, M_DoctorName, M_DoctorPjIsDefaultPJ + FROM m_doctorpj + JOIN m_doctor ON M_DoctorPjM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' + JOIN m_user ON M_DoctorPjM_BranchID = M_UserLoginM_BranchID + AND M_UserID = $userid + WHERE + M_DoctorPjIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "error select dokter" . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $doctorpjs = $query->result_array(); + if(count($doctorpjs) == 0){ + $sql = "SELECT M_DoctorID, M_DoctorName, M_DoctorPjIsDefaultPJ + FROM m_doctorpj + JOIN m_doctor ON M_DoctorPjM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' + WHERE + M_DoctorPjIsActive = 'Y' AND M_DoctorPjM_BranchID = 1"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "error select dokter default 1" . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $doctorpjs = $query->result_array(); + } + + + $pj1 = $doctorpjs[0]['M_DoctorID']; + $pj2 = count($doctorpjs) > 1 ? $doctorpjs[1]['M_DoctorID'] : 0; + + $header = []; + + + $sql = "SELECT fn_numbering_cpone_transaction('T','{$branch_id}') xnumber"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "select fn_numbering_cpone_transaction | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $nolab = $query->row()->xnumber; + + $header['T_OrderHeaderLabNumber'] = $nolab; + $header['T_OrderHeaderM_BranchID'] = $branch_id; + $header['T_OrderHeaderDate'] = date('Y-m-d H:i:s'); + $header['T_OrderHeaderM_PatientID'] = $prm['selected_patient']['M_PatientID']; + $header['T_OrderHeaderM_PatientAge'] = $prm['patient_age']; + $header['T_OrderHeaderCorporateID'] = $prm['selected_company']['CorporateID']; + $header['T_OrderHeaderMgm_McuID'] = isset($prm['selected_project']) ? $prm['selected_project']['id'] : 0; + $header['T_OrderHeaderM_PatientAge'] = $prm['patient_age']; + $header['T_OrderHeaderPjM_DoctorID'] = $pj1; + $header['T_OrderHeaderPj2M_DoctorID'] = $pj2; + $header['T_OrderHeaderDiagnose'] = $prm['diagnosa']; + $header['T_OrderHeaderFoNote'] = $prm['catatan_fo']; + $header['T_OrderHeaderFoNoteM_UserID'] = $userid; + $header['T_OrderHeaderCreated'] = date('Y-m-d H:i:s'); + $header['T_OrderHeaderCreatedUserID'] = $userid; + + $fn_save_order_header = $this->db_smartone->insert('t_orderheader', $header); + $header_id = $this->db_smartone->insert_id(); + if(!$header_id){ + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERHEADER', 'order/save_order_detail'], array( + 'header' => $header, + 'userid' => $userid + )); + $this->sys_error_db(["status" => "ERR", "message" => "error insert t_orderheader | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $references = []; + if (isset($prm['reference'])) { + $references = $prm['reference']; + } else if (isset($prm['header']['reference'])) { + $references = $prm['header']['reference']; + } else if (isset($prm['selected_reference'])) { + $references = $prm['selected_reference']; + } + + if (!is_array($references) || count($references) == 0) { + $this->db_smartone->trans_rollback(); + $this->sys_error("Reference wajib dipilih minimal 1"); + exit; + } + + $uniqueRef = []; + foreach ($references as $ref) { + if (is_array($ref) && isset($ref['M_ReferenceID'])) { + $uniqueRef[$ref['M_ReferenceID']] = (int)$ref['M_ReferenceID']; + } else if (is_object($ref) && isset($ref->M_ReferenceID)) { + $uniqueRef[$ref->M_ReferenceID] = (int)$ref->M_ReferenceID; + } + } + + if (count($uniqueRef) == 0) { + $this->db_smartone->trans_rollback(); + $this->sys_error("Reference wajib dipilih minimal 1"); + exit; + } + + $ordertype = null; + if (isset($prm['ordertype'])) { + $ordertype = $prm['ordertype']; + } else if (isset($prm['header']['ordertype'])) { + $ordertype = $prm['header']['ordertype']; + } + + if (!$ordertype || !is_array($ordertype) || !isset($ordertype['M_OrderTypeID'])) { + $this->db_smartone->trans_rollback(); + $this->sys_error("Order Type wajib dipilih"); + exit; + } + + foreach ($uniqueRef as $refId) { + $sql_ref = "INSERT INTO t_orderreference( + T_OrderreferenceT_OrderheaderID, + T_OrderreferenceM_ReferenceID, + T_OrderreferenceIsActive, + T_OrderreferenceCreated, + T_OrderreferenceLastUpdated, + T_OrderreferenceUserID + ) VALUES ( + ?, ?, 'Y', NOW(), NOW(), ? + )"; + $qry_ref = $this->db_smartone->query($sql_ref, [$header_id, $refId, $userid]); + if (!$qry_ref) { + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERREFERENCE', 'order/save'], [ + 'header_id' => $header_id, + 'ref_id' => $refId, + 'error' => $this->db_smartone->error() + ]); + $this->sys_error_db([ + "status" => "ERR", + "message" => "error insert t_orderreference | " . $this->db_smartone->error()["message"], + "debug" => $this->db_smartone->last_query() + ]); + exit; + } + } + + $sql_ordertype = "INSERT INTO t_ordertype ( + T_OrderTypeT_OrderHeaderID, + T_OrderTypeM_OrderTypeID, + T_OrderTypeM_OrderTypeCode, + T_OrderTypeCreated, + T_OrderTypeCreatedUserID, + T_OrderTypeLastUpdated, + T_OrderTypeLastUpdatedUserID + ) VALUES ( + ?, ?, ?, NOW(), ?, NOW(), ? + )"; + + $qry_ordertype = $this->db_smartone->query($sql_ordertype, [ + $header_id, + intval($ordertype['M_OrderTypeID']), + $ordertype['M_OrderTypeCode'], + $userid, + $userid + ]); + + if (!$qry_ordertype) { + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERTYPE', 'order/save'], [ + 'header_id' => $header_id, + 'ordertype' => $ordertype, + 'error' => $this->db_smartone->error() + ]); + $this->sys_error_db([ + "status" => "ERR", + "message" => "error insert t_ordertype | " . $this->db_smartone->error()["message"], + "debug" => $this->db_smartone->last_query() + ]); + exit; + } + + $fisik_template_mapping_id = $prm['selected_fisik_template']['fisik_template_id']? $prm['selected_fisik_template']['fisik_template_id'] : 0; + + $icd10_code = $prm['selected_icd10']['code']?$prm['selected_icd10']['code']:''; + $icd10_display = $prm['selected_icd10']['display']?$prm['selected_icd10']['display']:''; + + $price_header_id = $prm['selected_mou']['price_header_id']?$prm['selected_mou']['price_header_id']:0; + $cito_id = $prm['cito_id']['id']?$prm['cito_id']:0; + + $sql = "INSERT INTO t_orderheaderaddon( + T_OrderHeaderAddOnT_OrderHeaderID, + T_OrderHeaderAddOnT_PriceHeaderID, + T_OrderHeaderAddOnM_DoctorSenderID, + T_OrderHeaderAddOnFisikTemplateMappingID, + T_OrderHeaderAddOnICD10Code, + T_OrderHeaderAddOnICD10Display, + T_OrderHeaderAddOnReceiveSample, + T_OrderHeaderAddOnReceiveSampleTime, + T_OrderHeaderAddonNat_CitoID, + T_OrderHeaderAddOnCreated, + T_OrderHeaderAddOnCreatedUserID + ) + VALUES(?,?,?,?,?,?,?,?,?,NOW(),?)"; + $prm_orderheaderaddon = [ + $header_id, + $price_header_id, + $prm['selected_doctor']['M_DoctorID'], + $fisik_template_mapping_id, + $icd10_code, + $icd10_display, + $prm['received_sample'] == 'Y' ? 'Y' : 'N', + $prm['received_sample_time'], + $cito_id, + $userid + ]; + + $query_orderheaderaddon = $this->db_smartone->query($sql, $prm_orderheaderaddon); + if(!$query_orderheaderaddon){ + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERHEADERADDON', 'order/save_order_detail'], array( + 'orderheaderaddon' => $prm_orderheaderaddon, + 'userid' => $userid + )); + $this->sys_error_db(["status" => "ERR", "message" => "error insert t_orderheaderaddon | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $save_order_detai_order = $this->save_orderdetail_order($test_orders,$header_id,$userid); + if(!$save_order_detai_order['status']){ + $this->db_smartone->trans_rollback(); + $message = $save_order_detai_order['message'] ?? 'Terjadi kesalahan saat menyimpan data detail order'; + $this->sys_error($message); + exit; + } + + $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'; + $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'; + $this->sys_error($message); + exit; + } + + $fn_generate_location = $this->generate_location($header_id,$userid); + if(!$fn_generate_location['status']){ + $this->db_smartone->trans_rollback(); + $message = $fn_generate_location['message'] ?? 'Terjadi kesalahan saat membuat lokasi'; + $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'; + $this->sys_error($message); + exit; + } + + $this->load->library('Promise'); + $test_ids = array_column($details, 't_id'); + $fn_generate_promise = $this->promise->get_schedule_results_grouped($test_ids, $header['T_OrderHeaderDate'], $branch_id, $header_id); + + if(count($fn_generate_promise) == 0){ + $this->db_smartone->trans_rollback(); + $message = $fn_generate_promise['message'] ?? 'Terjadi kesalahan saat membuat promise'; + $this->sys_error($message); + exit; + }else{ + + $promise_data = $fn_generate_promise; + if(count($promise_data) > 0){ + foreach($promise_data as $key => $value){ + $sql = "INSERT INTO t_orderpromises( + T_OrderPromisesT_OrderHeaderID, + T_OrderPromisesDateTime, + T_OrderPromisesTestIDs, + T_OrderPromisesM_ScheduleID, + T_OrderPromisesM_ScheduleFlagAtTime, + T_OrderPromisesM_ScheduleAtTime, + T_OrderPromisesTAT_Menit, + T_OrderPromisesM_ScheduleStartHourMinute, + T_OrderPromisesM_ScheduleEndHourMinute, + T_OrderPromisesCreated, + T_OrderPromisesCreatedUserID + ) VALUES ( + ?,?,?,?,?,?,?,?,?,NOW(),? + )"; + $query = $this->db_smartone->query($sql, [ + $header_id, + $value['JanjiHasil'], + $value['TestIDs'], + $value['ScheduleID'], + $value['M_ScheduleFlagAtTime'], + $value['M_ScheduleAtTime'], + $value['TAT_Menit'], + $value['M_ScheduleStartHourMinute'], + $value['M_ScheduleEndHourMinute'], + $userid + ]); + if(!$query){ + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERPROMISES_ERROR', 'order/save'], array( + 'promise_data' => $value, + 'header_id' => $header_id + )); + $message = 'Terjadi kesalahan saat membuat promise'; + $this->sys_error($message); + exit; + } + $promise_id = $this->db_smartone->insert_id(); + $order_detail_ids = explode(",", $value['OrderDetailIDs']); + if(count($order_detail_ids) > 0){ + foreach($order_detail_ids as $key_order_detail_id => $value_order_detail_id){ + $sql = "INSERT INTO t_orderdetail_promise( + T_OrderDetailPromiseT_OrderHeaderID, + T_OrderDetailPromiseT_OrderDetailID, + T_OrderDetailPromiseT_OrderPromiseID, + T_OrderDetailPromiseCreated, + T_OrderDetailPromiseCreatedUserID + ) VALUES (?, ?, ?, NOW(), ?)"; + $query = $this->db_smartone->query($sql, [$header_id, $value_order_detail_id, $promise_id, $userid]); + if(!$query){ + $this->db_smartone->trans_rollback(); + $this->insert_log_error($this->db_smartone->last_query(), ['INSERT_T_ORDERDETAIL_PROMISE_ERROR', 'order/save'], array( + 'promise_data' => $value, + 'header_id' => $header_id, + 'order_detail_id' => $value_order_detail_id, + 'promise_id' => $promise_id, + 'userid' => $userid + )); + $message = 'Terjadi kesalahan saat membuat promise'; + $this->sys_error($message); + exit; + } + } + } + } + } + } + + $fn_order_delivery = $this->save_delivery($header_id,$prm['deliveries'],$userid); + if(!$fn_order_delivery['status']){ + $this->db_smartone->trans_rollback(); + $message = $fn_order_delivery['message'] ?? 'Terjadi kesalahan saat membuat delivery'; + $this->sys_error($message); + exit; + } + + $data_lang = array( + array( + 'T_OrderHeaderLangT_OrderHeaderID' => $header_id , + 'T_OrderHeaderLangM_LangID' => 1 , + 'T_OrderHeaderLangCreated' => date('Y-m-d H:i:s'), + 'T_OrderHeaderLangCreatedUserID' => $userid + ) + ); + + if(intval($prm['selected_language_2']) > 0){ + $data_lang[] = array( + 'T_OrderHeaderLangT_OrderHeaderID' => $header_id , + 'T_OrderHeaderLangM_LangID' => $prm['selected_language_2'] , + 'T_OrderHeaderLangCreated' => date('Y-m-d H:i:s'), + 'T_OrderHeaderLangCreatedUserID' => $userid + ); + } + + $save_lang =$this->db_smartone->insert_batch('t_orderheaderlang', $data_lang); + if(!$save_lang){ + $this->sys_error_db(["status" => "ERR", "message" => "error insert t_orderheaderlang | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $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) { + $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); + $message = 'Terjadi kesalahan saat mengambil data order header'; + $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); + + $received_sample = $prm['received_sample'] == 'Y' ? 'Y' : 'N'; + //echo $received_sample; + //echo $received_sample_time; + $received_sample_time = $prm['received_sample_time']?$prm['received_sample_time']:'0000-00-00 00:00:00'; + if($received_sample == 'Y' && $received_sample_time != '0000-00-00 00:00:00'){ + //echo $received_sample_time; + $received_sample_time = date('Y-m-d H:i:s', strtotime($received_sample_time)); + $sql = "UPDATE t_ordersample SET + T_OrderSampleSampling = 'Y', + T_OrderSampleSamplingDate = DATE('{$received_sample_time}'), + T_OrderSampleSamplingTime = TIME('{$received_sample_time}'), + T_OrderSampleSamplingUserID = {$userid}, + T_OrderSampleReceive = 'Y', + T_OrderSampleReceiveDate = DATE('{$received_sample_time}'), + T_OrderSampleReceiveTime = TIME('{$received_sample_time}'), + T_OrderSampleReadyToProcessDateTime = '{$received_sample_time}', + T_OrderSampleProcessing = 'Y', + T_OrderSampleProcessingTime = TIME('{$received_sample_time}'), + T_OrderSampleProcessingUserID = {$userid}, + T_OrderSampleReceiveUserID = {$userid}, + T_OrderSampleProcessingDate = DATE('{$received_sample_time}') + WHERE T_OrderSampleT_OrderHeaderID = ? AND T_OrderSampleIsActive = 'Y'"; + $query = $this->db_smartone->query($sql, [$header_id]); + //echo $this->db_smartone->last_query(); + //exit; + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "error update t_ordersample | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + } + + $genqrcode = $this->genqrcode($lab_number, $header_id); + $genpatientqrcode = $this->genpatientqrcode($lab_number); + + if($fisik_template_mapping_id > 0){ + $sql = "SELECT COUNT(DISTINCT FisikTemplateID) as jumlah_fisik_template + FROM fisik_template_mapping + JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND FisikTemplateMappingDetailIsActive = 'Y' + JOIN fisik_template ON FisikTemplateID = FisikTemplateMappingDetailFisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateType = 'Riwayat' + WHERE FisikTemplateMappingID = ? AND FisikTemplateMappingIsActive = 'Y'"; + $query_fisik_template_mapping = $this->db_smartone->query($sql, [$fisik_template_mapping_id]); + if(!$query_fisik_template_mapping){ + $this->sys_error_db(["status" => "ERR", "message" => "select fisik_template_mapping | " . + $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $dt_fisik_template_mapping = $query_fisik_template_mapping->row_array(); + $jumlah_fisik_template = $dt_fisik_template_mapping['jumlah_fisik_template']; + + if($jumlah_fisik_template > 0){ + $pre_registerid = 0; + $genformqrcode = ''; + $uuid = ''; + $form_code = ''; + $gen_uuid = $this->generate_code_form($pre_registerid, $header_id); + if ($gen_uuid['uuid'] != '') { + $uuid = $gen_uuid['uuid']; + $form_code = $gen_uuid['code']; + $genformqrcode = $this->genformqrcode($gen_uuid['uuid']); + + } + } + } + + $this->db_smartone->trans_commit(); + //print_r($dt_menu); + $xurl = ''; + + $get_order_header = $this->get_order_header($header_id); + if(!$get_order_header['status']){ + $this->sys_error($get_order_header['message']); + exit; + } + $order_header = $get_order_header['data']; + + $sql = "SELECT t_orderdetail.*, t_orderheader.* + FROM t_orderdetail + JOIN t_test ON T_OrderDetailT_TestID = T_TestID AND T_TestIsActive = 'Y' AND T_TestIsPrice = 'Y' + JOIN t_orderheader ON T_OrderDetailT_OrderHeaderID = T_OrderHeaderID + WHERE + T_OrderDetailT_OrderHeaderID = ? AND + T_OrderDetailIsActive = 'Y'"; + $query_orderdetail = $this->db_smartone->query($sql, [$header_id]); + if(!$query_orderdetail){ + $this->sys_error_db(["status" => "ERR", "message" => "error select t_orderdetail | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $data_log = $query_orderdetail->result_array(); + + $sqllog = "INSERT INTO order_log( + orderLogType, + orderLogT_OrderHeaderID, + orderLogJSONBefore, + orderLogJSONAfter, + orderLogCreated, + orderLogUserID) + VALUES ('REGISTER',?,'',?,now(),?)"; + $querylog = $this->db_smartone->query($sqllog, [$header_id, json_encode($data_log),$userid]); + if(!$querylog){ + $this->sys_error_db(["status" => "ERR", "message" => "error insert order_log | " . $this->db_log->error()["message"], "debug" => $this->db_log->last_query()]); + exit; + } + + //$this->load->library('Apilis'); + //$kesimpulan = $this->apilis->GetOrderDetail($lab_number); + + $sql = "SELECT * FROM s_menu WHERE S_MenuIsActive = 'Y' AND + S_MenuName = 'Kasir WA Kwitansi' LIMIT 1"; + $query_menu = $this->db_smartone->query($sql); + if(!$query_menu){ + $this->sys_error_db(["status" => "ERR", "message" => "error select s_menu | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + $row_menu = $query_menu->row_array(); + $url_menu_cashier = $row_menu['S_MenuUrl']; + + $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, + 'url_qrform' => $genformqrcode['url'], + 'uuid' => $uuid, + 'form_code' => $form_code != '' ? $form_code : '', + 'tipe'=> 'new', + 'url' => $xurl, + 'data' => array('id' => $header_id,'number' => $lab_number), + 'order_header' => $order_header, + 'url_menu_cashier' => $url_menu_cashier + + ]; + + $this->sys_ok($dt_order); + exit; + + } + + function get_details_order(){ + + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $header_id = $prm['header_id']; + + /*$get_order_detail = $this->get_order_detail($header_id); + if(!$get_order_detail['status']){ + $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']){ + $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']){ + $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']){ + $this->sys_error($get_details['message']); + exit; + } + $order_details = $get_details['data']; + + + + $this->sys_ok([ + 'order_delivery' => $order_delivery, + 'order_promise' => $order_promise, + 'order_detail' => $order_details + ]); + exit; + } + + function save_orderdetail_order($test_orders,$header_id,$userid){ + $return = [ + "status" => true, + "message" => "", + "data" => [] + ]; + foreach($test_orders as $test_order){ + $sql = "INSERT INTO t_orderdetailorder( + T_OrderDetailOrderT_OrderHeaderID, + T_OrderDetailOrderT_TestID, + T_OrderDetailOrderT_TestName, + T_OrderDetailOrderIsPacket, + T_OrderDetailOrderPacketType, + T_OrderDetailOrderT_PacketID, + T_OrderDetailOrderT_PacketName, + T_OrderDetailOrderCreated, + T_OrderDetailOrderCreatedUserID + ) + VALUES(?,?,?,?,?,?,?,NOW(),?)"; + $query = $this->db_smartone->query($sql, [ + $header_id, + $test_order['t_testid'], + $test_order['t_testname'], + $test_order['is_packet'], + $test_order['packet_type'], + $test_order['packet_id'], + $test_order['packet_name'], + $userid + ]); + if(!$query){ + $return['status'] = false; + $return['message'] = "Terjadi kesalahan saat menyimpan data detail order"; + return $return; + } + } + + $return['status'] = true; + $return['message'] = "Data detail order berhasil disimpan"; + return $return; + } + + function get_order_promises($order_id){ + $return = [ + "status" => true, + "message" => "", + "data" => [] + ]; + $sql = "SELECT *, DATE_FORMAT(T_OrderPromisesDateTime,'%d-%m-%Y %H:%i') as T_OrderPromiseDateTime_ina + FROM t_orderpromises + WHERE + T_OrderPromisesT_OrderHeaderID = ? AND + T_OrderPromisesIsActive = '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 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, + IFNULL(T_OrderDeliveryNote,T_OrderDeliveryDestination) as xdesc + FROM t_orderdelivery + JOIN m_deliverytype ON T_OrderDeliveryM_DeliveryTypeID = M_DeliveryTypeID + JOIN m_delivery ON T_OrderDeliveryM_DeliveryID = M_DeliveryID + 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){ + $rst[] = array( + 'type' => $value['xtype'], + 'source' => $value['source'], + 'label' => $value['label'], + 'desc' => $value['xdesc'] + ); + } + $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, + 'N' as M_CompanyIsBill, + '0' as M_CompanyMinDP, + pj1.M_DoctorName as doctor_pj1, + pj2.M_DoctorName as doctor_pj2, + sender.M_DoctorName as doctor_sender, + sender.M_DoctorAddress as doctor_sender_address, + CorporateName as order_company, + T_OrderHeaderDate as order_date, + T_OrderHeaderID as order_id, + T_OrderHeaderLabNumber as order_no, + T_PriceHeaderName 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 as patient_name, + CONCAT(M_PatientAddress,'
',M_PatientAddressVillage, ', ', M_PatientAddressDistrict, ', ', M_PatientAddressCity) as patient_address, + M_PatientHp as patient_phone, + M_PatientEmail as patient_email, + t_orderheader.*, + IFNULL(Nat_CitoName,'') as cito_name, + IFNULL(Mgm_McuNumber,'') as mcu_number, + IFNULL(Mgm_McuLabel,'') as mcu_label + 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 AND M_PatientIsActive = 'Y' + JOIN corporate ON T_OrderHeaderCorporateID = CorporateID AND CorporateIsActive = 'Y' + JOIN t_priceheader ON T_OrderHeaderAddOnT_PriceHeaderID = T_PriceHeaderID + JOIN m_doctor pj1 ON T_OrderHeaderPjM_DoctorID = pj1.M_DoctorID AND pj1.M_DoctorIsActive = 'Y' + LEFT JOIN m_doctor pj2 ON T_OrderHeaderPj2M_DoctorID = pj2.M_DoctorID AND pj2.M_DoctorIsActive = 'Y' + JOIN m_doctor sender ON T_OrderHeaderAddOnM_DoctorSenderID = sender.M_DoctorID AND sender.M_DoctorIsActive = 'Y' + LEFT JOIN nat_cito ON T_OrderHeaderAddonNat_CitoID = Nat_CitoID AND Nat_CitoIsActive = 'Y' + LEFT JOIN mgm_mcu ON T_OrderHeaderMgm_McuID = Mgm_McuID AND Mgm_McuIsActive = 'Y' + WHERE `T_OrderHeaderID` = ? + GROUP BY T_OrderHeaderID"; + $query = $this->db_smartone->query($sql, [$order_id]); + + 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(); + $return['data'] = $data; + return $return; + } + + + + function get_details($order_id){ + $return = [ + "status" => true, + "message" => "", + "data" => [] + ]; + $sql = "SELECT * + FROM `t_orderdetail` + 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, + T_OrderDetailOrderIsPacket as t_ispacket, + T_OrderDetailOrderT_TestName as t_name, + '' as t_price, + '' as t_disc, + '' as t_discamount, + '' as t_disctotal, + '' 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){ + $sql = "SELECT T_OrderDetailPrice, + T_OrderDetailDisc, + T_OrderDetailDiscAmount, + T_OrderDetailDiscTotal, + T_OrderDetailTotal + FROM t_orderdetail + WHERE T_OrderDetailT_OrderDetailOrderID = ? AND T_OrderDetailIsActive = 'Y' + GROUP BY T_OrderDetailT_OrderDetailOrderID"; + $query = $this->db_smartone->query($sql, [$value['d_id']]); + if (!$query) { + $return['status'] = false; + $return['message'] = "Terjadi kesalahan saat mengambil data detail order"; + $dt_log = ['data' => $value['d_id'],'error' => $this->db_smartone->error()]; + $prm_log = ['SELECT_T_ORDERDETAIL', 'order/get_order_detail']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $return['data'] = []; + return $return; + } + $data_price = $query->row_array(); + $value['t_price'] = $data_price['T_OrderDetailPrice']; + $value['t_disc'] = $data_price['T_OrderDetailDisc']; + $value['t_discamount'] = $data_price['T_OrderDetailDiscAmount']; + $value['t_disctotal'] = $data_price['T_OrderDetailDiscTotal']; + $value['t_total'] = $data_price['T_OrderDetailTotal']; + $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_detail($details,$header_id,$userid){ + $return = [ + "status" => true, + "message" => "", + "data" => [] + ]; + + $sql = "SELECT T_OrderDetailOrderID as d_oid, + T_OrderDetailOrderT_TestID as d_otid, + T_OrderDetailOrderIsPacket as d_oispacket, + T_OrderDetailOrderT_PacketID as d_opacketid + FROM t_orderdetailorder + WHERE + T_OrderDetailOrderT_OrderHeaderID = ? AND + T_OrderDetailOrderIsActive = 'Y'"; + $query = $this->db_smartone->query($sql, [$header_id]); + if(!$query){ + $this->sys_error_db(["status" => "ERR", "message" => "error select t_orderdetailorder | " . $this->db_smartone->error()["message"], "debug" => $this->db_smartone->last_query()]); + exit; + } + + $orderdetailorders = $query->result_array(); + if(count($orderdetailorders) == 0){ + $this->insert_log_error($this->db_smartone->last_query(), ['ORDERDETAILORDER_NOT_FOUND', 'order/save_order_detail'], array( + 'orderdetailorders' => $orderdetailorders, + 'details' => $details, + 'header_id' => $header_id, + 'userid' => $userid + )); + $return['status'] = false; + $return['message'] = "Data detail order tidak ditemukan"; + return $return; + exit; + } + + $tests = []; + foreach($details as $k => $v){ + $detail_order = []; + foreach($orderdetailorders as $orderdetailorder){ + if(($orderdetailorder['d_oispacket'] == 'N' && intval($orderdetailorder['d_otid']) == intval($v['t_id'])) || + ($orderdetailorder['d_oispacket'] == 'Y' && intval($orderdetailorder['d_opacketid']) == intval($v['t_packetid']))){ + $detail_order = $orderdetailorder; + break; + } + } + + $detail_order_id = $detail_order['d_oid']; + $insert_order_detail = $this->insert_order_detail($header_id, $detail_order_id, $v, $userid); + + if(!$insert_order_detail['status']){ + //print_r($this->insert_order_detail); + $message = $this->insert_order_detail['message'] ?? 'Terjadi kesalahan saat menyimpan data order detail'; + $this->sys_error($message); + exit; + } + } + + return $return; + } + + function insert_order_detail($header_id, $detail_order_id, $detail,$userid) + { + // Buat array untuk informasi error/success + $result = [ + 'status' => true, + 'message' => 'Success', + 'test_name' => isset($detail['t_name']) ? $detail['t_name'] : '', + 'test_id' => isset($detail['t_id']) ? $detail['t_id'] : '', + 'test_code' => '', + 'error_type' => '', + 'error_detail' => [] + ]; + + // Cek data test + $sql = "SELECT * FROM t_test WHERE T_TestID = ? AND T_TestIsActive = 'Y' LIMIT 1"; + $query = $this->db_smartone->query($sql, $detail['t_id']); + + if (!$query) { + $this->insert_log_error($this->db_smartone->last_query(), ['DB_QUERY_ERROR_GET_TEST', 'order/save_order_detail'], array( + 'test' => $detail['t_name'], + 'detail' => $detail + )); + $result['status'] = false; + $result['message'] = 'Terjadi kesalahan saat mengambil data test '.$detail['t_name'].' | '.$this->db_smartone->error()["message"]; + $result['error_type'] = 'DB_QUERY_ERROR'; + + return $result; + } + + $rows_test = $query->result_array(); + if(count($rows_test) == 0){ + $this->insert_log_error($this->db_smartone->last_query(), ['TEST_NOT_FOUND', 'order/save_order_detail'], array( + 'test' => $detail['t_name'], + 'detail' => $detail + )); + $result['status'] = false; + $result['message'] = 'Test tidak ditemukan'; + $result['error_type'] = 'TEST_NOT_FOUND IN ORDER DETAIL'; + return $result; + } + if (count($rows_test) == 0) { + $result['status'] = false; + $result['message'] = 'Test tidak ditemukan'; + $result['error_type'] = 'TEST_NOT_FOUND'; + $this->insert_log_error($this->db_smartone->last_query(), ['SELECT_T_TEST', 'order/save_order_detail'], array( + 'test' => $detail['t_name'], + 'detail' => $detail + )); + 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']; + + $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"; + $query = $this->db_smartone->query($sql, $detail['t_id']); + if(!$query){ + $this->insert_log_error($this->db_smartone->last_query(), ['SELECT_NAT_UNIT', 'order/save_order_detail'], array( + 'test' => $detail['t_name'], + 'detail' => $detail + )); + $result['status'] = false; + $result['message'] = 'Unit tidak ditemukan'; + $result['error_type'] = 'NAT_UNIT_NOT_FOUND'; + return $result; + } + $dt_unit = $query->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'], + $detail['t_cito'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 : $detail['t_amount'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 :$detail['t_amount'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 : $detail['t_discount'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 : $detail['t_discount_rp'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 : $detail['t_subtotal'], + $dt_test['T_TestIsPrice'] == 'N' ? 0 : $detail['t_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'] = false; + $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, array('test' => $dt_test,'orderdetail_order_id' => $detail_order_id) ); + 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'] = false; + $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']); + 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'] = false; + $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']); + return $result; + } + } + } + + // 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' => [] + ]; + + $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']; + 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); + $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) { + $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 + ]; + + 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; + } + } + } + + return $result; + } + + function generate_location($header_id,$userid) + { + $result = [ + 'status' => true, + 'message' => 'Success', + 'error_type' => '', + 'error_detail' => [] + ]; + + + $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); + + $data_samples = $qry->result_array(); + foreach ($data_samples as $k => $v) { + $sample_id = $v['T_SampleStationID']; + $sql = "SELECT M_LocationID as loc_id + FROM m_location + WHERE M_LocationT_SampleStationID = ? + ORDER BY M_LocationPriority DESC, M_LocationID ASC + LIMIT 1"; + $qry = $this->db_smartone->query($sql, $sample_id); + if (!$qry) { + $result['status'] = false; + $result['message'] = 'Terjadi kesalahan saat mengambil data lokasi ' . $v['T_SampleStationName']; + $result['error_type'] = 'LOCATION_QUERY_ERROR'; + $result['error_detail'] = [ + 'sql_error' => $this->db_smartone->error(), + 'last_query' => $this->db_smartone->last_query() + ]; + $prm_log = ['SELECT_LOCATION', 'order/generate_location']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log); + //$this->db_smartone->trans_rollback(); + return $result; + } + $loc_id = $qry->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(),?)"; + $prm_orderlocation = [ + $header_id, + $loc_id, + $sample_id, + $userid + ]; + $qry = $this->db_smartone->query($sql, $prm_orderlocation); + if (!$qry) { + $result['status'] = false; + $result['message'] = 'Terjadi kesalahan saat menyimpan data lokasi'; + $result['error_type'] = 'ORDER_LOCATION_INSERT_ERROR'; + $result['error_detail'] = [ + 'sql_error' => $this->db_smartone->error(), + 'last_query' => $this->db_smartone->last_query() + ]; + $prm_log = ['INSERT_T_ORDERLOCATION', 'order/generate_location']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log); + //$this->db_smartone->trans_rollback(); + return $result; + } + + //file_get_contents("http://127.0.0.1:9088/broadcast/sm.new." . $sample_id . "." . $mcuid . "." . $branch_id); + } + + return $result; + } + + 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' => [] + ]; + + if(count($deliveries) > 0){ + foreach($deliveries as $key => $value){ + if($value['chex'] == 'Y'){ + $sql = "INSERT INTO t_orderdelivery( + T_OrderDeliveryT_OrderHeaderID, + T_OrderDeliveryM_DeliveryTypeID, + T_OrderDeliveryM_DeliveryID, + T_OrderDeliveryDestination, + T_OrderDeliveryNote, + T_OrderDeliveryCreated, + T_OrderDeliveryCreatedUserID + ) VALUES (?,?,?,?,?,NOW(),?)"; + $query = $this->db_smartone->query($sql, [ + $header_id, + $value['delivery_type'], + $value['delivery_id'], + $value['description'], + $value['note'], + $userid + ]); + if(!$query){ + $result['status'] = false; + $result['message'] = 'Terjadi kesalahan saat menyimpan data delivery'; + $result['error_type'] = 'INSERT_ORDER_DELIVERY_ERROR'; + $result['error_detail'] = [ + 'sql_error' => $this->db_smartone->error(), + 'last_query' => $this->db_smartone->last_query() + ]; + $prm_log = ['INSERT_ORDER_DELIVERY', 'order/save_delivery']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, ['delivery' => $value]); + return $result; + } + } + } + } + + 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_smartone->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_smartone->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, + concat(if(M_TitleID is null, '', concat(M_TitleName, ' ')),IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) as patient_name, + 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(); + //echo $this->db_smartone->last_query(); + return $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); + } 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') { + $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(M_PatientEmail,'Belum ada email 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 = '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(M_PatientEmail,'Belum ada email 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 = '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(M_PatientHP,'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; + $data_mou = $this->db_smartone->query($sql)->row_array(); + //print_r($data_mou); + $sql = " + SELECT 0 as kelurahan, + M_CompanyAddressRegionalCd 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 perusahaan', 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 agreement', 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 pengirim',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(); + //print_r($row_company); + $rst['selected_company'] = $row_company; + $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_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'; + 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; + }*/ + $sql = "SELECT * FROM mgm_mcudelivery + WHERE Mgm_McuDeliveryMgm_McuID = {$row_header['Mgm_McuID']} AND Mgm_McuDeliveryM_DeliveryID = {$v_ordev['delivery_id']} AND + Mgm_McuDeliveryAddressID = {$v_ordev['address_id']} AND Mgm_McuDeliveryIsActive = 'Y'"; + $check_centang_dev = $this->db_smartone->query($sql)->result_array(); + if (count($check_centang_dev) > 0) { + $rst['data_deliveries'][$k_ordev]['chex'] = 'Y'; + } + } + + + $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' ORDER BY M_ReferenceName ASC"; + $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; + } + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Patient.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Patient.php new file mode 100644 index 0000000..8210209 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Patient.php @@ -0,0 +1,974 @@ +sys_debug(); + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + + } + */ + +class Patient extends MY_Controller +{ + var $db_smartone; + var $db_log; + public function index() + { + echo "Patient API"; + } + public function __construct() + { + parent::__construct(); + $this->db_smartone = $this->load->database("onedev", true); + $this->db_log = $this->load->database("cpone_log", true); + } + function _add_address(&$pat) { + if (count($pat) == "0") { + return array(); + } + foreach($pat as $idx => $p ) { + $pat[$idx]["address"] = array($p["M_PatientAddress"]); + } + $this->_add_history($pat); + } + function _add_history(&$pat) { + $pat_list = "-1"; + foreach($pat as $idx => $p) { + $pat_list .= ", " . $p["M_PatientID"]; + if (! isset($pat[$idx]["history"])) $pat[$idx]["history"] = array(); + } + $sql = "select T_OrderHeaderM_PatientID,T_OrderHeaderLabNumber,T_OrderHeaderDate, + concat(T_OrderDetailT_TestName) T_TestName + from + t_orderheader + join t_orderdetail on + T_OrderHeaderID = T_OrderDetailID and + T_OrderHeaderIsActive = 'Y' and T_OrderDetailIsActive = 'Y' + and T_OrderHeaderM_PatientID in ( $pat_list ) + join t_test on T_OrderDetailT_TestID = T_TestID + and T_TestIsPrice = 'Y' + order by T_OrderHeaderM_PatientID,T_OrderHeaderLabNumber"; + $query = $this->db_smartone->query($sql); + if ($query) { + $rows= $query->result_array(); + foreach($rows as $r) { + $patientID = $r["T_OrderHeaderM_PatientID"]; + foreach($pat as $idx => $p) { + if($p["M_PatientID"] == $patientID) { + $pat[$idx]["history"][] = $r; + } + } + } + } else { + $this->sys_error_db("m_patient history",$this->db_smartone); + exit; + } + } + + public function search() + { + $prm = $this->sys_input; + + $max_rst = 100; + $tot_count =0; + $number_limit = 10; + $number_offset = (!isset($prm['current_page'])?1:$prm['current_page'] - 1) * $number_limit ; + + $q = [ + 'noreg' => "", + 'name' => '', + 'hp' => '', + 'dob' => '', + 'address' => '' + ]; + + $search_address = ''; + + if ($prm['noreg'] != '') + $q['noreg'] = "AND M_PatientNoReg = '{$prm['noreg']}'"; + + if ($prm['search'] != '') + { + $e = explode('+', $prm['search']); + if (isset($e[0])){ + $e[0] = str_replace("'", "\\'", $e[0]); + $q['name'] = "AND M_PatientName LIKE '%{$e[0]}%'"; + } + if (isset($e[1])) + $q['hp'] = "AND ((M_PatientHP LIKE '%{$e[1]}%' and M_PatientHP IS NOT NULL) OR (M_PatientHP IS NULL AND '{$e[1]}' = ''))"; + if (isset($e[2])) + $q['dob'] = "AND ((DATE_FORMAT(M_PatientDOB, '%d-%m-%Y') LIKE '%{$e[2]}%' and M_PatientDOB IS NOT NULL) OR (M_PatientDOB IS NULL AND '{$e[2]}' = ''))"; + if (isset($e[3])) + $q['address'] = "AND M_PatientAddress LIKE '%{$e[3]}%'"; + } + + if($q['address'] == ''){ + $q['address'] = "AND M_PatientAddressNote = 'Utama'"; + } + + + $sql = "SELECT 'N' divider,M_PatientID, M_PatientNoReg,M_PatientEmail,M_PatientPrefix,M_PatientSuffix, + concat(M_TitleName,' ',IFNULL(M_PatientPrefix,''),' ',M_PatientName,' ',IFNULL(M_PatientSuffix,'')) M_PatientName, + M_PatientName M_PatientRealName, M_TitleID, M_TitleName, + IF(M_PatientGender = 'male', 'Laki-laki', 'Perempuan') M_SexName, + M_PatientHP, '' as M_PatientPOB, M_PatientDOB, DATE_FORMAT(M_PatientDOB,'%d-%m-%Y') as dob_ina, + M_PatientAddress, + '' as M_PatientAddressID, + M_PatientAddress as M_PatientAddressDescription, 'NNIDN' M_PatientIdentifierCode, + 'Nomor Induk Kependudukan (KTP)' M_PatientIdentifierDisplay, + 'http://terminology.hl7.org/CodeSystem/v2-0203' M_PatientIdentifierSystem, + M_PatientIdentifierValue M_PatientIDNumber, + M_PatientAddressRegionalCd, + '' as M_PatientAddressLocation, + M_PatientAddressCity, + M_PatientAddressRT, + M_PatientAddressRW, + M_PatientAddressVillage, + M_PatientAddressDistrict, + M_PatientAddressState, + M_PatientAddressCountry, + '' as M_PatientAddressCountryCode, + M_PatientAddOnPOB as M_PatientPOB, + IFNULL(M_PatientAddOnNote, '') M_PatientNote, + M_PatientPhoto, + M_PatientHP hp, + '' as info, + 0 as M_KelurahanID, 0 M_DistrictID, 0 M_CityID, 0 M_ProvinceID, 0 M_PatientM_ReligionID, + 'xhis.code.religion' as M_PatientReligionSystem, + M_PatientReligionCode as M_PatientReligionCode, + M_PatientReligionCode as M_PatientReligionDisplay, + M_PatientBloodTypeCode, + M_PatientBloodTypeSystem, + '' as blood_type_display, + M_PatientBloodRhCode as blood_rh_code, + 'http://loinc.org' as blood_rh_system, + '' as blood_rh_display, + M_PatientEtnicCode, + 'xhis.code.etnicity' as M_PatientEtnicSystem, + '' as etnic_display, + M_PatientCitizenship, + M_PatientEducationSystem, + M_PatientEducationCode, + M_PatientEducationCode as M_PatientEducationDisplay, + M_PatientNIP, + M_PatientJob, + M_PatientPosisi, + M_PatientDivisi, + M_PatientLocation, + M_PatientDepartement, + M_PatientRegisteredByCorporateID as corporate_id, + '' as corporate_name + FROM m_patient + JOIN m_title on M_PatientM_TitleID = M_TitleID + LEFT JOIN m_patient_addon ON M_PatientAddOnM_PatientID = M_PatientID AND M_PatientAddOnIsActive = 'Y' + WHERE + M_PatientIsActive = 'Y' + {$q['noreg']} + {$q['name']} + {$q['hp']} + {$q['dob']} + GROUP BY M_PatientID + limit $number_limit offset $number_offset"; + $query = $this->db_smartone->query($sql); + + if ($query) { + $rows = $query->result_array(); + + foreach ($rows as $k => $v) + { + $rows[$k]['M_PatientName'] = stripslashes($rows[$k]['M_PatientName']); + $rows[$k]['M_PatientAddress'] = stripslashes($rows[$k]['M_PatientAddressDescription']); + $info = $this->db_smartone->query("SELECT fn_fo_patient_visit(?) info", [$v['M_PatientID']])->row(); + $rows[$k]['info'] = json_decode($info->info); + + if($v['corporate_id'] > 0){ + $corporate = $this->db_smartone->query("SELECT CorporateName FROM corporate WHERE CorporateID = ? AND CorporateIsActive = 'Y'", [$v['corporate_id']])->row(); + $rows[$k]['corporate_name'] = $corporate->CorporateName; + } + + if($v['M_PatientBloodTypeCode']){ + $blood_type = $this->get_terminology('Patient', 'Patient.blood.type', $v['M_PatientBloodTypeCode']); + $rows[$k]['M_PatientBloodTypeCode'] = $blood_type['code']; + $rows[$k]['M_PatientBloodTypeDisplay'] = $blood_type['display']; + $rows[$k]['M_PatientBloodTypeSystem'] = $blood_type['code_system']; + } + + if($v['M_PatientBloodRhCode']){ + $blood_rh = $this->get_terminology('Patient', 'Patient.blood.rhesus', $v['M_PatientBloodRhCode']); + $rows[$k]['M_PatientBloodRhCode'] = $blood_rh['code']; + $rows[$k]['M_PatientBloodRhDisplay'] = $blood_rh['display']; + $rows[$k]['M_PatientBloodRhSystem'] = $blood_rh['code_system']; + } + + if($v['M_PatientEtnicCode']){ + $etnic = $this->get_terminology('Patient', 'Patient.etnicity', $v['M_PatientEtnicCode']); + $rows[$k]['M_PatientEtnicCode'] = $etnic['code']; + $rows[$k]['M_PatientEtnicDisplay'] = $etnic['display']; + $rows[$k]['M_PatientEtnicSystem'] = $etnic['code_system']; + } + + if($v['M_PatientEducationCode']){ + $education = $this->get_terminology('Person', 'Person.education', $v['M_PatientEducationCode']); + $rows[$k]['M_PatientEducationCode'] = $education['code']; + $rows[$k]['M_PatientEducationDisplay'] = $education['display']; + $rows[$k]['M_PatientEducationSystem'] = $education['code_system']; + } + + if($v['M_PatientReligionCode']){ + $religion = $this->get_terminology('Patient', 'Patient.religion.code', $v['M_PatientReligionCode']); + $rows[$k]['M_PatientReligionCode'] = $religion['code']; + $rows[$k]['M_PatientReligionDisplay'] = $religion['display']; + $rows[$k]['M_PatientReligionSystem'] = $religion['code_system']; + } + } + + $result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_smartone->last_query()); + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_patient rows",$this->db_smartone); + exit; + } + + + } + + function get_terminology($resource_type, $attribute_path, $code){ + $params = []; + $filter_where = ''; + $filter_resource_type = ''; + if(!$resource_type){ + $filter_resource_type = "resource_type = ?"; + if($filter_where != ''){ + $filter_where .= " AND "; + }else{ + $filter_where .= " WHERE "; + } + $filter_where .= $filter_resource_type; + $params[] = $resource_type; + } + + $filter_attribute_path = ''; + if(!$attribute_path){ + $filter_attribute_path = "attribute_path = ?"; + if($filter_where != ''){ + $filter_where .= " AND "; + }else{ + $filter_where .= " WHERE "; + } + $filter_where .= $filter_attribute_path; + $params[] = $attribute_path; + } + + $filter_code = ''; + if(!$code){ + $filter_code = "code = ?"; + if($filter_where != ''){ + $filter_where .= " AND "; + }else{ + $filter_where .= " WHERE "; + } + $filter_where .= $filter_code; + $params[] = $code; + } + + + + $sql = "SELECT * FROM terminology {$filter_where} limit 1"; + $query = $this->db_smartone->query($sql, $params); + if ($query) { + $row = $query->row_array(); + return $row; + } + else { + return null; + } + } + + + function add_new() + { + $userid = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + + /* + TABLE STRUCTURE : + CREATE TABLE `m_patient` ( + `M_PatientID` int NOT NULL AUTO_INCREMENT, + `M_PatientRegisteredByCorporateID` int NOT NULL DEFAULT '0', + `M_PatientOldPID` varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `M_PatientNoReg` varchar(50) NOT NULL DEFAULT '', + `M_PatientM_TitleID` int NOT NULL DEFAULT '0', + `M_PatientPrefix` varchar(50) NOT NULL DEFAULT '', + `M_PatientName` varchar(255) NOT NULL DEFAULT '', + `M_PatientSuffix` varchar(50) NOT NULL DEFAULT '', + `M_PatientGender` char(10) NOT NULL DEFAULT '' COMMENT 'male, female', + `M_PatientDOB` date NOT NULL DEFAULT '0000-00-00', + `M_PatientReligionCode` varchar(50) NOT NULL DEFAULT '', + `M_PatientReligionSystem` varchar(100) NOT NULL DEFAULT '', + `M_PatientBloodTypeCode` varchar(50) NOT NULL DEFAULT '', + `M_PatientBloodTypeSystem` varchar(100) NOT NULL DEFAULT '', + `M_PatientBloodRhCode` varchar(50) NOT NULL DEFAULT '', + `M_PatientBloodRhSystem` varchar(100) NOT NULL DEFAULT '', + `M_PatientEducationCode` varchar(50) NOT NULL DEFAULT '', + `M_PatientEducationSystem` varchar(100) NOT NULL DEFAULT '', + `M_PatientCitizenship` char(3) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'WNI' COMMENT 'WNI, WNA', + `M_PatientEtnicCode` varchar(50) NOT NULL DEFAULT '', + `M_PatientEtnicSystem` varchar(100) NOT NULL DEFAULT '', + `M_PatientIdentifierCode` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'NNIDN', + `M_PatientIdentifierSystem` varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'http://terminology.hl7.org/CodeSystem/v2-0203', + `M_PatientIdentifierValue` varchar(50) NOT NULL DEFAULT '', + `M_PatientNIP` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, + `M_PatientJob` varchar(255) NOT NULL DEFAULT '', + `M_PatientPosisi` varchar(255) NOT NULL DEFAULT '', + `M_PatientDivisi` varchar(255) NOT NULL DEFAULT '', + `M_PatientLocation` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `M_PatientDepartement` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `M_PatientHp` varchar(50) NOT NULL DEFAULT '', + `M_PatientEmail` varchar(50) NOT NULL DEFAULT '', + `M_PatientPhoto` varchar(255) NOT NULL DEFAULT '', + `M_PatientPhotoThumb` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `M_PatientPhotoCounter` tinyint NOT NULL DEFAULT '0', + `M_PatientPhotoLastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `M_PatientPhotoLastUpdatedUserID` int NOT NULL DEFAULT '0', + `M_PatientAddress` text NOT NULL, + `M_PatientAddressRegionalCd` varchar(50) NOT NULL DEFAULT '', + `M_PatientAddressCity` varchar(255) NOT NULL DEFAULT '', + `M_PatientAddressRT` varchar(50) NOT NULL DEFAULT '', + `M_PatientAddressRW` varchar(50) NOT NULL DEFAULT '', + `M_PatientAddressVillage` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `M_PatientAddressDistrict` varchar(255) NOT NULL DEFAULT '', + `M_PatientAddressState` varchar(255) NOT NULL DEFAULT '', + `M_PatientAddressCountry` varchar(255) NOT NULL DEFAULT '', + `M_PatientIsActive` char(1) NOT NULL DEFAULT 'Y', + `M_PatientCreated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `M_PatientCreatedUserID` int NOT NULL DEFAULT '0', + `M_PatientLastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `M_PatientLastUpdatedUserID` int NOT NULL DEFAULT '0', + `M_PatientDeletedUserID` int NOT NULL DEFAULT '0', + `M_PatientDeleted` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`M_PatientID`), + UNIQUE KEY `M_PatientNoRegUnik` (`M_PatientNoReg`), + KEY `M_PatientM_TitleID` (`M_PatientM_TitleID`), + KEY `M_PatientNoReg` (`M_PatientNoReg`), + KEY `M_PatientIdentifierValue` (`M_PatientIdentifierValue`), + KEY `M_PatientIdentifierCode` (`M_PatientIdentifierCode`), + KEY `M_PatientNIP` (`M_PatientNIP`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1; + + SELECT `fn_numbering_cpone`('PATIENT') AS M_PatientNoReg + + payload: + { + "M_PatientName": "fdsfsdf", + "M_PatientM_TitleID": "2", + "M_PatientPrefix": "", + "M_PatientSuffix": "", + "M_PatientGender": { + "id": "male", + "name": "Laki-laki" + }, + "M_PatientPOB": "fsdfdsf", + "M_PatientDOB": "21-12-2002", + "M_PatientHP": "-", + "M_PatientEmail": "", + "M_PatientIdentifierCode": "NNIDN", + "M_PatientIDNumber": "", + "M_PatientAddressDescription": "RT 04 RW 02 Desa Hayam Wuruk", + "M_PatientAddressCountryCode": "ID", + "M_PatientAddressCountry": "Indonesia", + "M_PatientAddressRegionalCd": "3209181005", + "M_PatientAddressLocation": "3209181005", + "M_PatientAddressCity": "Kab. Cirebon", + "M_PatientAddressVillage": "Muara", + "M_PatientAddressDistrict": "Suranenggala", + "M_PatientAddressState": "Jawa Barat", + "M_PatientAddressID": 0, + "M_PatientRegisteredByCorporateID": 0, + "M_PatientNIP": "", + "M_PatientJob": "", + "M_PatientPosisi": "", + "M_PatientDivisi": "", + "M_PatientLocation": "", + "M_PatientDepartement": "", + "M_PatientBloodTypeCode": "LA19710-5", + "M_PatientBloodTypeSystem": "http://loinc.org", + "M_PatientBloodRhCode": "LA6576-8", + "M_PatientBloodRhSystem": "http://loinc.org", + "M_PatientEducationCode": "D3", + "M_PatientEducationSystem": "xhis.code.education.level", + "M_PatientEtnicCode": "Ternate", + "M_PatientEtnicSystem": "xhis.code.etnicity", + "use": true, + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJNX1VzZXJJRCI6IjIiLCJNX1VzZXJFbWFpbCI6Impva29AZ21haWwuY29tIiwiTV9Vc2VyVXNlcm5hbWUiOiJqb2tvQGdtYWlsLmNvbSIsIk1fVXNlckdyb3VwRGFzaGJvYXJkIjoib25lLXVpXC90ZXN0XC92dWV4XC9vbmUtbWQtdXNlcmdyb3VwLXVzZXItdjVcLyIsIk1fVXNlckRlZmF1bHRUX1NhbXBsZVN0YXRpb25JRCI6IjEiLCJNX1N0YWZmTmFtZSI6IkFkbWluIENQT05FIiwiaXNfY291cmllciI6Ik4iLCJNX0JyYW5jaElEIjoiMTIiLCJNX0JyYW5jaE5hbWUiOiJXZXN0ZXJpbmRvIEJhbmR1bmciLCJ0aW1lX2F1dG9sb2dvdXQiOiIxNSIsImlwIjoiMTI4LjE5OS44Ni43IiwiYWdlbnQiOiJHby1odHRwLWNsaWVudFwvMS4xIiwidmVyc2lvbiI6InYyIiwibGFzdC1sb2dpbiI6IjIwMjUtMTItMDMgMDk6MTA6NDAifQ.xs2k-8gG8utuYKD8hswFbTJttDumxwikGfF_o61geSA" + } + + CREATE TABLE `log_patient` ( + `Log_PatientID` int NOT NULL AUTO_INCREMENT, + `Log_PatientM_PatientID` int NOT NULL DEFAULT '0', + `Log_PatientDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `Log_PatientCode` varchar(25) NOT NULL DEFAULT '' COMMENT 'ADD, EDIT, DELETE', + `Log_PatientJsonBefore` text, + `Log_PatientJsonAfter` text, + `Log_PatientUserID` int NOT NULL DEFAULT '0', + PRIMARY KEY (`Log_PatientID`), + KEY `Log_PatientDate` (`Log_PatientDate`), + KEY `Log_PatientCode` (`Log_PatientCode`), + KEY `Log_PatientUserID` (`Log_PatientUserID`), + KEY `Log_PatientM_PatientID` (`Log_PatientM_PatientID`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + + */ + + $this->db_smartone->trans_begin(); + + $sql = "SELECT `fn_numbering_cpone`('P') AS M_PatientNoReg"; + $query = $this->db_smartone->query($sql); + if(!$query){ + $this->db_smartone->trans_rollback(); + $this->sys_error_db("Failed to get M_PatientNoReg"); + exit; + } + $row = $query->row_array(); + $M_PatientNoReg = $row['M_PatientNoReg']; + + // Prepare patient data + $M_PatientTitleID = isset($prm['M_PatientM_TitleID']) ? $prm['M_PatientM_TitleID'] : 0; + if($M_PatientTitleID == 0) { + $this->db_smartone->trans_rollback(); + $this->sys_error_db("M_PatientM_TitleID is required"); + exit; + } + $M_PatientPrefix = isset($prm['M_PatientPrefix']) ? $prm['M_PatientPrefix'] : ''; + $M_PatientSuffix = isset($prm['M_PatientSuffix']) ? $prm['M_PatientSuffix'] : ''; + $M_PatientRegisteredByCorporateID = isset($prm['M_PatientRegisteredByCorporateID']) ? $prm['M_PatientRegisteredByCorporateID'] : 0; + + // Handle DOB conversion + $M_PatientDOB = isset($prm['M_PatientDOB']) && $prm['M_PatientDOB'] != '' ? date('Y-m-d', strtotime($prm['M_PatientDOB'])) : '0000-00-00'; + + // Handle Gender - can be object or string + $M_PatientGender = ''; + + if(isset($prm['M_PatientGender']) && $prm['M_PatientGender'] != '') { + $M_PatientGender = $prm['M_PatientGender']['id']; + }else{ + $this->db_smartone->trans_rollback(); + $this->sys_error_db("M_PatientGender is required"); + exit; + } + // Handle Religion + $M_PatientReligionCode = isset($prm['M_PatientReligionCode']) ? $prm['M_PatientReligionCode'] : ''; + $M_PatientReligionSystem = isset($prm['M_PatientReligionSystem']) ? $prm['M_PatientReligionSystem'] : 'xhis.code.religion'; + + // Handle Identifier + $M_PatientIdentifierCode = isset($prm['M_PatientIdentifierCode']) ? $prm['M_PatientIdentifierCode'] : 'NNIDN'; + $M_PatientIdentifierSystem = isset($prm['M_PatientIdentifierSystem']) ? $prm['M_PatientIdentifierSystem'] : 'http://terminology.hl7.org/CodeSystem/v2-0203'; + $M_PatientIdentifierValue = isset($prm['M_PatientIDNumber']) ? $prm['M_PatientIDNumber'] : ''; + + // Sanitize patient name + $M_PatientName = isset($prm['M_PatientName']) ? str_replace("'", "\\'", $prm['M_PatientName']) : ''; + if($M_PatientName == '') { + $this->db_smartone->trans_rollback(); + $this->sys_error_db("M_PatientName is required"); + exit; + } + + // Prepare address description for m_patient table + $M_PatientAddress = isset($prm['M_PatientAddressDescription']) ? str_replace("'", "\\'", $prm['M_PatientAddressDescription']) : ''; + if($M_PatientAddress == '') { + $this->db_smartone->trans_rollback(); + $this->sys_error_db("M_PatientAddressDescription is required"); + exit; + } + + $M_PatientPOB = isset($prm['M_PatientPOB']) ? str_replace("'", "\\'", $prm['M_PatientPOB']) : ''; + if($M_PatientPOB == '') { + $this->db_smartone->trans_rollback(); + $this->sys_error_db("M_PatientPOB is required"); + exit; + } + + $M_PatientRegisteredByCorporateID = isset($prm['M_PatientRegisteredByCorporateID']) ? $prm['M_PatientRegisteredByCorporateID'] : 0; + + // Build patient data array + $ptn = [ + 'M_PatientRegisteredByCorporateID' => $M_PatientRegisteredByCorporateID, + 'M_PatientOldPID' => isset($prm['M_PatientOldPID']) ? $prm['M_PatientOldPID'] : '', + 'M_PatientNoReg' => $M_PatientNoReg, + 'M_PatientM_TitleID' => $M_PatientTitleID, + 'M_PatientPrefix' => $M_PatientPrefix, + 'M_PatientName' => $M_PatientName, + 'M_PatientSuffix' => $M_PatientSuffix, + 'M_PatientGender' => $M_PatientGender, + 'M_PatientDOB' => $M_PatientDOB, + 'M_PatientReligionCode' => $M_PatientReligionCode, + 'M_PatientReligionSystem' => $M_PatientReligionSystem, + 'M_PatientBloodTypeCode' => isset($prm['M_PatientBloodTypeCode']) ? $prm['M_PatientBloodTypeCode'] : '', + 'M_PatientBloodTypeSystem' => isset($prm['M_PatientBloodTypeSystem']) ? $prm['M_PatientBloodTypeSystem'] : '', + 'M_PatientBloodRhCode' => isset($prm['M_PatientBloodRhCode']) ? $prm['M_PatientBloodRhCode'] : '', + 'M_PatientBloodRhSystem' => isset($prm['M_PatientBloodRhSystem']) ? $prm['M_PatientBloodRhSystem'] : '', + 'M_PatientEducationCode' => isset($prm['M_PatientEducationCode']) ? $prm['M_PatientEducationCode'] : '', + 'M_PatientEducationSystem' => isset($prm['M_PatientEducationSystem']) ? $prm['M_PatientEducationSystem'] : '', + 'M_PatientCitizenship' => isset($prm['M_PatientCitizenship']) ? $prm['M_PatientCitizenship'] : 'WNI', + 'M_PatientEtnicCode' => isset($prm['M_PatientEtnicCode']) ? $prm['M_PatientEtnicCode'] : '', + 'M_PatientEtnicSystem' => isset($prm['M_PatientEtnicSystem']) ? $prm['M_PatientEtnicSystem'] : '', + 'M_PatientIdentifierCode' => $M_PatientIdentifierCode, + 'M_PatientIdentifierSystem' => $M_PatientIdentifierSystem, + 'M_PatientIdentifierValue' => $M_PatientIdentifierValue, + 'M_PatientNIP' => isset($prm['M_PatientNIP']) ? $prm['M_PatientNIP'] : '', + 'M_PatientJob' => isset($prm['M_PatientJob']) ? $prm['M_PatientJob'] : '', + 'M_PatientPosisi' => isset($prm['M_PatientPosisi']) ? $prm['M_PatientPosisi'] : '', + 'M_PatientDivisi' => isset($prm['M_PatientDivisi']) ? $prm['M_PatientDivisi'] : '', + 'M_PatientLocation' => isset($prm['M_PatientLocation']) ? $prm['M_PatientLocation'] : '', + 'M_PatientDepartement' => isset($prm['M_PatientDepartement']) ? $prm['M_PatientDepartement'] : '', + 'M_PatientHp' => isset($prm['M_PatientHP']) ? $prm['M_PatientHP'] : '', + 'M_PatientEmail' => isset($prm['M_PatientEmail']) ? $prm['M_PatientEmail'] : '', + 'M_PatientPhoto' => isset($prm['M_PatientPhoto']) ? $prm['M_PatientPhoto'] : '', + 'M_PatientPhotoThumb' => isset($prm['M_PatientPhotoThumb']) ? $prm['M_PatientPhotoThumb'] : '', + 'M_PatientPhotoCounter' => isset($prm['M_PatientPhotoCounter']) ? $prm['M_PatientPhotoCounter'] : 0, + 'M_PatientPhotoLastUpdated' => isset($prm['M_PatientPhotoLastUpdated']) ? $prm['M_PatientPhotoLastUpdated'] : '0000-00-00 00:00:00', + 'M_PatientPhotoLastUpdatedUserID' => isset($prm['M_PatientPhotoLastUpdatedUserID']) ? $prm['M_PatientPhotoLastUpdatedUserID'] : 0, + 'M_PatientAddress' => $M_PatientAddress, + 'M_PatientAddressRegionalCd' => isset($prm['M_PatientAddressRegionalCd']) ? $prm['M_PatientAddressRegionalCd'] : '', + 'M_PatientAddressCity' => isset($prm['M_PatientAddressCity']) ? $prm['M_PatientAddressCity'] : '', + 'M_PatientAddressRT' => isset($prm['M_PatientAddressRT']) ? $prm['M_PatientAddressRT'] : '', + 'M_PatientAddressRW' => isset($prm['M_PatientAddressRW']) ? $prm['M_PatientAddressRW'] : '', + 'M_PatientAddressVillage' => isset($prm['M_PatientAddressVillage']) ? $prm['M_PatientAddressVillage'] : '', + 'M_PatientAddressDistrict' => isset($prm['M_PatientAddressDistrict']) ? $prm['M_PatientAddressDistrict'] : '', + 'M_PatientAddressState' => isset($prm['M_PatientAddressState']) ? $prm['M_PatientAddressState'] : '', + 'M_PatientAddressCountry' => isset($prm['M_PatientAddressCountry']) ? $prm['M_PatientAddressCountry'] : '', + 'M_PatientNIP' => isset($prm['M_PatientNIP']) ? $prm['M_PatientNIP'] : '', + 'M_PatientJob' => isset($prm['M_PatientJob']) ? $prm['M_PatientJob'] : '', + 'M_PatientPosisi' => isset($prm['M_PatientPosisi']) ? $prm['M_PatientPosisi'] : '', + 'M_PatientDivisi' => isset($prm['M_PatientDivisi']) ? $prm['M_PatientDivisi'] : '', + 'M_PatientLocation' => isset($prm['M_PatientLocation']) ? $prm['M_PatientLocation'] : '', + 'M_PatientDepartement' => isset($prm['M_PatientDepartement']) ? $prm['M_PatientDepartement'] : '', + 'M_PatientBloodTypeCode' => isset($prm['M_PatientBloodTypeCode']) ? $prm['M_PatientBloodTypeCode'] : '', + 'M_PatientBloodTypeSystem' => isset($prm['M_PatientBloodTypeSystem']) ? $prm['M_PatientBloodTypeSystem'] : '', + 'M_PatientBloodRhCode' => isset($prm['M_PatientBloodRhCode']) ? $prm['M_PatientBloodRhCode'] : '', + 'M_PatientBloodRhSystem' => isset($prm['M_PatientBloodRhSystem']) ? $prm['M_PatientBloodRhSystem'] : '', + 'M_PatientEducationCode' => isset($prm['M_PatientEducationCode']) ? $prm['M_PatientEducationCode'] : '', + 'M_PatientEducationSystem' => isset($prm['M_PatientEducationSystem']) ? $prm['M_PatientEducationSystem'] : '', + 'M_PatientEtnicCode' => isset($prm['M_PatientEtnicCode']) ? $prm['M_PatientEtnicCode'] : '', + 'M_PatientEtnicSystem' => isset($prm['M_PatientEtnicSystem']) ? $prm['M_PatientEtnicSystem'] : '', + 'M_PatientCitizenship' => isset($prm['M_PatientCitizenship']) ? $prm['M_PatientCitizenship'] : 'WNI', + 'M_PatientIsActive' => 'Y', + 'M_PatientCreated' => date('Y-m-d H:i:s'), + 'M_PatientCreatedUserID' => $userid, + 'M_PatientLastUpdated' => date('Y-m-d H:i:s'), + 'M_PatientLastUpdatedUserID' => $userid, + 'M_PatientDeletedUserID' => 0, + 'M_PatientDeleted' => '0000-00-00 00:00:00' + ]; + + $this->db_smartone->insert('m_patient', $ptn); + + $err = $this->db_smartone->error(); + if ( $err['message'] != "" ) + { + $this->db_smartone->trans_rollback(); + $this->sys_error_db("m_patient rows", $this->db_smartone); + return; + } + + $id = $this->db_smartone->insert_id(); + + // LOG FO + $ptn_log = json_encode($ptn); + // $this->db_smartone->query("CALL one_log.log_me('FO', 'FO.PATIENT.ADD', '{$ptn_log}', '0')"); + + // Insert log to log_patient table + $log_data = [ + 'Log_PatientM_PatientID' => $id, + 'Log_PatientDate' => date('Y-m-d H:i:s'), + 'Log_PatientCode' => 'ADD', + 'Log_PatientJsonBefore' => null, + 'Log_PatientJsonAfter' => $ptn_log, + 'Log_PatientUserID' => $userid + ]; + $this->db_log->insert('log_patient', $log_data); + $err_log = $this->db_log->error(); + if ( $err_log['message'] != "" ) + { + // Log error but don't fail the transaction + error_log("Failed to insert log_patient: " . $err_log['message']); + } + + // Commit transaction if all operations succeed + $this->db_smartone->trans_commit(); + + // get + $r = $this->db_smartone->where('M_PatientID', $id) + ->get('m_patient') + ->row(); + + $rst = array("id" => $id, 'noreg'=>$r->M_PatientNoReg); + $this->sys_ok($rst); + } + + function edit() + { + $prm = $this->sys_input; + $userid = $this->sys_user["M_UserID"]; + $prm['M_PatientDOB'] = date('Y-m-d', strtotime($prm['M_PatientDOB'])); + $patient_name = str_replace("'", "\\'", $prm['M_PatientName']); + + $this->db_smartone->set('M_PatientName', $patient_name) + ->set('M_PatientM_TitleID', $prm['M_PatientM_TitleID']) + ->set('M_PatientPrefix', $prm['M_PatientPrefix']) + ->set('M_PatientSuffix', $prm['M_PatientSuffix']) + ->set('M_PatientM_SexID', $prm['M_PatientM_SexID']) + ->set('M_PatientM_ReligionID', $prm['M_PatientM_ReligionID']) + ->set('M_PatientDOB', $prm['M_PatientDOB']) + ->set('M_PatientPOB', $prm['M_PatientPOB']) + ->set('M_PatientHP', $prm['M_PatientHP']) + ->set('M_PatientPhone', $prm['M_PatientPhone']) + ->set('M_PatientEmail', $prm['M_PatientEmail']) + ->set('M_PatientM_IdTypeID', $prm['M_PatientM_IdTypeID']) + ->set('M_PatientIDNumber', $prm['M_PatientIDNumber']) + ->set('M_PatientNote', $prm['M_PatientNote']) + ->set('M_PatientUserID', $userid) + ->set('M_PatientLastUpdatedUserID', $userid) + ->where('M_PatientID', $prm['id']) + ->update('m_patient'); + + $err = $this->db_smartone->error(); + if ( $err['message'] != "" ) + { + $this->sys_error_db("m_patient rows", $this->db_smartone); + return; + } + + $id = $prm['id']; + + // LOG FO + unset($prm['token']); + $ptn = json_encode($prm); + $id_address = isset($prm['M_PatientAddressID']) && $prm['M_PatientAddressID'] > 0 ? $prm['M_PatientAddressID']:0; + + $address_description = str_replace("'", "\\'", $prm['M_PatientAddressDescription']); + $this->db_smartone->set('M_PatientAddressRegionalCd', $prm['M_PatientAddressRegionalCd']) + ->set('M_PatientAddressLocation', $prm['M_PatientAddressLocation']) + ->set('M_PatientAddressCity', $prm['M_PatientAddressCity']) + ->set('M_PatientAddressVillage', $prm['M_PatientAddressVillage']) + ->set('M_PatientAddressDistrict', $prm['M_PatientAddressDistrict']) + ->set('M_PatientAddressState', $prm['M_PatientAddressState']) + ->set('M_PatientAddressCountry', $prm['M_PatientAddressCountry']) + ->set('M_PatientAddressCountryCode', $prm['M_PatientAddressCountryCode']) + ->set('M_PatientAddressDescription', $address_description ) + ->set('M_PatientAddressUserID', $userid ) + ->set('M_PatientAddressLastUpdatedUserID', $userid) + ->where('M_PatientAddressID', $id_address) + ->update('m_patientaddress'); + + $err = $this->db_smartone->error(); + if ( $err['message'] != "" ) + { + $this->sys_error_db("m_patientaddress rows", $this->db_smartone); + return; + } + // echo $this->db_smartone->last_query(); + + // LOG FO + + //$this->db_smartone->query("CALL one_log.log_me('FO', 'FO.PATIENT.ADDRESS.EDIT', '{$add}', '0')"); + + // get + $r = $this->db_smartone->where('M_PatientID', $id) + ->get('m_patient') + ->row(); + + $rst = array("id" => $id, 'noreg'=>$r->M_PatientNoReg); + $this->sys_ok($rst); + } + + + public function search_idtype() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + $array_rst = [ + ['id'=>'NNIDN', 'display'=>'Nomor Induk Kependudukan (KTP)'], + ['id'=>'PPN', 'display'=>'Passport'] + ]; + $result = array("records" => $array_rst); + $this->sys_ok($result); + exit; + } + + function searchregion(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm['search']; + + $sql = "SELECT + r.regional_cd, + r.regional_cd AS id, + r.regional_nm, + r.full_name AS text_nm, + r.pro_cd, IFNULL(pro.regional_nm,'') AS pro_nm, + r.kab_cd, IFNULL(kab.regional_nm,'') AS kab_nm, + r.kec_cd, IFNULL(kec.regional_nm,'') AS kec_nm, + r.kel_cd, IFNULL(kel.regional_nm,'') AS kel_nm, + r.status_cd, r.old_nm + FROM regional r + LEFT JOIN regional pro ON CONCAT(r.pro_cd, REPEAT('0', 8)) = pro.regional_cd + LEFT JOIN regional kab ON CONCAT(r.pro_cd, r.kab_cd, REPEAT('0', 6)) = kab.regional_cd + LEFT JOIN regional kec ON CONCAT(r.pro_cd, r.kab_cd, r.kec_cd, REPEAT('0', 3)) = kec.regional_cd + LEFT JOIN regional kel ON CONCAT(r.pro_cd, r.kab_cd, r.kec_cd, r.kel_cd) = kel.regional_cd + WHERE (MATCH(r.full_name) AGAINST('%$search%' IN BOOLEAN MODE) + OR r.full_name LIKE '%$search%' + OR r.regional_nm LIKE '%$search%' + OR r.full_name REGEXP '$search' + OR r.regional_nm REGEXP '$search' + OR LOWER(r.full_name) LIKE LOWER('%$search%') + OR LOWER(r.regional_nm) LIKE LOWER('%$search%')) + LIMIT 100 + "; + + $qry = $this->db_onedev->query($sql); + + if (!$qry) { + $this->sys_error_db("search wilayah select error", $this->db_onedev); + exit; + } + + $rows = $qry->result_array(); + + $result = array( + "records" => $rows, + "sql" => $this->db_onedev->last_query() + ); + + $this->sys_ok($result); + exit; + } + + function search_countries(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm['search']; + + if(!$search || $search == ''){ + $search = 'Indonesia'; + } + + $sql = "SELECT * FROM terminology WHERE attribute_path = 'Address.country' AND display LIKE '%$search%' ORDER BY display ASC LIMIT 20"; + $query = $this->db_onedev->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + + function get_titles(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $gender_id = $prm['gender_id']; + + $sql = "SELECT * FROM m_title WHERE M_TitleIsActive = 'Y' AND M_TitleGender = ? ORDER BY M_TitleOrder ASC"; + $query = $this->db_smartone->query($sql, array($gender_id)); + $rows = $query->result_array(); + if(!$query){ + $this->sys_error_db("m_title rows", $this->db_smartone); + exit; + } + $result = array("records" => $rows); + $this->sys_ok($result); + } + + function get_religions(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $sql = " SELECT code, display + FROM terminology + WHERE + resource_type = 'Patient' AND + attribute_path = 'Patient.religion.code' + ORDER BY order_no ASC"; + $query = $this->db_smartone->query($sql); + //echo $this->db_smartone->last_query(); + $rows = $query->result_array(); + if(!$query){ + $this->sys_error_db("terminology rows", $this->db_smartone); + exit; + } + $result = array("records" => $rows); + $this->sys_ok($result); + } + + function search_blood_type(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $gender_id = $prm['gender_id']; + + $sql = "SELECT * FROM terminology WHERE resource_type = 'Patient' AND attribute_path = 'Patient.blood.type' ORDER BY order_no ASC"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + + function search_blood_rh_type(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $gender_id = $prm['gender_id']; + $sql = "SELECT * FROM terminology WHERE resource_type = 'Patient' AND attribute_path = 'Patient.blood.rhesus' ORDER BY order_no ASC"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + + function search_education_type(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $gender_id = $prm['gender_id']; + $sql = "SELECT * FROM terminology WHERE resource_type = 'Person' AND attribute_path = 'Person.education' ORDER BY order_no ASC"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + + function search_etnic_type(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $gender_id = $prm['gender_id']; + $sql = "SELECT * FROM terminology WHERE resource_type = 'Patient' AND attribute_path = 'Patient.etnicity' ORDER BY order_no ASC"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + + + + function search_corporate(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + $search = $prm['search']; + + /* + CREATE TABLE `corporate` ( + `CorporateID` int NOT NULL AUTO_INCREMENT, + `CorporateOldCompanyID` varchar(50) DEFAULT NULL, + `CorporateCorporateTypeID` int DEFAULT '0', + `CorporateCode` varchar(50) NOT NULL DEFAULT '', + `CorporateName` varchar(255) NOT NULL DEFAULT '', + `CorporateAddress` varchar(500) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressRegionalCd` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressRT` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressRW` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressVillage` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressDistrict` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressCity` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressState` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateAddressCountry` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT '', + `CorporateEmail` text CHARACTER SET latin1 COLLATE latin1_swedish_ci, + `CorporatePhone` varchar(50) NOT NULL DEFAULT '', + `CorporatePICName` varchar(150) NOT NULL DEFAULT '', + `CorporatePICEmail` text CHARACTER SET latin1 COLLATE latin1_swedish_ci, + `CorporatePICPhone` varchar(50) NOT NULL DEFAULT '', + `CorporateFlagHolding` char(1) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'N' COMMENT 'holding true atau Y (ke centang) baru ada dropdown induk; default nya TRUE atau Y', + `CorporateHoldingCorporateID` int NOT NULL DEFAULT '0', + `CorporatePICBillName` varchar(150) NOT NULL DEFAULT '', + `CorporatePICBillEmail` text CHARACTER SET latin1 COLLATE latin1_swedish_ci, + `CorporatePICBillPhone` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, + `CorporateBillAddress` text CHARACTER SET latin1 COLLATE latin1_swedish_ci, + `CorporateDueDate` int NOT NULL DEFAULT '0' COMMENT 'dalam hari', + `CorporateFlagJPA` varchar(15) NOT NULL DEFAULT 'netto' COMMENT 'netto, bruto', + `CorporateUsername` varchar(150) NOT NULL DEFAULT '', + `CorporatePassword` varchar(32) NOT NULL DEFAULT '', + `CorporateOldID` varchar(32) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, + `CorporateCreated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `CorporateCreatedUserID` int NOT NULL DEFAULT '0', + `CorporateLastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `CorporateLastUpdatedUserID` int NOT NULL DEFAULT '0', + `CorporateDeleted` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `CorporateDeletedUserID` int NOT NULL DEFAULT '0', + `CorporateIsActive` char(1) NOT NULL DEFAULT 'Y', + PRIMARY KEY (`CorporateID`), + KEY `CorporateHoldingCorporateID` (`CorporateHoldingCorporateID`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1; + */ + + $sql = "SELECT CorporateID, CorporateName, CorporateCode FROM corporate WHERE CorporateName LIKE '%$search%' ORDER BY CorporateName ASC LIMIT 20"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + + } + + function search_icd10(){ + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + $search = $prm['search']; + $sql = "SELECT * FROM terminology WHERE `attribute_path` = 'icd10' AND + CONCAT(code, ' - ', display) LIKE '%$search%' + ORDER BY order_no ASC LIMIT 20"; + $query = $this->db_smartone->query($sql); + $rows = $query->result_array(); + $result = array("records" => $rows); + $this->sys_ok($result); + exit; + } + +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Patientaddress.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Patientaddress.php new file mode 100644 index 0000000..39245b8 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Patientaddress.php @@ -0,0 +1,49 @@ +sys_debug(); + try { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $prm = $this->sys_input; + + } catch(Exception $exc) { + $message = $exc->getMessage(); + $this->sys_error($message); + } + + } + */ + +class Patientaddress extends MY_Controller +{ + var $db_smartone; + public function index() + { + echo "Patient API"; + } + public function __construct() + { + parent::__construct(); + $this->db_smartone = $this->load->database("onedev", true); + } + + public function get_all() + { + $prm = $this->sys_input; + + $sql = "select M_PatientAddressID, M_PatientAddressNote, + M_PatientAddressDescription, M_KelurahanName as M_KelurahanName + from m_patientaddress + left join m_kelurahan on m_patientaddressm_kelurahanid = m_kelurahanid + where m_patientaddressm_patientid = ?"; + + $query = $this->db_smartone->query($sql, array($prm['patient_id'])); + $rows = $query->result_array(); + + $result = array("status" => "OK", "records" => $rows); + $this->sys_ok($result); + } +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Payment.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Payment.php new file mode 100644 index 0000000..d58eff4 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Payment.php @@ -0,0 +1,279 @@ + +db_smartone = $this->load->database("onedev", true); + } + + public function get_order() { + $prm = $this->sys_input; + + $rst = ["order_header"=>[], "order_detail"=>[], "order_delivery"=>[]]; + + $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, + concat(if(M_TitleID is null, '', concat(M_TitleName, ' ')), M_PatientName) as patient_name, + M_PatientNoReg as patient_mr, + M_MouName as order_mou, + M_CompanyName 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 M_CompanyIsBill, M_MouMinDP M_CompanyMinDP, + M_MouIsAgingOnHold M_CompanyIsAgingOnHold, M_MouIsAgingOnHoldNote M_CompanyIsAgingOnHoldNote + from t_orderheader + join m_patient on T_OrderHeaderM_PatientID = M_PatientID + join m_company on T_OrderHeaderM_CompanyID = M_CompanyID + 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 = ?"; + $query = $this->db_smartone->query($sql, array($prm['id'])); + if ($query) { + $rows = (array) $query->row(); + $rst['order_header'] = $rows; + // $result = array("status" => "OK" , "data" => $rst); + // $this->sys_ok($result); + // exit; + } else { + $this->sys_error_db("m_doctoraddress ", $this->db_smartone); + exit; + } + + $sql = "CALL sp_fo_payment_get_delivery('{$prm['id']}')"; + $query = $this->db_smartone->query($sql); + $this->clean_mysqli_connection($this->db_smartone->conn_id); + + if ($query) { + $rows = $query->row(); + $rst['order_delivery'] = json_decode($rows->delivery); + // $result = array("status" => "OK" , "data" => $rst); + // $this->sys_ok($result); + // exit; + } else { + $this->sys_error_db("m_doctoraddress delivery ", $this->db_smartone); + exit; + } + +// { n:1, d_id:1, t_id:1, t_name:'SGOT', t_price:80000, t_disctotal:7000, t_total:73000 }, +// { n:2, d_id:2, t_id:2, t_name:'SGPT', t_price:75000, t_disctotal:8000, t_total:67000 } +// T_OrderDetailPrice double [0] +// T_OrderDetailPriceForDisc double [0] +// T_OrderDetailDisc double [0] +// T_OrderDetailDiscAmount double [0] +// T_OrderDetailTotal + + $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 = ? + 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, array($prm['id'])); + if ($query) { + $rows = $query->result_array(); + $rst['order_detail'] = $rows; + + $result = array("status" => "OK" , "data" => $rst); + $this->sys_ok($result); + exit; + } else { + $this->sys_error_db("m_doctoraddress ", $this->db_smartone); + exit; + } + } + + public function search() + { + $prm = $this->sys_input; + + $max_rst = 100; + $tot_count =0; + + $q = [ + 'search' => '%' + ]; + + if ($prm['search'] != '') + { + $q['search'] = "%{$prm['search']}%"; + } + + // QUERY TOTAL + $sql = "select count(*) total + from + m_paymenttype + where M_PaymentTypeIsActive = 'Y' + and M_PaymentTypeName like ?"; + $query = $this->db_smartone->query($sql, array($q['search'])); + + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } + else { + $this->sys_error_db("m_paymenttype count",$this->db_smartone); + exit; + } + + $sql = "select M_PaymentTypeID payment_type_id, M_PaymentTypeName payment_type_name, M_PaymentTypeCode payment_type_code, + 0 payment_amount, '' payment_note, 'Nomor Kartu' payment_note_label, 'N' payment_enable, + 0 payment_change, 0 payment_actual, 0 payment_card_id, 0 payment_edc_id, 0 payment_account_id + from m_paymenttype + where M_PaymentTypeIsActive = 'Y' + and M_PaymentTypeName like ?"; + $query = $this->db_smartone->query($sql, array($q['search'])); + + if ($query) { + $rows = $query->result_array(); + + foreach($rows as $k => $v) { + + if ($v['payment_type_code'] == 'CASH') + $v['payment_note_label'] = 'Kembali'; + if ($v['payment_type_code'] == 'VOUCHER') + $v['payment_note_label'] = 'Nomor Voucher'; + + $rows[$k] = $v; + } + + $result = $rows; + $this->sys_ok($result); + } + else { + $this->sys_error_db("m_paymenttype rows",$this->db_smartone); + exit; + } + } + + function save() + { + $prm = $this->sys_input; + $payment_json = json_encode($prm['payments']); + + $sql = "CALL sp_fo_payment('{$prm['order_id']}', '{$payment_json}', '{$this->sys_user['M_UserID']}');"; + $query = $this->db_smartone->query($sql); + + if ($query) + { + $rst = $query->row(); + $rst->data = json_decode($rst->data); + echo json_encode($rst); + } + else + { + $this->sys_error_db("save payment", $this->db_smartone); + exit; + } + } + + function endshowtime() + { + $prm = $this->sys_input; + $sql = "UPDATE t_orderheaderaddon SET + T_OrderHeaderAddonFoTimeStart = '{$prm['time_start']}', + T_OrderHeaderAddonFoTimeEnd = NOW() + WHERE + T_OrderHeaderAddOnT_OrderHeaderID = {$prm['order_id']}"; + $query = $this->db_smartone->query($sql); + + if ($query) + { + $result = array( + "total" => 1, + "records" => array() + ); + $this->sys_ok($result); + exit; + } + else + { + $this->sys_error_db("save payment", $this->db_smartone); + exit; + } + } + + public function search_bank() + { + $prm = $this->sys_input; + + if (isset($prm['card'])) + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank WHERE Nat_BankIsCard = 'Y' ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + else if (isset($prm['edc'])) + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank WHERE Nat_BankIsEDC = 'Y' ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + else + { + $sql = "SELECT Nat_BankID, Nat_BankName + FROM nat_bank ORDER BY Nat_BankName ASC"; + $query = $this->db_smartone->query($sql); + } + + + if ($query) + { + $rows = $query->result_array(); + $this->sys_ok(["records"=>$rows, "total"=>sizeof($rows), "q"=>$this->db_smartone->last_query()]); + } + else + { + $this->sys_error_db("NAT BANK",$this->db_smartone); + exit; + } + } + + /*function endshowtime() + { + $prm = $this->sys_input; + $sql = "UPDATE t_orderheaderaddon SET + T_OrderHeaderAddonFoTimeStart = {$prm['time_start']}, + T_OrderHeaderAddonFoTimeEnd = NOW() + WHERE + T_OrderHeaderAddOnT_OrderHeaderID = {$prm['order_id']}"; + + $query = $this->db_smartone->query($sql); + if ($query) + { + $rows = $query->result_array(); + $this->sys_ok(["records"=>array(), "total"=>sizeof($rows), "q"=>''); + } + else + { + $this->sys_error_db("NAT BANK",$this->db_smartone); + exit; + } + }*/ +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Photo.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Photo.php new file mode 100644 index 0000000..299e3c9 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Photo.php @@ -0,0 +1,145 @@ +db_smartone = $this->load->database("onedev", true); + $this->load->library('ImageManipulator'); + } + + public function upload() + { + $inp = $this->sys_input; + + $home_dir = "/home/one/project/one/"; + $target_dir = $home_dir . "one-media/one-photo/patient/" . date("Y") . "/"; + $y = $this->regenerateOldPhoto($home_dir, $inp['id']); + + // get patient mr + $p = $this->db_smartone->select("M_PatientNoReg") + ->where("M_PatientID", $inp['id']) + ->get('m_patient') + ->row(); + + if (!file_exists($target_dir)) { + mkdir($target_dir, 0755, true); + } + + $target_path = $target_dir . $p->M_PatientNoReg . ".jpg"; + $this->base64_to_jpeg($inp['data'], $target_path); + + // CROP Image + $im = new ImageManipulator($target_path); + $w = $im->getWidth(); + $h = $im->getHeight(); + + $mw = ceil(3 * $h / 4); + if ($w <= $mw) + { + $x1 = 0; + $y1 = 0; + $x2 = $w; + $y2 = $h; + } + else + { + $x1 = floor(($w - $mw) / 2); + $y1 = 0; + $x2 = ceil($w - (($w - $mw) / 2)); + $y2 = $h; + } + + $im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically + $im->save($target_path); + + $x = $this->generateThumbnail($target_path, 75, 100); + + // Save to DB + $this->db_smartone->set("M_PatientPhoto", "/" . str_replace($home_dir, "", $target_path)) + ->set("M_PatientPhotoThumb", "/" . str_replace($home_dir, "", $x)) + ->set('M_PatientPhotoCounter', '`M_PatientPhotoCounter` + 1', false) + ->set('M_PatientLastUpdated', date("Y-m-d H:i:s")) + ->set('M_PatientLastUpdatedUserID', $this->sys_user['M_UserID']) + ->where('M_PatientID', $inp['id']) + ->update('m_patient'); + + // echo $this->db_smartone->last_query(); + // LOGGING + $code = $y ? "PHOTO.PATIENT.EDIT" : "PHOTO.PATIENT.ADD"; + $this->db_smartone->set('Log_PhotoCode', $code) + ->set('Log_PhotoM_PatientID', $inp['id']) + ->set('Log_PhotoUrl', $y ? $y : "/" . str_replace($home_dir, "", $target_path)) + ->insert('log_photo'); + + $this->sys_ok(["rename"=>$y, "patient_id"=>$inp['id'], "patient_mr"=>$p->M_PatientNoReg, "photo_url"=>"http://" . $_SERVER['SERVER_NAME'] . "/" . str_replace($home_dir, "", $target_path) . "?d=" . date("YmdHis")]); + } + + function base64_to_jpeg($base64_string, $output_file) { + // open the output file for writing + $ifp = fopen( $output_file, 'wb' ); + + // split the string on commas + // $data[ 0 ] == "data:image/png;base64" + // $data[ 1 ] == + $data = explode( ',', $base64_string ); + + // we could add validation here with ensuring count( $data ) > 1 + fwrite( $ifp, base64_decode( $data[ 1 ] ) ); + + // clean up the file resource + fclose( $ifp ); + + return $output_file; + } + + function generateThumbnail($img, $width, $height, $quality = 90) + { + if (is_file($img)) { + $imagick = new Imagick(realpath($img)); + $imagick->setImageFormat('jpeg'); + $imagick->setImageCompression(Imagick::COMPRESSION_JPEG); + $imagick->setImageCompressionQuality($quality); + $imagick->thumbnailImage($width, $height, false, false); + $filename_no_ext = reset(explode('.', $img)); + if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) { + throw new Exception("Could not put contents."); + } + return $filename_no_ext . '_thumb' . '.jpg'; + } + else { + throw new Exception("No valid image provided with {$img}."); + } + } + + function regenerateOldPhoto($home_dir, $id) + { + $r = $this->db_smartone->select('m_patientphoto, m_patientphotocounter', false) + ->where('m_patientid', $id) + ->get('m_patient') + ->row(); + if ($r->m_patientphoto != null && $r->m_patientphotocounter > 0) { + $full_path = substr_replace($home_dir ,"", -1) . $r->m_patientphoto; + $path_parts = pathinfo($full_path); + + $rename = $path_parts['dirname'] . '/' . $path_parts['filename'] . '-' . $r->m_patientphotocounter . '.' . $path_parts['extension']; + rename($full_path, $rename); + // echo $path_parts['dirname'], "\n"; + // echo $path_parts['extension'], "\n"; + // echo $path_parts['filename'], "\n"; + + return "/" . str_replace($home_dir, "", $rename); + } + + return false; + } + +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Px.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Px.php new file mode 100644 index 0000000..3807ce9 --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Px.php @@ -0,0 +1,704 @@ +db_smartone = $this->load->database("onedev", true); + } + function _add_ref_test(&$rows) { + $ids = "-1"; + foreach($rows as $idx => $r) { + $ids .= "," . $r["T_TestID"]; + if (! $rows[$idx]["ref_test"] ) $rows[$idx]["ref_test"] == array(); + } + $sql="select T_TestID,T_RefTestName, T_TestName + from + t_reftest + join t_test on T_RefTestID = T_TestT_RefTestID + and T_RefTestIsActive = 'Y' + where T_TestID in ( $ids )"; + + + } + public function profile() + { + $prm = $this->sys_input; + $search = $prm["search"]; + $mou_id = $prm["mou_id"]; + $max_rst = 8; + + $sql_param = array("%$search%"); + $sql = "select count(distinct T_ProfileID) total + from t_profile + join t_profiledetail on t_profileid = t_profiledetailt_profileid + and t_profiledetailisactive = 'Y' + where t_profilename like ?"; + $query = $this->db_smartone->query($sql, $sql_param); + + $tot_count =0; + if ($query) { + $tot_count = $query->row()->total; + } else { + $this->sys_error_db("Test Profile count", $this->db_smartone); + exit; + } + + $sql = "select T_ProfileID, T_ProfileName, CONCAT('[', GROUP_CONCAT( JSON_OBJECT('T_TestID', T_TestID, 'T_TestName', T_TestName, 'T_TestRequirement', T_TestRequirement) SEPARATOR ','), ']') detail + from t_profile + join t_profiledetail on t_profileid = t_profiledetailt_profileid + and t_profiledetailisactive = 'Y' + join t_test on t_profiledetailt_testid = t_testid + where t_profilename like ? + group by t_profileid + limit 0, $max_rst"; + $query = $this->db_smartone->query($sql, $sql_param); + $rows = $query->result_array(); + + foreach($rows as $k => $r) + { + $err = 0; + $detail = json_decode($r['detail']); + foreach ($detail as $l => $w) + { + $sql_param = array($w->T_TestID, date('Y-m-d'), 'N', $mou_id); + $sql = "select fn_price(?, ?, ?, ?) as price"; + $query = $this->db_smartone->query($sql, $sql_param); + + if ($query) + { + $price = json_decode($query->row()->price); + + $detail[$l]->T_PriceAmount = $price->test_price; + $detail[$l]->T_PriceDisc = $price->test_disc; + $detail[$l]->T_PriceDiscRp = $price->test_discrp; + $detail[$l]->T_PriceID = $price->price_id; + $detail[$l]->T_PriceIsCito = "N"; + $detail[$l]->T_PriceM_CompanyID = $price->company_id; + $detail[$l]->T_PriceM_MouID = $price->mou_id; + $detail[$l]->T_PriceOther = $price->test_other; + $detail[$l]->T_PriceSubTotal = $price->test_subtotal; + $detail[$l]->T_PriceT_TestID = $price->test_id; + $detail[$l]->T_PriceTotal = $price->test_total; + + if ($price->test_price == 0) + $err++; + } + } + + $rows[$k]['detail'] = $detail; + $rows[$k]['err'] = $err; + } + + $result = array("total" => $tot_count, "records" => $rows ); + $this->sys_ok($result); + exit; + } + + public function panel() { + $prm = $this->sys_input; + $search = $prm["search"]; + $mouCompanyID = $prm["mouCompanyID"]; + + $sql_param = array($mouCompanyID, "%$search%"); + $sql = "select count(distinct T_TestPanelID) total + from + t_testpanel + join t_testpaneldetail on T_TestPanelID = T_TestPanelDetailT_TestPanelID + and T_TestPanelIsActive = 'Y' and T_TestPanelDetailIsActive = 'Y' + join t_test on T_TestPanelDetailT_TestID = T_TestID + and T_TestIsActive = 'Y' + join t_testprice on T_TestID = T_TestPriceT_TestID + and T_TestIsPrice = 'Y' + and T_TestPriceIsActive = 'Y' + and T_TestPriceM_MouCompanyID = ? + where + T_TestPanelName like ? "; + $query = $this->db_smartone->query($sql, $sql_param); + $tot_count =0; + if ($query) { + $tot_count = $query->result_array()[0]["total"]; + } else { + $this->sys_error_db("m_testpanel count", $this->db_smartone); + exit; + } + $sql = "select distinct T_TestPanelID + from + t_testpanel + join t_testpaneldetail on T_TestPanelID = T_TestPanelDetailT_TestPanelID + and T_TestPanelIsActive = 'Y' and T_TestPanelDetailIsActive = 'Y' + join t_test on T_TestPanelDetailT_TestID = T_TestID + and T_TestIsActive = 'Y' + join t_testprice on T_TestID = T_TestPriceT_TestID + and T_TestIsPrice = 'Y' + and T_TestPriceIsActive = 'Y' + and T_TestPriceM_MouCompanyID = ? + where + T_TestPanelName like ? + limit 0,20"; + $query = $this->db_smartone->query($sql,$sql_param); + $xrows = $query->result_array(); + $a_tpid = "-1"; + foreach($xrows as $r) { + $a_tpid .= "," . $r["T_TestPanelID"]; + } + $sql = "select distinct T_TestPanelID,T_TestPanelName, + T_TestID,T_TestName, 'Y' IsFromPanel,T_TestRequirement, + t_testprice.* + from + t_testpanel + join t_testpaneldetail on T_TestPanelID = T_TestPanelDetailT_TestPanelID + and T_TestPanelIsActive = 'Y' and T_TestPanelDetailIsActive = 'Y' + join t_test on T_TestPanelDetailT_TestID = T_TestID + and T_TestIsActive = 'Y' + join t_testprice on T_TestID = T_TestPriceT_TestID + and T_TestIsPrice = 'Y' + and T_TestPriceM_MouCompanyID = ? + and T_TestPriceIsActive = 'Y' + where + T_TestPanelID in ( $a_tpid ) + order by T_TestPanelID"; + $query = $this->db_smartone->query($sql,array($mouCompanyID)); + $xrows = $query->result_array(); + $rows = array(); + $prev_tpanel_id = 0; + foreach($xrows as $r) { + $tpanel_id = $r["T_TestPanelID"]; + if ($tpanel_id != $prev_tpanel_id) { + $rows[] = array( + "T_TestPanelID" => $r["T_TestPanelID"], + "T_TestPanelName" => $r["T_TestPanelName"], + "test" => array() + ); + } + $idx = count($rows) - 1; + $rows[$idx]["test"][] = $r; + $prev_tpanel_id = $tpanel_id; + } + $result = array("total" => $tot_count, "records" => $rows ); + $this->sys_ok($result); + exit; + } + + public function search_v2() + { + + $prm = $this->sys_input; + $search = $prm["search"]; + $mouCompanyID = $prm["mouCompanyID"]; + $project_id = isset($prm["project_id"]) ? (int)$prm["project_id"] : 0; + + $userid = $this->sys_user["M_UserID"]; + + $sql_branch = "SELECT M_BranchIsSteemCell + FROM m_user + JOIN m_branch ON M_UserLoginM_BranchID = M_BranchID + WHERE M_UserID = ?"; + $query_branch = $this->db_smartone->query($sql_branch, [$userid]); + $is_stemcell = 'N'; + if ($query_branch && $query_branch->num_rows() > 0) { + $is_stemcell = $query_branch->row_array()['M_BranchIsSteemCell']; + } + + $sql_param = array($mouCompanyID, "%$search%"); + + $query = $this->db_smartone->query("CALL sp_fo_px_count_v2(?, ?)", $sql_param); + + $this->clean_mysqli_connection($this->db_smartone->conn_id); + + $tot_count = 0; + if ($query) { + $tot_count = $query->result_array()[0]["data"]; + } else { + $this->sys_error_db("PX count", $this->db_smartone); + exit; + } + + + if (trim($search) == "") + $query = $this->db_smartone->query("CALL sp_fo_px_search_favorite_v2(?, ?)", $sql_param); + else + $query = $this->db_smartone->query("CALL sp_fo_px_search_v2(?, ?)", $sql_param); + $this->clean_mysqli_connection($this->db_smartone->conn_id); + + // echo $this->db_smartone->last_query(); + // $query = $this->db_smartone->query($sql); + if ($query) + { + $rows_complete = $query->result_array(); + + $rows = $this->_filter_project_packets($rows_complete, $project_id); + $rows = $this->_filter_stemcell($rows, $is_stemcell); + + $id_to_remove = []; + + // var_dump($rows); + foreach ($rows as $k => $v) + { + $rows[$k]['requirement'] = []; + /*if($v['px_type'] == "PX"){ + $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$v['T_TestID']}') x") + ->row(); + if ($x->x != null) + $rows[$k]['requirement'] = json_decode($x->x); + }*/ + + + // Janji Hasil per PX + //$x = $this->db_smartone->query("SELECT fn_fo_find_promise_by_one_px('{$v['T_TestID']}') x")->row(); + if($v['is_packet'] == 'N'){ + $tests = $v['T_PriceT_TestID']; + $panels = ''; + } + else{ + $tests = ''; + $panels = $v['T_PriceT_TestID']; + } + + $rows[$k]['nat_test'] = json_decode($v['nat_test']); + $rows[$k]['child_test'] = json_decode($v['child_test']); + + + + // IF PROFILE + if ($v['px_type'] == "PR" || $v['px_type'] == "PXR" || $v['px_type'] == "PN") { + + if ($v['T_TestID'] == null) + { + $id_to_remove[] = $k; + continue; + } + else + { + foreach ($rows[$k]['child_test'] as $l => $w) { + $rows[$k]['child_test'][$l]->requirement = []; + $rows[$k]['child_test'][$l]->nat_test = json_decode($w->nat_test); + $rows[$k]['child_test'][$l]->promise = null; + //echo "SELECT fn_fo_requirement_get('{$w->T_TestID}')"; + if($w->px_type == "PX"){ + /*$x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$w->T_TestID}') x")->row(); + if ($x->x != null) + $rows[$k]['child_test'][$l]->requirement = json_decode($x->x);*/ + } + else{ + $rows[$k]['child_test'][$l]->requirement = []; + } + + if($v['px_type'] != "PXR"){ + $rows[$k]['child_test'][$l]->is_packet = 'Y'; + $rows[$k]['child_test'][$l]->packet_id = $v['T_TestID']; + $rows[$k]['child_test'][$l]->packet_type = $v['px_type']; + $rows[$k]['child_test'][$l]->packet_name = $v['T_TestName']; + $sql = "SELECT T_PacketSasCode as code FROM t_packet WHERE T_PacketID = {$v['T_TestID']}"; + $query = $this->db_smartone->query($sql); + if ($query) { + $r = $query->result_array()[0]; + $rows[$k]['child_test'][$l]->packet_code = $r['code']; + }else{ + $this->sys_error_db("get packet code", $this->db_smartone); + exit; + } + } + } + } + } + } + + // REMOVE INDEXES + + foreach ($id_to_remove as $l => $w) + { $x = $w - $l; array_splice($rows, $x, 1); } + + $result = array( + "total" => count($rows), + "records" => (array) $rows, + "query" => isset($sqlx) ? $sqlx : "", + "query2" => isset($sqly) ? $sqly : "" + ); + $this->sys_ok($result); + exit; + } + + } + + function get_price() + { + $prm = $this->sys_input; + $r = []; + + $sql_param = array($prm['test_id'], date('Y-m-d'), $prm['cito'], $prm['mou_id']); + $sql = "select fn_price(?, ?, ?, ?) as price"; + $query = $this->db_smartone->query($sql, $sql_param); + + if ($query) { + $r = $query->result_array()[0]; + $r = json_decode($r['price']); + $this->sys_ok($r); + + exit; + } else { + $this->sys_error_db("get price", $this->db_smartone); + + exit; + } + } + + public function search() + { + $prm = $this->sys_input; + $search = $prm["search"]; + $mouCompanyID = $prm["mouCompanyID"]; + + $sql_param = array($mouCompanyID, "%$search%"); + + $query = $this->db_smartone->query("CALL sp_fo_px_count(?, ?)", $sql_param); + $this->clean_mysqli_connection($this->db_smartone->conn_id); + + $tot_count = 0; + if ($query) { + $tot_count = $query->result_array()[0]["data"]; + } else { + $this->sys_error_db("PX count", $this->db_smartone); + exit; + } + + if (isset($prm['order_id'])) + $query = $this->db_smartone->query("CALL sp_fo_px_search_byorder(?, ?)", [$prm['order_id'], $mouCompanyID]); + else if (isset($prm['clinic_id'])) + $query = $this->db_smartone->query("CALL sp_fo_px_search_byclinic(?, ?)", [$prm['clinic_id'], $mouCompanyID]); + else if ($search == "") + $query = $this->db_smartone->query("CALL sp_fo_px_search_favorite(?, ?)", $sql_param); + else + $query = $this->db_smartone->query("CALL sp_fo_px_search(?, ?)", $sql_param); + $this->clean_mysqli_connection($this->db_smartone->conn_id); + + // echo $this->db_smartone->last_query(); + // $query = $this->db_smartone->query($sql); + if ($query) + { + $rows = $query->result_array(); + $id_to_remove = []; + + // var_dump($rows); + foreach ($rows as $k => $v) + { + $rows[$k]['requirement'] = []; + + $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$v['T_TestID']}') x") + ->row(); + if ($x->x != null) + $rows[$k]['requirement'] = json_decode($x->x); + + $rows[$k]['nat_test'] = json_decode($v['nat_test']); + $rows[$k]['child_test'] = json_decode($v['child_test']); + + // IF PROFILE + if ($v['px_type'] == "PR" || $v['px_type'] == "PXR") { + + if ($v['T_TestID'] == null) + { + $id_to_remove[] = $k; + continue; + } + + else + { + foreach ($rows[$k]['child_test'] as $l => $w) { + $rows[$k]['child_test'][$l]->requirement = []; + $rows[$k]['child_test'][$l]->nat_test = json_decode($w->nat_test); + $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$w->T_TestID}') x") + ->row(); + if ($x->x != null) + $rows[$k]['child_test'][$l]->requirement = json_decode($x->x); + } + } + } + } + + // REMOVE INDEXES + + foreach ($id_to_remove as $l => $w) + { $x = $w - $l; array_splice($rows, $x, 1); } + + $result = array("total" => $tot_count, "records" => (array) $rows, "query" => $sqlx, "query2" => $sqly ); + $this->sys_ok($result); + exit; + } + + } + + function packet_reqs() + { + $prm = $this->sys_input; + $child_test = $prm['pxs']; + $reqs = array(); + foreach($child_test as $k => $v){ + $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$v['T_TestID']}') x")->row(); + if ($x->x != null){ + $now_reqs = json_decode($x->x); + foreach($now_reqs as $kr => $vr){ + $idx = $this->check_reqs_exist($reqs,$vr->req_id); + if($idx == -1){ + $xtests = array(); + array_push($xtests,$v['T_TestID']); + $vr->tests = $xtests; + array_push($reqs,$vr); + } + else{ + $xtests = $reqs[$idx]->tests; + array_push($xtests,$v['T_TestID']); + $reqs[$idx]->tests = $xtests; + } + } + } + + } + + $this->sys_ok($reqs); + exit; + } + + function check_reqs_exist($reqs,$req_id){ + $rtn = -1; + foreach($reqs as $k => $v){ + if(intval($v->req_id) == intval($req_id)){ + $rtn = $k; + break; + } + } + return $rtn; + } + + function get_requirement() + { + $prm = $this->sys_input; + $test_id = $prm['test_id']; + $reqs = array(); + + $x = $this->db_smartone->query("SELECT fn_fo_requirement_get('{$test_id}') x")->row(); + if ($x->x != null) { + $reqs = json_decode($x->x); + } + + $this->sys_ok($reqs); + exit; + } + + function get_appx_schedule() + { + if (! $this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + $user_id = $this->sys_user["M_UserID"]; + $prm = $this->sys_input; + $x_datetime = date('Y-m-d H:i:s'); + + $sql = "SELECT M_UserLoginM_BranchID as branch_id FROM m_user WHERE M_UserID = ?"; + $query = $this->db_smartone->query($sql, [$user_id]); + $user = $query->row_array(); + $branch_id = $user['branch_id']; + + $r = []; + $test_ids = $prm['test_ids']; + $panel_ids = $prm['panel_ids']; + + if($panel_ids != ""){ + $sql = "SELECT T_PacketDetailT_TestID as test_id + FROM t_packetdetail + WHERE + T_PacketDetailT_PacketID IN ( $panel_ids ) AND + T_PacketDetailIsActive = 'Y' + "; + + $query = $this->db_smartone->query($sql); + $packet_test_ids = $query->result_array(); + $packet_test_ids = array_column($packet_test_ids, 'test_id'); + if(count($packet_test_ids) > 0){ + foreach($packet_test_ids as $k => $v){ + $test_ids .= "," . $v['test_id']; + } + } + } + + + $this->load->library('Promise'); + $result = $this->promise->get_schedule_results_grouped($test_ids, $x_datetime, $branch_id); + $rtn = array("records" => $result); + $this->sys_ok($rtn); + exit; + } + + public function search_cito() + { + $prm = $this->sys_input; + + $sql = "SELECT Nat_CitoID, Nat_CitoName, Nat_CitoIsDefault + FROM nat_cito WHERE Nat_CitoIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + + if ($query) + { + $rows = $query->result_array(); + $this->sys_ok(["records"=>$rows]); + return; + } + + $this->sys_error_db("CITO", $this->db_smartone); + } + + public function add_promise() + { + $prm = $this->sys_input; + + $this->sys_ok("OK"); + } + + private function _filter_stemcell($rows, $is_stemcell) + { + // Kumpulkan semua test ID yang perlu dicek nat_group-nya + $test_ids = []; + foreach ($rows as $row) { + if ($row['is_packet'] == 'N') { + $test_ids[] = (int)$row['T_TestID']; + } else { + $children = json_decode($row['child_test'], true); + if (is_array($children)) { + foreach ($children as $child) { + if (isset($child['T_TestID'])) { + $test_ids[] = (int)$child['T_TestID']; + } + } + } + } + } + + if (empty($test_ids)) return $rows; + + $ids_str = implode(',', array_unique($test_ids)); + $sql = "SELECT T_TestID, T_TestNat_GroupID FROM t_test WHERE T_TestID IN ($ids_str)"; + $query = $this->db_smartone->query($sql); + + $nat_group_map = []; + if ($query) { + foreach ($query->result_array() as $r) { + $nat_group_map[(int)$r['T_TestID']] = (int)$r['T_TestNat_GroupID']; + } + } + + $filtered = []; + foreach ($rows as $row) { + if ($row['is_packet'] == 'N') { + $test_id = (int)$row['T_TestID']; + $nat_group = isset($nat_group_map[$test_id]) ? $nat_group_map[$test_id] : 0; + + if ($is_stemcell == 'N' && $nat_group == 7) continue; + if ($is_stemcell == 'Y' && $nat_group != 7) continue; + } else { + $children = json_decode($row['child_test'], true); + if (!is_array($children) || empty($children)) { + $filtered[] = $row; + continue; + } + + $child_nat_groups = []; + foreach ($children as $child) { + $child_id = isset($child['T_TestID']) ? (int)$child['T_TestID'] : 0; + $child_nat_groups[] = isset($nat_group_map[$child_id]) ? $nat_group_map[$child_id] : 0; + } + + $all_stemcell = !in_array(false, array_map(fn($g) => $g == 7, $child_nat_groups), true); + $any_stemcell = in_array(7, $child_nat_groups); + + if ($is_stemcell == 'Y' && !$all_stemcell) continue; + if ($is_stemcell == 'N' && $any_stemcell) continue; + } + $filtered[] = $row; + } + + return $filtered; + } + + private function _get_project_packet_ids($project_id) + { + $ids = array(); + + if ((int)$project_id <= 0) { + return $ids; + } + + $sql = "SELECT DISTINCT Mgm_McuPacketT_PacketID as packet_id + FROM mgm_mcupacket + JOIN mgm_mcu + ON Mgm_McuID = Mgm_McuPacketMgm_McuID + WHERE + Mgm_McuPacketMgm_McuID = ? + AND Mgm_McuPacketIsActive = 'Y' + AND Mgm_McuIsActive = 'Y' + AND Mgm_McuStartDate <= date(now()) + AND Mgm_McuEndDate >= date(now())"; + $query = $this->db_smartone->query($sql, array($project_id)); + + if (!$query) { + $this->sys_error_db("mgm_mcupacket rows", $this->db_smartone); + exit; + } + + $rows = $query->result_array(); + foreach ($rows as $r) { + $ids[] = (int)$r['packet_id']; + } + + return $ids; + } + + private function _filter_project_packets($rows, $project_id) + { + if ((int)$project_id <= 0) { + return $rows; + } + + $allowed_packet_ids = $this->_get_project_packet_ids($project_id); + + // Kalau project tidak punya mapping paket, maka semua paket disembunyikan + // tapi PX non-paket tetap boleh muncul + $filtered = array(); + + foreach ($rows as $row) { + $is_packet_row = false; + + + // fallback tambahan bila SP mengirim flag is_packet + if ( + isset($row['is_packet']) && + $row['is_packet'] == 'Y' + ) { + $is_packet_row = true; + } + + // kalau bukan paket, tetap tampil + if (!$is_packet_row) { + $filtered[] = $row; + continue; + } + + // paket -> harus ada di mgm_mcupacket + $packet_id = isset($row['T_TestID']) ? (int)$row['T_TestID'] : 0; + if (in_array($packet_id, $allowed_packet_ids)) { + $filtered[] = $row; + } + } + + return $filtered; + } + + +} diff --git a/application/controllers/mockup/fo/walk_in_registration_stemcell/Reference.php b/application/controllers/mockup/fo/walk_in_registration_stemcell/Reference.php new file mode 100644 index 0000000..6f089bf --- /dev/null +++ b/application/controllers/mockup/fo/walk_in_registration_stemcell/Reference.php @@ -0,0 +1,104 @@ +db_smartone = $this->load->database("onedev", true); + } + + public function searchreference() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $q = [ + 'search' => '%' + ]; + + if (isset($prm['search']) && $prm['search'] != '') { + $q['search'] = "%{$prm['search']}%"; + } + + $sql = "SELECT + M_ReferenceID, + M_ReferenceName, + M_ReferenceIsActive + FROM m_reference + WHERE M_ReferenceIsActive = 'Y' + AND M_ReferenceName LIKE ? + ORDER BY M_ReferenceName ASC"; + + $qry = $this->db_smartone->query($sql, array($q['search'])); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("reference error", $this->db_smartone); + exit; + } + + $result = array( + "records" => $rows, + "total_display" => sizeof($rows) + ); + + $this->sys_ok($result); + } + + public function searchordertype() + { + if (!$this->isLogin) { + $this->sys_error("Invalid Token"); + exit; + } + + $prm = $this->sys_input; + + $q = [ + 'search' => '%' + ]; + + if (isset($prm['search']) && $prm['search'] != '') { + $q['search'] = "%{$prm['search']}%"; + } + + $sql = "SELECT + M_OrderTypeID, + M_OrderTypeCode, + M_OrderTypeName, + M_OrderTypeIsActive + FROM m_ordertype + WHERE M_OrderTypeIsActive = 'Y' + AND ( + M_OrderTypeName LIKE ? + OR M_OrderTypeCode LIKE ? + ) + ORDER BY M_OrderTypeName ASC"; + + $qry = $this->db_smartone->query($sql, array($q['search'], $q['search'])); + if ($qry) { + $rows = $qry->result_array(); + } else { + $this->sys_error_db("ordertype error", $this->db_smartone); + exit; + } + + $result = array( + "records" => $rows, + "total_display" => sizeof($rows) + ); + + $this->sys_ok($result); + } +} \ No newline at end of file