Initial import

This commit is contained in:
sas.fajri
2026-04-27 10:26:26 +07:00
commit bf9b9097ee
2388 changed files with 3002242 additions and 0 deletions

View File

@@ -0,0 +1,435 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Apilis
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
function GetOrderDetail($nolab)
{
//$param = $this->param();
//$nolab = $param["orderNumber"];
$debug=true;
$sql = "SELECT COUNT(*) as exist_rujukan
FROM t_orderheader
JOIN t_orderheaderaddon ON T_OrderHeaderID = T_OrderHeaderAddonT_OrderHeaderID AND
T_OrderHeaderAddonIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN corporate ON T_OrderHeaderCorporateID = CorporateID AND CorporateIsActive = 'Y' AND
CorporateCorporateTypeID IN (1,3,4,12)
WHERE T_OrderHeaderLabNumber = ? AND T_OrderHeaderIsActive = 'Y'";
$qry = $this->db_onedev->query($sql, [$nolab]);
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail Rujukan issue [Order004]"],
"orderItemList" => [],
]);
exit;
}
$get_rujukan = $qry->row_array();
$exits_rujukan = $get_rujukan["exist_rujukan"];
if($exits_rujukan == 0) {
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
'CpOne001' AS physicianId,
'Dokter Laboratorium' AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
M_BranchCode AS guarantorId,
M_BranchName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}else{
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
M_DoctorCode AS physicianId,
M_DoctorName AS physicianName,
'' as isCito,
'' as diagnoseId,
T_OrderHeaderDiagnose as diagnoseName,
CorporateOldCompanyID AS guarantorId,
CorporateName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderAddOnIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN
m_doctor ON T_OrderHeaderAddOnM_DoctorSenderID = M_DoctorID
AND M_DoctorIsActive = 'Y'
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail issue [Order004]"],
"orderItemList" => [],
"debug" => $this->db_onedev->last_query()
]);
exit;
}
$rows = $qry->result_array();
//echo json_encode($rows);
//echo count($rows);
if($debug){
$q_las = $this->db_onedev->last_query();
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYPO',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,$q_las]);
//echo $this->db_onedev->last_query();
}
if(count($rows) > 0){
$result = [];
foreach ($rows as $idx => $r) {
if ($idx == 0) {
$result = $r;
unset($result["ItemCode"]);
unset($result["ItemName"]);
$result["orderItemList"] = [];
$result["ReceivedFlag"] = (bool) false;
}
$result["orderItemList"][] = [
"OrderItemId" => $r["ItemCode"],
"OrderItemName" => $r["ItemName"]
];
}
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSTDT',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($result)]);
}
//echo json_encode($result);
if(count($result) > 0){
$rst = $this->send_order($result);
}
return true;
}else{
return false;
}
}
function send_order($params)
{
$this->insert_api_push("new",$params,'');
$sql = "SELECT S_SystemsAPiPushUrl as urlx
FROM conf_systems
WHERE S_SystemsIsActive = 'Y'
LIMIT 1";
$qry = $this->db_onedev->query($sql);
// URL endpoint yang ingin dikirimkan POST request
$url = $qry->row()->urlx;
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYSYS',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($url)]);
}
// Inisialisasi CURL
$ch = curl_init($url);
// Mengatur CURL untuk mengirim POST request dengan JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
// Eksekusi CURL dan mendapatkan respons dari server
$response = curl_exec($ch);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSPN',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($response)]);
}
// Cek apakah ada error saat eksekusi CURL
/*if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
$response = curl_error($ch);
}*/
// Tutup CURL
curl_close($ch);
// print_r($response);
$this->insert_api_push("new",$params,$response);
$rst = json_decode($response);
$rst_rspn = stripslashes(json_encode($rst));
return $rst;
}
function insert_api_push($type,$params,$response){
//echo $response;
$rst = json_decode($response);
//print_r($rst);
//echo $rst->message;
$rst_save = stripslashes(json_encode($rst));
$res = json_encode($response);
$save_param = $params;
$nolab_lis = '';
$message = '';
if($response && $rst){
$nolab_lis = $rst->orderNumber?$rst->orderNumber:"Kosong";
$message = $rst->message;
}
$sql = "INSERT INTO api_push (
Api_PushDateTime,
Api_PushT_OrderHeaderLabNumber,
Api_PushParams,
Api_PushResponse,
Api_PushRetry,
Api_PushLISLabNumber,
Api_PushStatus,
Api_PushCreated
)
VALUES(NOW(),?,?,?,?,?,?,NOW())
ON DUPLICATE KEY
UPDATE Api_PushLastUpdated = NOW(), Api_PushParams = ?, Api_PushResponse = ?, Api_PushRetry = IF('{$type}' = 'retry', Api_PushRetry + 1,Api_PushRetry), Api_PushStatus = ?";
$qry = $this->db_onedev->query($sql, [$params['orderNumber'], stripslashes(json_encode($save_param)), $rst_save, 1, $nolab_lis, $message,stripslashes(json_encode($save_param)), $rst_save, $message]);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, Debug_LogMessage)
VALUES ('QRYPUSH',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab_lis,$this->db_onedev->last_query()]);
}
//echo $this->db_onedev->last_query();
//exit;
return true;
}
function generate_kelainan_nonlab($orderID,$userID){
$sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID
FROM so_resultentry_category_result
JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND
So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y'
JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND
T_OrderHeaderID = ?
JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_OrderDetailT_TestID = T_TestID
JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND
Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs)
WHERE
So_ResultEntryCategoryResultIsActive = 'Y'";
$qry = $this->db_onedev->query($sql,array($orderID));
if (!$qry) {
echo $this->db_onedev->last_query();
echo json_encode([
"status" => "ERR",
"message" => "Error get order | " . $this->db_onedev->error()["message"]
]);
exit;
}
$rows = $qry->result_array();
$sql = "UPDATE t_kelainan_nonlab SET
T_KelainanNonLabIsActive = 'N'
WHERE
T_KelainanNonLabT_OrderHeaderID = ? AND
T_KelainanNonLabIsActive = 'Y'
";
$qry = $this->db_onedev->query($sql,array($orderID));
foreach ($rows as $key => $value) {
$sql = "INSERT INTO t_kelainan_nonlab (
T_KelainanNonLabSo_ResultEntryID,
T_KelainanNonLabT_OrderHeaderID,
T_KelainanNonLabNat_TestID,
T_KelainanNonLabMcu_SummaryNonlabID,
T_KelainanNonLabCreatedUserID,
T_KelainanLabNonCreated
) VALUES(?,?,?,?,?,NOW())";
$qry = $this->db_onedev->query($sql,[
$value['So_ResultEntryID'],
$value['T_OrderHeaderID'],
$value['T_TestNat_TestID'],
$value['Mcu_SummaryNonlabID'],
$userID
]);
}
}
}

View File

@@ -0,0 +1,435 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Apilis
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
function GetOrderDetail($nolab)
{
//$param = $this->param();
//$nolab = $param["orderNumber"];
$debug=true;
$sql = "SELECT COUNT(*) as exist_rujukan
FROM t_orderheader
JOIN t_orderheaderaddon ON T_OrderHeaderID = T_OrderHeaderAddonT_OrderHeaderID AND
T_OrderHeaderAddonIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN corporate ON T_OrderHeaderCorporateID = CorporateID AND CorporateIsActive = 'Y' AND
CorporateCorporateTypeID IN (1,3,4,12)
WHERE T_OrderHeaderLabNumber = ? AND T_OrderHeaderIsActive = 'Y'";
$qry = $this->db_onedev->query($sql, [$nolab]);
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail Rujukan issue [Order004]"],
"orderItemList" => [],
]);
exit;
}
$get_rujukan = $qry->row_array();
$exits_rujukan = $get_rujukan["exist_rujukan"];
if($exits_rujukan == 0) {
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
'CpOne001' AS physicianId,
'Dokter Laboratorium' AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
M_BranchCode AS guarantorId,
M_BranchName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}else{
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
M_DoctorCode AS physicianId,
M_DoctorName AS physicianName,
'' as isCito,
'' as diagnoseId,
T_OrderHeaderDiagnose as diagnoseName,
CorporateOldCompanyID AS guarantorId,
CorporateName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderAddOnIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN
m_doctor ON T_OrderHeaderAddOnM_DoctorSenderID = M_DoctorID
AND M_DoctorIsActive = 'Y'
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail issue [Order004]"],
"orderItemList" => [],
"debug" => $this->db_onedev->last_query()
]);
exit;
}
$rows = $qry->result_array();
//echo json_encode($rows);
//echo count($rows);
if($debug){
$q_las = $this->db_onedev->last_query();
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYPO',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,$q_las]);
//echo $this->db_onedev->last_query();
}
if(count($rows) > 0){
$result = [];
foreach ($rows as $idx => $r) {
if ($idx == 0) {
$result = $r;
unset($result["ItemCode"]);
unset($result["ItemName"]);
$result["orderItemList"] = [];
$result["ReceivedFlag"] = (bool) false;
}
$result["orderItemList"][] = [
"OrderItemId" => $r["ItemCode"],
"OrderItemName" => $r["ItemName"]
];
}
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSTDT',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($result)]);
}
//echo json_encode($result);
if(count($result) > 0){
$rst = $this->send_order($result);
}
return true;
}else{
return false;
}
}
function send_order($params)
{
$this->insert_api_push("new",$params,'');
$sql = "SELECT S_SystemsAPiPushUrl as urlx
FROM conf_systems
WHERE S_SystemsIsActive = 'Y'
LIMIT 1";
$qry = $this->db_onedev->query($sql);
// URL endpoint yang ingin dikirimkan POST request
$url = $qry->row()->urlx;
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYSYS',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($url)]);
}
// Inisialisasi CURL
$ch = curl_init($url);
// Mengatur CURL untuk mengirim POST request dengan JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
// Eksekusi CURL dan mendapatkan respons dari server
$response = curl_exec($ch);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSPN',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($response)]);
}
// Cek apakah ada error saat eksekusi CURL
/*if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
$response = curl_error($ch);
}*/
// Tutup CURL
curl_close($ch);
// print_r($response);
$this->insert_api_push("new",$params,$response);
$rst = json_decode($response);
$rst_rspn = stripslashes(json_encode($rst));
return $rst;
}
function insert_api_push($type,$params,$response){
//echo $response;
$rst = json_decode($response);
//print_r($rst);
//echo $rst->message;
$rst_save = stripslashes(json_encode($rst));
$res = json_encode($response);
$save_param = $params;
$nolab_lis = '';
$message = '';
if($response && $rst){
$nolab_lis = $rst->orderNumber?$rst->orderNumber:"Kosong";
$message = $rst->message;
}
$sql = "INSERT INTO api_push (
Api_PushDateTime,
Api_PushT_OrderHeaderLabNumber,
Api_PushParams,
Api_PushResponse,
Api_PushRetry,
Api_PushLISLabNumber,
Api_PushStatus,
Api_PushCreated
)
VALUES(NOW(),?,?,?,?,?,?,NOW())
ON DUPLICATE KEY
UPDATE Api_PushLastUpdated = NOW(), Api_PushParams = ?, Api_PushResponse = ?, Api_PushRetry = IF('{$type}' = 'retry', Api_PushRetry + 1,Api_PushRetry), Api_PushStatus = ?";
$qry = $this->db_onedev->query($sql, [$params['orderNumber'], stripslashes(json_encode($save_param)), $rst_save, 1, $nolab_lis, $message,stripslashes(json_encode($save_param)), $rst_save, $message]);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, Debug_LogMessage)
VALUES ('QRYPUSH',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab_lis,$this->db_onedev->last_query()]);
}
//echo $this->db_onedev->last_query();
//exit;
return true;
}
function generate_kelainan_nonlab($orderID,$userID){
$sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID
FROM so_resultentry_category_result
JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND
So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y'
JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND
T_OrderHeaderID = ?
JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_OrderDetailT_TestID = T_TestID
JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND
Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs)
WHERE
So_ResultEntryCategoryResultIsActive = 'Y'";
$qry = $this->db_onedev->query($sql,array($orderID));
if (!$qry) {
echo $this->db_onedev->last_query();
echo json_encode([
"status" => "ERR",
"message" => "Error get order | " . $this->db_onedev->error()["message"]
]);
exit;
}
$rows = $qry->result_array();
$sql = "UPDATE t_kelainan_nonlab SET
T_KelainanNonLabIsActive = 'N'
WHERE
T_KelainanNonLabT_OrderHeaderID = ? AND
T_KelainanNonLabIsActive = 'Y'
";
$qry = $this->db_onedev->query($sql,array($orderID));
foreach ($rows as $key => $value) {
$sql = "INSERT INTO t_kelainan_nonlab (
T_KelainanNonLabSo_ResultEntryID,
T_KelainanNonLabT_OrderHeaderID,
T_KelainanNonLabNat_TestID,
T_KelainanNonLabMcu_SummaryNonlabID,
T_KelainanNonLabCreatedUserID,
T_KelainanLabNonCreated
) VALUES(?,?,?,?,?,NOW())";
$qry = $this->db_onedev->query($sql,[
$value['So_ResultEntryID'],
$value['T_OrderHeaderID'],
$value['T_TestNat_TestID'],
$value['Mcu_SummaryNonlabID'],
$userID
]);
}
}
}

View File

@@ -0,0 +1,435 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Apilis
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
function GetOrderDetail($nolab)
{
//$param = $this->param();
//$nolab = $param["orderNumber"];
$debug=true;
$sql = "SELECT COUNT(*) as exist_rujukan
FROM t_orderheader
JOIN t_orderheaderaddon ON T_OrderHeaderID = T_OrderHeaderAddonT_OrderHeaderID AND
T_OrderHeaderAddonIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN corporate ON T_OrderHeaderCorporateID = CorporateID AND CorporateIsActive = 'Y' AND
CorporateCorporateTypeID = 1
WHERE T_OrderHeaderLabNumber = ? AND T_OrderHeaderIsActive = 'Y'";
$qry = $this->db_onedev->query($sql, [$nolab]);
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail Rujukan issue [Order004]"],
"orderItemList" => [],
]);
exit;
}
$get_rujukan = $qry->row_array();
$exits_rujukan = $get_rujukan["exist_rujukan"];
if($exits_rujukan == 0) {
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
'CpOne001' AS physicianId,
'Dokter Laboratorium' AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
M_BranchCode AS guarantorId,
M_BranchName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}else{
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
M_DoctorCode AS physicianId,
M_DoctorName AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
CorporateOldCompanyID AS guarantorId,
CorporateName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName,
IF(Nat_TestReferID IS NULL, 'N', 'Y') AS IsRefer
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderAddOnIsActive = 'Y' AND T_OrderHeaderAddOnOrderType = 'RUJUKAN'
JOIN
m_doctor ON T_OrderHeaderAddOnM_DoctorSenderID = M_DoctorID
AND M_DoctorIsActive = 'Y'
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN nat_testrefer ON Nat_TestReferNat_TestID = T_TestNat_TestID AND Nat_TestReferIsActive = 'Y' AND Nat_TestReferM_BranchID = M_BranchID
LEFT JOIN nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN m_title ON M_PatientM_TitleID = M_TitleID
WHERE
T_OrderHeaderIsActive = 'Y' AND ISNULL(Nat_TestReferNat_TestID)
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
}
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail issue [Order004]"],
"orderItemList" => [],
"debug" => $this->db_onedev->last_query()
]);
exit;
}
$rows = $qry->result_array();
//echo json_encode($rows);
//echo count($rows);
if($debug){
$q_las = $this->db_onedev->last_query();
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYPO',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,$q_las]);
//echo $this->db_onedev->last_query();
}
if(count($rows) > 0){
$result = [];
foreach ($rows as $idx => $r) {
if ($idx == 0) {
$result = $r;
unset($result["ItemCode"]);
unset($result["ItemName"]);
$result["orderItemList"] = [];
$result["ReceivedFlag"] = (bool) false;
}
$result["orderItemList"][] = [
"OrderItemId" => $r["ItemCode"],
"OrderItemName" => $r["ItemName"]
];
}
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSTDT',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($result)]);
}
//echo json_encode($result);
if(count($result) > 0){
$rst = $this->send_order($result);
}
return true;
}else{
return false;
}
}
function send_order($params)
{
$this->insert_api_push("new",$params,'');
$sql = "SELECT S_SystemsAPiPushUrl as urlx
FROM conf_systems
WHERE S_SystemsIsActive = 'Y'
LIMIT 1";
$qry = $this->db_onedev->query($sql);
// URL endpoint yang ingin dikirimkan POST request
$url = $qry->row()->urlx;
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYSYS',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($url)]);
}
// Inisialisasi CURL
$ch = curl_init($url);
// Mengatur CURL untuk mengirim POST request dengan JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
// Eksekusi CURL dan mendapatkan respons dari server
$response = curl_exec($ch);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSPN',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($response)]);
}
// Cek apakah ada error saat eksekusi CURL
/*if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
$response = curl_error($ch);
}*/
// Tutup CURL
curl_close($ch);
// print_r($response);
$this->insert_api_push("new",$params,$response);
$rst = json_decode($response);
$rst_rspn = stripslashes(json_encode($rst));
return $rst;
}
function insert_api_push($type,$params,$response){
//echo $response;
$rst = json_decode($response);
//print_r($rst);
//echo $rst->message;
$rst_save = stripslashes(json_encode($rst));
$res = json_encode($response);
$save_param = $params;
$nolab_lis = '';
$message = '';
if($response && $rst){
$nolab_lis = $rst->orderNumber?$rst->orderNumber:"Kosong";
$message = $rst->message;
}
$sql = "INSERT INTO api_push (
Api_PushDateTime,
Api_PushT_OrderHeaderLabNumber,
Api_PushParams,
Api_PushResponse,
Api_PushRetry,
Api_PushLISLabNumber,
Api_PushStatus,
Api_PushCreated
)
VALUES(NOW(),?,?,?,?,?,?,NOW())
ON DUPLICATE KEY
UPDATE Api_PushLastUpdated = NOW(), Api_PushParams = ?, Api_PushResponse = ?, Api_PushRetry = IF('{$type}' = 'retry', Api_PushRetry + 1,Api_PushRetry), Api_PushStatus = ?";
$qry = $this->db_onedev->query($sql, [$params['orderNumber'], stripslashes(json_encode($save_param)), $rst_save, 1, $nolab_lis, $message,stripslashes(json_encode($save_param)), $rst_save, $message]);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, Debug_LogMessage)
VALUES ('QRYPUSH',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab_lis,$this->db_onedev->last_query()]);
}
//echo $this->db_onedev->last_query();
//exit;
return true;
}
function generate_kelainan_nonlab($orderID,$userID){
$sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID
FROM so_resultentry_category_result
JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND
So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y'
JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND
T_OrderHeaderID = ?
JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_OrderDetailT_TestID = T_TestID
JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND
Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs)
WHERE
So_ResultEntryCategoryResultIsActive = 'Y'";
$qry = $this->db_onedev->query($sql,array($orderID));
if (!$qry) {
echo $this->db_onedev->last_query();
echo json_encode([
"status" => "ERR",
"message" => "Error get order | " . $this->db_onedev->error()["message"]
]);
exit;
}
$rows = $qry->result_array();
$sql = "UPDATE t_kelainan_nonlab SET
T_KelainanNonLabIsActive = 'N'
WHERE
T_KelainanNonLabT_OrderHeaderID = ? AND
T_KelainanNonLabIsActive = 'Y'
";
$qry = $this->db_onedev->query($sql,array($orderID));
foreach ($rows as $key => $value) {
$sql = "INSERT INTO t_kelainan_nonlab (
T_KelainanNonLabSo_ResultEntryID,
T_KelainanNonLabT_OrderHeaderID,
T_KelainanNonLabNat_TestID,
T_KelainanNonLabMcu_SummaryNonlabID,
T_KelainanNonLabCreatedUserID,
T_KelainanLabNonCreated
) VALUES(?,?,?,?,?,NOW())";
$qry = $this->db_onedev->query($sql,[
$value['So_ResultEntryID'],
$value['T_OrderHeaderID'],
$value['T_TestNat_TestID'],
$value['Mcu_SummaryNonlabID'],
$userID
]);
}
}
}

View File

@@ -0,0 +1,302 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Apilis
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
function GetOrderDetail($nolab)
{
//$param = $this->param();
//$nolab = $param["orderNumber"];
$sql = "SELECT
M_BranchCodeLab AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
CONCAT(
IF(M_PatientPrefix IS NOT NULL, M_PatientPrefix, ''),
IF(M_PatientPrefix IS NOT NULL, ' ', ''),
M_PatientName,
IF(M_PatientSuffix IS NOT NULL, M_PatientSuffix, ''),
IF(M_PatientSuffix IS NOT NULL, ' ', '')
) AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
'CpOne001' AS physicianId,
'Dokter Laboratorium' AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
M_BranchCode AS guarantorId,
M_BranchName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderIsActive = 'Y'
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN
nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN
m_title ON M_PatientM_TitleID = M_TitleID
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
//echo $this->db_onedev->last_query();
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail issue [Order004]"],
"orderItemList" => [],
]);
exit;
}
$rows = $qry->result_array();
if($rows){
$result = [];
foreach ($rows as $idx => $r) {
if ($idx == 0) {
$result = $r;
unset($result["ItemCode"]);
unset($result["ItemName"]);
$result["orderItemList"] = [];
$result["ReceivedFlag"] = (bool) false;
}
$result["orderItemList"][] = [
"OrderItemId" => $r["ItemCode"],
"OrderItemName" => $r["ItemName"]
];
}
//echo json_encode($result);
if(count($result) > 0){
$rst = $this->send_order($result);
}
return true;
}else{
return false;
}
}
function send_order($params)
{
//$this->insert_api_push("new",$params,'');
$sql = "SELECT S_SystemsAPiPushUrl as urlx
FROM conf_systems
WHERE S_SystemsIsActive = 'Y'
LIMIT 1";
$qry = $this->db_onedev->query($sql);
// URL endpoint yang ingin dikirimkan POST request
$url = $qry->row()->urlx;
// Inisialisasi CURL
$ch = curl_init($url);
// Mengatur CURL untuk mengirim POST request dengan JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
// Eksekusi CURL dan mendapatkan respons dari server
$response = curl_exec($ch);
// Cek apakah ada error saat eksekusi CURL
/*if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
$response = curl_error($ch);
}*/
// Tutup CURL
curl_close($ch);
//print_r($response);
$this->insert_api_push("new",$params,$response);
$rst = json_decode($response);
$rst_rspn = stripslashes(json_encode($rst));
return $rst;
}
function insert_api_push($type,$params,$response){
//echo $response;
$rst = json_decode($response);
//print_r($rst);
//echo $rst->message;
$rst_save = stripslashes(json_encode($rst));
$res = json_encode($response);
$save_param = $params;
$nolab_lis = '';
$message = '';
if($response && $rst){
$nolab_lis = $rst->orderNumber?$rst->orderNumber:"Kosong";
$message = $rst->message;
}
$sql = "INSERT INTO api_push (
Api_PushDateTime,
Api_PushT_OrderHeaderLabNumber,
Api_PushParams,
Api_PushResponse,
Api_PushRetry,
Api_PushLISLabNumber,
Api_PushStatus,
Api_PushCreated
)
VALUES(NOW(),?,?,?,?,?,?,NOW())
ON DUPLICATE KEY
UPDATE Api_PushLastUpdated = NOW(), Api_PushParams = ?, Api_PushResponse = ?, Api_PushRetry = IF('{$type}' = 'retry', Api_PushRetry + 1,Api_PushRetry), Api_PushStatus = ?";
$qry = $this->db_onedev->query($sql, [$params['orderNumber'], stripslashes(json_encode($save_param)), $rst_save, 1, $nolab_lis, $message,stripslashes(json_encode($save_param)), $rst_save, $message]);
return true;
}
function generate_kelainan_nonlab($orderID,$userID){
$sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID
FROM so_resultentry_category_result
JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND
So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y'
JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND
T_OrderHeaderID = ?
JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_OrderDetailT_TestID = T_TestID
JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND
Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs)
WHERE
So_ResultEntryCategoryResultIsActive = 'Y'";
$qry = $this->db_onedev->query($sql,array($orderID));
if (!$qry) {
echo $this->db_onedev->last_query();
echo json_encode([
"status" => "ERR",
"message" => "Error get order | " . $this->db_onedev->error()["message"]
]);
exit;
}
$rows = $qry->result_array();
$sql = "UPDATE t_kelainan_nonlab SET
T_KelainanNonLabIsActive = 'N'
WHERE
T_KelainanNonLabT_OrderHeaderID = ? AND
T_KelainanNonLabIsActive = 'Y'
";
$qry = $this->db_onedev->query($sql,array($orderID));
foreach ($rows as $key => $value) {
$sql = "INSERT INTO t_kelainan_nonlab (
T_KelainanNonLabSo_ResultEntryID,
T_KelainanNonLabT_OrderHeaderID,
T_KelainanNonLabNat_TestID,
T_KelainanNonLabMcu_SummaryNonlabID,
T_KelainanNonLabCreatedUserID,
T_KelainanLabNonCreated
) VALUES(?,?,?,?,?,NOW())";
$qry = $this->db_onedev->query($sql,[
$value['So_ResultEntryID'],
$value['T_OrderHeaderID'],
$value['T_TestNat_TestID'],
$value['Mcu_SummaryNonlabID'],
$userID
]);
}
}
}

View File

@@ -0,0 +1,324 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Apilis
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
function GetOrderDetail($nolab)
{
//$param = $this->param();
//$nolab = $param["orderNumber"];
$debug=true;
$sql = "SELECT
M_BranchCodeBridging AS outletId,
T_OrderHeaderLabNumber as orderNumber,
REPLACE(T_OrderHeaderDate, '-', '/') AS orderDT,
T_OrderHeaderLabNumber AS visitNumber,
M_PatientNoreg AS patientId,
M_PatientName AS patientName,
IF(LOWER(M_PatientGender) = 'male', 'L', 'P') AS sexId,
IF(LOWER(M_PatientGender) = 'male', 'Male', 'Female') AS sexName,
REPLACE(M_PatientDOB, '-', '/') AS dob,
IFNULL(M_TitleName,'') as titleName,
'' AS pob,
M_PatientAddress AS addressName,
'' AS cityId,
M_PatientAddressCity AS cityName,
M_PatientHp as mobileNumber,
'' AS phoneNumber,
'' AS faxNumber,
M_PatientEmail as email,
M_PatientIdentifierValue as idNIK,
'' as idSIM,
'' as idPassport,
'CpOne001' AS physicianId,
'Dokter Laboratorium' AS physicianName,
'' as isCito,
'' as diagnoseId,
'' as diagnoseName,
M_BranchCode AS guarantorId,
M_BranchName AS guarantorName,
'Cp1' AS agreementId,
'CpOne' AS agreementName,
'' as serviceUnitId,
'' as serviceUnitName,
'' as wardPoliId,
'' as wardPoliName,
'' as roomId,
'' as roomName,
CorporateID as bedId,
CorporateName as bedName,
'' as classId,
'' as className,
1 as regUserId,
'admin' as regUserName,
RIGHT(M_BranchCode, 6) AS BranchCode,
M_BranchName AS BranchName,
FALSE AS ReceivedFlag,
NULL AS LabRegNo,
NULL AS ReceivedDateTime,
IFNULL(Nat_TestMapCode, 'Un-Map') AS ItemCode,
T_TestName AS ItemName
FROM
t_orderheader
JOIN
m_branch ON T_OrderHeaderLabNumber = ?
AND T_OrderHeaderIsActive = 'Y'
AND T_OrderHeaderM_BranchID = M_BranchID
AND M_BranchIsActive = 'Y'
JOIN
corporate ON T_OrderHeaderCorporateID = CorporateID
AND CorporateIsActive = 'Y'
JOIN
m_patient ON T_OrderHeaderM_PatientID = M_PatientID
JOIN
t_orderdetail ON T_OrderHeaderID = T_OrderDetailT_OrderHeaderID
AND T_OrderDetailIsActive = 'Y'
JOIN
t_test ON T_OrderDetailT_TestID = T_TestID
AND T_TestIsPrice = 'Y'
AND T_TestNat_GroupID = 1
LEFT JOIN
nat_testmap ON T_TestNat_TestID = Nat_TestMapNat_TestID
AND Nat_TestMapIsActive = 'Y'
LEFT JOIN
m_title ON M_PatientM_TitleID = M_TitleID
ORDER BY
T_OrderHeaderLabNumber, Nat_TestMapCode;";
$qry = $this->db_onedev->query($sql, [$nolab]);
//echo $this->db_onedev->last_query();
if (!$qry) {
echo json_encode([
"Status" => ["OK" => false, "Code" => 0, "Messages" => "Get Order Detail issue [Order004]"],
"orderItemList" => [],
]);
exit;
}
$rows = $qry->result_array();
//echo json_encode($rows);
//echo count($rows);
if($debug){
$q_las = $this->db_onedev->last_query();
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYPO',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,$q_las]);
//echo $this->db_onedev->last_query();
}
if(count($rows) > 0){
$result = [];
foreach ($rows as $idx => $r) {
if ($idx == 0) {
$result = $r;
unset($result["ItemCode"]);
unset($result["ItemName"]);
$result["orderItemList"] = [];
$result["ReceivedFlag"] = (bool) false;
}
$result["orderItemList"][] = [
"OrderItemId" => $r["ItemCode"],
"OrderItemName" => $r["ItemName"]
];
}
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSTDT',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($result)]);
}
//echo json_encode($result);
if(count($result) > 0){
$rst = $this->send_order($result);
}
return true;
}else{
return false;
}
}
function send_order($params)
{
$this->insert_api_push("new",$params,'');
$sql = "SELECT S_SystemsAPiPushUrl as urlx
FROM conf_systems
WHERE S_SystemsIsActive = 'Y'
LIMIT 1";
$qry = $this->db_onedev->query($sql);
// URL endpoint yang ingin dikirimkan POST request
$url = $qry->row()->urlx;
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('QUERYSYS',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($url)]);
}
// Inisialisasi CURL
$ch = curl_init($url);
// Mengatur CURL untuk mengirim POST request dengan JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
// Eksekusi CURL dan mendapatkan respons dari server
$response = curl_exec($ch);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, DebugLogMessage)
VALUES ('RSPN',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab,json_encode($response)]);
}
// Cek apakah ada error saat eksekusi CURL
/*if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
$response = curl_error($ch);
}*/
// Tutup CURL
curl_close($ch);
// print_r($response);
$this->insert_api_push("new",$params,$response);
$rst = json_decode($response);
$rst_rspn = stripslashes(json_encode($rst));
return $rst;
}
function insert_api_push($type,$params,$response){
//echo $response;
$rst = json_decode($response);
//print_r($rst);
//echo $rst->message;
$rst_save = stripslashes(json_encode($rst));
$res = json_encode($response);
$save_param = $params;
$nolab_lis = '';
$message = '';
if($response && $rst){
$nolab_lis = $rst->orderNumber?$rst->orderNumber:"Kosong";
$message = $rst->message;
}
$sql = "INSERT INTO api_push (
Api_PushDateTime,
Api_PushT_OrderHeaderLabNumber,
Api_PushParams,
Api_PushResponse,
Api_PushRetry,
Api_PushLISLabNumber,
Api_PushStatus,
Api_PushCreated
)
VALUES(NOW(),?,?,?,?,?,?,NOW())
ON DUPLICATE KEY
UPDATE Api_PushLastUpdated = NOW(), Api_PushParams = ?, Api_PushResponse = ?, Api_PushRetry = IF('{$type}' = 'retry', Api_PushRetry + 1,Api_PushRetry), Api_PushStatus = ?";
$qry = $this->db_onedev->query($sql, [$params['orderNumber'], stripslashes(json_encode($save_param)), $rst_save, 1, $nolab_lis, $message,stripslashes(json_encode($save_param)), $rst_save, $message]);
if($debug){
$sql = "INSERT INTO debug_log (DebugLogCode, DebugLogRefID, Debug_LogMessage)
VALUES ('QRYPUSH',?,?)";
$qry = $this->db_onedev->query($sql,[$nolab_lis,$this->db_onedev->last_query()]);
}
//echo $this->db_onedev->last_query();
//exit;
return true;
}
function generate_kelainan_nonlab($orderID,$userID){
$sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID
FROM so_resultentry_category_result
JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND
So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y'
JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND
T_OrderHeaderID = ?
JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_OrderDetailT_TestID = T_TestID
JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND
Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs)
WHERE
So_ResultEntryCategoryResultIsActive = 'Y'";
$qry = $this->db_onedev->query($sql,array($orderID));
if (!$qry) {
echo $this->db_onedev->last_query();
echo json_encode([
"status" => "ERR",
"message" => "Error get order | " . $this->db_onedev->error()["message"]
]);
exit;
}
$rows = $qry->result_array();
$sql = "UPDATE t_kelainan_nonlab SET
T_KelainanNonLabIsActive = 'N'
WHERE
T_KelainanNonLabT_OrderHeaderID = ? AND
T_KelainanNonLabIsActive = 'Y'
";
$qry = $this->db_onedev->query($sql,array($orderID));
foreach ($rows as $key => $value) {
$sql = "INSERT INTO t_kelainan_nonlab (
T_KelainanNonLabSo_ResultEntryID,
T_KelainanNonLabT_OrderHeaderID,
T_KelainanNonLabNat_TestID,
T_KelainanNonLabMcu_SummaryNonlabID,
T_KelainanNonLabCreatedUserID,
T_KelainanLabNonCreated
) VALUES(?,?,?,?,?,NOW())";
$qry = $this->db_onedev->query($sql,[
$value['So_ResultEntryID'],
$value['T_OrderHeaderID'],
$value['T_TestNat_TestID'],
$value['Mcu_SummaryNonlabID'],
$userID
]);
}
}
}

View File

@@ -0,0 +1,230 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Autosamplingverif
{
function __construct()
{
$CI = &get_instance();
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection( $dbc )
{
while( mysqli_more_results($dbc) )
{
if(mysqli_next_result($dbc))
{
$result = mysqli_use_result($dbc);
if( get_class($result) == 'mysqli_stmt' )
{
mysqli_stmt_free_result($result);
}
else
{
unset($result);
}
}
}
}
function doaction($rst_id,$samplingtime,$userid){
$sql = "call sp_fo_barcode_generate_again_not_exist(" . $rst_id . ")";
$this->db_onedev->query($sql);
$this->clean_mysqli_connection($this->db_onedev->conn_id);
$sql = "SELECT *
FROM t_orderheader
JOIN t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID
WHERE T_OrderHeaderID = {$rst_id}";
//echo $sql;
$row_addon = $this->db_onedev->query($sql)->row_array();
$readytime = date('Y-m-d H:i:s', strtotime($samplingtime));
//echo $readytime;
$sql = "UPDATE t_ordersample
SET
T_OrderSampleSampling = 'Y',
T_OrderSampleSamplingDate = DATE('{$samplingtime}'),
T_OrderSampleSamplingTime = TIME('{$samplingtime}'),
T_OrderSampleSamplingUserID = {$userid},
T_OrderSampleReceive = 'Y',
T_OrderSampleReceiveDate = DATE('{$samplingtime}'),
T_OrderSampleReceiveTime = TIME('{$samplingtime}'),
T_OrderSampleReadyToProcessDateTime = '{$readytime}',
T_OrderSampleVerification = 'Y',
T_OrderSampleVerificationDate = CURDATE(),
T_OrderSampleVerificationTime = CURTIME(),
T_OrderSampleVerificationUserID = {$userid},
T_OrderSampleSendHandling = 'Y',
T_OrderSampleSendHandlingDate = CURDATE(),
T_OrderSampleSendHandlingTime = CURTIME(),
T_OrderSampleSendHandlingUserID = {$userid},
T_OrderSampleReceiveUserID = {$userid},
T_OrderSampleReceiveHandling = 'Y',
T_OrderSampleReceiveHandlingDate = CURDATE(),
T_OrderSampleReceiveHandlingTime = CURTIME(),
T_OrderSampleReceiveHandlingUserID = {$userid}
WHERE
T_OrderSampleT_OrderHeaderID = {$rst_id}";
$upd_ordersample = $this->db_onedev->query($sql);
//echo $sql;
$sql = "SELECT *
FROM t_ordersample
JOIN t_barcodelab ON T_OrderSampleT_BarcodeLabID = T_BarcodeLabID AND T_BarcodeLabIsActive = 'Y'
JOIN t_sampletype ON T_SampleTypeID = T_OrderSampleT_SampleTypeID
JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID
JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID
WHERE
T_OrderSampleT_OrderHeaderID = {$rst_id} AND
T_OrderSampleIsActive = 'Y'";
$data_loop = $this->db_onedev->query($sql)->result_array();
if ($data_loop) {
foreach ($data_loop as $ks => $vs) {
$sql = "INSERT INTO t_ordersamplereq(
T_OrderSampleReqT_OrderHeaderID,
T_OrderSampleReqT_SampleStationID,
T_OrderSampleReqT_OrderSampleID,
T_OrderSampleReqNat_PositionID,
T_OrderSampleReqStatus,
T_OrderSampleReqs,
T_OrderSampleReqUserID,
T_OrderSampleReqCreated
)
VALUES(
{$rst_id},
{$vs['T_SampleStationID']},
{$vs['T_OrderSampleID']},
'2',
'Y',
'[]',
{$userid},
NOW()
)ON DUPLICATE KEY UPDATE
T_OrderSampleReqStatus = 'Y',
T_OrderSampleReqs = '[]',
T_OrderSampleReqUserID = {$userid}";
//echo $sql;
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Sampling.Sampled',
{$rst_id},
{$vs['T_BarcodeLabID']},
'Y',
'[]',
{$userid},
'{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}'
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Sampling.Received',
{$rst_id},
{$vs['T_BarcodeLabID']},
'Y',
'[]',
{$userid},
'{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}'
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Verification.Verify',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Verification.To.Handling',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Handling.From.Verification',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$query = " INSERT INTO t_sampling_queue_last_status (
T_SamplingQueueLastStatusT_SampleStationID,
T_SamplingQueueLastStatusT_OrderHeaderID,
T_SamplingQueueLastStatusT_SamplingQueueStatusID,
T_SamplingQueueLastStatusUserID)
VALUES(
{$vs['T_SampleStationID']},
{$rst_id},
'5',
{$userid})
ON DUPLICATE KEY UPDATE
T_SamplingQueueLastStatusT_SamplingQueueStatusID = 5,
T_SamplingQueueLastStatusUserID = {$userid}";
//echo $query;
$this->db_onedev->query($query);
}
}
}
}

View File

@@ -0,0 +1,249 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Checkmenu
{
function __construct()
{
$CI = &get_instance();
$this->db_onedev = $CI->load->database("default", true);
}
function clean_mysqli_connection( $dbc )
{
while( mysqli_more_results($dbc) )
{
if(mysqli_next_result($dbc))
{
$result = mysqli_use_result($dbc);
if( get_class($result) == 'mysqli_stmt' )
{
mysqli_stmt_free_result($result);
}
else
{
unset($result);
}
}
}
}
function test_priviledge($menu_code,$userID){
$sql = "SELECT COUNT(*) as xcount
FROM s_privilege
JOIN m_user ON M_UserID = {$userID} AND M_UserIsActive = 'Y' AND
M_UserM_UserGroupID = S_PrivilegeM_UserGroupID
JOIN s_menu ON S_PrivilegeS_MenuID = S_MenuID AND S_MenuCode = '{$menu_code}'
WHERE
S_PrivilegeIsActive = 'Y'";
// echo $sql;
$check_exist = $this->db_onedev->query($sql)->row_array();
//echo $this->db_onedev->last_query();
if($check_exist['xcount'] > 0 ){
return true;
}
else{
return false;
}
}
function doaction($rst_id,$samplingtime,$userid){
$sql = "call sp_fo_barcode_generate_again_not_exist(" . $rst_id . ")";
$this->db_onedev->query($sql);
$this->clean_mysqli_connection($this->db_onedev->conn_id);
$sql = "SELECT *
FROM t_orderheader
JOIN t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID
WHERE T_OrderHeaderID = {$rst_id}";
//echo $sql;
$row_addon = $this->db_onedev->query($sql)->row_array();
$readytime = date('Y-m-d H:i:s', strtotime($samplingtime));
//echo $readytime;
$sql = "UPDATE t_ordersample
SET
T_OrderSampleSampling = 'Y',
T_OrderSampleSamplingDate = DATE('{$samplingtime}'),
T_OrderSampleSamplingTime = TIME('{$samplingtime}'),
T_OrderSampleSamplingUserID = {$userid},
T_OrderSampleReceive = 'Y',
T_OrderSampleReceiveDate = DATE('{$samplingtime}'),
T_OrderSampleReceiveTime = TIME('{$samplingtime}'),
T_OrderSampleReadyToProcessDateTime = '{$readytime}',
T_OrderSampleVerification = 'Y',
T_OrderSampleVerificationDate = CURDATE(),
T_OrderSampleVerificationTime = CURTIME(),
T_OrderSampleVerificationUserID = {$userid},
T_OrderSampleSendHandling = 'Y',
T_OrderSampleSendHandlingDate = CURDATE(),
T_OrderSampleSendHandlingTime = CURTIME(),
T_OrderSampleSendHandlingUserID = {$userid},
T_OrderSampleReceiveUserID = {$userid},
T_OrderSampleReceiveHandling = 'Y',
T_OrderSampleReceiveHandlingDate = CURDATE(),
T_OrderSampleReceiveHandlingTime = CURTIME(),
T_OrderSampleReceiveHandlingUserID = {$userid}
WHERE
T_OrderSampleT_OrderHeaderID = {$rst_id}";
$upd_ordersample = $this->db_onedev->query($sql);
//echo $sql;
$sql = "SELECT *
FROM t_ordersample
JOIN t_barcodelab ON T_OrderSampleT_BarcodeLabID = T_BarcodeLabID AND T_BarcodeLabIsActive = 'Y'
JOIN t_sampletype ON T_SampleTypeID = T_OrderSampleT_SampleTypeID
JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID
JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID
WHERE
T_OrderSampleT_OrderHeaderID = {$rst_id} AND
T_OrderSampleIsActive = 'Y'";
$data_loop = $this->db_onedev->query($sql)->result_array();
if ($data_loop) {
foreach ($data_loop as $ks => $vs) {
$sql = "INSERT INTO t_ordersamplereq(
T_OrderSampleReqT_OrderHeaderID,
T_OrderSampleReqT_SampleStationID,
T_OrderSampleReqT_OrderSampleID,
T_OrderSampleReqNat_PositionID,
T_OrderSampleReqStatus,
T_OrderSampleReqs,
T_OrderSampleReqUserID,
T_OrderSampleReqCreated
)
VALUES(
{$rst_id},
{$vs['T_SampleStationID']},
{$vs['T_OrderSampleID']},
'2',
'Y',
'[]',
{$userid},
NOW()
)ON DUPLICATE KEY UPDATE
T_OrderSampleReqStatus = 'Y',
T_OrderSampleReqs = '[]',
T_OrderSampleReqUserID = {$userid}";
//echo $sql;
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Sampling.Sampled',
{$rst_id},
{$vs['T_BarcodeLabID']},
'Y',
'[]',
{$userid},
'{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}'
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Sampling.Received',
{$rst_id},
{$vs['T_BarcodeLabID']},
'Y',
'[]',
{$userid},
'{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}'
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Verification.Verify',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Verification.To.Handling',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$sql = "INSERT INTO sample_by_step(
SampleByStepM_StatusSampleCode,
SampleByStepT_OrderHeaderID,
SampleByStepT_BarcodeLabID,
SampleByStepRequirementStatus,
SampleByStepRequirements,
SampleByStepUserID,
SampleByStepDateTime
)
VALUES(
'SAMPLING.Handling.From.Verification',
{$prm['sample']['T_OrderHeaderID']},
{$prm['sample']['T_BarcodeLabID']},
'{$prm['sample']['requirement_status']}',
'{$requirements}',
{$userid},
NOW()
)";
$this->db_onedev->query($sql);
$query = " INSERT INTO t_sampling_queue_last_status (
T_SamplingQueueLastStatusT_SampleStationID,
T_SamplingQueueLastStatusT_OrderHeaderID,
T_SamplingQueueLastStatusT_SamplingQueueStatusID,
T_SamplingQueueLastStatusUserID)
VALUES(
{$vs['T_SampleStationID']},
{$rst_id},
'5',
{$userid})
ON DUPLICATE KEY UPDATE
T_SamplingQueueLastStatusT_SamplingQueueStatusID = 5,
T_SamplingQueueLastStatusUserID = {$userid}";
//echo $query;
$this->db_onedev->query($query);
}
}
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* PHP QR Code porting for Codeigniter
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @porting author dwi.setiyadi@gmail.com
* @original author http://phpqrcode.sourceforge.net/
*
* @version 1.0
*/
class Ciqrcode
{
var $cacheable = true;
var $cachedir = 'application/cache/';
var $errorlog = 'application/logs/';
var $quality = true;
var $size = 1024;
function __construct($config = array()) {
// call original library
include "qrcode/qrconst.php";
include "qrcode/qrtools.php";
include "qrcode/qrspec.php";
include "qrcode/qrimage.php";
include "qrcode/qrinput.php";
include "qrcode/qrbitstream.php";
include "qrcode/qrsplit.php";
include "qrcode/qrrscode.php";
include "qrcode/qrmask.php";
include "qrcode/qrencode.php";
$this->initialize($config);
}
public function initialize($config = array()) {
$this->cacheable = (isset($config['cacheable'])) ? $config['cacheable'] : $this->cacheable;
$this->cachedir = (isset($config['cachedir'])) ? $config['cachedir'] : FCPATH.$this->cachedir;
$this->errorlog = (isset($config['errorlog'])) ? $config['errorlog'] : FCPATH.$this->errorlog;
$this->quality = (isset($config['quality'])) ? $config['quality'] : $this->quality;
$this->size = (isset($config['size'])) ? $config['size'] : $this->size;
// use cache - more disk reads but less CPU power, masks and format templates are stored there
if (!defined('QR_CACHEABLE')) define('QR_CACHEABLE', $this->cacheable);
// used when QR_CACHEABLE === true
if (!defined('QR_CACHE_DIR')) define('QR_CACHE_DIR', $this->cachedir);
// default error logs dir
if (!defined('QR_LOG_DIR')) define('QR_LOG_DIR', $this->errorlog);
// if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
if ($this->quality) {
if (!defined('QR_FIND_BEST_MASK')) define('QR_FIND_BEST_MASK', true);
} else {
if (!defined('QR_FIND_BEST_MASK')) define('QR_FIND_BEST_MASK', false);
if (!defined('QR_DEFAULT_MASK')) define('QR_DEFAULT_MASK', $this->quality);
}
// if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
if (!defined('QR_FIND_FROM_RANDOM')) define('QR_FIND_FROM_RANDOM', false);
// maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images
if (!defined('QR_PNG_MAXIMUM_SIZE')) define('QR_PNG_MAXIMUM_SIZE', $this->size);
}
public function generate($params = array()) {
if (isset($params['black'])
&& is_array($params['black'])
&& count($params['black']) == 3
&& array_filter($params['black'], 'is_int') === $params['black']) {
QRimage::$black = $params['black'];
}
if (isset($params['white'])
&& is_array($params['white'])
&& count($params['white']) == 3
&& array_filter($params['white'], 'is_int') === $params['white']) {
QRimage::$white = $params['white'];
}
$params['data'] = (isset($params['data'])) ? $params['data'] : 'QR Code Library';
if (isset($params['savename'])) {
$level = 'L';
if (isset($params['level']) && in_array($params['level'], array('L','M','Q','H'))) $level = $params['level'];
$size = 4;
if (isset($params['size'])) $size = min(max((int)$params['size'], 1), 10);
QRcode::png($params['data'], $params['savename'], $level, $size, 2);
return $params['savename'];
} else {
$level = 'L';
if (isset($params['level']) && in_array($params['level'], array('L','M','Q','H'))) $level = $params['level'];
$size = 4;
if (isset($params['size'])) $size = min(max((int)$params['size'], 1), 10);
QRcode::png($params['data'], NULL, $level, $size, 2);
}
}
}
/* end of file */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'vendor/autoload.php';
class Gmail
{
function send(
$sender,
$subject,
$message,
$recipients,
$cc,
$isHtml = false,
$attachment = [],
$username,
$password
) {
$mail = new PHPMailer(true);
//Configure an SMTP
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
// $mail->Username = "sascpone@gmail.com";
// $mail->Password = "ahpn zkcw ymkg hsij";
$mail->Username = $username;
$mail->Password = $password;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Post = 587;
$mail->setFrom($sender["email"], $sender["name"]);
foreach ($recipients as $rec) {
$mail->addAddress($rec["email"], $rec["name"]);
}
foreach ($cc as $rec) {
$mail->addCC($rec["email"], $rec["name"]);
}
$mail->isHTML($isHtml);
$mail->Subject = $subject;
$mail->Body = $message;
if (count($attachment) > 0) {
$arr_tmp = [];
for ($i_att = 0; $i_att < count($attachment); $i_att++) {
$tmpName = tempnam("/tmp", "att-");
$fname = $attachment[$i_att]["name"];
$url = $attachment[$i_att]["url"];
if ($tmpName === false) {
return [false, "Failed Create tmpFile for $fname"];
}
$tmp_data = file_get_contents($url);
$status = file_put_contents($tmpName, $tmp_data);
if ($status === false) {
return [false, "Failed Create tmpFile for $fname put"];
}
$arr_tmp[] = $tmpName;
$mail->addAttachment($tmpName, $fname);
}
}
if (!$mail->send()) {
$mail->smtpClose();
foreach ($arr_tmp as $tmpName) {
unlink($tmpName);
}
return [false, $mail->ErrorInfo];
} else {
$mail->smtpClose();
foreach ($arr_tmp as $tmpName) {
unlink($tmpName);
}
return [true, ""];
}
}
}

View File

@@ -0,0 +1,279 @@
<?php
class ImageManipulator
{
/**
* @var int
*/
protected $width;
/**
* @var int
*/
protected $height;
/**
* @var resource
*/
protected $image;
/**
* Image manipulator constructor
*
* @param string $file OPTIONAL Path to image file or image data as string
* @return void
*/
public function __construct($file = null)
{
if (null !== $file) {
if (is_file($file)) {
$this->setImageFile($file);
} else {
$this->setImageString($file);
}
}
}
/**
* Set image resource from file
*
* @param string $file Path to image file
* @return ImageManipulator for a fluent interface
* @throws InvalidArgumentException
*/
public function setImageFile($file)
{
if (!(is_readable($file) && is_file($file))) {
throw new InvalidArgumentException("Image file $file is not readable");
}
if (is_resource($this->image)) {
imagedestroy($this->image);
}
list ($this->width, $this->height, $type) = getimagesize($file);
switch ($type) {
case IMAGETYPE_GIF :
$this->image = imagecreatefromgif($file);
break;
case IMAGETYPE_JPEG :
$this->image = imagecreatefromjpeg($file);
break;
case IMAGETYPE_PNG :
$this->image = imagecreatefrompng($file);
break;
default :
throw new InvalidArgumentException("Image type $type not supported");
}
return $this;
}
/**
* Set image resource from string data
*
* @param string $data
* @return ImageManipulator for a fluent interface
* @throws RuntimeException
*/
public function setImageString($data)
{
if (is_resource($this->image)) {
imagedestroy($this->image);
}
if (!$this->image = imagecreatefromstring($data)) {
throw new RuntimeException('Cannot create image from data string');
}
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
return $this;
}
/**
* Resamples the current image
*
* @param int $width New width
* @param int $height New height
* @param bool $constrainProportions Constrain current image proportions when resizing
* @return ImageManipulator for a fluent interface
* @throws RuntimeException
*/
public function resample($width, $height, $constrainProportions = true)
{
if (!is_resource($this->image)) {
throw new RuntimeException('No image set');
}
if ($constrainProportions) {
if ($this->height >= $this->width) {
$width = round($height / $this->height * $this->width);
} else {
$height = round($width / $this->width * $this->height);
}
}
$temp = imagecreatetruecolor($width, $height);
imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
return $this->_replace($temp);
}
/**
* Enlarge canvas
*
* @param int $width Canvas width
* @param int $height Canvas height
* @param array $rgb RGB colour values
* @param int $xpos X-Position of image in new canvas, null for centre
* @param int $ypos Y-Position of image in new canvas, null for centre
* @return ImageManipulator for a fluent interface
* @throws RuntimeException
*/
public function enlargeCanvas($width, $height, array $rgb = array(), $xpos = null, $ypos = null)
{
if (!is_resource($this->image)) {
throw new RuntimeException('No image set');
}
$width = max($width, $this->width);
$height = max($height, $this->height);
$temp = imagecreatetruecolor($width, $height);
if (count($rgb) == 3) {
$bg = imagecolorallocate($temp, $rgb[0], $rgb[1], $rgb[2]);
imagefill($temp, 0, 0, $bg);
}
if (null === $xpos) {
$xpos = round(($width - $this->width) / 2);
}
if (null === $ypos) {
$ypos = round(($height - $this->height) / 2);
}
imagecopy($temp, $this->image, (int) $xpos, (int) $ypos, 0, 0, $this->width, $this->height);
return $this->_replace($temp);
}
/**
* Crop image
*
* @param int|array $x1 Top left x-coordinate of crop box or array of coordinates
* @param int $y1 Top left y-coordinate of crop box
* @param int $x2 Bottom right x-coordinate of crop box
* @param int $y2 Bottom right y-coordinate of crop box
* @return ImageManipulator for a fluent interface
* @throws RuntimeException
*/
public function crop($x1, $y1 = 0, $x2 = 0, $y2 = 0)
{
if (!is_resource($this->image)) {
throw new RuntimeException('No image set');
}
if (is_array($x1) && 4 == count($x1)) {
list($x1, $y1, $x2, $y2) = $x1;
}
$x1 = max($x1, 0);
$y1 = max($y1, 0);
$x2 = min($x2, $this->width);
$y2 = min($y2, $this->height);
$width = $x2 - $x1;
$height = $y2 - $y1;
$temp = imagecreatetruecolor($width, $height);
imagecopy($temp, $this->image, 0, 0, $x1, $y1, $width, $height);
return $this->_replace($temp);
}
/**
* Replace current image resource with a new one
*
* @param resource $res New image resource
* @return ImageManipulator for a fluent interface
* @throws UnexpectedValueException
*/
protected function _replace($res)
{
if (!is_resource($res)) {
throw new UnexpectedValueException('Invalid resource');
}
if (is_resource($this->image)) {
imagedestroy($this->image);
}
$this->image = $res;
$this->width = imagesx($res);
$this->height = imagesy($res);
return $this;
}
/**
* Save current image to file
*
* @param string $fileName
* @return void
* @throws RuntimeException
*/
public function save($fileName, $type = IMAGETYPE_JPEG)
{
$dir = dirname($fileName);
if (!is_dir($dir)) {
if (!mkdir($dir, 0755, true)) {
throw new RuntimeException('Error creating directory ' . $dir);
}
}
try {
switch ($type) {
case IMAGETYPE_GIF :
if (!imagegif($this->image, $fileName)) {
throw new RuntimeException;
}
break;
case IMAGETYPE_PNG :
if (!imagepng($this->image, $fileName)) {
throw new RuntimeException;
}
break;
case IMAGETYPE_JPEG :
default :
if (!imagejpeg($this->image, $fileName, 95)) {
throw new RuntimeException;
}
}
} catch (Exception $ex) {
throw new RuntimeException('Error saving image file to ' . $fileName);
}
}
/**
* Returns the GD image resource
*
* @return resource
*/
public function getResource()
{
return $this->image;
}
/**
* Get current image resource width
*
* @return int
*/
public function getWidth()
{
return $this->width;
}
/**
* Get current image height
*
* @return int
*/
public function getHeight()
{
return $this->height;
}
}

View File

@@ -0,0 +1,52 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class JurnalApi {
private $hmacUsername;
private $hmacSecret;
private $apiUrl;
public function __construct($params) {
$this->hmacUsername = $params['username'];
$this->hmacSecret = $params['secret'];
// Set the environment (default to sandbox)
$environment = isset($params['environment']) ? $params['environment'] : 'sandbox';
$this->apiUrl = $environment === 'production' ? 'https://api.mekari.com' : 'https://sandbox-api.mekari.com';
}
private function generateSignature($method, $path) {
$dateString = gmdate('D, d M Y H:i:s') . ' GMT';
$requestLine = $method . ' ' . $path . ' HTTP/1.1';
$dataToSign = 'date: ' . $dateString . "\n" . $requestLine;
$signature = base64_encode(hash_hmac('sha256', $dataToSign, $this->hmacSecret, true));
return [
'signature' => $signature,
'date' => $dateString
];
}
public function request($method, $path) {
$signatureData = $this->generateSignature($method, $path);
$hmacHeader = 'hmac username="' . $this->hmacUsername . '", algorithm="hmac-sha256", headers="date request-line", signature="' . $signatureData['signature'] . '"';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiUrl . $path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: ' . $hmacHeader,
'Date: ' . $signatureData['date'],
'Accept: application/json'
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return 'cURL Error: ' . curl_error($ch);
} else {
return $response;
}
curl_close($ch);
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* JSON Web Token implementation, based on this spec:
* http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
*
* PHP version 5
*
* @category Authentication
* @package Authentication_JWT
* @author Neuman Vong <neuman@twilio.com>
* @author Anant Narayanan <anant@php.net>
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
* @link https://github.com/firebase/php-jwt
*/
class JWT
{
/**
* Decodes a JWT string into a PHP object.
*
* @param string $jwt The JWT
* @param string|null $key The secret key
* @param bool $verify Don't skip verification process
*
* @return object The JWT's payload as a PHP object
* @throws UnexpectedValueException Provided JWT was invalid
* @throws DomainException Algorithm was not provided
*
* @uses jsonDecode
* @uses urlsafeB64Decode
*/
public static function decode($jwt, $key = null, $verify = true)
{
$tks = explode('.', $jwt);
if (count($tks) != 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
throw new UnexpectedValueException('Invalid segment encoding');
}
if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
throw new UnexpectedValueException('Invalid segment encoding');
}
$sig = JWT::urlsafeB64Decode($cryptob64);
if ($verify) {
if (empty($header->alg)) {
throw new DomainException('Empty algorithm');
}
if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) {
throw new UnexpectedValueException('Signature verification failed');
}
}
return $payload;
}
/**
* Converts and signs a PHP object or array into a JWT string.
*
* @param object|array $payload PHP object or array
* @param string $key The secret key
* @param string $algo The signing algorithm. Supported
* algorithms are 'HS256', 'HS384' and 'HS512'
*
* @return string A signed JWT
* @uses jsonEncode
* @uses urlsafeB64Encode
*/
public static function encode($payload, $key, $algo = 'HS256')
{
$header = array('typ' => 'JWT', 'alg' => $algo);
$segments = array();
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
$signing_input = implode('.', $segments);
$signature = JWT::sign($signing_input, $key, $algo);
$segments[] = JWT::urlsafeB64Encode($signature);
return implode('.', $segments);
}
/**
* Sign a string with a given key and algorithm.
*
* @param string $msg The message to sign
* @param string $key The secret key
* @param string $method The signing algorithm. Supported
* algorithms are 'HS256', 'HS384' and 'HS512'
*
* @return string An encrypted message
* @throws DomainException Unsupported algorithm was specified
*/
public static function sign($msg, $key, $method = 'HS256')
{
$methods = array(
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
);
if (empty($methods[$method])) {
throw new DomainException('Algorithm not supported');
}
return hash_hmac($methods[$method], $msg, $key, true);
}
/**
* Decode a JSON string into a PHP object.
*
* @param string $input JSON string
*
* @return object Object representation of JSON string
* @throws DomainException Provided string was invalid JSON
*/
public static function jsonDecode($input)
{
$obj = json_decode($input);
if (function_exists('json_last_error') && $errno = json_last_error()) {
JWT::_handleJsonError($errno);
} else if ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
}
return $obj;
}
/**
* Encode a PHP object into a JSON string.
*
* @param object|array $input A PHP object or array
*
* @return string JSON representation of the PHP object or array
* @throws DomainException Provided object could not be encoded to valid JSON
*/
public static function jsonEncode($input)
{
$json = json_encode($input);
if (function_exists('json_last_error') && $errno = json_last_error()) {
JWT::_handleJsonError($errno);
} else if ($json === 'null' && $input !== null) {
throw new DomainException('Null result with non-null input');
}
return $json;
}
/**
* Decode a string with URL-safe Base64.
*
* @param string $input A Base64 encoded string
*
* @return string A decoded string
*/
public static function urlsafeB64Decode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* Encode a string with URL-safe Base64.
*
* @param string $input The string you want encoded
*
* @return string The base64 encode of what you passed in
*/
public static function urlsafeB64Encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
/**
* Helper method to create a JSON error.
*
* @param int $errno An error number from json_last_error()
*
* @return void
*/
private static function _handleJsonError($errno)
{
$messages = array(
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
);
throw new DomainException(
isset($messages[$errno])
? $messages[$errno]
: 'Unknown JSON error: ' . $errno
);
}
}

View File

@@ -0,0 +1,152 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kapus{
public function calc($date,$userID = 3)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
//cek if current date is posted
$this->db->trans_start();
$sql = "select * from sys_f_kapus_sum where sysFKapusSumDate = ?
and sysFKapusIsActive = 'Y' ";
$qry = $this->db->query($sql , array($date));
$sysFKapusSumID = 0;
if ($qry ) {
$rows = $qry->result_array();
if ( count($rows) > 0 ) {
$sysFKapusSumID = $rows[0]["sysFKapusSumID"];
if ($rows[0]["sysFKapusSumIsPosted"] == "Y" ) {
return array("status" => "ERR" , "message" => "Kapus at $date already posted");
}
}
}
$sql = "select * from sys_kapus limit 0,1";
$qry = $this->db->query($sql);
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Invalid Kapus Setting" . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Invalid Kapus Setting");
}
$companyID = $rows[0]["sysKaPusM_CompanyID"] . "," . $rows[0]["sysKaPusM_CompanyID2"];
$paymentTypeID = $rows[0]["sysKaPusM_PaymentTypeID"];
$targetPct = $rows[0]["sysKaPusPct"];
// get kapus
$sql = "select sum(F_PaymentDetailAmount) TotalAmount
from t_orderheader
join f_payment on T_OrderHeaderID = F_PaymentT_OrderHeaderID
and F_PaymentIsActive = 'Y' and T_OrderHeaderIsActive = 'Y'
and date(T_OrderHeaderDate) = date(?)
and F_PaymentDate = date(?)
join f_paymentdetail on F_PaymentID = F_PaymentDetailF_PaymentID
and F_PaymentDetailM_PaymentTypeID = ?
and F_PaymentDetailIsActive = 'Y' ";
$qry = $this->db->query($sql, array($date,$date, $paymentTypeID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error get total payment " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
$this->db->trans_rollback();
return array("status" => "OK" , "message" => "No Payment Type , $paymentTypeID , $date ");
}
// seluruh kas
$totalAmount = $rows[0]["TotalAmount"];
if ($totalAmount == 0 ) {
$this->db->trans_rollback();
return array("status" => "OK" , "message" => "Total Amount Zero ");
}
$sql = "drop table if exists xtmp_kapus";
$qry = $this->db->query($sql);
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Drop Tmp table " . print_r($this->db->error(),true));
}
$sql = "
create temporary table xtmp_kapus
select F_PaymentT_OrderHeaderID, cast(sum(F_PaymentDetailAmount) as decimal(15,0)) Total
from f_payment
join t_orderheader on F_PaymentT_OrderHeaderID = T_OrderHeaderID and T_OrderHeaderM_CompanyID in ($companyID)
join f_paymentdetail on F_PaymentDetailF_PaymentID = F_PaymentID and F_PaymentDetailIsActive = 'Y'
and F_PaymentIsActive = 'Y'
where F_PaymentDate = ? and F_PaymentDetailM_PaymentTypeID = ?
group by F_PaymentT_OrderHeaderID";
$qry = $this->db->query($sql, array($date,$paymentTypeID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Create Tmp table " . print_r($this->db->error(),true));
}
$sql = "
select T_OrderHeaderID, cast(T_OrderHeaderTotal as decimal(15,0) ) as T_OrderHeaderTotal
from t_orderheader
join xtmp_kapus on T_OrderHeaderID = F_PaymentT_OrderHeaderID
and Total = T_OrderHeaderTotal
and date(T_OrderHeaderDate) = ?
order by T_OrderHeaderID";
$qry = $this->db->query($sql, array($date));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error get detail payment " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
$sum_total = 0;
if ($sysFKapusSumID == 0) {
$sql = "insert into sys_f_kapus_sum(sysFKapusSumDate, sysFKapusSumUserID,sysFKapusSumTargetPct,
sysFKapusSumTotal) values(?,?,?,?)";
$qry = $this->db->query($sql,array($date, $userID, $targetPct, $totalAmount));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error create sysFKapusSum " . print_r($this->db->error(),true));
}
$sysFKapusSumID = $this->db->insert_id();
}
$qry = $this->db->query("update sys_f_kapus set sysFKapusIsActive='N' where sysFKapusSysFKapusSumID=?", array($sysFKapusSumID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error reset sysFKapus " . print_r($this->db->error(),true));
}
$sql_i = "insert into sys_f_kapus( sysFKapusT_OrderHeaderID, sysFKapusAmount, sysFKapusRunAmount,
sysFKapusM_UserID, sysFKapusDate, sysFKapusPct, sysFKapusSysFKapusSumID )
values(?,?,?, ?,?,?,?)";
$curPct = 0;
foreach($rows as $r) {
$x_id = $r["T_OrderHeaderID"];
$x_total = $r["T_OrderHeaderTotal"];
$sum_total += $x_total;
$curPct = $sum_total / $totalAmount * 100 ;
$qry = $this->db->query($sql_i, array($x_id, $x_total, $sum_total,
$userID,$date, $curPct,$sysFKapusSumID ) );
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error insert sys_f_kapus " . print_r($this->db->error(),true));
}
if ($curPct >= $targetPct ) {
break;
}
}
$sql = "update sys_f_kapus_sum set sysFKapusSumAmount = ? , sysFKapusSumActualPct = ? ,
sysFKapusSumTargetPct = ?
where sysFKapusSumID = ?";
$qry = $this->db->query($sql, array($sum_total, $curPct, $targetPct, $sysFKapusSumID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error update sysFKapusSum " . print_r($this->db->error(),true));
}
$this->db->trans_commit();
return array("status" => "OK" , "message" => "");
}
}

View File

@@ -0,0 +1,162 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kapus{
public function calc($date,$userID = 3)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
//cek if current date is posted
$this->db->trans_start();
$sql = "select * from sys_f_kapus_sum where sysFKapusSumDate = ?
and sysFKapusIsActive = 'Y' ";
$qry = $this->db->query($sql , array($date));
$sysFKapusSumID = 0;
if ($qry ) {
$rows = $qry->result_array();
if ( count($rows) > 0 ) {
$sysFKapusSumID = $rows[0]["sysFKapusSumID"];
if ($rows[0]["sysFKapusSumIsPosted"] == "Y" ) {
return array("status" => "ERR" , "message" => "Kapus at $date already posted");
}
}
}
$sql = "select * from sys_kapus limit 0,1";
$qry = $this->db->query($sql);
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Invalid Kapus Setting" . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Invalid Kapus Setting");
}
$companyID = $rows[0]["sysKaPusM_CompanyID"] . "," . $rows[0]["sysKaPusM_CompanyID2"];
$paymentTypeID = $rows[0]["sysKaPusM_PaymentTypeID"];
$targetPct = $rows[0]["sysKaPusPct"];
// get kapus
$sql = "select sum(F_PaymentDetailAmount) TotalAmount,
sum(F_PaymentDetailAmount - F_PaymentDetailAmount mod 500 ) TotalAmountAfterRounding
from t_orderheader
join f_payment on T_OrderHeaderID = F_PaymentT_OrderHeaderID
and F_PaymentIsActive = 'Y' and T_OrderHeaderIsActive = 'Y'
and date(T_OrderHeaderDate) = date(?)
and F_PaymentDate = date(?)
join f_paymentdetail on F_PaymentID = F_PaymentDetailF_PaymentID
and F_PaymentDetailM_PaymentTypeID = ?
and F_PaymentDetailIsActive = 'Y' ";
$qry = $this->db->query($sql, array($date,$date, $paymentTypeID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error get total payment " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
$this->db->trans_rollback();
return array("status" => "OK" , "message" => "No Payment Type , $paymentTypeID , $date ");
}
// seluruh kas
$totalAmount = $rows[0]["TotalAmount"];
$totalAmountAfterRounding = $rows[0]["TotalAmountAfterRounding"];
if ($totalAmount == 0 ) {
$this->db->trans_rollback();
return array("status" => "OK" , "message" => "Total Amount Zero ");
}
$sql = "drop table if exists xtmp_kapus";
$qry = $this->db->query($sql);
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Drop Tmp table " . print_r($this->db->error(),true));
}
$sql = "
create temporary table xtmp_kapus
select F_PaymentT_OrderHeaderID,
cast(sum(F_PaymentDetailAmount) as decimal(15,0)) Total
from f_payment
join t_orderheader on F_PaymentT_OrderHeaderID = T_OrderHeaderID and T_OrderHeaderM_CompanyID in ($companyID)
join f_paymentdetail on F_PaymentDetailF_PaymentID = F_PaymentID and F_PaymentDetailIsActive = 'Y'
and F_PaymentIsActive = 'Y'
where F_PaymentDate = ? and F_PaymentDetailM_PaymentTypeID = ?
group by F_PaymentT_OrderHeaderID";
$qry = $this->db->query($sql, array($date,$paymentTypeID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Create Tmp table " . print_r($this->db->error(),true));
}
$sql = "
select T_OrderHeaderID,
cast(T_OrderHeaderTotal as decimal(15,0) ) as T_OrderHeaderTotal ,
cast(T_OrderHeaderTotal - T_OrderHeaderTotal mod 500 as decimal(15,0) ) as T_OrderHeaderTotalAfterRounding
from t_orderheader
join xtmp_kapus on T_OrderHeaderID = F_PaymentT_OrderHeaderID
and Total = T_OrderHeaderTotal
and date(T_OrderHeaderDate) = ?
order by T_OrderHeaderID";
$qry = $this->db->query($sql, array($date));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error get detail payment " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if ($sysFKapusSumID == 0) {
$sql = "insert into sys_f_kapus_sum(sysFKapusSumDate, sysFKapusSumUserID,sysFKapusSumTargetPct,
sysFKapusSumTotal, sysFKapusSumTotalAfterRounding) values(?,?,?,?,?)";
$qry = $this->db->query($sql,array($date, $userID, $targetPct, $totalAmount, $totalAmountAfterRounding));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error create sysFKapusSum " . print_r($this->db->error(),true));
}
$sysFKapusSumID = $this->db->insert_id();
}
$qry = $this->db->query("update sys_f_kapus set sysFKapusIsActive='N' where sysFKapusSysFKapusSumID=?", array($sysFKapusSumID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error reset sysFKapus " . print_r($this->db->error(),true));
}
$sql_i = "insert into sys_f_kapus( sysFKapusT_OrderHeaderID, sysFKapusAmount, sysFKapusRunAmount,
sysFKapusAmountAfterRounding,
sysFKapusM_UserID, sysFKapusDate, sysFKapusPct, sysFKapusSysFKapusSumID )
values(?,?,?, ?, ?,?,?,?)";
$curPct = 0;
$sum_total = 0;
$sum_total_after_rounding = 0;
foreach($rows as $r) {
$x_id = $r["T_OrderHeaderID"];
$x_total = $r["T_OrderHeaderTotal"];
$x_total_after_rounding = $r["T_OrderHeaderTotalAfterRounding"];
$sum_total += $x_total;
$sum_total_after_rounding += $x_total_after_rounding;
$curPct = $sum_total / $totalAmount * 100 ;
$qry = $this->db->query($sql_i, array($x_id, $x_total, $sum_total,
$x_total_after_rounding,
$userID,$date, $curPct,$sysFKapusSumID ) );
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error insert sys_f_kapus " . print_r($this->db->error(),true));
}
if ($curPct >= $targetPct ) {
break;
}
}
$sql = "update sys_f_kapus_sum set sysFKapusSumAmount = ? , sysFKapusSumActualPct = ? ,
sysFKapusSumTargetPct = ?, sysFKapusSumAmountAfterRounding = ?
where sysFKapusSumID = ?";
$qry = $this->db->query($sql, array($sum_total, $curPct, $targetPct, $sum_total_after_rounding, $sysFKapusSumID));
if (! $qry ) {
$this->db->trans_rollback();
return array("status" => "ERR" , "message" => "Error update sysFKapusSum " . print_r($this->db->error(),true));
}
$this->db->trans_commit();
return array("status" => "OK" , "message" => "");
}
}

View File

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,187 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class NatPatientLib
{
//dev
//var $NAT_PATIENT_API = "http://10.9.8.249/one-api/nat_patient/r_api/";
//prod
var $NAT_PATIENT_API = "http://192.168.50.250/one-api/nat_patient/r_api/";
function __construct()
{
$CI = &get_instance();
$this->db = $CI->load->database("default", true);
}
//remote => status : Y|N Y confirm N, not confirm.
/*
create table m_patient_nat_validation(
M_PatientNatValidationID int not null auto_increment primary key,
M_PatientNatValidationM_PatientID int,
M_PatientNatValidationM_UserID int,
M_PatientNatValidationM_UserUsername varchar(100),
M_PatientNatValidationIsActive char(1) default 'Y',
M_PatientNatValidationCreated datetime default current_timestamp(),
M_PatientNatValidationLastUpdated datetime default current_timestamp() on update current_timestamp(),
key(M_PatientNatValidationM_PatientID),
key(M_PatientNatValidationIsActive),
);
create table m_patient_nat_log (
M_PatientNatLogID int not null auto_increment primary key,
M_PatientNatLogDate datetime default current_timestamp(),
M_PatientNatLogStatus enum('New','Retry','Sent'),
M_PatientNatLogLastUpdated datetime default current_timestamp() on update current_timestamp(),
M_PatientNatLogJson text,
key(M_PatientNatLogDate),
key(M_PatientNatLogStatus)
);
*/
function save_nasional($userName, $patient)
{
$resp = $this->get_branch();
if ($resp["status"] != "OK") {
return $resp;
}
$param = [
"M_BranchID" => $resp["branchID"],
"M_BranchCode" => $resp["branchCode"],
"Username" => $userName,
"patient" => $patient
];
$z_param = gzcompress(json_encode($param));
$url = $this->NAT_PATIENT_API . "/update_from_local";
$zresp = $this->post($url, $z_param);
$jresp = gzuncompress($zresp);
$resp = json_decode($jresp, true);
if (!isset($resp["status"])) {
$resp["status"] = "ERR";
$resp["message"] = $zresp;
}
return $resp;
}
function confirm($localM_PatientID, $arr_remote, $userID, $userName)
{
$payload = [
"userID" => $userID,
"userName" => $userName,
"lokalM_PatientID" => $localM_PatientID,
"remote" => $arr_remote,
];
$jsonPayload = json_encode($payload);
$sql = "insert into m_patient_nat_log(M_PatientNatLogStatus,M_PatientNatLogJson)
values('New',?)";
$qry = $this->db->query($sql, [$jsonPayload]);
if (!$qry) {
return [
"status" => "ERR",
"message" => $this->db->error()["message"],
];
}
return ["status" => "OK"];
}
function check_connection()
{
$start = date("Y-m-d H:i:s");
$url = $this->NAT_PATIENT_API . "/check_connection";
$zresp = $this->post($url, ["dummy" => "load"]);
$jresp = gzuncompress($zresp);
$resp = json_decode($jresp, true);
if (!isset($resp["status"])) {
$resp["status"] = "ERR";
$resp["message"] = $zresp;
}
$stop = date("Y-m-d H:i:s");
$resp["start"] = $start;
$resp["stop"] = $stop;
return $resp;
}
function get_branch()
{
$sql =
"select M_BranchID, M_BranchCode from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault='Y'";
$qry = $this->db->query($sql);
if (!$qry) {
return [
"status" => "ERR",
"message" =>
$this->db->error()["message"] .
"|\n" .
$this->db->last_query(),
];
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return ["status" => "ERR", "message" => "No Default Branch"];
}
return [
"status" => "OK",
"branchID" => $rows[0]["M_BranchID"],
"branchCode" => $rows[0]["M_BranchCode"],
];
}
function search($query)
{
$start = date("Y-m-d H:i:s");
$url = $this->NAT_PATIENT_API . "/search_bizone";
$jparam = json_encode(["search" => $query]);
$zresp = $this->post($url, $jparam);
$jresp = gzuncompress($zresp);
$resp = json_decode($jresp, true);
if (!isset($resp["status"])) {
$resp["status"] = "ERR";
$resp["message"] = $zresp;
}
$stop = date("Y-m-d H:i:s");
$resp["start"] = $start;
$resp["stop"] = $stop;
return $resp;
}
// param array ->
function search_by_nik($param)
{
$start = date("Y-m-d H:i:s");
$url = $this->NAT_PATIENT_API . "/search_by_nik";
$resp = $this->get_branch();
if ($resp["status"] != "OK") {
return $resp;
}
$jparam = json_encode($param);
$zresp = $this->post($url, $jparam);
$jresp = gzuncompress($zresp);
$resp = json_decode($jresp, true);
if (!isset($resp["status"])) {
$resp["status"] = "ERR";
$resp["message"] = $zresp;
}
$stop = date("Y-m-d H:i:s");
$resp["start"] = $start;
$resp["stop"] = $stop;
return $resp;
}
public function post($url, $data)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/text",
"Content-Length: " . strlen($data),
]);
$result = curl_exec($ch);
if (curl_error($ch) != "") {
echo json_encode([
"status" => "ERR",
"message" => "Http Error : " . curl_error($ch),
]);
curl_close($ch);
exit();
}
curl_close($ch);
return $result;
}
}

View File

@@ -0,0 +1,714 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Nonlabtemplate
{
function generate($T_SamplingSOID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "SELECT NonlabTemplateID as template_id,
NonlabTemplateName as template_name,
T_SamplingSoT_OrderHeaderID as order_header_id,
T_OrderDetailID as order_detail_id
FROM t_samplingso
JOIN t_orderdetail ON T_SamplingSoT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND T_SamplingSoT_TestID = T_OrderDetailT_TestID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_SamplingSoT_TestID = T_TestID
JOIN nat_test ON Nat_TestID = T_TestNat_TestID
JOIN nonlab_template_mapping ON NonlabTemplateMappingNat_TestID = Nat_TestID AND
NonlabTemplateMappingIsActive = 'Y'
JOIN nonlab_template ON NonlabTemplateMappingNonlabTemplateID = NonlabTemplateID AND NonlabTemplateIsActive = 'Y'
LEFT JOIN so_resultentry ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND
So_ResultEntryT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND
So_ResultEntryIsActive = 'Y'
WHERE
T_SamplingSoID = ? AND
T_SamplingSoIsActive = 'Y' AND
So_ResultEntryID IS NULL
GROUP BY NonlabTemplateID
LIMIT 1";
$qry = $this->db->query($sql, array($T_SamplingSOID));
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$row_arr = $qry->row_array();
if ($row_arr) {
//print_r($row_arr);
$template_name = $row_arr['template_name'];
if($row_arr['template_name'] == 'Fisik Umum'){
$sql = "SELECT FisikTemplateType as xtype
FROM fisik_template
JOIN t_orderheader ON T_OrderHeaderID = {$row_arr['order_header_id']}
JOIN mgm_mcutemplate ON Mgm_McuTemplateMgm_McuID = T_OrderHeaderMgm_McuID
JOIN fisik_template_mapping ON Mgm_McuTemplateFisikTemplateMappingID = FisikTemplateMappingID
JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND
FisikTemplateMappingDetailFisikTemplateID = FisikTemplateID AND
FisikTemplateMappingDetailIsActive = 'Y'
WHERE
FisikTemplateIsActive = 'Y'
GROUP BY FisikTemplateType";
$qry = $this->db->query($sql);
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$arr_types = $qry->result_array();
$xtypes = [];
foreach ($arr_types as $key => $value) {
$xtypes[] = $value['xtype'];
}
$template_name = "Fisik Umum";
if(in_array("K3", $xtypes)){
$template_name = "Fisik Umum K3";
}
//echo $template_name;
}
$sql = "INSERT INTO so_resultentry(
So_ResultEntryT_OrderHeaderID,
So_ResultEntryT_OrderDetailID,
So_ResultEntryNonlab_TemplateID,
So_ResultEntryNonlab_TemplateName,
So_ResultEntryCreated
)
VALUES(?,?,?,?,NOW())";
$qry = $this->db->query($sql, array(
$row_arr['order_header_id'],
$row_arr['order_detail_id'],
$row_arr['template_id'],
$template_name
));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$soresultentryid = $this->db->insert_id();
$sql = "SELECT * FROM t_orderheaderlang
WHERE
T_OrderHeaderLangT_OrderHeaderID = ? AND T_OrderHeaderLangIsActive = 'Y'";
$qry = $this->db->query($sql, array(
$row_arr['order_header_id']
));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$order_langs = $qry->result_array();
foreach ($order_langs as $k_lang => $val_lang) {
$sql = "SELECT *
FROM nonlab_template_detail
JOIN t_orderheader ON T_OrderHeaderID = ?
JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID AND ( NonlabTemplateDetailGender = 'all' OR NonlabTemplateDetailGender = M_PatientGender)
WHERE
NonlabTemplateDetailNonlabTemplateID = ? AND NonlabTemplateDetailIsActive = 'Y' AND NonlabTemplateDetaiM_LangID = ? ";
$qry = $this->db->query($sql, array(
$row_arr['order_header_id'],
$row_arr['template_id'],
$val_lang['T_OrderHeaderLangM_LangID']
));
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows_result = $qry->result_array();
if($rows_result && count($rows_result) > 0){
foreach ($rows_result as $key => $value) {
if(intval($val_lang['T_OrderHeaderLangM_LangID']) == 1){
$sql = "INSERT INTO so_resultentrydetail (
So_ResultEntryDetailSo_ResultEntryID,
So_ResultEntryDetailNonlab_TemplateDetailID,
So_ResultEntryDetailNonlab_TemplateDetailName,
So_ResultEntryDetailCreated
)
VALUES(?,?,?,NOW())";
$qry = $this->db->query($sql, array(
$soresultentryid,
$value['NonlabTemplateDetailID'],
$value['NonlabTemplateDetailName']
));
}
}
}
}
$sql = "SELECT *
FROM so_resultentry
WHERE
So_ResultEntryID = ? ";
$qry = $this->db->query($sql, array(
$soresultentryid
));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows_return = $qry->row_array();
return $rows_return;
} else {
return false;
}
}
function create($tPriceHeaderID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$this->db->trans_begin();
$sql = "select * from t_priceheader where T_PriceHeaderID = ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "T PriceHeader ID : $tPriceHeaderID not found");
}
$sql = "select distinct T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceT_PriceHeaderID= ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
$this->db->trans_rollback();
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
// HANYA DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
$this->db->trans_rollback();
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID,
T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp,
0 T_PriceSubTotal, 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell,
'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceT_PriceHeaderID= ? ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql);
if (!$qry) {
//DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketT_PriceHeaderID= ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, 0 T_PricePriority,
T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc,
0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
JOIN t_packet ON T_PacketDetailT_PacketID = T_PacketID
JOIN t_price ON T_PacketDetailT_TestID = T_PriceT_TestID AND T_PriceIsActive = 'Y' AND T_PriceT_PriceHeaderID = T_PacketT_PriceHeaderID
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query(
"delete from ss_price_mou where Ss_PriceMouT_PriceHeaderID=?",
array($tPriceHeaderID)
);
if (!$qry) {
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
$this->db->insert_batch("ss_price_mou", $rows);
$err = $this->db->error();
if ($err["code"] != 0) {
echo "ERR Code : " . $err["code"] . " | " . $err["message"] . " \n";
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
// $sql_i = "insert into ss_price_mou(
// T_TestID, T_TestName,
// IsFromPanel, Nat_TestID,T_PriceT_TestID, T_PriceIsCito,
// T_PricePriority, T_PriceAmount, T_PriceDisc,
// T_PriceDiscRp, T_PriceSubTotal, T_PriceOther, T_PriceTotal,
// T_TestForceSell, is_packet, packet_id, px_type,
// nat_test, child_test, IsFavourite, Ss_PriceMouT_PriceHeaderID)
// values (
// ?,?,
// ?,?,?,?,
// ?,?,?,
// ?,?,?,?,
// ?,?,?,?,
// ?,?,?,?
// )";
// foreach ($rows as $r) {
// $arr = [
// $r["T_TestID"],
// $r["T_TestName"],
// $r["IsFromPanel"],
// $r["Nat_TestID"],
// $r["T_PriceT_TestID"],
// $r["T_PriceIsCito"],
// $r["T_PricePriority"],
// $r["T_PriceAmount"],
// $r["T_PriceDisc"],
// $r["T_PriceDiscRp"],
// $r["T_PriceSubTotal"],
// $r["T_PriceOther"],
// $r["T_PriceTotal"],
// $r["T_TestForceSell"],
// $r["is_packet"],
// $r["packet_id"],
// $r["px_type"],
// $r["nat_test"],
// $r["child_test"],
// $r["IsFavourite"],
// $r["Ss_PriceMouT_PriceHeaderID"],
// ];
// $qry = $this->db->query($sql_i, $arr);
// if (!$qry) {
//
// header("Content-Type: text/plain");
// print_r($r);
// echo $this->db->last_query();
// return array(false, "Regional " . print_r($this->db->error(), true));
// }
// }
$this->db->trans_commit();
return array(true, "OK");
}
// retrun array status, message
public function bisone_create($mouID)
{
$CI = &get_instance();
$this->db = $CI->load->database("one", true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
return array(true, "OK");
}
}

View File

@@ -0,0 +1,704 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Nonlabtemplate
{
function generate($T_SamplingSOID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "SELECT NonlabTemplateID as template_id,
NonlabTemplateName as template_name,
T_SamplingSoT_OrderHeaderID as order_header_id,
T_OrderDetailID as order_detail_id
FROM t_samplingso
JOIN t_orderdetail ON T_SamplingSoT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND T_SamplingSoT_TestID = T_OrderDetailT_TestID AND T_OrderDetailIsActive = 'Y'
JOIN t_test ON T_SamplingSoT_TestID = T_TestID
JOIN nat_test ON Nat_TestID = T_TestNat_TestID
JOIN nonlab_template_mapping ON NonlabTemplateMappingNat_TestID = Nat_TestID AND
NonlabTemplateMappingIsActive = 'Y'
JOIN nonlab_template ON NonlabTemplateMappingNonlabTemplateID = NonlabTemplateID AND NonlabTemplateIsActive = 'Y'
WHERE
T_SamplingSoID = ? AND
T_SamplingSoIsActive = 'Y'
GROUP BY NonlabTemplateID
LIMIT 1";
$qry = $this->db->query($sql, array($T_SamplingSOID));
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$row_arr = $qry->row_array();
if ($row_arr) {
//print_r($row_arr);
$template_name = $row_arr['template_name'];
if($row_arr['template_name'] == 'Fisik Umum'){
$sql = "SELECT FisikTemplateType as xtype
FROM fisik_template
JOIN t_orderheader ON T_OrderHeaderID = {$row_arr['order_header_id']}
JOIN mgm_mcutemplate ON Mgm_McuTemplateMgm_McuID = T_OrderHeaderMgm_McuID
JOIN fisik_template_mapping ON Mgm_McuTemplateFisikTemplateMappingID = FisikTemplateMappingID
JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND
FisikTemplateMappingDetailFisikTemplateID = FisikTemplateID AND
FisikTemplateMappingDetailIsActive = 'Y'
WHERE
FisikTemplateIsActive = 'Y'
GROUP BY FisikTemplateType";
$qry = $this->db->query($sql);
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$arr_types = $qry->result_array();
$xtypes = [];
foreach ($arr_types as $key => $value) {
$xtypes[] = $value['xtype'];
}
$template_name = "Fisik Umum";
if(in_array("K3", $xtypes)){
$template_name = "Fisik Umum K3";
}
//echo $template_name;
}
$sql = "INSERT INTO so_resultentry(
So_ResultEntryT_OrderHeaderID,
So_ResultEntryT_OrderDetailID,
So_ResultEntryNonlab_TemplateID,
So_ResultEntryNonlab_TemplateName,
So_ResultEntryCreated
)
VALUES(?,?,?,?,NOW())";
$qry = $this->db->query($sql, array(
$row_arr['order_header_id'],
$row_arr['order_detail_id'],
$row_arr['template_id'],
$template_name
));
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$soresultentryid = $this->db->insert_id();
$sql = "SELECT * FROM t_orderheaderlang
WHERE
T_OrderHeaderLangT_OrderHeaderID = ? AND T_OrderHeaderLangIsActive = 'Y'";
$qry = $this->db->query($sql, array(
$row_arr['order_header_id']
));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$order_langs = $qry->result_array();
foreach ($order_langs as $k_lang => $val_lang) {
$sql = "SELECT *
FROM nonlab_template_detail
WHERE
NonlabTemplateDetailNonlabTemplateID = ? AND NonlabTemplateDetailIsActive = 'Y' AND NonlabTemplateDetaiM_LangID = ? ";
$qry = $this->db->query($sql, array(
$row_arr['template_id'],
$val_lang['T_OrderHeaderLangM_LangID']
));
//echo $this->db->last_query();
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows_result = $qry->result_array();
if($rows_result && count($rows_result) > 0){
foreach ($rows_result as $key => $value) {
if(intval($val_lang['T_OrderHeaderLangM_LangID']) == 1){
$sql = "INSERT INTO so_resultentrydetail (
So_ResultEntryDetailSo_ResultEntryID,
So_ResultEntryDetailNonlab_TemplateDetailID,
So_ResultEntryDetailNonlab_TemplateDetailName,
So_ResultEntryDetailCreated
)
VALUES(?,?,?,NOW())";
$qry = $this->db->query($sql, array(
$soresultentryid,
$value['NonlabTemplateDetailID'],
$value['NonlabTemplateDetailName']
));
}
}
}
}
$sql = "SELECT *
FROM so_resultentry
WHERE
So_ResultEntryID = ? ";
$qry = $this->db->query($sql, array(
$soresultentryid
));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows_return = $qry->row_array();
return $rows_return;
} else {
return false;
}
}
function create($tPriceHeaderID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$this->db->trans_begin();
$sql = "select * from t_priceheader where T_PriceHeaderID = ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "T PriceHeader ID : $tPriceHeaderID not found");
}
$sql = "select distinct T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceT_PriceHeaderID= ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
$this->db->trans_rollback();
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
// HANYA DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
$this->db->trans_rollback();
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID,
T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp,
0 T_PriceSubTotal, 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell,
'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceT_PriceHeaderID= ? ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql);
if (!$qry) {
//DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketT_PriceHeaderID= ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, 0 T_PricePriority,
T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc,
0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
JOIN t_packet ON T_PacketDetailT_PacketID = T_PacketID
JOIN t_price ON T_PacketDetailT_TestID = T_PriceT_TestID AND T_PriceIsActive = 'Y' AND T_PriceT_PriceHeaderID = T_PacketT_PriceHeaderID
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query(
"delete from ss_price_mou where Ss_PriceMouT_PriceHeaderID=?",
array($tPriceHeaderID)
);
if (!$qry) {
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
$this->db->insert_batch("ss_price_mou", $rows);
$err = $this->db->error();
if ($err["code"] != 0) {
echo "ERR Code : " . $err["code"] . " | " . $err["message"] . " \n";
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
// $sql_i = "insert into ss_price_mou(
// T_TestID, T_TestName,
// IsFromPanel, Nat_TestID,T_PriceT_TestID, T_PriceIsCito,
// T_PricePriority, T_PriceAmount, T_PriceDisc,
// T_PriceDiscRp, T_PriceSubTotal, T_PriceOther, T_PriceTotal,
// T_TestForceSell, is_packet, packet_id, px_type,
// nat_test, child_test, IsFavourite, Ss_PriceMouT_PriceHeaderID)
// values (
// ?,?,
// ?,?,?,?,
// ?,?,?,
// ?,?,?,?,
// ?,?,?,?,
// ?,?,?,?
// )";
// foreach ($rows as $r) {
// $arr = [
// $r["T_TestID"],
// $r["T_TestName"],
// $r["IsFromPanel"],
// $r["Nat_TestID"],
// $r["T_PriceT_TestID"],
// $r["T_PriceIsCito"],
// $r["T_PricePriority"],
// $r["T_PriceAmount"],
// $r["T_PriceDisc"],
// $r["T_PriceDiscRp"],
// $r["T_PriceSubTotal"],
// $r["T_PriceOther"],
// $r["T_PriceTotal"],
// $r["T_TestForceSell"],
// $r["is_packet"],
// $r["packet_id"],
// $r["px_type"],
// $r["nat_test"],
// $r["child_test"],
// $r["IsFavourite"],
// $r["Ss_PriceMouT_PriceHeaderID"],
// ];
// $qry = $this->db->query($sql_i, $arr);
// if (!$qry) {
//
// header("Content-Type: text/plain");
// print_r($r);
// echo $this->db->last_query();
// return array(false, "Regional " . print_r($this->db->error(), true));
// }
// }
$this->db->trans_commit();
return array(true, "OK");
}
// retrun array status, message
public function bisone_create($mouID)
{
$CI = &get_instance();
$this->db = $CI->load->database("one", true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
return array(true, "OK");
}
}

View File

@@ -0,0 +1,440 @@
<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Promise
{
function __construct()
{
$CI = &get_instance();
$this->db_smartone = $CI->load->database("default", true);
}
function get_schedule_results_grouped($test_ids, $x_datetime, $branch_id, $order_id = null)
{
// Validasi input
if (empty($test_ids) || empty($x_datetime) || empty($branch_id)) {
return array("status" => "ERR", "message" => "Parameter tidak lengkap", "data" => array());
}
// Konversi test_ids ke array integer
if (is_array($test_ids)) {
$test_ids_array = array_map('intval', $test_ids);
} else {
$test_ids_array = array_filter(array_map('intval', array_map('trim', explode(",", $test_ids))));
}
if (empty($test_ids_array)) {
return array("status" => "ERR", "message" => "Test IDs tidak valid", "data" => array());
}
$branch_id_escaped = intval($branch_id);
$test_ids_in = implode(",", $test_ids_array);
// Pre-calculate untuk optimasi
$x_datetime_ts = strtotime($x_datetime);
$time_str = date('H:i', $x_datetime_ts);
$date_str = date('Y-m-d', $x_datetime_ts);
$day_of_week = date('w', $x_datetime_ts); // 0=Sunday, 6=Saturday
$mysql_day_of_week = ($day_of_week == 0) ? 1 : $day_of_week + 1;
// ============================================
// STEP 1: Ambil data test (query sederhana)
// ============================================
$sql = "SELECT
T_TestID,
T_TestName,
T_TestSasCode,
T_TestParentT_TestID,
T_TestNat_TestID,
T_TestIsResult
FROM t_test
WHERE T_TestID IN ({$test_ids_in})
AND T_TestIsActive = 'Y'";
$query = $this->db_smartone->query($sql);
if (!$query) {
return array("status" => "ERR", "message" => "Gagal ambil data test", "data" => array());
}
$tests = $query->result_array();
$test_list = array();
$parent_test_ids = array();
$sas_codes = array();
// Proses test: pisahkan yang result dan yang parent
foreach ($tests as $test) {
if ($test['T_TestIsResult'] == 'Y') {
$test_list[$test['T_TestID']] = $test;
} else {
$parent_test_ids[] = $test['T_TestID'];
$sas_codes[] = $this->db_smartone->escape($test['T_TestSasCode']);
}
}
// Ambil child test dari parent (jika ada)
if (!empty($sas_codes)) {
$sql_parts = array();
foreach ($sas_codes as $sas_code) {
$sql_parts[] = "T_TestSasCode LIKE CONCAT({$sas_code}, '%')";
}
$sql = "SELECT
T_TestID,
T_TestName,
T_TestSasCode,
T_TestParentT_TestID,
T_TestNat_TestID,
T_TestIsResult
FROM t_test
WHERE (" . implode(" OR ", $sql_parts) . ")
AND T_TestIsActive = 'Y'
AND T_TestIsResult = 'Y'";
$query = $this->db_smartone->query($sql);
if ($query) {
$child_tests = $query->result_array();
foreach ($child_tests as $child) {
$test_list[$child['T_TestID']] = $child;
}
}
}
if (empty($test_list)) {
return array("status" => "OK", "message" => "No test found", "data" => array());
}
// ============================================
// STEP 1.5: Ambil T_OrderDetailID jika order_id diberikan (setelah child test ditambahkan)
// ============================================
$order_detail_map = array(); // [test_id => order_detail_id]
if (!empty($order_id)) {
$order_id_escaped = intval($order_id);
// Ambil semua test_ids dari test_list (termasuk child yang baru ditambahkan)
$all_test_ids = array_keys($test_list);
$all_test_ids_in = implode(",", array_map('intval', $all_test_ids));
$sql = "SELECT
T_OrderDetailID,
T_OrderDetailT_TestID AS T_TestID
FROM t_orderdetail
WHERE T_OrderDetailT_OrderHeaderID = {$order_id_escaped}
AND T_OrderDetailT_TestID IN ({$all_test_ids_in})
AND T_OrderDetailIsActive = 'Y'";
$query = $this->db_smartone->query($sql);
if ($query) {
$order_details = $query->result_array();
foreach ($order_details as $od) {
$order_detail_map[$od['T_TestID']] = $od['T_OrderDetailID'];
}
}
}
// ============================================
// STEP 2: Ambil schedule untuk semua test (query sederhana)
// ============================================
$nat_test_ids = array_unique(array_column($test_list, 'T_TestNat_TestID'));
$nat_test_ids_in = implode(",", array_map('intval', $nat_test_ids));
$sql = "SELECT
s.M_ScheduleID,
s.M_ScheduleFlagAtTime,
s.M_ScheduleAtTime,
s.M_ScheduleMinute,
s.M_ScheduleMonth,
s.M_ScheduleWeek,
s.M_ScheduleDay,
s.M_ScheduleHour,
s.M_ScheduleStartHourMinute,
s.M_ScheduleEndHourMinute,
sgt.M_ScheduleGroupTestNat_TestID AS Nat_TestID
FROM m_schedule s
INNER JOIN m_schedulegroup sg ON s.M_ScheduleM_ScheduleGroupID = sg.M_ScheduleGroupID
INNER JOIN m_schedulegrouptest sgt ON sg.M_ScheduleGroupID = sgt.M_ScheduleGroupTestM_ScheduleGroupID
WHERE s.M_ScheduleIsActive = 'Y'
AND sg.M_ScheduleGroupIsActive = 'Y'
AND sgt.M_ScheduleGroupTestIsActive = 'Y'
AND sg.M_ScheduleGroupM_BranchID = {$branch_id_escaped}
AND s.M_ScheduleDayOfWeek = {$mysql_day_of_week}
AND sgt.M_ScheduleGroupTestNat_TestID IN ({$nat_test_ids_in})
AND '{$time_str}' >= s.M_ScheduleStartHourMinute
AND '{$time_str}' <= s.M_ScheduleEndHourMinute";
$query = $this->db_smartone->query($sql);
if (!$query) {
return array("status" => "ERR", "message" => "Gagal ambil schedule", "data" => array());
}
$schedules = $query->result_array();
//$this->order_debug('get_schedule_results_grouped/get_schedule', $this->db_smartone->last_query(), $schedules, "Ambil schedule untuk semua test");
// ============================================
// STEP 3: Proses di PHP - hitung janji hasil untuk setiap test
// ============================================
$test_schedules = array(); // [test_id => [schedule1, schedule2, ...]]
foreach ($test_list as $test_id => $test) {
$test_schedules[$test_id] = array();
// Cari schedule untuk test ini
foreach ($schedules as $schedule) {
if ($schedule['Nat_TestID'] == $test['T_TestNat_TestID']) {
// Hitung janji hasil
if ($schedule['M_ScheduleFlagAtTime'] == 'Y') {
$janji_hasil = $date_str . ' ' . $schedule['M_ScheduleAtTime'] . ':00';
} else {
$janji_hasil_ts = $this->calculate_janji_hasil_ts($x_datetime_ts, $schedule);
$janji_hasil = date('Y-m-d H:i:s', $janji_hasil_ts);
$data_debug = array(
'test_id' => $test_id,
'test_name' => $test['T_TestName'],
'test_nat_test_id' => $test['T_TestNat_TestID'],
'schedule_id' => $schedule['M_ScheduleID'],
'schedule_flag_at_time' => $schedule['M_ScheduleFlagAtTime'],
'schedule_at_time' => $schedule['M_ScheduleAtTime'],
'schedule_month' => $schedule['M_ScheduleMonth'],
'schedule_week' => $schedule['M_ScheduleWeek'],
'schedule_day' => $schedule['M_ScheduleDay'],
'schedule_hour' => $schedule['M_ScheduleHour'],
'schedule_minute' => $schedule['M_ScheduleMinute'],
'schedule_start_hour_minute' => $schedule['M_ScheduleStartHourMinute'],
'schedule_end_hour_minute' => $schedule['M_ScheduleEndHourMinute']
);
//$this->order_debug('get_schedule_results_grouped/loop_schedule', '', $data_debug, "check schedule for test_id: $test_id");
}
// Convert day, hour, minute to total minutes
$tat_menit = ($schedule['M_ScheduleDay'] * 24 * 60) + ($schedule['M_ScheduleHour'] * 60) + $schedule['M_ScheduleMinute'];
$test_schedules[$test_id][] = array(
'ScheduleID' => $schedule['M_ScheduleID'],
'JanjiHasil' => $janji_hasil,
'JanjiHasil_TS' => strtotime($janji_hasil),
'M_ScheduleFlagAtTime' => $schedule['M_ScheduleFlagAtTime'],
'M_ScheduleAtTime' => $schedule['M_ScheduleAtTime'],
'TAT_Menit' => $tat_menit,
'M_ScheduleStartHourMinute' => $schedule['M_ScheduleStartHourMinute'],
'M_ScheduleEndHourMinute' => $schedule['M_ScheduleEndHourMinute']
);
}
}
// Jika tidak ada schedule langsung, cari dari parent atau sibling
if (empty($test_schedules[$test_id]) && !empty($test['T_TestParentT_TestID'])) {
$parent_id = $test['T_TestParentT_TestID'];
// Cari schedule dari parent
foreach ($schedules as $schedule) {
// Cek apakah ada test parent dengan nat_test_id yang sama
foreach ($tests as $parent_test) {
if ($parent_test['T_TestID'] == $parent_id &&
$parent_test['T_TestNat_TestID'] == $schedule['Nat_TestID']) {
// Hitung janji hasil
if ($schedule['M_ScheduleFlagAtTime'] == 'Y') {
$janji_hasil = $date_str . ' ' . $schedule['M_ScheduleAtTime'] . ':00';
} else {
$janji_hasil_ts = $this->calculate_janji_hasil_ts($x_datetime_ts, $schedule);
$janji_hasil = date('Y-m-d H:i:s', $janji_hasil_ts);
}
// Convert day, hour, minute to total minutes
$tat_menit = ($schedule['M_ScheduleDay'] * 24 * 60) + ($schedule['M_ScheduleHour'] * 60) + $schedule['M_ScheduleMinute'];
$test_schedules[$test_id][] = array(
'ScheduleID' => $schedule['M_ScheduleID'],
'JanjiHasil' => $janji_hasil,
'JanjiHasil_TS' => strtotime($janji_hasil),
'M_ScheduleFlagAtTime' => $schedule['M_ScheduleFlagAtTime'],
'M_ScheduleAtTime' => $schedule['M_ScheduleAtTime'],
'TAT_Menit' => $tat_menit,
'M_ScheduleStartHourMinute' => $schedule['M_ScheduleStartHourMinute'],
'M_ScheduleEndHourMinute' => $schedule['M_ScheduleEndHourMinute']
);
break 2; // Break dari kedua loop
}
}
}
// Jika masih tidak ada, cari dari sibling (test lain dengan parent yang sama)
if (empty($test_schedules[$test_id])) {
foreach ($test_list as $sibling_id => $sibling_test) {
if ($sibling_id != $test_id &&
$sibling_test['T_TestParentT_TestID'] == $parent_id) {
// Cari schedule sibling
foreach ($schedules as $schedule) {
if ($sibling_test['T_TestNat_TestID'] == $schedule['Nat_TestID']) {
if ($schedule['M_ScheduleFlagAtTime'] == 'Y') {
$janji_hasil = $date_str . ' ' . $schedule['M_ScheduleAtTime'] . ':00';
} else {
$janji_hasil_ts = $this->calculate_janji_hasil_ts($x_datetime_ts, $schedule);
$janji_hasil = date('Y-m-d H:i:s', $janji_hasil_ts);
}
// Convert day, hour, minute to total minutes
$tat_menit = ($schedule['M_ScheduleDay'] * 24 * 60) + ($schedule['M_ScheduleHour'] * 60) + $schedule['M_ScheduleMinute'];
$test_schedules[$test_id][] = array(
'ScheduleID' => $schedule['M_ScheduleID'],
'JanjiHasil' => $janji_hasil,
'JanjiHasil_TS' => strtotime($janji_hasil),
'M_ScheduleFlagAtTime' => $schedule['M_ScheduleFlagAtTime'],
'M_ScheduleAtTime' => $schedule['M_ScheduleAtTime'],
'TAT_Menit' => $tat_menit,
'M_ScheduleStartHourMinute' => $schedule['M_ScheduleStartHourMinute'],
'M_ScheduleEndHourMinute' => $schedule['M_ScheduleEndHourMinute']
);
break 2;
}
}
}
}
}
// Jika masih tidak ada, default +24 jam
if (empty($test_schedules[$test_id])) {
$janji_hasil_ts = $x_datetime_ts + (24 * 3600);
$test_schedules[$test_id][] = array(
'ScheduleID' => null,
'JanjiHasil' => date('Y-m-d H:i:s', $janji_hasil_ts),
'JanjiHasil_TS' => $janji_hasil_ts,
'M_ScheduleFlagAtTime' => null,
'M_ScheduleAtTime' => null,
'TAT_Menit' => null,
'M_ScheduleStartHourMinute' => null,
'M_ScheduleEndHourMinute' => null
);
}
} elseif (empty($test_schedules[$test_id])) {
// Default +24 jam jika tidak ada schedule
$janji_hasil_ts = $x_datetime_ts + (24 * 3600);
$test_schedules[$test_id][] = array(
'ScheduleID' => null,
'JanjiHasil' => date('Y-m-d H:i:s', $janji_hasil_ts),
'JanjiHasil_TS' => $janji_hasil_ts,
'M_ScheduleFlagAtTime' => null,
'M_ScheduleAtTime' => null,
'TAT_Menit' => null,
'M_ScheduleStartHourMinute' => null,
'M_ScheduleEndHourMinute' => null
);
}
// Ambil schedule dengan janji hasil terbesar (ranking di PHP)
usort($test_schedules[$test_id], function($a, $b) {
return $b['JanjiHasil_TS'] - $a['JanjiHasil_TS'];
});
}
// ============================================
// STEP 4: Grouping berdasarkan tanggal dan jam (di PHP)
// ============================================
$grouped = array(); // [group_key => [tests]]
foreach ($test_schedules as $test_id => $schedules) {
$best_schedule = $schedules[0]; // Sudah di-sort, ambil yang terbesar
$test = $test_list[$test_id];
// Group key: tanggal + jam (tanpa detik)
$janji_ts = $best_schedule['JanjiHasil_TS'];
$group_key = date('Y-m-d H:i', $janji_ts);
if (!isset($grouped[$group_key])) {
$grouped[$group_key] = array(
'JanjiHasil' => $best_schedule['JanjiHasil'],
'JanjiHasil_Tanggal' => date('Y-m-d', $janji_ts),
'JanjiHasil_Waktu' => date('H:i:s', $janji_ts),
'TestIDs' => array(),
'TestNames' => array(),
'OrderDetailIDs' => array(), // Tambahkan untuk optimasi insert
'ScheduleID' => $best_schedule['ScheduleID'],
'M_ScheduleFlagAtTime' => $best_schedule['M_ScheduleFlagAtTime'],
'M_ScheduleAtTime' => $best_schedule['M_ScheduleAtTime'],
'TAT_Menit' => $best_schedule['TAT_Menit'],
'M_ScheduleStartHourMinute' => $best_schedule['M_ScheduleStartHourMinute'],
'M_ScheduleEndHourMinute' => $best_schedule['M_ScheduleEndHourMinute']
);
}
$grouped[$group_key]['TestIDs'][] = $test_id;
$grouped[$group_key]['TestNames'][] = $test['T_TestName'];
// Tambahkan OrderDetailID jika ada
if (!empty($order_detail_map[$test_id])) {
$grouped[$group_key]['OrderDetailIDs'][] = $order_detail_map[$test_id];
}
}
// ============================================
// STEP 5: Format hasil akhir
// ============================================
$results = array();
foreach ($grouped as $group) {
$results[] = array(
'JanjiHasil_Tanggal' => $group['JanjiHasil_Tanggal'],
'JanjiHasil_Waktu' => $group['JanjiHasil_Waktu'],
'JanjiHasil' => $group['JanjiHasil'],
'TestIDs' => implode(',', $group['TestIDs']),
'TestNames' => implode(', ', $group['TestNames']),
'OrderDetailIDs' => !empty($group['OrderDetailIDs']) ? implode(',', $group['OrderDetailIDs']) : null, // Tambahkan OrderDetailIDs
'ScheduleID' => $group['ScheduleID'],
'M_ScheduleFlagAtTime' => $group['M_ScheduleFlagAtTime'],
'M_ScheduleAtTime' => $group['M_ScheduleAtTime'],
'TAT_Menit' => $group['TAT_Menit'],
'M_ScheduleStartHourMinute' => $group['M_ScheduleStartHourMinute'],
'M_ScheduleEndHourMinute' => $group['M_ScheduleEndHourMinute']
);
}
// Sort by tanggal dan waktu
usort($results, function($a, $b) {
$ts_a = strtotime($a['JanjiHasil']);
$ts_b = strtotime($b['JanjiHasil']);
return $ts_a - $ts_b;
});
return $results;
}
/**
* Helper function untuk menghitung janji_hasil_ts berdasarkan schedule
* Memperhitungkan M_ScheduleMonth, M_ScheduleWeek, M_ScheduleDay, M_ScheduleHour, dan M_ScheduleMinute
*
* @param int $base_ts - Base timestamp
* @param array $schedule - Array schedule data
* @return int - Timestamp hasil perhitungan
*/
private function calculate_janji_hasil_ts($base_ts, $schedule)
{
$dt = new DateTime();
$dt->setTimestamp($base_ts);
// Tambahkan M_ScheduleMonth (jika ada)
if (!empty($schedule['M_ScheduleMonth']) && $schedule['M_ScheduleMonth'] > 0) {
$dt->modify('+' . intval($schedule['M_ScheduleMonth']) . ' months');
}
// Tambahkan M_ScheduleWeek (jika ada)
if (!empty($schedule['M_ScheduleWeek']) && $schedule['M_ScheduleWeek'] > 0) {
$dt->modify('+' . intval($schedule['M_ScheduleWeek']) . ' weeks');
}
// Tambahkan M_ScheduleDay (jika ada)
if (!empty($schedule['M_ScheduleDay']) && $schedule['M_ScheduleDay'] > 0) {
$dt->modify('+' . intval($schedule['M_ScheduleDay']) . ' days');
}
// Tambahkan M_ScheduleHour (jika ada)
if (!empty($schedule['M_ScheduleHour']) && $schedule['M_ScheduleHour'] > 0) {
$dt->modify('+' . intval($schedule['M_ScheduleHour']) . ' hours');
}
// Tambahkan M_ScheduleMinute (jika ada)
if (!empty($schedule['M_ScheduleMinute']) && $schedule['M_ScheduleMinute'] > 0) {
$dt->modify('+' . intval($schedule['M_ScheduleMinute']) . ' minutes');
}
return $dt->getTimestamp();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ResultCalc{
public function auto($id)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select
T_TestCalculationID,T_TestCalculationFormula,
T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
T_TestCalculationID,T_OrderDetailResult,
fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
T_TestCalculationNat_SexID
from t_orderdetail
join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID
and T_OrderHeaderID = ?
join m_patient on T_OrderHeaderM_PatientID = M_PatientID
join t_test on T_OrderDetailT_TestID = T_TestID
and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
join t_testcalculation on T_TestNat_TestID = T_TestCalculationNat_TestID
and T_TestCalculationIsActive = 'Y'
and (
T_TestCalculationNat_SexID = M_PatientM_SexID
or
T_TestCalculationNat_SexID = 0
)
";
$sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
from
t_testcalculation_detail td
join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
and T_TestCalculationID = ?
join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID
left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
and T_OrderDetailT_OrderHeaderID = ?
where T_OrderDetailID is not null";
$qry = $this->db->query($sql, array($id));
$rows = $qry->result_array();
if ( count($rows) > 0 ) {
foreach($rows as $r) {
$tc_id = $r["T_TestCalculationID"];
$qry_det = $this->db->query($sql_det, array($tc_id, $id));
$drows = $qry_det->result_array();
$formula = $r["T_TestCalculationFormula"];
$have_all = true;
$have_one = false;
$formula = str_replace("AGE",$r["AgeInYear"], $formula);
$flag_recursive = false;
if (strpos($formula,"[REC]") > -1 ) {
$flag_recursive = true;
}
//echo "$formula " . $r["T_OrderDetailResult"] . "\n";
if ( ! $flag_recursive ) {
if( trim($r["T_OrderDetailResult"]) != "") continue;
}
$formula = str_replace("[REC]","", $formula);
foreach($drows as $dr) {
$code = $dr["T_TestCalculationDetailCode"];
$value = $dr["T_OrderDetailResult"];
//echo "$code , $value , $formula \n";
if($dr["T_OrderDetailResult"] == "" ) {
$have_all = false;
break;
}
$have_one = true;
$formula = str_replace($code, $value,$formula);
}
if ($have_all && $have_one) {
eval("\$f_value = $formula;");
//formating
//echo "\n$f_value ..";
$f_value = $this->format_value($f_value,$r["Nat_TestID"]);
if (is_numeric($f_value)) {
$f_value = $this->format_value($f_value,$r["Nat_TestID"]);
}
$od_id = $r["T_OrderDetailID"];
$sql = "update t_orderdetail set T_OrderDetailResult = ?
where T_OrderDetailID = ?";
$this->db->query($sql, array($f_value,$od_id));
$sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
$this->db->query($sql, array($od_id,$formula,$f_value));
}
}
}
}
function format_value($f_value, $nat_test_id){
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from m_instrumentmethode
where M_InstrumentMethodeIsActive = 'Y'
and M_InstrumentMethodeNat_TestID = ?
limit 0,1";
$qry = $this->db->query($sql, array($nat_test_id) );
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
if ($f_value > 0 ) {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
} else {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
}
$idx = strpos($fmt,".");
$dec = strlen($fmt) - $idx;
if ($dec > 0 ) $dec = $dec -1;
return number_format($f_value,$dec);
}
}
return number_format($f_value,0,".",",");
}
}

View File

@@ -0,0 +1,123 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ResultCalc{
public function auto($id)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select
T_TestCalculationID,T_TestCalculationFormula,
T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
T_TestCalculationID,T_OrderDetailResult,
fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
T_TestCalculationNat_SexID
from t_orderdetail
join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID
and T_OrderHeaderID = ?
join m_patient on T_OrderHeaderM_PatientID = M_PatientID
join t_test on T_OrderDetailT_TestID = T_TestID
and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
join t_testcalculation on T_TestNat_TestID = T_TestCalculationNat_TestID
and T_TestCalculationIsActive = 'Y'
and (
T_TestCalculationNat_SexID = M_PatientM_SexID
or
T_TestCalculationNat_SexID = 0
)
";
$sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
from
t_testcalculation_detail td
join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
and T_TestCalculationID = ? and T_TestCalculationDetailIsActive = 'Y'
join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID
left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
and T_OrderDetailT_OrderHeaderID = ?
where T_OrderDetailID is not null";
$qry = $this->db->query($sql, array($id));
$rows = $qry->result_array();
if ( count($rows) > 0 ) {
foreach($rows as $r) {
$tc_id = $r["T_TestCalculationID"];
$qry_det = $this->db->query($sql_det, array($tc_id, $id));
$drows = $qry_det->result_array();
$formula = $r["T_TestCalculationFormula"];
$have_all = true;
$have_one = false;
$formula = str_replace("AGE",$r["AgeInYear"], $formula);
$flag_recursive = false;
if (strpos($formula,"[REC]") > -1 ) {
$flag_recursive = true;
}
//echo "$formula " . $r["T_OrderDetailResult"] . "\n";
if ( ! $flag_recursive ) {
if( trim($r["T_OrderDetailResult"]) != "") continue;
}
$formula = str_replace("[REC]","", $formula);
$s_code_value = "";
foreach($drows as $dr) {
$code = $dr["T_TestCalculationDetailCode"];
$value = $dr["T_OrderDetailResult"];
$s_code_value .= "^$code=$value";
//echo "$code , $value , $formula \n";
if($dr["T_OrderDetailResult"] == "" ) {
$have_all = false;
break;
}
$have_one = true;
$formula = str_replace($code, $value,$formula);
}
if ($have_all && $have_one) {
eval("\$f_value = $formula;");
//formating
//echo "\n$f_value ..";
$f_value = $this->format_value($f_value,$r["Nat_TestID"]);
if (is_numeric($f_value)) {
$f_value = $this->format_value($f_value,$r["Nat_TestID"]);
}
$od_id = $r["T_OrderDetailID"];
$sql = "update t_orderdetail set T_OrderDetailResult = ?
where T_OrderDetailID = ?";
$this->db->query($sql, array($f_value,$od_id));
try {
if ($tc_id == 2 ) {
$sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
$this->db->query($sql, array($od_id,$formula . " | " . $s_code_value ,$f_value));
}
} catch(Exception $e) {
}
}
}
}
}
function format_value($f_value, $nat_test_id){
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from m_instrumentmethode
where M_InstrumentMethodeIsActive = 'Y'
and M_InstrumentMethodeNat_TestID = ?
limit 0,1";
$qry = $this->db->query($sql, array($nat_test_id) );
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
if ($f_value > 0 ) {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
} else {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
}
$idx = strpos($fmt,".");
$dec = strlen($fmt) - $idx;
if ($dec > 0 ) $dec = $dec -1;
return number_format($f_value,$dec);
}
}
return number_format($f_value,0,".",",");
}
}

View File

@@ -0,0 +1,99 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ResultCalc{
public function auto($id)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select
T_TestCalculationID,T_TestCalculationFormula,
T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
T_TestCalculationID,T_OrderDetailResult,
fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
T_TestCalculationNat_SexID
from t_orderdetail
join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID
and T_OrderHeaderID = ?
join m_patient on T_OrderHeaderM_PatientID = M_PatientID
join t_test on T_OrderDetailT_TestID = T_TestID
and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
join t_testcalculation on T_TestNat_TestID = T_TestCalculationNat_TestID
and T_TestCalculationIsActive = 'Y'
and (
T_TestCalculationNat_SexID = M_PatientM_SexID
or
T_TestCalculationNat_SexID = 0
)
";
$sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
from
t_testcalculation_detail td
join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
and T_TestCalculationID = ?
join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID
left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
and T_OrderDetailT_OrderHeaderID = ?
where T_OrderDetailID is not null";
$qry = $this->db->query($sql, array($id));
$rows = $qry->result_array();
if ( count($rows) > 0 ) {
foreach($rows as $r) {
if ($r["T_OrderDetailResult"] != "") continue;
$tc_id = $r["T_TestCalculationID"];
$qry_det = $this->db->query($sql_det, array($tc_id, $id));
$drows = $qry_det->result_array();
$formula = $r["T_TestCalculationFormula"];
$have_all = true;
$have_one = false;
$formula = str_replace("AGE",$r["AgeInYear"], $formula);
foreach($drows as $dr) {
if($dr["T_OrderDetailResult"] == "" ) {
$have_all = false;
break;
}
$have_one = true;
$code = $dr["T_TestCalculationDetailCode"];
$value = $dr["T_OrderDetailResult"];
$formula = str_replace($code, $value,$formula);
}
if ($have_all && $have_one) {
eval("\$f_value = $formula;");
//formating
$f_value = $this->format_value($f_value,$r["Nat_TestID"]);
$od_id = $r["T_OrderDetailID"];
$sql = "update t_orderdetail set T_OrderDetailResult = ?
where T_OrderDetailID = ?";
$this->db->query($sql, array($f_value,$od_id));
}
}
}
}
function format_value($f_value, $nat_test_id){
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from m_instrumentmethode
where M_InstrumentMethodeIsActive = 'Y'
and M_InstrumentMethodeNat_TestID = ?
limit 0,1";
$qry = $this->db->query($sql, array($nat_test_id) );
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
if ($f_value > 0 ) {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
} else {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
}
$idx = strpos($fmt,".");
$dec = strlen($fmt) - $idx;
if ($dec > 0 ) $dec = $dec -1;
return number_format($f_value,$dec);
}
}
return number_format($f_value,0,".",",");
}
}

View File

@@ -0,0 +1,175 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class ResultCalc
{
public function auto($id, $debug = "")
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "select
T_TestCalculationID,T_TestCalculationFormula,
T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
T_TestCalculationID,T_OrderDetailResult,
fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
T_TestCalculationNat_SexID,
T_OrderDetailT_TestName
from t_orderdetail
join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID
and T_OrderHeaderID = ?
join m_patient on T_OrderHeaderM_PatientID = M_PatientID
join t_test on T_OrderDetailT_TestID = T_TestID
and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
join t_testcalculation on T_TestNat_TestID = T_TestCalculationNat_TestID
and T_TestCalculationIsActive = 'Y'
and (
T_TestCalculationNat_SexID = M_PatientM_SexID
or
T_TestCalculationNat_SexID = 0
)
";
$sql_det = "select T_OrderDetailT_TestName, T_TestCalculationDetailCode, T_OrderDetailResult
from
t_testcalculation_detail td
join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
and T_TestCalculationID = ? and T_TestCalculationDetailIsActive = 'Y'
join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID
left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
and T_OrderDetailT_OrderHeaderID = ?
Order by T_TestCalculationDetailCode,T_OrderDetailResult desc";
//where T_OrderDetailID is not null";
$qry = $this->db->query($sql, array($id));
$date = date("Y-m-d H:i:s");
//file_put_contents("/xtmp/debug-calc.log", "$date : {$this->db->last_query()} \n");
$rows = $qry->result_array();
if ($debug != "") {
print_r($rows);
}
if (count($rows) > 0) {
foreach ($rows as $r) {
$tc_id = $r["T_TestCalculationID"];
$qry_det = $this->db->query($sql_det, array($tc_id, $id));
$drows = $qry_det->result_array();
$formula = $r["T_TestCalculationFormula"];
$have_all = true;
$have_one = false;
$formula = str_replace("AGE", $r["AgeInYear"], $formula);
$flag_recursive = false;
if (strpos($formula, "[REC]") > -1) {
$flag_recursive = true;
}
if (!$flag_recursive) {
if (trim($r["T_OrderDetailResult"]) != "") continue;
}
$formula = str_replace("[REC]", "", $formula);
$org_formula = $formula;
$s_code_value = "";
$tc_name = $r["T_OrderDetailT_TestName"];
$arr_code = array();
$arr_param = [];
foreach ($drows as $dr) {
$code = $dr["T_TestCalculationDetailCode"];
$value = $dr["T_OrderDetailResult"];
$s_code_value .= "^$code=$value";
$arr_param[] = $code;
if (isset($arr_code[$code])) continue;
$arr_code[$code] = "exist";
if ($dr["T_OrderDetailResult"] == "" || $dr["T_OrderDetailResult"] == "-") {
$have_all = false;
break;
}
$arr_code[$code] = $value;
$have_one = true;
$formula = str_replace($code, $value, $formula);
}
$have_all = true;
if (count($arr_param) == 0) $have_all = false;
foreach($arr_param as $p) {
if ($debug != "") {
echo "code $p : ";
}
if (!isset($arr_code[$p])) {
if ($debug != "") {
echo "not exists \n";
}
$have_all = false;
break;
} else {
if ($arr_code[$p] == "exist") {
$have_all = false;
}
if ($debug != "") {
echo "exists : {$arr_code[$p]} \n";
}
}
}
if ($debug != "") {
echo "$formula " . $r["T_OrderDetailResult"] . "\n";
echo "-- have one : " . $have_one ? "Y" : "N";
echo "\n";
echo "-- have all : " . $have_all ? "Y" : "N";
echo "\n";
}
if ($have_all && $have_one) {
$date = date("Y-m-d H:i:s");
try {
// file_put_contents("/xtmp/debug-calc.log", "$date : $tc_name => \$f_value = $formula; \n");
// file_put_contents("/xtmp/debug-calc.log", "$date : Formula : $org_formula\n",FILE_APPEND);
// file_put_contents("/xtmp/debug-calc.log", print_r($drows,true),FILE_APPEND);
eval("\$f_value = $formula;");
//formating
$f_value = $this->format_value($f_value, $r["Nat_TestID"]);
if (is_numeric($f_value)) {
$f_value = $this->format_value($f_value, $r["Nat_TestID"]);
}
$od_id = $r["T_OrderDetailID"];
$sql = "update t_orderdetail set T_OrderDetailResult = ?
where T_OrderDetailID = ?";
$this->db->query($sql, array($f_value, $od_id));
if ($tc_id == 2) {
$sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
$this->db->query($sql, array($od_id, $formula . " | " . $s_code_value, $f_value));
}
} catch (Exception $e) {
//print_r($e);
}
}
}
}
}
function format_value($f_value, $nat_test_id)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "select * from m_instrumentmethode
where M_InstrumentMethodeIsActive = 'Y'
and M_InstrumentMethodeNat_TestID = ?
limit 0,1";
$qry = $this->db->query($sql, array($nat_test_id));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0) {
if ($f_value > 0) {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
} else {
$fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
}
$idx = strpos($fmt, ".");
$dec = strlen($fmt) - $idx;
if ($dec > 0) $dec = $dec - 1;
return number_format($f_value, $dec);
}
}
return number_format($f_value, 0, ".", ",");
}
}

View File

@@ -0,0 +1,575 @@
<?php
class Satu_sehat
{
var $base_url, $base_consent_url, $base_oauth_url;
var $is_staging, $organizationID;
var $key, $secret;
var $tz;
var $db, $dbname;
function __construct()
{
$this->tz = "+07:00";
$this->is_staging = false;
$this->base_url = "https://api-satusehat.kemkes.go.id/fhir-r4/v1";
$this->base_oauth_url = "https://api-satusehat.kemkes.go.id/oauth2/v1";
$this->base_consent_url = "https://api-satusehat.dto.kemkes.go.id/consent/v1";
$CI = &get_instance();
$this->db = $CI->load->database("default", true);
$this->dbname = "one_health";
if ($this->is_staging) {
$this->base_url = "https://api-satusehat-stg.kemkes.go.id/fhir-r4/v1";
$this->base_oauth_url = "https://api-satusehat-stg.kemkes.go.id/oauth2/v1";
$this->base_consent_url = "https://api-satusehat-stg.dto.kemkes.go.id/consent/v1";
$this->dbname = "one_health_dev";
}
$this->get_organization_id();
}
function ss_organization()
{
$this->get_organization_id();
$o_resp = $this->ss_get("/Organization/{$this->organizationID}");
$resp = $this->objToArray($o_resp);
$id = $resp["id"];
$name = $resp["name"];
$x_type = $resp["type"][0]["coding"][0];
$type = $x_type["display"];
$code = $x_type["code"];
$system = $x_type["system"];
return json_encode([
"ID" => $id,
"Name" => $name,
"Type" => $type,
"CodeSystem" => $code . " | " . $system,
]);
}
function search_practicioner_by_nik($nik, $debug = "")
{
$service = "/Practitioner?identifier=https://fhir.kemkes.go.id/id/nik|" . $nik;
$o_resp = $this->ss_get($service, $debug);
$resp = $this->objToArray($o_resp);
if (count($resp["entry"]) > 0) {
$rs = $resp["entry"][0]["resource"];
return json_encode([
"status" => "OK",
"ihsID" => $rs["id"],
"name" => $rs["name"][0]["text"]
]);
}
return json_encode([
"status" => "ERR",
"message" => "Practitioner not found [$nik]"
]);
}
function search_patient_by_nik($nik, $debug = "")
{
$service = "/Patient?identifier=https://fhir.kemkes.go.id/id/nik|" . $nik;
$resp = $this->ss_get($service);
if ($debug != "") {
echo "resp : ";
print_r($resp);
}
$a_resp = $this->objToArray($resp);
if (isset($a_resp["entry"][0]["resource"]["id"])) {
return $a_resp["entry"][0]["resource"]["id"];
}
return "";
}
function location_by_organization($organizationIhsID, $debug = "")
{
$service = "/Location?organization=" . $organizationIhsID;
$resp = $this->ss_get($service);
if ($debug != "") {
echo "resp : ";
print_r($resp);
}
$a_resp = $this->objToArray($resp);
return $a_resp;
}
function location_create(
$code,
$name,
$description,
$address,
$city,
$kodePos,
$administrativeCode,
$rt,
$rw,
$phone,
$type,
$partOf = "",
$email = "",
$fax = "",
$url = "",
$long = "",
$lat = ""
) {
$this->get_organization_id();
$organizationID = $this->organizationID;
list($type_code, $type_display) = explode("^", $type);
$telecom = [];
$telecom[] = ["system" => "phone", "value" => "$phone", "use" => "work"];
if ($fax != "") $telecom[] = ["system" => "fax", "value" => "$fax", "use" => "work"];
if ($email != "") $telecom[] = ["system" => "email", "value" => "$email"];
if ($url != "") $telecom[] = ["system" => "url", "value" => "$url"];
$provCode = substr($administrativeCode, 0, 2);
$cityCode = substr($administrativeCode, 0, 4);
$districtCode = substr($administrativeCode, 0, 7);
$villageCode = substr($administrativeCode, 0, 10);
$data = [
"resourceType" => "Location",
"identifier" => [
[
"system" => "http://sys-ids.kemkes.go.id/location/{$organizationID}",
"value" => "$code",
],
],
"status" => "active",
"name" => "$name",
"description" => "$description",
"mode" => "instance",
"telecom" => $telecom,
"address" => [
"use" => "work",
"line" => [
$address,
],
"city" => "$city",
"postalCode" => "$kodePos",
"country" => "ID",
"extension" => [
[
"url" =>
"https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode",
"extension" => [
["url" => "province", "valueCode" => $provCode],
["url" => "city", "valueCode" => $cityCode],
["url" => "district", "valueCode" => "$districtCode"],
["url" => "village", "valueCode" => "$villageCode"],
["url" => "rt", "valueCode" => "$rt"],
["url" => "rw", "valueCode" => "$rw"],
],
],
],
],
"physicalType" => [
"coding" => [
[
"system" =>
"http://terminology.hl7.org/CodeSystem/location-physical-type",
"code" => "$type_code",
"display" => "$type_display",
],
],
],
"position" => [
"longitude" => intval($long),
"latitude" => intval($lat),
"altitude" => 0,
],
"managingOrganization" => ["reference" => "Organization/{$organizationID}"],
];
if ($partOf != "") {
$data["partOf"] = [
"reference" => "Location/$partOf"
];
}
$service = "/Location";
$resp = $this->ss_post($service, $data);
return $this->objToArray($resp);
}
function location_nonactive(
$ihsID
) {
$this->get_organization_id();
$data = [
[
"op" => "replace",
"path" => "/status",
"value" => "inactive"
]
];
$service = "/Location/$ihsID";
$resp = $this->ss_patch($service, $data);
return $this->objToArray($resp);
}
function get_location($locationID)
{
}
function encounter_by_id($encounterID)
{
$this->get_organization_id();
$service = "/Encounter/$";
$resp = $this->ss_get($service);
return $this->objToArray($resp);
}
function encounter_by_subject($patientIhsID)
{
$this->get_organization_id();
$service = "/Encounter?subject=$patientIhsID";
$resp = $this->ss_get($service);
return $this->objToArray($resp);
}
function encounter(
$orderDate,
$patientIhsID,
$patientName,
$doctorIhsID,
$doctorName,
$locationID,
$locationName,
$labNumber,
$tz = "+07:00",
$payload_only = false
) {
$service = "/Encounter";
$xdate = substr($orderDate, 0, 10) . "T" . substr($orderDate, 11) . $tz;
$this->get_organization_id();
$param = $this->encounter_param(
$patientIhsID,
$patientName,
$doctorIhsID,
$doctorName,
$locationID,
$locationName,
$this->organizationID,
$labNumber,
$xdate
);
$payload = json_encode($param);
if ($payload_only) {
return ["", "", $payload, ""];
}
$jresp = $this->ss_post($service, $param);
$resp = $this->objToArray($jresp);
$response = json_encode($resp);
if (is_array($resp) && isset($resp["id"])) {
$encounterResponseID = $resp["id"];
return [$encounterResponseID, "", $payload, $response];
} else {
return ["", $response, $payload, $response];
}
}
function encounter_param(
$patientIhs,
$patientName,
$dpjpIhs,
$dpjpName,
$locationIhs,
$locationName,
$organizationID,
$orderHeaderNumber,
$dateTime // 2022-06-14T07:00:00+07:00
) {
if ($this->is_staging) {
$dpjpIhs = "N10000001";
$dpjpName = "Dokter Bronsig";
}
$encounterParam = [
"resourceType" => "Encounter",
"status" => "arrived",
"class" => [
"system" => "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code" => "AMB",
"display" => "ambulatory"
],
"subject" => [
"reference" => "Patient/{$patientIhs}",
"display" => "$patientName"
],
"participant" => [
[
"type" => [
[
"coding" => [
[
"system" => "http://terminology.hl7.org/CodeSystem/v3-ParticipationType",
"code" => "ATND",
"display" => "attender"
]
]
]
],
"individual" => [
"reference" => "Practitioner/{$dpjpIhs}",
"display" => "$dpjpName"
]
]
],
"period" => [
"start" => "$dateTime",
],
"location" => [
[
"location" => [
"reference" => "Location/$locationIhs",
"display" => "$locationName"
]
]
],
"statusHistory" => [
[
"status" => "arrived",
"period" => [
"start" => $dateTime
]
]
],
"serviceProvider" => [
"reference" => "Organization/{$organizationID}"
],
"identifier" => [
[
"system" => "http://sys-ids.kemkes.go.id/encounter/{$organizationID}",
"value" => "$orderHeaderNumber"
]
]
];
return $encounterParam;
}
// helper
function get_organization_id()
{
$sql = "SELECT organizationID
FROM {$this->dbname}.organization
JOIN m_branch ON organizationM_BranchID = M_BranchID AND M_BranchIsDefault = 'Y' AND M_BranchIsActive = 'Y'
WHERE organizationIsActive = 'Y'";
$qry = $this->db->query($sql);
if (!$qry) {
return;
}
$rows = $qry->result_array();
if (count($rows) > 0) {
$this->organizationID = $rows[0]["organizationID"];
}
}
function ss_patch($service, $data)
{
$token = $this->get_token();
$authorization = "Authorization: Bearer " . $token;
$xbase_url = $this->base_url;
$url = $xbase_url . "$service";
$ch = curl_init($url);
# Setup request to send json via POST.
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json-patch+json', $authorization));
# Return response instead of printing.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
$data_rst = json_decode($result);
return $data_rst;
}
function get_client_key($debug = "")
{
$sql = "select * from {$this->dbname}.client where clientIsActive = 'Y'";
$qry = $this->db->query($sql);
if (!$qry) {
return [false, "", ""];
}
$rows = $qry->result_array();
if (count($rows) == 0) {
if ($debug != "") {
print_r([false, "", ""]);
}
return [false, "", ""];
}
if ($debug != "") {
print_r([true, $rows[0]["clientKey"], $rows[0]["clientSecret"]]);
}
return [true, $rows[0]["clientKey"], $rows[0]["clientSecret"]];
}
function reset_token()
{
$sql = "delete from {$this->dbname}.token ";
$qry = $this->db->query($sql);
if (!$qry) {
echo "ERR : " . $this->db->error()["message"];
echo " " . $this->db->last_query();
exit;
}
}
function put_token()
{
$auth_url = $this->base_oauth_url;
$url = $auth_url . "/accesstoken?grant_type=client_credentials";
list($status, $key, $secret) = $this->get_client_key();
$data = [
"client_id" => $key,
"client_secret" => $secret
];
$ch = curl_init($url);
$post_data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$token_rst = json_decode($result);
$sql = "select count(*) as xcount, tokenID
from {$this->dbname}.token
where
tokenIsActive = 'y'
";
$qry = $this->db->query($sql);
if (!$qry) {
echo "get count token error";
exit;
}
$rst_count = $qry->row_array();
// print_r($token_rst);
if ($rst_count['xcount'] > 0) {
$sql = "update {$this->dbname}.token set tokenValue = ?, tokenExpired = date_add(now(), interval 50 minute)
where tokenID = ?";
$qry = $this->db->query($sql, [$token_rst->access_token, $rst_count['tokenID']]);
if (!$qry) {
$this->sys_error_db("refresh token error", $this->db->last_query());
exit;
}
} else {
$sql = "update {$this->dbname}.token set tokenIsActive = 'N' where tokenIsActive = 'Y'";
$qry = $this->db->query($sql);
if (!$qry) {
echo "nonactive token error";
exit;
}
$sql = "insert into {$this->dbname}.token(tokenValue,tokenExpired) values(?,date_add(now(), interval 50 minute))";
$qry = $this->db->query($sql, [$token_rst->access_token]);
if (!$qry) {
echo "insert token error";
exit;
}
}
$sql = "select tokenValue
from {$this->dbname}.token
where
tokenIsActive = 'Y' limit 1
";
$qry = $this->db->query($sql);
if (!$qry) {
echo "get token error";
exit;
}
return $qry->row()->tokenValue;
}
}
function get_token()
{
$sql = "SELECT COUNT(*) as xcount, tokenValue
FROM {$this->dbname}.token
WHERE tokenIsActive = 'Y' AND NOW() < tokenExpired AND tokenValue IS NOT NULL ";
$qry = $this->db->query($sql);
$this->check_error($qry, "select token");
$data_token = $qry->row_array();
//print_r($data_token);
if ($data_token['xcount'] > 0) {
return $data_token['tokenValue'];
} else {
return $this->put_token();
}
}
function ss_post($service, $data)
{
$token = $this->get_token();
$authorization = "Authorization: Bearer " . $token;
$xbase_url = $this->base_url;
$url = $xbase_url . "$service";
$ch = curl_init($url);
# Setup request to send json via POST.
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
# Return response instead of printing.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
$data_rst = json_decode($result);
return $data_rst;
}
function ss_get($service, $debug = "")
{
$token = $this->get_token();
$authorization = "Authorization: Bearer " . $token;
$xbase_url = $this->base_url;
$url = $xbase_url . "$service";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
# Return response instead of printing.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
if ($debug != "") {
echo "url : $url \n";
print_r($result);
}
$data_rst = json_decode($result);
return $data_rst;
}
protected function objToArray($obj)
{
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
return $arr;
}
function check_error($qry, $stage)
{
if (!$qry) {
echo json_encode([
"status" => "ERR",
"message" => $this->db->error(),
"sql" => $this->db->last_query()
]);
exit;
}
}
}

View File

@@ -0,0 +1,859 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class SsPriceMou
{
function create($tPriceHeaderID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$this->db->trans_begin();
$sql = "select * from t_priceheader where T_PriceHeaderID = ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "T PriceHeader ID : $tPriceHeaderID not found");
}
$sql = "select distinct T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceT_PriceHeaderID= ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
$this->db->trans_rollback();
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
// HANYA DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
$this->db->trans_rollback();
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID,
T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp,
0 T_PriceSubTotal, 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell,
'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceT_PriceHeaderID= ? ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql);
if (!$qry) {
//DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketT_PriceHeaderID= ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, 0 T_PricePriority,
T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc,
0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
JOIN t_packet ON T_PacketDetailT_PacketID = T_PacketID
JOIN t_price ON T_PacketDetailT_TestID = T_PriceT_TestID AND T_PriceIsActive = 'Y' AND T_PriceT_PriceHeaderID = T_PacketT_PriceHeaderID
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query(
"delete from ss_price_mou where Ss_PriceMouT_PriceHeaderID=?",
array($tPriceHeaderID)
);
if (!$qry) {
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
$this->db->insert_batch("ss_price_mou", $rows);
$err = $this->db->error();
if ($err["code"] != 0) {
echo "ERR Code : " . $err["code"] . " | " . $err["message"] . " \n";
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
// $sql_i = "insert into ss_price_mou(
// T_TestID, T_TestName,
// IsFromPanel, Nat_TestID,T_PriceT_TestID, T_PriceIsCito,
// T_PricePriority, T_PriceAmount, T_PriceDisc,
// T_PriceDiscRp, T_PriceSubTotal, T_PriceOther, T_PriceTotal,
// T_TestForceSell, is_packet, packet_id, px_type,
// nat_test, child_test, IsFavourite, Ss_PriceMouT_PriceHeaderID)
// values (
// ?,?,
// ?,?,?,?,
// ?,?,?,
// ?,?,?,?,
// ?,?,?,?,
// ?,?,?,?
// )";
// foreach ($rows as $r) {
// $arr = [
// $r["T_TestID"],
// $r["T_TestName"],
// $r["IsFromPanel"],
// $r["Nat_TestID"],
// $r["T_PriceT_TestID"],
// $r["T_PriceIsCito"],
// $r["T_PricePriority"],
// $r["T_PriceAmount"],
// $r["T_PriceDisc"],
// $r["T_PriceDiscRp"],
// $r["T_PriceSubTotal"],
// $r["T_PriceOther"],
// $r["T_PriceTotal"],
// $r["T_TestForceSell"],
// $r["is_packet"],
// $r["packet_id"],
// $r["px_type"],
// $r["nat_test"],
// $r["child_test"],
// $r["IsFavourite"],
// $r["Ss_PriceMouT_PriceHeaderID"],
// ];
// $qry = $this->db->query($sql_i, $arr);
// if (!$qry) {
//
// header("Content-Type: text/plain");
// print_r($r);
// echo $this->db->last_query();
// return array(false, "Regional " . print_r($this->db->error(), true));
// }
// }
$this->db->trans_commit();
return array(true, "OK");
}
// retrun array status, message
public function bisone_create($mouID)
{
$CI = &get_instance();
$this->db = $CI->load->database("one", true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
return array(true, "OK");
}
public function edit($mouID, $testID, $cito)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "select * from t_test where T_TestID = ? ";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "No Test $testID found");
}
$sasCode = $rows[0]["T_TestSasCode"];
if (strlen($sasCode) == 8) {
$flagProfile = false;
} else {
$flagProfile = true;
}
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "No MOU $mouID found");
}
$mouName = $rows[0]["M_MouName"];
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?";
$qry = $this->db->query($sql, array($testID, $cito, $mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
}
if (count($rows) > 0) {
$r = $rows[0];
unset($r["T_TestSasCode"]);
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
}
$sasCode = substr($sasCode, 0, 8);
foreach ($rows as $idx => $r) {
if (strlen($r["T_TestSasCode"]) > 8) {
unset($rows[$idx]);
} else {
unset($rows[$idx]["T_TestSasCode"]);
}
}
if ($cito == 'Y') {
return array(true, "OK", $rows);
}
// for non cito
if ($flagProfile) {
//wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sasCodeLike = $sasCode . "%";
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = 'N'
and T_TestSasCode like ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($sasCodeLike, $mouID));
if (!$qry) {
return array(false, "Regional child_test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional nat_test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
foreach ($p_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(), true));
}
}
$rows = array_merge($rows, $p_rows);
}
//Update Panel yang mengandung Test
$sql = "select
distinct T_PacketDetailT_PacketID
from
t_packetdetail
where T_PacketDetailIsActive = 'Y'
and T_PacketDetailT_TestID = ?";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$packet_ids = "0";
foreach ($xrows as $r) {
$packet_ids .= "," . $r["T_PacketDetailT_PacketID"];
}
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
foreach ($pn_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
}
$rows = array_merge($rows, $pn_rows);
return array(true, "OK", $rows);
}
}

View File

@@ -0,0 +1,69 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Soresultlog
{
function __construct()
{
$CI = &get_instance();
$this->db_onedev = $CI->load->database("default", true);
$this->db_smartone = $CI->load->database("default", true);
}
function clean_mysqli_connection($dbc)
{
while (mysqli_more_results($dbc)) {
if (mysqli_next_result($dbc)) {
$result = mysqli_use_result($dbc);
if (get_class($result) == 'mysqli_stmt') {
mysqli_stmt_free_result($result);
} else {
unset($result);
}
}
}
}
public function step_action($act,$re_id,$userid)
{
//$CI = &get_instance();
//$this->db = $CI->load->database("one", true);
$sql = "INSERT INTO so_reactionlog(
So_REActionLogDate,
So_REActionLogSo_ResultEntryID,
So_REActionLogAction,
So_REActionLogUserID
)
VALUES(
NOW(),?,?,?
)";
$qry = $this->db_onedev->query($sql, array($re_id,$act,$userid));
if (!$qry) {
return array(false, print_r($this->db_onedev->error(), true));
}else
return array(true);
}
public function log_result($data_json,$re_id,$userid)
{
//$CI = &get_instance();
//$this->db = $CI->load->database("one", true);
//echo $re_id;
$sql = "INSERT INTO cpone_log.log_resultentry_so(
Log_ResultEntrySoDate,
Log_ResultEntrySoReID,
Log_ResultEntrySoJSON,
Log_ResultEntrySoUserID
)
VALUES(
NOW(),?,?,?
)";
$qry = $this->db_onedev->query($sql, array($re_id,$data_json,$userid));
if (!$qry) {
return array(false, print_r($this->db_onedev->error(), true));
}else
return array(true);
}
}

View File

@@ -0,0 +1,542 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SsPriceMou{
// retrun array status, message
public function create($mouID) {
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional select t_price " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, "Regional panel " . print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional Profile " . print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional child test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional P_Codes $p_codes " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
0 T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalPrice T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalPrice - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional Paket " . print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc, 0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows,$p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if ( ! $qry ) {
return array(false, "Regional Del Mou " . print_r($this->db->error(),true));
}
if ( ! empty($rows) ) {
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if ( ! $qry ) {
return array(false, "Regional Insert Batch Ss Price Mou" . print_r($this->db->error(),true));
}
}
return array(true, "OK");
}
public function edit($mouID,$testID,$cito) {
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from t_test where T_TestID = ? ";
$qry = $this->db->query($sql, array($testID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No Test $testID found");
}
$sasCode = $rows[0]["T_TestSasCode"];
if ( strlen($sasCode) == 8 ) {
$flagProfile = false;
} else {
$flagProfile = true;
}
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No MOU $mouID found");
}
$mouName = $rows[0]["M_MouName"];
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?";
$qry = $this->db->query($sql, array($testID, $cito, $mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
if ( count($rows) > 0 ) {
$r = $rows[0];
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
}
$sasCode = substr($sasCode,0,8);
if ($cito == 'Y' ) {
return array(true,"OK",$rows);
}
// for non cito
if($flagProfile ) {
//wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($sasCode));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sasCodeLike = $sasCode . "%";
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = 'N'
and T_TestSasCode like ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($sasCodeLike,$mouID));
if (!$qry ) {
return array(false, "Regional child_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional nat_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
foreach($p_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(),true));
}
}
$rows = array_merge($rows,$p_rows);
}
//Update Panel yang mengandung Test
$sql = "select
distinct T_PacketDetailT_PacketID
from
t_packetdetail
where T_PacketDetailIsActive = 'Y'
and T_PacketDetailT_TestID = ?";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$packet_ids = "0";
foreach($xrows as $r ) {
$packet_ids .= "," . $r["T_PacketDetailT_PacketID"];
}
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
0 T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalPrice T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalPrice - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc, 0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
foreach($pn_rows as $r ) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
}
$rows = array_merge($rows,$pn_rows);
return array(true,"OK",$rows);
}
}

View File

@@ -0,0 +1,547 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SsPriceMou{
// retrun array status, message
public function create($mouID) {
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional select t_price " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional child test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows,$p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if ( ! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if ( ! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
return array(true, "OK");
}
public function edit($mouID,$testID,$cito) {
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from t_test where T_TestID = ? ";
$qry = $this->db->query($sql, array($testID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No Test $testID found");
}
$sasCode = $rows[0]["T_TestSasCode"];
if ( strlen($sasCode) == 8 ) {
$flagProfile = false;
} else {
$flagProfile = true;
}
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No MOU $mouID found");
}
$mouName = $rows[0]["M_MouName"];
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?";
$qry = $this->db->query($sql, array($testID, $cito, $mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
}
if ( count($rows) > 0 ) {
$r = $rows[0];
unset($r["T_TestSasCode"]);
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
}
$sasCode = substr($sasCode,0,8);
foreach($rows as $idx => $r ) {
if ( strlen($r["T_TestSasCode"]) > 8 ) {
unset($rows[$idx]);
} else {
unset($rows[$idx]["T_TestSasCode"]);
}
}
if ($cito == 'Y' ) {
return array(true,"OK",$rows);
}
// for non cito
if($flagProfile ) {
//wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($sasCode));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sasCodeLike = $sasCode . "%";
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = 'N'
and T_TestSasCode like ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($sasCodeLike,$mouID));
if (!$qry ) {
return array(false, "Regional child_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional nat_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
foreach($p_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(),true));
}
}
$rows = array_merge($rows,$p_rows);
}
//Update Panel yang mengandung Test
$sql = "select
distinct T_PacketDetailT_PacketID
from
t_packetdetail
where T_PacketDetailIsActive = 'Y'
and T_PacketDetailT_TestID = ?";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$packet_ids = "0";
foreach($xrows as $r ) {
$packet_ids .= "," . $r["T_PacketDetailT_PacketID"];
}
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
foreach($pn_rows as $r ) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
}
$rows = array_merge($rows,$pn_rows);
return array(true,"OK",$rows);
}
}

View File

@@ -0,0 +1,559 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SsPriceMou{
// retrun array status, message
public function create($mouID) {
$CI =& get_instance();
$this->db = $CI->load->database("regional",true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional select t_price " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional child test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, "Regional " . print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows,$p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if ( ! $qry ) {
return array(false, "Regional Delete : " . print_r($this->db->error(),true));
}
if ( count($rows) == 0 ) {
return array(false,"Empty Data");
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if ( ! $qry ) {
return array(false, "Regional Insert : " . print_r($this->db->error(),true));
}
return array(true, "OK");
}
public function edit($mouID,$testID,$cito) {
$CI =& get_instance();
$this->db = $CI->load->database("regional",true);
$sql = "select * from t_test where T_TestID = ? ";
$qry = $this->db->query($sql, array($testID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No Test $testID found");
}
$sasCode = $rows[0]["T_TestSasCode"];
if ( strlen($sasCode) == 8 ) {
$flagProfile = false;
} else {
$flagProfile = true;
}
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
if (count($rows) == 0 ) {
return array(false, "No MOU $mouID found");
}
$mouName = $rows[0]["M_MouName"];
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?";
$qry = $this->db->query($sql, array($testID, $cito, $mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$rows = $qry->result_array();
foreach($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
break;
default :
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
}
if ( count($rows) > 0 ) {
$r = $rows[0];
unset($r["T_TestSasCode"]);
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
if ($this->db->affected_rows() == 0 ) {
$this->db->insert("ss_price_mou", $r);
}
}
$sasCode = substr($sasCode,0,8);
foreach($rows as $idx => $r ) {
if ( strlen($r["T_TestSasCode"]) > 8 ) {
unset($rows[$idx]);
} else {
unset($rows[$idx]["T_TestSasCode"]);
}
}
if ($cito == 'Y' ) {
return array(true,"OK",$rows);
}
// for non cito
if($flagProfile ) {
//wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($sasCode));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$p_rows = $qry->result_array();
$sasCodeLike = $sasCode . "%";
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = 'N'
and T_TestSasCode like ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql,array($sasCodeLike,$mouID));
if (!$qry ) {
return array(false, "Regional child_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
if ( ! isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql,array($mouID));
if (!$qry ) {
return array(false, "Regional nat_test " . print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach($xrows as $r ) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach($p_rows as $idx => $r) {
$T_TestName= $r["T_TestName"] ;
$sasCode = $r["T_TestSasCode"];
if ( isset($arr_child[$sasCode]) ) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs,true);
if ( isset($arr_nat[$sasCode] )) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
foreach($p_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(),true));
}
if ($this->db->affected_rows() == 0 ) {
$this->db->insert("ss_price_mou", $r);
}
}
$rows = array_merge($rows,$p_rows);
}
//Update Panel yang mengandung Test
$sql = "select
distinct T_PacketDetailT_PacketID
from
t_packetdetail
where T_PacketDetailIsActive = 'Y'
and T_PacketDetailT_TestID = ?";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(),true));
}
$xrows = $qry->result_array();
$packet_ids = "0";
foreach($xrows as $r ) {
$packet_ids .= "," . $r["T_PacketDetailT_PacketID"];
}
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
$pn_rows = $qry->result_array();
foreach($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
";
$qry = $this->db->query($sql,array($packetID));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql,array($sasCode));
if (!$qry ) {
return array(false, print_r($this->db->error(),true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach($nt_rows as $nr) {
$t_rows[] = intval( $nr["T_TestNat_TestID"]);
$p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0 ) {
$x_arr = array();
foreach($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
foreach($pn_rows as $r ) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou",$r);
if (! $qry ) {
return array(false, print_r($this->db->error(),true));
}
if ($this->db->affected_rows() == 0 ) {
$this->db->insert("ss_price_mou", $r);
}
}
$rows = array_merge($rows,$pn_rows);
return array(true,"OK",$rows);
}
}

View File

@@ -0,0 +1,859 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class SsPriceMou
{
function create($tPriceHeaderID)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$this->db->trans_begin();
$sql = "select * from t_priceheader where T_PriceHeaderID = ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "T PriceHeader ID : $tPriceHeaderID not found");
}
$sql = "select distinct T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceT_PriceHeaderID= ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
$this->db->trans_rollback();
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
// HANYA DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
$this->db->trans_rollback();
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID,
T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp,
0 T_PriceSubTotal, 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell,
'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceT_PriceHeaderID= ? ";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql);
if (!$qry) {
//DEBUG
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito,
0 T_PricePriority, T_PacketOriginalPrice T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalPrice - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$tPriceHeaderID Ss_PriceMouT_PriceHeaderID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketT_PriceHeaderID= ?";
$qry = $this->db->query($sql, array($tPriceHeaderID));
if (!$qry) {
// echo $this->db->last_query();
// print_r($this->db->error());
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, 0 T_PricePriority,
T_PacketDetailPrice T_PriceAmount,
0 T_PriceDisc,
0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
JOIN t_packet ON T_PacketDetailT_PacketID = T_PacketID
JOIN t_price ON T_PacketDetailT_TestID = T_PriceT_TestID AND T_PriceIsActive = 'Y' AND T_PriceT_PriceHeaderID = T_PacketT_PriceHeaderID
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query(
"delete from ss_price_mou where Ss_PriceMouT_PriceHeaderID=?",
array($tPriceHeaderID)
);
if (!$qry) {
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
$this->db->insert_batch("ss_price_mou", $rows);
$err = $this->db->error();
if ($err["code"] != 0) {
echo "ERR Code : " . $err["code"] . " | " . $err["message"] . " \n";
$this->db->trans_rollback();
return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query());
}
// $sql_i = "insert into ss_price_mou(
// T_TestID, T_TestName,
// IsFromPanel, Nat_TestID,T_PriceT_TestID, T_PriceIsCito,
// T_PricePriority, T_PriceAmount, T_PriceDisc,
// T_PriceDiscRp, T_PriceSubTotal, T_PriceOther, T_PriceTotal,
// T_TestForceSell, is_packet, packet_id, px_type,
// nat_test, child_test, IsFavourite, Ss_PriceMouT_PriceHeaderID)
// values (
// ?,?,
// ?,?,?,?,
// ?,?,?,
// ?,?,?,?,
// ?,?,?,?,
// ?,?,?,?
// )";
// foreach ($rows as $r) {
// $arr = [
// $r["T_TestID"],
// $r["T_TestName"],
// $r["IsFromPanel"],
// $r["Nat_TestID"],
// $r["T_PriceT_TestID"],
// $r["T_PriceIsCito"],
// $r["T_PricePriority"],
// $r["T_PriceAmount"],
// $r["T_PriceDisc"],
// $r["T_PriceDiscRp"],
// $r["T_PriceSubTotal"],
// $r["T_PriceOther"],
// $r["T_PriceTotal"],
// $r["T_TestForceSell"],
// $r["is_packet"],
// $r["packet_id"],
// $r["px_type"],
// $r["nat_test"],
// $r["child_test"],
// $r["IsFavourite"],
// $r["Ss_PriceMouT_PriceHeaderID"],
// ];
// $qry = $this->db->query($sql_i, $arr);
// if (!$qry) {
//
// header("Content-Type: text/plain");
// print_r($r);
// echo $this->db->last_query();
// return array(false, "Regional " . print_r($this->db->error(), true));
// }
// }
$this->db->trans_commit();
return array(true, "OK");
}
// retrun array status, message
public function bisone_create($mouID)
{
$CI = &get_instance();
$this->db = $CI->load->database("one", true);
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "MOU ID : $mouID not found");
}
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?
and length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional select t_price " . print_r($this->db->error(), true));
}
$rows = $qry->result_array();
$flag_error = false;
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($rows[$idx]["T_TestSasCode"]);
}
//Test Profile
// wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y'
and T_PriceIsCito = 'N'
and length(T_TestSasCode) = 10
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional child test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
//Paket Panel / Profile
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y'
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
$rows = array_merge($rows, $p_rows, $pn_rows);
$qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
$qry = $this->db->insert_batch("ss_price_mou", $rows);
if (!$qry) {
return array(false, "Regional " . print_r($this->db->error(), true));
}
return array(true, "OK");
}
public function edit($mouID, $testID, $cito)
{
$CI = &get_instance();
$this->db = $CI->load->database("onedev", true);
$sql = "select * from t_test where T_TestID = ? ";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "No Test $testID found");
}
$sasCode = $rows[0]["T_TestSasCode"];
if (strlen($sasCode) == 8) {
$flagProfile = false;
} else {
$flagProfile = true;
}
$sql = "select * from m_mou where M_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
if (count($rows) == 0) {
return array(false, "No MOU $mouID found");
}
$mouName = $rows[0]["M_MouName"];
$companyID = $rows[0]["M_MouM_CompanyID"];
$sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_price
join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
where T_PriceM_MouID = ?";
$qry = $this->db->query($sql, array($testID, $cito, $mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$rows = $qry->result_array();
foreach ($rows as $idx => $r) {
$nat_testType = $r["Nat_TestNat_TestTypeID"];
switch ($nat_testType) {
case 1: //Single
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
case 3: //Multi
case 4: //Panel
$sasCode = $r["T_TestSasCode"] . '%';
$sql = "select T_TestNat_TestID
from t_test
where T_TestIsResult = 'Y'
and T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array($r["Nat_TestID"]);
foreach ($nt_rows as $nr) {
$t_rows[] = $nr["T_TestNat_TestID"];
}
$rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]";
break;
default:
$rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
break;
}
unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
}
if (count($rows) > 0) {
$r = $rows[0];
unset($r["T_TestSasCode"]);
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
}
$sasCode = substr($sasCode, 0, 8);
foreach ($rows as $idx => $r) {
if (strlen($r["T_TestSasCode"]) > 8) {
unset($rows[$idx]);
} else {
unset($rows[$idx]["T_TestSasCode"]);
}
}
if ($cito == 'Y') {
return array(true, "OK", $rows);
}
// for non cito
if ($flagProfile) {
//wip profile
$sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
from t_test
join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
where length(T_TestSasCode) = 8 ";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$p_rows = $qry->result_array();
$sasCodeLike = $sasCode . "%";
$sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
from t_price
join t_test on T_PriceT_TestID = T_TestID
and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y'
and T_TestIsPrice = 'Y' and T_PriceIsCito = 'N'
and T_TestSasCode like ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
where T_PriceM_MouID = ? ";
$qry = $this->db->query($sql, array($sasCodeLike, $mouID));
if (!$qry) {
return array(false, "Regional child_test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_child = array();
$p_codes = "'0'";
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
if (!isset($arr_child[$pCode])) {
$arr_child[$pCode] = array();
}
$cCode = $r["T_TestSasCode"];
$p_codes .= ", '$cCode'";
unset($r["parentCode"]);
$arr_child[$pCode][] = $r;
}
$sql = "select substr(T_TestSasCode,1,8) parentCode,
group_concat(distinct T_TestNat_TestID) nat
from t_test
where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
and T_TestSasCode in ( $p_codes )
and T_TestIsActive = 'Y'
group by parentCode";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, "Regional nat_test " . print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$arr_nat = array();
foreach ($xrows as $r) {
$pCode = $r["parentCode"];
//if ( ! isset($arr_nat[$pCode])) {
// $arr_nat[$pCode] = array();
//}
$arr_nat[$pCode] = $r["nat"];
}
$flag_error = false;
foreach ($p_rows as $idx => $r) {
$T_TestName = $r["T_TestName"];
$sasCode = $r["T_TestSasCode"];
if (isset($arr_child[$sasCode])) {
$the_childs = $arr_child[$sasCode];
$p_rows[$idx]['child_test'] = json_encode($the_childs, true);
if (isset($arr_nat[$sasCode])) {
$p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
}
unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($p_rows[$idx]["T_TestSasCode"]);
} else {
unset($p_rows[$idx]);
}
}
foreach ($p_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(), true));
}
}
$rows = array_merge($rows, $p_rows);
}
//Update Panel yang mengandung Test
$sql = "select
distinct T_PacketDetailT_PacketID
from
t_packetdetail
where T_PacketDetailIsActive = 'Y'
and T_PacketDetailT_TestID = ?";
$qry = $this->db->query($sql, array($testID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$xrows = $qry->result_array();
$packet_ids = "0";
foreach ($xrows as $r) {
$packet_ids .= "," . $r["T_PacketDetailT_PacketID"];
}
$sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc,
(T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id,
T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
$mouID Ss_PriceMouM_MouID
from
t_packet
where
T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
and T_PacketM_MouID = ?";
$qry = $this->db->query($sql, array($mouID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$pn_rows = $qry->result_array();
foreach ($pn_rows as $idx => $pnr) {
$packetID = $pnr["packet_id"];
//child test
$sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID,
$mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount,
T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
0 T_PriceOther, T_PacketDetailPrice T_PriceTotal,
'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
from t_packetdetail
join t_test on T_PacketDetailT_TestID = T_TestID
and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y'
and T_PacketDetailT_PacketID = ?
join nat_test on T_TestNat_TestID = Nat_TestID
and Nat_TestIsActive = 'Y'
";
$qry = $this->db->query($sql, array($packetID));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$ct_rows = $qry->result_array();
$p_nat_test = array();
foreach ($ct_rows as $ct_idx => $cr) {
$sasCode = $cr["T_TestSasCode"] . '%';
$sql = "select distinct T_TestNat_TestID
from t_test
where T_TestSasCode like ?
and T_TestIsActive = 'Y'";
$qry = $this->db->query($sql, array($sasCode));
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
$nt_rows = $qry->result_array();
$t_rows = array();
foreach ($nt_rows as $nr) {
$t_rows[] = intval($nr["T_TestNat_TestID"]);
$p_nat_test[] = intval($nr["T_TestNat_TestID"]);
}
$ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK);
}
if (count($ct_rows) > 0) {
$x_arr = array();
foreach ($ct_rows as $x_cr) {
$x_arr[] = $x_cr;
}
$pn_rows[$idx]['child_test'] = json_encode($x_arr, true);
$pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true);
}
unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
unset($pn_rows[$idx]["T_TestSasCode"]);
}
foreach ($pn_rows as $r) {
$this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
$this->db->where("T_TestID", $r["T_TestID"]);
$this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
$qry = $this->db->update("ss_price_mou", $r);
if (!$qry) {
return array(false, print_r($this->db->error(), true));
}
}
$rows = array_merge($rows, $pn_rows);
return array(true, "OK", $rows);
}
}

View File

@@ -0,0 +1,52 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SsPriceMouPx {
public function create($mouID) {
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select * from ss_price_mou where Ss_PriceMouM_MouID = ? and px_type in ('PR','PXR')";
$qry = $this->db->query($sql, array($mouID));
if ( ! $qry ) {
return array(false, "Ss Price Mou " . print_r($this->db->error(),true));
}
$rows = $qry->result_array();
$sql ="delete from ss_price_mou_px where Ss_PriceMouPxSs_PriceMouID in ( select Ss_PriceMouID from ss_price_mou
where Ss_PriceMouM_MouID = ? )";
$qry = $this->db->query($sql, array($mouID));
if ( ! $qry ) {
return array(false, "Clear Ss Price Mou Px" . print_r($this->db->error(),true));
}
$a_data = array();
foreach($rows as $r) {
$j_ct = $r["child_test"];
$ct = json_decode($j_ct,true);
foreach($ct as $c) {
$a_data[] = array(
"Ss_PriceMouPxM_MouID" => $r["Ss_PriceMouM_MouID"],
"Ss_PriceMouPxSs_PriceMouID" => $r["Ss_PriceMouID"],
"Ss_PriceMouPxT_TestID" => $c["T_TestID"],
"Ss_PriceMouPxT_TestName" => $c["T_TestName"],
"Ss_PriceMouPxT_PriceIsCito" => $c["T_PriceIsCito"],
"Ss_PriceMouPxT_PriceM_CompanyID" => $c["T_PriceM_CompanyID"],
"Ss_PriceMouPxT_PricePriority" => $c["T_PricePriority"],
"Ss_PriceMouPxT_PriceAmount" => $c["T_PriceAmount"],
"Ss_PriceMouPxT_PriceDisc" => $c["T_PriceDisc"],
"Ss_PriceMouPxT_PriceDiscRp" => $c["T_PriceDiscRp"],
"Ss_PriceMouPxT_PriceSubTotal" => $c["T_PriceSubTotal"],
"Ss_PriceMouPxT_PriceOther" => $c["T_PriceOther"],
"Ss_PriceMouPxT_PriceTotal" => $c["T_PriceTotal"],
"Ss_PriceMouPxT_TestForceSell" => $c["T_TestForSell"],
"nat_test" => $c["nat_test"]
);
}
}
$qry = $this->db->insert_batch("ss_price_mou_px",$a_data);
if ( ! $qry ) {
return array(false, "Batch Ss Price Mou Px" . print_r($this->db->error(),true));
}
return array(true, "");
}
}

View File

@@ -0,0 +1,285 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TxBranchStatus{
public function update_multi($stage,$ids ,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$s_ids = join(",",$ids);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID in ($s_ids) ";
$qry = $this->db->query($sql);
$incomingRefID = 0;
$s_detail_ids = "0";
$s_child_ids = "0";
$headerID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$s_test = "0";
foreach($rows as $r) {
$s_test .= "," . $r["T_OrderDetailT_TestID"];
}
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
$flag_found = false;
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
foreach($rowsd as $r) {
$s_detail_ids .= "," . $r["incomingRefDetailID"];
}
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
foreach($rowsd as $r) {
$s_child_ids .= "," . $r["incomingRefChildID"];
}
}
}
}
}
}
if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
if ( $val_note == null ) $val_note = "";
}
}
}
$note = "$stage by $username";
if ($s_detail_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID in ($s_detail_ids)
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
if ($s_child_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID in ($s_child_ids)
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}
public function update($stage,$orderDetailID,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID = ? ";
$qry = $this->db->query($sql, array($orderDetailID));
$incomingRefID = 0;
$incomingRefDetailID = 0;
$flag_child = false;
if ($qry) {
$rows = $qry->result_array();
$flag_found = false;
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$testID = $rows[0]["T_OrderDetailT_TestID"];
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
$flag_found = true;
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
$flag_found = true;
$flag_child = true;
}
}
}
}
}
if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
if ( $val_note == null ) $val_note = "";
}
}
}
$note = "$stage by $username";
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID = ?
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
if ($flag_child ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID = ?
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
}
$qry = $this->db->query($sql, array($note, $val_note, $incomingRefDetailID));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}

View File

@@ -0,0 +1,300 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TxBranchStatus{
public function update_multi($stage,$ids ,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$s_ids = join(",",$ids);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID in ($s_ids) ";
$qry = $this->db->query($sql);
$incomingRefID = 0;
$s_detail_ids = "0";
$s_child_ids = "0";
$headerID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$s_test = "0";
foreach($rows as $r) {
$s_test .= "," . $r["T_OrderDetailT_TestID"];
}
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
$flag_found = false;
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
foreach($rowsd as $r) {
$s_detail_ids .= "," . $r["incomingRefDetailID"];
}
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
foreach($rowsd as $r) {
$s_child_ids .= "," . $r["incomingRefChildID"];
}
}
}
}
}
}
if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
$val_note_int = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
$val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
if ( $val_note == null ) $val_note = "";
if ( $val_note_int == null ) $val_note_int = "";
}
}
}
$note = "$stage by $username";
if ($s_detail_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID in ($s_detail_ids)
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
if ($s_child_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID in ($s_child_ids)
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}
public function update($stage,$orderDetailID,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID = ? ";
$qry = $this->db->query($sql, array($orderDetailID));
$incomingRefID = 0;
$incomingRefDetailID = 0;
$flag_child = false;
if ($qry) {
$rows = $qry->result_array();
$flag_found = false;
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$testID = $rows[0]["T_OrderDetailT_TestID"];
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
$flag_found = true;
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
$flag_found = true;
$flag_child = true;
}
}
}
}
}
if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
$val_note_int = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
$val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
if ( $val_note == null ) $val_note = "";
if ( $val_note_int == null ) $val_note_int = "";
}
}
}
$note = "$stage by $username";
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID = ?
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
if ($flag_child ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID = ?
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
}
$qry = $this->db->query($sql, array($note, $val_note, $val_note_int, $incomingRefDetailID));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}

View File

@@ -0,0 +1,300 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TxBranchStatus{
public function update_multi($stage,$ids ,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$s_ids = join(",",$ids);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID in ($s_ids) ";
$qry = $this->db->query($sql);
$incomingRefID = 0;
$s_detail_ids = "0";
$s_child_ids = "0";
$headerID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$s_test = "0";
foreach($rows as $r) {
$s_test .= "," . $r["T_OrderDetailT_TestID"];
}
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
$flag_found = false;
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
foreach($rowsd as $r) {
$s_detail_ids .= "," . $r["incomingRefDetailID"];
}
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
foreach($rowsd as $r) {
$s_child_ids .= "," . $r["incomingRefChildID"];
}
}
}
}
}
}
if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
$val_note_int = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
$val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
if ( $val_note == null ) $val_note = "";
if ( $val_note_int == null ) $val_note_int = "";
}
}
}
$note = "$stage by $username";
if ($s_detail_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID in ($s_detail_ids)
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
if ($s_child_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID in ($s_child_ids)
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}
public function update($stage,$orderDetailID,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID
from
t_orderdetail
where T_OrderDetailID = ? ";
$qry = $this->db->query($sql, array($orderDetailID));
$incomingRefID = 0;
$incomingRefDetailID = 0;
$flag_child = false;
if ($qry) {
$rows = $qry->result_array();
$flag_found = false;
if(count($rows) > 0 ) {
$headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
$testID = $rows[0]["T_OrderDetailT_TestID"];
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
$flag_found = true;
}
}
//check child
if(! $flag_found ) {
$sql = "select incomingRefChildID , incomingRefChildIncomingRefID
from incoming_ref_child
where incomingRefChildNewT_OrderHeaderID = ?
and incomingRefChildT_TestID = ?";
$qryd = $this->db->query($sql, array($headerID,$testID));
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
$incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
$flag_found = true;
$flag_child = true;
}
}
}
}
}
if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
$val_note_int = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
$val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
if ( $val_note == null ) $val_note = "";
if ( $val_note_int == null ) $val_note_int = "";
}
}
}
$note = "$stage by $username";
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID = ?
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
if ($flag_child ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefChildID,
incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
'' incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note,
? validation_note_internal
from incoming_ref_child
join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
and incomingRefChildID = ?
left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
}
$qry = $this->db->query($sql, array($note, $val_note, $val_note_int, $incomingRefDetailID));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}

View File

@@ -0,0 +1,112 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Txmikro {
public function update($order_header_id,$username)
{
$CI =& get_instance();
$this->db = $CI->load->database("onedev",true);
$s_ids = join(",",$ids);
$sql = "select T_OrderDetailT_TestID
from
t_orderdetail
join other_mikro on Other_MikroT_OrderDetailID = T_OrderDetailID
and T_OrderDetailValidation = 'Y'
where T_OrderDetailT_OrderHeaderID = ? ";
$qry = $this->db->query($sql,$array($order_header_id));
$incomingRefID = 0;
$s_detail_ids = "0";
$s_child_ids = "0";
$headerID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows) > 0 ) {
$headerID = $order_header_id
$s_test = "0";
foreach($rows as $r) {
$s_test .= "," . $r["T_OrderDetailT_TestID"];
}
$sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
from incoming_ref_detail
where incomingRefDetailNewT_OrderHeaderID = ?
and incomingRefDetailT_TestID in ($s_test) ";
$qryd = $this->db->query($sql, array($headerID));
$flag_found = false;
if($qryd) {
$rowsd = $qryd->result_array();
if ( count($rowsd) > 0 ) {
$incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
foreach($rowsd as $r) {
$s_detail_ids .= "," . $r["incomingRefDetailID"];
}
}
}
}
}
if ($s_detail_ids == "0" ) {
return false;
}
$sql = "select M_BranchID, M_BranchIPAddress
from m_branch
join incoming_ref
on M_BranchID = incomingRefM_BranchID
where incomingRefID = ?";
$qry = $this->db->query($sql, array($incomingRefID));
$branchID = 0;
if ($qry) {
$rows = $qry->result_array();
if(count($rows)>0) {
$branchID = $rows[0]["M_BranchID"];
$branchIPAddress = $rows[0]["M_BranchIPAddress"];
}
}
if ($branchID == 0 ) {
return false;
}
$val_note = "";
if ($headerID > 0 ) {
$sql = "select T_OrderHeaderAddOnValidationNote
from t_orderheaderaddon
where T_orderHeaderAddOnT_OrderHeaderID = ?";
$qry = $this->db->query($sql,array($headerID));
if ($qry) {
$rows = $qry->result_array();
if (count($rows) > 0 ) {
$val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
if ( $val_note == null ) $val_note = "";
}
}
}
$note = "$stage by $username";
if ($s_detail_ids!= "0" ) {
$sql = "select
incomingRefT_RefDeliveryOrderID,
incomingRefDetailT_OrderDetailID,
incomingRefDetailStatus,
T_OrderDetailResult,
T_OrderDetailNat_NormalValueID,
T_OrderDetailVerification,
T_OrderDetailValidation,
T_OrderDetailNote,
? note,
? validation_note
from incoming_ref_detail
join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
and incomingRefDetailID in ($s_detail_ids)
left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
$qry = $this->db->query($sql, array($note,$val_note));
if ($qry) {
$rows = $qry->result_array();
$param = json_encode($rows);
//insert to
$sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
values (?,?,?,?,?)";
$qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
}
}
}
}

View File

@@ -0,0 +1,38 @@
<?php
include_once BASEPATH . "../vendor/kirim_pesan/ClientV3.php";
use KrmPesan\ClientV3;
class Wa_krmv3
{
var $id_token = "eyJraWQiOiJnUFdURUFqekZLTmFnTGhSa28rbGszeEhRMCtEWm42Z29XcDR1ZEhvV0RZPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyNTJjNGZiYS0xMGFhLTQ1NzUtOTZjYy01ZDBiZjdmMzE0MDQiLCJjb2duaXRvOmdyb3VwcyI6WyJ1c2VyIiwiREVWIzYyODUyMzY4MTEzMzAiXSwiZW1haWxfdmVyaWZpZWQiOnRydWUsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC5hcC1zb3V0aGVhc3QtMS5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMV9Fa0M0emJUVXUiLCJjb2duaXRvOnVzZXJuYW1lIjoiMjUyYzRmYmEtMTBhYS00NTc1LTk2Y2MtNWQwYmY3ZjMxNDA0Iiwib3JpZ2luX2p0aSI6ImJjZTcxZTY4LWVhZTYtNGE3MC05ZjA5LTE5MjEyNjFmMWYxNyIsImF1ZCI6IjIybXZnMnNhc2Y5aDZsbTVhdWk4YjByN2pqIiwiZXZlbnRfaWQiOiI3MDMxYjQ0Ni00MjBjLTQ4ZjktOGIzMi1mMGZiMzFlYjUzNzgiLCJ0b2tlbl91c2UiOiJpZCIsImF1dGhfdGltZSI6MTY5ODkxMjk1MiwibmFtZSI6IlByYW1pdGEgTGFiIiwiZXhwIjoxNjk4OTk5MzUyLCJpYXQiOjE2OTg5MTI5NTIsImp0aSI6IjU5NjZhZTVjLTkyZDAtNGYxYS05NzVhLTVhMjFjZjlhNjAxZCIsImVtYWlsIjoiaW5mb0BwcmFtaXRhLmNvLmlkIn0.FrIVco9oW4QSwPWWSpUc-CyNGm3hjoDXtrKECBLdKdbyJsX0Qws48S2AXbQ7gqb8dSLpH4tFUyM5boTOxYR55bc8QuN6hF9n9-1QOFfKGyLA37tSdVE-9bziycIUQ5g0cqBH_3eFebAaeDIIYKr6Tu_bs0ZAuRqvjLqj8mSoDNrDaeOhVLKMfFUwXtesjxkOV0TvV_OFQ4_96Q4Kk3wul7R2mJTuONsDa8u1UgWFVrcmRKYzq_qSs6K5eFD_kekRpZrMkNeC4ch3fvP1ZQ3z2SsNVwvLtpRYdFiEYuV91jYtZC33WR6dOL1d-wUdowNXfdGrQlAHOah2NyDbDuF96Q";
var $refresh_token = "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.bTjo6WiUaTZjjUohwGi0M52we5pG-yrqauLHRrFrHD5CTItWuFnceFCtt8l-rxwST9jvBC3VqkOvRkP2sA1M-U4jt0LSP1aJl5dTNo2ejxvCRGyvw7Un5ykM1XqvxYWzVrWC5hi-Jf87sJco2myJqjlHAiPiHmH-vvrcdSiMjEnu83jatHmGimQQzZUq6xKjn6UW5Ok0bEKqOJMh3Lo_32WHpH01G1i26Iz35Dn9yKbzL3wam52tuD3pbTA98fYXeMZGOf0jjJAt-Xk2DAOYiKrkqY6nWW8nuqKqT71PUxKDTooB77qd9F1pqmMG_r97pWXMzpIzO5O1w34jb2cymQ.fLP07rW7cC79w1rm.oMv0SEleK1pi4p-FbjmABIc39N8KRRp6l3cTSi1ndmM4wnnjwLbV9XLYpVPZZ9oz2zhZH9p7h3POgUKzazm4raP_pRA-SeyrqKQZa6U5cACeRmRbIdPMXInjACxiyaSD09rwP3_htgIpz0urTzWt9d0zMXdaczORdSPcC-GHtanHPfDVkr-u9dYG2ZYeJmx-u0NIi2OmgnqUiBJmD5gx1LdzFnrmTizrVeAnxA_fB8FF0isHTLUo3imAgGGG9dgYa_dSodqdWpK9rgX5AtVe5NVAzqudACx5KwOfM7EpwLhaLFI-RA4KXB2OQlMAU3TqBvBjt89Gs6AMtBaFxKg3HWxkOiynLX4hV8I4WnEWhYoAN6sOBcuW6h2Dhqxpd9fDYQdS1VqmgZkBrNzMnmcb91F6QmPs5jMqMK2aL7S_T9I9L6y-ci6OCdDmpwlwM5wsiIK7PBdI367sgWE9-oXGvGopiV_e17FJRqLWItnEjPJoel3hr5jcil5LAie4VGBjUOCY50PjP_gRdxdtwrWgBZu48AuNekHGXlQKy_QyOgLK0WAtXBms0_-VvpUyOKVWOt27ExxweayKfDeLpkX8uh-Iy7VXK2tDUVky7EHCZirQccb93Y0hNaxpEqto0fm12RzycHGye0ScbPh1NoeAcqc77lI6-TmtfcBiweDALrUVriQIMRcbnOrQNSBazYMVVQiNsXrsrBs36yqKV60Y5cScG9d7sq83N9ENLM90Q2XYATnLlE_wOMa9WpYNkNo62fMZQZDNCdzRXcnZNjJvAXhxmlqdCpceg_TbbYmOSge6iq2Qz5gprdbsf89cD-EbgqHUfhZlbQ1wZtTcO0DepY4K3jwseF3CXJbksbfNMGLYVjrIRSeCbOoKJ1EcQqVfP56F9kSAvohOQBTrWQU74pJI9S_m_Gzx21y9eJXbM9XNHhguU2ZcmXFOZSZ65-JApQqdao2gNjkfq-WZQwrW-RctUv2XRUV6MJjkIysx3zpnS8r5zmSYqqcj929aAI7LiL7c2VtMgQLJNiw0023LovrgU2QzMGu8dNw790wAwNv7X8C_oMTEk44aKFMaG2MRvjuO6jPv7qRqDIi6igzhk4lJuGA1gYPGFLBu68CdBgpA3FxVtmxJhXDCr4rfgtJ7XY1TWBe_gjqHw3c_FMhLOjBzD25mGC-vWwSdLpwaCrkvz3B73yl0PJXvfl_PQdiW8UzrIRZ-J1KKnBv0n5lEj3W4Ahy6v0IwcYxRdkkUHKu87r_MFNJQlRJiiXeFuHpxb5IVF-Xb6IGj0wxhbCzQKaMX1N91xogecORoUncx1mGl8HuHyflQphtp2fj9mkWf6tEyJcLX5rVD09sbG5QIc2aWZGK7WrVPx7iezEwmVOSGYs6Bb8KJfb33KlsFo0hHMm00VRhGwV2PxgCw1GJX7GzCuWeInkCOL4_7Z3CSwKceu0-FlSFcfFr4OdALzSVMthRg_Jle.tSoFTKWQVTvUfZgSkaTyuQ";
var $device_id = "ap-southeast-1_60ed15bd-eb92-4d89-a5e0-85595ac26530";
var $template = "qrorder";
var $client;
function __construct()
{
$this->client = new ClientV3([
"deviceId" => $this->device_id,
"refreshToken" => $this->refresh_token,
"idToken" => $this->id_token
]);
}
function upload($url)
{
//create tmp file
$fname = tempnam("/tmp","rpt") . "-rpt.pdf";
file_put_contents($fname,file_get_contents($url));
$resp = $this->client->upload($fname);
unlink($fname);
return $resp;
}
function send_qrcode($phone, $url, $name, $date)
{
$urlImg = $this->upload($url);
$message = [$name,$date];
$resp = $this->client->sendMessageTemplateImage($phone,$this->template,"id",$message,$urlImg);
return json_decode($resp,true);
}
}

View File

@@ -0,0 +1,159 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Wa_sas
{
var $username, $host, $password;
function __construct()
{
// $this->host = "http://sasdev.jala.my.id:3000/send/";
//$this->host = "http://139.59.235.205:3000/send/";
$this->host = "http://devkedungdoro.aplikasi.web.id:7001/send/";
$this->username = "sasdev";
$this->password = "sasdev!#102938";
}
function fix_phone($phone)
{
//remove - and space
$phone = str_replace("-", "", $phone);
$phone = str_replace(" ", "", $phone);
//remove 1st +
if (substr($phone, 0, 1) == "+") {
$phone = substr($phone, 1);
}
if (substr($phone, 0, 1) == "0") {
$phone = "62" . substr($phone, 1);
}
if (substr($phone, 0, 2) != "62") {
$phone = "62" . $phone;
}
return $phone;
}
function send_image_group(
$phone,
$caption,
$url_image,
$contentType,
$file_name,
$extension,
$view_once = false,
$compress = false
) {
$tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
file_put_contents($tmpFile, file_get_contents($url_image));
$data = [
"phone" => $phone,
"caption" => $caption,
"view_once" => $view_once,
"compress" => $compress,
"image" => curl_file_create($tmpFile, $contentType, $file_name)
];
$ch = curl_init($this->host . "image");
//curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
$return = curl_exec($ch);
curl_close($ch);
unlink($tmpFile);
$j_return = json_decode($return, true);
if (json_last_error() != 0) {
return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
}
return $j_return;
}
function send_message($phone, $message, $is_group = false)
{
$data = [
"phone" => $is_group ? $phone : $this->fix_phone($phone),
"message" => $message
];
$ch = curl_init($this->host . "message");
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);
$j_return = json_decode($return, true);
if (json_last_error() != 0) {
return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
}
return $j_return;
}
function send_image(
$phone,
$caption,
$url_image,
$contentType,
$file_name,
$extension,
$view_once = false,
$compress = false
) {
$tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
file_put_contents($tmpFile, file_get_contents($url_image));
$data = [
"phone" => $this->fix_phone($phone),
"caption" => $caption,
"view_once" => $view_once,
"compress" => $compress,
"image" => curl_file_create($tmpFile, $contentType, $file_name)
];
$ch = curl_init($this->host . "image");
//curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
$return = curl_exec($ch);
curl_close($ch);
unlink($tmpFile);
$j_return = json_decode($return, true);
if (json_last_error() != 0) {
return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
}
return $j_return;
}
function send_file(
$phone,
$caption,
$url_file,
$contentType,
$file_name,
$extension,
$compress = false
) {
$tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
file_put_contents($tmpFile, file_get_contents($url_file));
$data = [
"phone" => $this->fix_phone($phone),
"caption" => $caption,
"compress" => $compress,
"file" => curl_file_create($tmpFile, $contentType, $file_name)
];
$ch = curl_init($this->host . "file");
//curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
$return = curl_exec($ch);
curl_close($ch);
unlink($tmpFile);
$j_return = json_decode($return, true);
if (json_last_error() != 0) {
return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
}
return $j_return;
}
}

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,180 @@
<?php
/*
* PHP QR Code encoder
*
* Bitstream class
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class QRbitstream {
public $data = array();
//----------------------------------------------------------------------
public function size()
{
return count($this->data);
}
//----------------------------------------------------------------------
public function allocate($setLength)
{
$this->data = array_fill(0, $setLength, 0);
return 0;
}
//----------------------------------------------------------------------
public static function newFromNum($bits, $num)
{
$bstream = new QRbitstream();
$bstream->allocate($bits);
$mask = 1 << ($bits - 1);
for($i=0; $i<$bits; $i++) {
if($num & $mask) {
$bstream->data[$i] = 1;
} else {
$bstream->data[$i] = 0;
}
$mask = $mask >> 1;
}
return $bstream;
}
//----------------------------------------------------------------------
public static function newFromBytes($size, $data)
{
$bstream = new QRbitstream();
$bstream->allocate($size * 8);
$p=0;
for($i=0; $i<$size; $i++) {
$mask = 0x80;
for($j=0; $j<8; $j++) {
if($data[$i] & $mask) {
$bstream->data[$p] = 1;
} else {
$bstream->data[$p] = 0;
}
$p++;
$mask = $mask >> 1;
}
}
return $bstream;
}
//----------------------------------------------------------------------
public function append(QRbitstream $arg)
{
if (is_null($arg)) {
return -1;
}
if($arg->size() == 0) {
return 0;
}
if($this->size() == 0) {
$this->data = $arg->data;
return 0;
}
$this->data = array_values(array_merge($this->data, $arg->data));
return 0;
}
//----------------------------------------------------------------------
public function appendNum($bits, $num)
{
if ($bits == 0)
return 0;
$b = QRbitstream::newFromNum($bits, $num);
if(is_null($b))
return -1;
$ret = $this->append($b);
unset($b);
return $ret;
}
//----------------------------------------------------------------------
public function appendBytes($size, $data)
{
if ($size == 0)
return 0;
$b = QRbitstream::newFromBytes($size, $data);
if(is_null($b))
return -1;
$ret = $this->append($b);
unset($b);
return $ret;
}
//----------------------------------------------------------------------
public function toByte()
{
$size = $this->size();
if($size == 0) {
return array();
}
$data = array_fill(0, (int)(($size + 7) / 8), 0);
$bytes = (int)($size / 8);
$p = 0;
for($i=0; $i<$bytes; $i++) {
$v = 0;
for($j=0; $j<8; $j++) {
$v = $v << 1;
$v |= $this->data[$p];
$p++;
}
$data[$i] = $v;
}
if($size & 7) {
$v = 0;
for($j=0; $j<($size & 7); $j++) {
$v = $v << 1;
$v |= $this->data[$p];
$p++;
}
$data[$bytes] = $v;
}
return $data;
}
}

View File

@@ -0,0 +1,17 @@
<?php
/*
* PHP QR Code encoder
*
* Config file, feel free to modify
*/
define('QR_CACHEABLE', true); // use cache - more disk reads but less CPU power, masks and format templates are stored there
define('QR_CACHE_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR); // used when QR_CACHEABLE === true
define('QR_LOG_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR); // default error logs dir
define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
define('QR_FIND_FROM_RANDOM', false); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false
define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images

View File

@@ -0,0 +1,54 @@
<?php
/*
* PHP QR Code encoder
*
* Common constants
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Encoding modes
define('QR_MODE_NUL', -1);
define('QR_MODE_NUM', 0);
define('QR_MODE_AN', 1);
define('QR_MODE_8', 2);
define('QR_MODE_KANJI', 3);
define('QR_MODE_STRUCTURE', 4);
// Levels of error correction.
define('QR_ECLEVEL_L', 0);
define('QR_ECLEVEL_M', 1);
define('QR_ECLEVEL_Q', 2);
define('QR_ECLEVEL_H', 3);
// Supported output formats
define('QR_FORMAT_TEXT', 0);
define('QR_FORMAT_PNG', 1);
class qrstr {
public static function set(&$srctab, $x, $y, $repl, $replLen = false) {
$srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
}
}

View File

@@ -0,0 +1,502 @@
<?php
/*
* PHP QR Code encoder
*
* Main encoder classes.
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class QRrsblock {
public $dataLength;
public $data = array();
public $eccLength;
public $ecc = array();
public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs)
{
$rs->encode_rs_char($data, $ecc);
$this->dataLength = $dl;
$this->data = $data;
$this->eccLength = $el;
$this->ecc = $ecc;
}
};
//##########################################################################
class QRrawcode {
public $version;
public $datacode = array();
public $ecccode = array();
public $blocks;
public $rsblocks = array(); //of RSblock
public $count;
public $dataLength;
public $eccLength;
public $b1;
//----------------------------------------------------------------------
public function __construct(QRinput $input)
{
$spec = array(0,0,0,0,0);
$this->datacode = $input->getByteStream();
if(is_null($this->datacode)) {
throw new Exception('null imput string');
}
QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec);
$this->version = $input->getVersion();
$this->b1 = QRspec::rsBlockNum1($spec);
$this->dataLength = QRspec::rsDataLength($spec);
$this->eccLength = QRspec::rsEccLength($spec);
$this->ecccode = array_fill(0, $this->eccLength, 0);
$this->blocks = QRspec::rsBlockNum($spec);
$ret = $this->init($spec);
if($ret < 0) {
throw new Exception('block alloc error');
return null;
}
$this->count = 0;
}
//----------------------------------------------------------------------
public function init(array $spec)
{
$dl = QRspec::rsDataCodes1($spec);
$el = QRspec::rsEccCodes1($spec);
$rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
$blockNo = 0;
$dataPos = 0;
$eccPos = 0;
for($i=0; $i<QRspec::rsBlockNum1($spec); $i++) {
$ecc = array_slice($this->ecccode,$eccPos);
$this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
$this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
$dataPos += $dl;
$eccPos += $el;
$blockNo++;
}
if(QRspec::rsBlockNum2($spec) == 0)
return 0;
$dl = QRspec::rsDataCodes2($spec);
$el = QRspec::rsEccCodes2($spec);
$rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el);
if($rs == NULL) return -1;
for($i=0; $i<QRspec::rsBlockNum2($spec); $i++) {
$ecc = array_slice($this->ecccode,$eccPos);
$this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs);
$this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc);
$dataPos += $dl;
$eccPos += $el;
$blockNo++;
}
return 0;
}
//----------------------------------------------------------------------
public function getCode()
{
$ret;
if($this->count < $this->dataLength) {
$row = $this->count % $this->blocks;
$col = $this->count / $this->blocks;
if($col >= $this->rsblocks[0]->dataLength) {
$row += $this->b1;
}
$ret = $this->rsblocks[$row]->data[$col];
} else if($this->count < $this->dataLength + $this->eccLength) {
$row = ($this->count - $this->dataLength) % $this->blocks;
$col = ($this->count - $this->dataLength) / $this->blocks;
$ret = $this->rsblocks[$row]->ecc[$col];
} else {
return 0;
}
$this->count++;
return $ret;
}
}
//##########################################################################
class QRcode {
public $version;
public $width;
public $data;
//----------------------------------------------------------------------
public function encodeMask(QRinput $input, $mask)
{
if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) {
throw new Exception('wrong version');
}
if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) {
throw new Exception('wrong level');
}
$raw = new QRrawcode($input);
QRtools::markTime('after_raw');
$version = $raw->version;
$width = QRspec::getWidth($version);
$frame = QRspec::newFrame($version);
$filler = new FrameFiller($width, $frame);
if(is_null($filler)) {
return NULL;
}
// inteleaved data and ecc codes
for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) {
$code = $raw->getCode();
$bit = 0x80;
for($j=0; $j<8; $j++) {
$addr = $filler->next();
$filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0));
$bit = $bit >> 1;
}
}
QRtools::markTime('after_filler');
unset($raw);
// remainder bits
$j = QRspec::getRemainder($version);
for($i=0; $i<$j; $i++) {
$addr = $filler->next();
$filler->setFrameAt($addr, 0x02);
}
$frame = $filler->frame;
unset($filler);
// masking
$maskObj = new QRmask();
if($mask < 0) {
if (QR_FIND_BEST_MASK) {
$masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel());
} else {
$masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel());
}
} else {
$masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel());
}
if($masked == NULL) {
return NULL;
}
QRtools::markTime('after_mask');
$this->version = $version;
$this->width = $width;
$this->data = $masked;
return $this;
}
//----------------------------------------------------------------------
public function encodeInput(QRinput $input)
{
return $this->encodeMask($input, -1);
}
//----------------------------------------------------------------------
public function encodeString8bit($string, $version, $level)
{
if(string == NULL) {
throw new Exception('empty string!');
return NULL;
}
$input = new QRinput($version, $level);
if($input == NULL) return NULL;
$ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string));
if($ret < 0) {
unset($input);
return NULL;
}
return $this->encodeInput($input);
}
//----------------------------------------------------------------------
public function encodeString($string, $version, $level, $hint, $casesensitive)
{
if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) {
throw new Exception('bad hint');
return NULL;
}
$input = new QRinput($version, $level);
if($input == NULL) return NULL;
$ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive);
if($ret < 0) {
return NULL;
}
return $this->encodeInput($input);
}
//----------------------------------------------------------------------
public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
{
$enc = QRencode::factory($level, $size, $margin);
return $enc->encodePNG($text, $outfile, $saveandprint=false);
}
//----------------------------------------------------------------------
public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
{
$enc = QRencode::factory($level, $size, $margin);
return $enc->encode($text, $outfile);
}
//----------------------------------------------------------------------
public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4)
{
$enc = QRencode::factory($level, $size, $margin);
return $enc->encodeRAW($text, $outfile);
}
}
//##########################################################################
class FrameFiller {
public $width;
public $frame;
public $x;
public $y;
public $dir;
public $bit;
//----------------------------------------------------------------------
public function __construct($width, &$frame)
{
$this->width = $width;
$this->frame = $frame;
$this->x = $width - 1;
$this->y = $width - 1;
$this->dir = -1;
$this->bit = -1;
}
//----------------------------------------------------------------------
public function setFrameAt($at, $val)
{
$this->frame[$at['y']][$at['x']] = chr($val);
}
//----------------------------------------------------------------------
public function getFrameAt($at)
{
return ord($this->frame[$at['y']][$at['x']]);
}
//----------------------------------------------------------------------
public function next()
{
do {
if($this->bit == -1) {
$this->bit = 0;
return array('x'=>$this->x, 'y'=>$this->y);
}
$x = $this->x;
$y = $this->y;
$w = $this->width;
if($this->bit == 0) {
$x--;
$this->bit++;
} else {
$x++;
$y += $this->dir;
$this->bit--;
}
if($this->dir < 0) {
if($y < 0) {
$y = 0;
$x -= 2;
$this->dir = 1;
if($x == 6) {
$x--;
$y = 9;
}
}
} else {
if($y == $w) {
$y = $w - 1;
$x -= 2;
$this->dir = -1;
if($x == 6) {
$x--;
$y -= 8;
}
}
}
if($x < 0 || $y < 0) return null;
$this->x = $x;
$this->y = $y;
} while(ord($this->frame[$y][$x]) & 0x80);
return array('x'=>$x, 'y'=>$y);
}
} ;
//##########################################################################
class QRencode {
public $casesensitive = true;
public $eightbit = false;
public $version = 0;
public $size = 3;
public $margin = 4;
public $structured = 0; // not supported yet
public $level = QR_ECLEVEL_L;
public $hint = QR_MODE_8;
//----------------------------------------------------------------------
public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4)
{
$enc = new QRencode();
$enc->size = $size;
$enc->margin = $margin;
switch ($level.'') {
case '0':
case '1':
case '2':
case '3':
$enc->level = $level;
break;
case 'l':
case 'L':
$enc->level = QR_ECLEVEL_L;
break;
case 'm':
case 'M':
$enc->level = QR_ECLEVEL_M;
break;
case 'q':
case 'Q':
$enc->level = QR_ECLEVEL_Q;
break;
case 'h':
case 'H':
$enc->level = QR_ECLEVEL_H;
break;
}
return $enc;
}
//----------------------------------------------------------------------
public function encodeRAW($intext, $outfile = false)
{
$code = new QRcode();
if($this->eightbit) {
$code->encodeString8bit($intext, $this->version, $this->level);
} else {
$code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
}
return $code->data;
}
//----------------------------------------------------------------------
public function encode($intext, $outfile = false)
{
$code = new QRcode();
if($this->eightbit) {
$code->encodeString8bit($intext, $this->version, $this->level);
} else {
$code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive);
}
QRtools::markTime('after_encode');
if ($outfile!== false) {
file_put_contents($outfile, join("\n", QRtools::binarize($code->data)));
} else {
return QRtools::binarize($code->data);
}
}
//----------------------------------------------------------------------
public function encodePNG($intext, $outfile = false,$saveandprint=false)
{
try {
ob_start();
$tab = $this->encode($intext);
$err = ob_get_contents();
ob_end_clean();
if ($err != '')
QRtools::log($outfile, $err);
$maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));
QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);
} catch (Exception $e) {
QRtools::log($outfile, $e->getMessage());
}
}
}

View File

@@ -0,0 +1,98 @@
<?php
/*
* PHP QR Code encoder
*
* Image output of code using GD2
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('QR_IMAGE', true);
class QRimage {
public static $black = array(255,255,255);
public static $white = array(0,0,0);
//----------------------------------------------------------------------
public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
Header("Content-type: image/png");
ImagePng($image);
} else {
if($saveandprint===TRUE){
ImagePng($image, $filename);
header("Content-type: image/png");
ImagePng($image);
}else{
ImagePng($image, $filename);
}
}
ImageDestroy($image);
}
//----------------------------------------------------------------------
public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
Header("Content-type: image/jpeg");
ImageJpeg($image, null, $q);
} else {
ImageJpeg($image, $filename, $q);
}
ImageDestroy($image);
}
//----------------------------------------------------------------------
private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4)
{
$h = count($frame);
$w = strlen($frame[0]);
$imgW = $w + 2*$outerFrame;
$imgH = $h + 2*$outerFrame;
$base_image =ImageCreate($imgW, $imgH);
$col[0] = ImageColorAllocate($base_image,QRImage::$black[0],QRImage::$black[1],QRImage::$black[2]);
$col[1] = ImageColorAllocate($base_image,QRImage::$white[0],QRImage::$white[1],QRImage::$white[2]);
imagefill($base_image, 0, 0, $col[0]);
for($y=0; $y<$h; $y++) {
for($x=0; $x<$w; $x++) {
if ($frame[$y][$x] == '1') {
ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]);
}
}
}
$target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);
ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);
ImageDestroy($base_image);
return $target_image;
}
}

View File

@@ -0,0 +1,729 @@
<?php
/*
* PHP QR Code encoder
*
* Input encoding class
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('STRUCTURE_HEADER_BITS', 20);
define('MAX_STRUCTURED_SYMBOLS', 16);
class QRinputItem {
public $mode;
public $size;
public $data;
public $bstream;
public function __construct($mode, $size, $data, $bstream = null)
{
$setData = array_slice($data, 0, $size);
if (count($setData) < $size) {
$setData = array_merge($setData, array_fill(0,$size-count($setData),0));
}
if(!QRinput::check($mode, $size, $setData)) {
throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData));
return null;
}
$this->mode = $mode;
$this->size = $size;
$this->data = $setData;
$this->bstream = $bstream;
}
//----------------------------------------------------------------------
public function encodeModeNum($version)
{
try {
$words = (int)($this->size / 3);
$bs = new QRbitstream();
$val = 0x1;
$bs->appendNum(4, $val);
$bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size);
for($i=0; $i<$words; $i++) {
$val = (ord($this->data[$i*3 ]) - ord('0')) * 100;
$val += (ord($this->data[$i*3+1]) - ord('0')) * 10;
$val += (ord($this->data[$i*3+2]) - ord('0'));
$bs->appendNum(10, $val);
}
if($this->size - $words * 3 == 1) {
$val = ord($this->data[$words*3]) - ord('0');
$bs->appendNum(4, $val);
} else if($this->size - $words * 3 == 2) {
$val = (ord($this->data[$words*3 ]) - ord('0')) * 10;
$val += (ord($this->data[$words*3+1]) - ord('0'));
$bs->appendNum(7, $val);
}
$this->bstream = $bs;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function encodeModeAn($version)
{
try {
$words = (int)($this->size / 2);
$bs = new QRbitstream();
$bs->appendNum(4, 0x02);
$bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size);
for($i=0; $i<$words; $i++) {
$val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45;
$val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1]));
$bs->appendNum(11, $val);
}
if($this->size & 1) {
$val = QRinput::lookAnTable(ord($this->data[$words * 2]));
$bs->appendNum(6, $val);
}
$this->bstream = $bs;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function encodeMode8($version)
{
try {
$bs = new QRbitstream();
$bs->appendNum(4, 0x4);
$bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size);
for($i=0; $i<$this->size; $i++) {
$bs->appendNum(8, ord($this->data[$i]));
}
$this->bstream = $bs;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function encodeModeKanji($version)
{
try {
$bs = new QRbitrtream();
$bs->appendNum(4, 0x8);
$bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2));
for($i=0; $i<$this->size; $i+=2) {
$val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]);
if($val <= 0x9ffc) {
$val -= 0x8140;
} else {
$val -= 0xc140;
}
$h = ($val >> 8) * 0xc0;
$val = ($val & 0xff) + $h;
$bs->appendNum(13, $val);
}
$this->bstream = $bs;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function encodeModeStructure()
{
try {
$bs = new QRbitstream();
$bs->appendNum(4, 0x03);
$bs->appendNum(4, ord($this->data[1]) - 1);
$bs->appendNum(4, ord($this->data[0]) - 1);
$bs->appendNum(8, ord($this->data[2]));
$this->bstream = $bs;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function estimateBitStreamSizeOfEntry($version)
{
$bits = 0;
if($version == 0)
$version = 1;
switch($this->mode) {
case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break;
case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break;
case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break;
case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break;
case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS;
default:
return 0;
}
$l = QRspec::lengthIndicator($this->mode, $version);
$m = 1 << $l;
$num = (int)(($this->size + $m - 1) / $m);
$bits += $num * (4 + $l);
return $bits;
}
//----------------------------------------------------------------------
public function encodeBitStream($version)
{
try {
unset($this->bstream);
$words = QRspec::maximumWords($this->mode, $version);
if($this->size > $words) {
$st1 = new QRinputItem($this->mode, $words, $this->data);
$st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words));
$st1->encodeBitStream($version);
$st2->encodeBitStream($version);
$this->bstream = new QRbitstream();
$this->bstream->append($st1->bstream);
$this->bstream->append($st2->bstream);
unset($st1);
unset($st2);
} else {
$ret = 0;
switch($this->mode) {
case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break;
case QR_MODE_AN: $ret = $this->encodeModeAn($version); break;
case QR_MODE_8: $ret = $this->encodeMode8($version); break;
case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break;
case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break;
default:
break;
}
if($ret < 0)
return -1;
}
return $this->bstream->size();
} catch (Exception $e) {
return -1;
}
}
};
//##########################################################################
class QRinput {
public $items;
private $version;
private $level;
//----------------------------------------------------------------------
public function __construct($version = 0, $level = QR_ECLEVEL_L)
{
if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) {
throw new Exception('Invalid version no');
return NULL;
}
$this->version = $version;
$this->level = $level;
}
//----------------------------------------------------------------------
public function getVersion()
{
return $this->version;
}
//----------------------------------------------------------------------
public function setVersion($version)
{
if($version < 0 || $version > QRSPEC_VERSION_MAX) {
throw new Exception('Invalid version no');
return -1;
}
$this->version = $version;
return 0;
}
//----------------------------------------------------------------------
public function getErrorCorrectionLevel()
{
return $this->level;
}
//----------------------------------------------------------------------
public function setErrorCorrectionLevel($level)
{
if($level > QR_ECLEVEL_H) {
throw new Exception('Invalid ECLEVEL');
return -1;
}
$this->level = $level;
return 0;
}
//----------------------------------------------------------------------
public function appendEntry(QRinputItem $entry)
{
$this->items[] = $entry;
}
//----------------------------------------------------------------------
public function append($mode, $size, $data)
{
try {
$entry = new QRinputItem($mode, $size, $data);
$this->items[] = $entry;
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function insertStructuredAppendHeader($size, $index, $parity)
{
if( $size > MAX_STRUCTURED_SYMBOLS ) {
throw new Exception('insertStructuredAppendHeader wrong size');
}
if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) {
throw new Exception('insertStructuredAppendHeader wrong index');
}
$buf = array($size, $index, $parity);
try {
$entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf);
array_unshift($this->items, $entry);
return 0;
} catch (Exception $e) {
return -1;
}
}
//----------------------------------------------------------------------
public function calcParity()
{
$parity = 0;
foreach($this->items as $item) {
if($item->mode != QR_MODE_STRUCTURE) {
for($i=$item->size-1; $i>=0; $i--) {
$parity ^= $item->data[$i];
}
}
}
return $parity;
}
//----------------------------------------------------------------------
public static function checkModeNum($size, $data)
{
for($i=0; $i<$size; $i++) {
if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){
return false;
}
}
return true;
}
//----------------------------------------------------------------------
public static function estimateBitsModeNum($size)
{
$w = (int)$size / 3;
$bits = $w * 10;
switch($size - $w * 3) {
case 1:
$bits += 4;
break;
case 2:
$bits += 7;
break;
default:
break;
}
return $bits;
}
//----------------------------------------------------------------------
public static $anTable = array(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
);
//----------------------------------------------------------------------
public static function lookAnTable($c)
{
return (($c > 127)?-1:self::$anTable[$c]);
}
//----------------------------------------------------------------------
public static function checkModeAn($size, $data)
{
for($i=0; $i<$size; $i++) {
if (self::lookAnTable(ord($data[$i])) == -1) {
return false;
}
}
return true;
}
//----------------------------------------------------------------------
public static function estimateBitsModeAn($size)
{
$w = (int)($size / 2);
$bits = $w * 11;
if($size & 1) {
$bits += 6;
}
return $bits;
}
//----------------------------------------------------------------------
public static function estimateBitsMode8($size)
{
return $size * 8;
}
//----------------------------------------------------------------------
public function estimateBitsModeKanji($size)
{
return (int)(($size / 2) * 13);
}
//----------------------------------------------------------------------
public static function checkModeKanji($size, $data)
{
if($size & 1)
return false;
for($i=0; $i<$size; $i+=2) {
$val = (ord($data[$i]) << 8) | ord($data[$i+1]);
if( $val < 0x8140
|| ($val > 0x9ffc && $val < 0xe040)
|| $val > 0xebbf) {
return false;
}
}
return true;
}
/***********************************************************************
* Validation
**********************************************************************/
public static function check($mode, $size, $data)
{
if($size <= 0)
return false;
switch($mode) {
case QR_MODE_NUM: return self::checkModeNum($size, $data); break;
case QR_MODE_AN: return self::checkModeAn($size, $data); break;
case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break;
case QR_MODE_8: return true; break;
case QR_MODE_STRUCTURE: return true; break;
default:
break;
}
return false;
}
//----------------------------------------------------------------------
public function estimateBitStreamSize($version)
{
$bits = 0;
foreach($this->items as $item) {
$bits += $item->estimateBitStreamSizeOfEntry($version);
}
return $bits;
}
//----------------------------------------------------------------------
public function estimateVersion()
{
$version = 0;
$prev = 0;
do {
$prev = $version;
$bits = $this->estimateBitStreamSize($prev);
$version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
if ($version < 0) {
return -1;
}
} while ($version > $prev);
return $version;
}
//----------------------------------------------------------------------
public static function lengthOfCode($mode, $version, $bits)
{
$payload = $bits - 4 - QRspec::lengthIndicator($mode, $version);
switch($mode) {
case QR_MODE_NUM:
$chunks = (int)($payload / 10);
$remain = $payload - $chunks * 10;
$size = $chunks * 3;
if($remain >= 7) {
$size += 2;
} else if($remain >= 4) {
$size += 1;
}
break;
case QR_MODE_AN:
$chunks = (int)($payload / 11);
$remain = $payload - $chunks * 11;
$size = $chunks * 2;
if($remain >= 6)
$size++;
break;
case QR_MODE_8:
$size = (int)($payload / 8);
break;
case QR_MODE_KANJI:
$size = (int)(($payload / 13) * 2);
break;
case QR_MODE_STRUCTURE:
$size = (int)($payload / 8);
break;
default:
$size = 0;
break;
}
$maxsize = QRspec::maximumWords($mode, $version);
if($size < 0) $size = 0;
if($size > $maxsize) $size = $maxsize;
return $size;
}
//----------------------------------------------------------------------
public function createBitStream()
{
$total = 0;
foreach($this->items as $item) {
$bits = $item->encodeBitStream($this->version);
if($bits < 0)
return -1;
$total += $bits;
}
return $total;
}
//----------------------------------------------------------------------
public function convertData()
{
$ver = $this->estimateVersion();
if($ver > $this->getVersion()) {
$this->setVersion($ver);
}
for(;;) {
$bits = $this->createBitStream();
if($bits < 0)
return -1;
$ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
if($ver < 0) {
throw new Exception('WRONG VERSION');
return -1;
} else if($ver > $this->getVersion()) {
$this->setVersion($ver);
} else {
break;
}
}
return 0;
}
//----------------------------------------------------------------------
public function appendPaddingBit(&$bstream)
{
$bits = $bstream->size();
$maxwords = QRspec::getDataLength($this->version, $this->level);
$maxbits = $maxwords * 8;
if ($maxbits == $bits) {
return 0;
}
if ($maxbits - $bits < 5) {
return $bstream->appendNum($maxbits - $bits, 0);
}
$bits += 4;
$words = (int)(($bits + 7) / 8);
$padding = new QRbitstream();
$ret = $padding->appendNum($words * 8 - $bits + 4, 0);
if($ret < 0)
return $ret;
$padlen = $maxwords - $words;
if($padlen > 0) {
$padbuf = array();
for($i=0; $i<$padlen; $i++) {
$padbuf[$i] = ($i&1)?0x11:0xec;
}
$ret = $padding->appendBytes($padlen, $padbuf);
if($ret < 0)
return $ret;
}
$ret = $bstream->append($padding);
return $ret;
}
//----------------------------------------------------------------------
public function mergeBitStream()
{
if($this->convertData() < 0) {
return null;
}
$bstream = new QRbitstream();
foreach($this->items as $item) {
$ret = $bstream->append($item->bstream);
if($ret < 0) {
return null;
}
}
return $bstream;
}
//----------------------------------------------------------------------
public function getBitStream()
{
$bstream = $this->mergeBitStream();
if($bstream == null) {
return null;
}
$ret = $this->appendPaddingBit($bstream);
if($ret < 0) {
return null;
}
return $bstream;
}
//----------------------------------------------------------------------
public function getByteStream()
{
$bstream = $this->getBitStream();
if($bstream == null) {
return null;
}
return $bstream->toByte();
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*
* PHP QR Code encoder
*
* Root library file, prepares environment and includes dependencies
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
$QR_BASEDIR = dirname(__FILE__).DIRECTORY_SEPARATOR;
// Required libs
include $QR_BASEDIR."qrconst.php";
include $QR_BASEDIR."qrconfig.php";
include $QR_BASEDIR."qrtools.php";
include $QR_BASEDIR."qrspec.php";
include $QR_BASEDIR."qrimage.php";
include $QR_BASEDIR."qrinput.php";
include $QR_BASEDIR."qrbitstream.php";
include $QR_BASEDIR."qrsplit.php";
include $QR_BASEDIR."qrrscode.php";
include $QR_BASEDIR."qrmask.php";
include $QR_BASEDIR."qrencode.php";

View File

@@ -0,0 +1,328 @@
<?php
/*
* PHP QR Code encoder
*
* Masking
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('N1', 3);
define('N2', 3);
define('N3', 40);
define('N4', 10);
class QRmask {
public $runLength = array();
//----------------------------------------------------------------------
public function __construct()
{
$this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0);
}
//----------------------------------------------------------------------
public function writeFormatInformation($width, &$frame, $mask, $level)
{
$blacks = 0;
$format = QRspec::getFormatInfo($mask, $level);
for($i=0; $i<8; $i++) {
if($format & 1) {
$blacks += 2;
$v = 0x85;
} else {
$v = 0x84;
}
$frame[8][$width - 1 - $i] = chr($v);
if($i < 6) {
$frame[$i][8] = chr($v);
} else {
$frame[$i + 1][8] = chr($v);
}
$format = $format >> 1;
}
for($i=0; $i<7; $i++) {
if($format & 1) {
$blacks += 2;
$v = 0x85;
} else {
$v = 0x84;
}
$frame[$width - 7 + $i][8] = chr($v);
if($i == 0) {
$frame[8][7] = chr($v);
} else {
$frame[8][6 - $i] = chr($v);
}
$format = $format >> 1;
}
return $blacks;
}
//----------------------------------------------------------------------
public function mask0($x, $y) { return ($x+$y)&1; }
public function mask1($x, $y) { return ($y&1); }
public function mask2($x, $y) { return ($x%3); }
public function mask3($x, $y) { return ($x+$y)%3; }
public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; }
public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; }
public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; }
public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; }
//----------------------------------------------------------------------
private function generateMaskNo($maskNo, $width, $frame)
{
$bitMask = array_fill(0, $width, array_fill(0, $width, 0));
for($y=0; $y<$width; $y++) {
for($x=0; $x<$width; $x++) {
if(ord($frame[$y][$x]) & 0x80) {
$bitMask[$y][$x] = 0;
} else {
$maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y);
$bitMask[$y][$x] = ($maskFunc == 0)?1:0;
}
}
}
return $bitMask;
}
//----------------------------------------------------------------------
public static function serial($bitFrame)
{
$codeArr = array();
foreach ($bitFrame as $line)
$codeArr[] = join('', $line);
return gzcompress(join("\n", $codeArr), 9);
}
//----------------------------------------------------------------------
public static function unserial($code)
{
$codeArr = array();
$codeLines = explode("\n", gzuncompress($code));
foreach ($codeLines as $line)
$codeArr[] = str_split($line);
return $codeArr;
}
//----------------------------------------------------------------------
public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false)
{
$b = 0;
$bitMask = array();
$fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat';
if (QR_CACHEABLE) {
if (file_exists($fileName)) {
$bitMask = self::unserial(file_get_contents($fileName));
} else {
$bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo))
mkdir(QR_CACHE_DIR.'mask_'.$maskNo);
file_put_contents($fileName, self::serial($bitMask));
}
} else {
$bitMask = $this->generateMaskNo($maskNo, $width, $s, $d);
}
if ($maskGenOnly)
return;
$d = $s;
for($y=0; $y<$width; $y++) {
for($x=0; $x<$width; $x++) {
if($bitMask[$y][$x] == 1) {
$d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]);
}
$b += (int)(ord($d[$y][$x]) & 1);
}
}
return $b;
}
//----------------------------------------------------------------------
public function makeMask($width, $frame, $maskNo, $level)
{
$masked = array_fill(0, $width, str_repeat("\0", $width));
$this->makeMaskNo($maskNo, $width, $frame, $masked);
$this->writeFormatInformation($width, $masked, $maskNo, $level);
return $masked;
}
//----------------------------------------------------------------------
public function calcN1N3($length)
{
$demerit = 0;
for($i=0; $i<$length; $i++) {
if($this->runLength[$i] >= 5) {
$demerit += (N1 + ($this->runLength[$i] - 5));
}
if($i & 1) {
if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) {
$fact = (int)($this->runLength[$i] / 3);
if(($this->runLength[$i-2] == $fact) &&
($this->runLength[$i-1] == $fact) &&
($this->runLength[$i+1] == $fact) &&
($this->runLength[$i+2] == $fact)) {
if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) {
$demerit += N3;
} else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) {
$demerit += N3;
}
}
}
}
}
return $demerit;
}
//----------------------------------------------------------------------
public function evaluateSymbol($width, $frame)
{
$head = 0;
$demerit = 0;
for($y=0; $y<$width; $y++) {
$head = 0;
$this->runLength[0] = 1;
$frameY = $frame[$y];
if ($y>0)
$frameYM = $frame[$y-1];
for($x=0; $x<$width; $x++) {
if(($x > 0) && ($y > 0)) {
$b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]);
$w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]);
if(($b22 | ($w22 ^ 1))&1) {
$demerit += N2;
}
}
if(($x == 0) && (ord($frameY[$x]) & 1)) {
$this->runLength[0] = -1;
$head = 1;
$this->runLength[$head] = 1;
} else if($x > 0) {
if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) {
$head++;
$this->runLength[$head] = 1;
} else {
$this->runLength[$head]++;
}
}
}
$demerit += $this->calcN1N3($head+1);
}
for($x=0; $x<$width; $x++) {
$head = 0;
$this->runLength[0] = 1;
for($y=0; $y<$width; $y++) {
if($y == 0 && (ord($frame[$y][$x]) & 1)) {
$this->runLength[0] = -1;
$head = 1;
$this->runLength[$head] = 1;
} else if($y > 0) {
if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) {
$head++;
$this->runLength[$head] = 1;
} else {
$this->runLength[$head]++;
}
}
}
$demerit += $this->calcN1N3($head+1);
}
return $demerit;
}
//----------------------------------------------------------------------
public function mask($width, $frame, $level)
{
$minDemerit = PHP_INT_MAX;
$bestMaskNum = 0;
$bestMask = array();
$checked_masks = array(0,1,2,3,4,5,6,7);
if (QR_FIND_FROM_RANDOM !== false) {
$howManuOut = 8-(QR_FIND_FROM_RANDOM % 9);
for ($i = 0; $i < $howManuOut; $i++) {
$remPos = rand (0, count($checked_masks)-1);
unset($checked_masks[$remPos]);
$checked_masks = array_values($checked_masks);
}
}
$bestMask = $frame;
foreach($checked_masks as $i) {
$mask = array_fill(0, $width, str_repeat("\0", $width));
$demerit = 0;
$blacks = 0;
$blacks = $this->makeMaskNo($i, $width, $frame, $mask);
$blacks += $this->writeFormatInformation($width, $mask, $i, $level);
$blacks = (int)(100 * $blacks / ($width * $width));
$demerit = (int)((int)(abs($blacks - 50) / 5) * N4);
$demerit += $this->evaluateSymbol($width, $mask);
if($demerit < $minDemerit) {
$minDemerit = $demerit;
$bestMask = $mask;
$bestMaskNum = $i;
}
}
return $bestMask;
}
//----------------------------------------------------------------------
}

View File

@@ -0,0 +1,210 @@
<?php
/*
* PHP QR Code encoder
*
* Reed-Solomon error correction support
*
* Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q
* (libfec is released under the GNU Lesser General Public License.)
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class QRrsItem {
public $mm; // Bits per symbol
public $nn; // Symbols per block (= (1<<mm)-1)
public $alpha_to = array(); // log lookup table
public $index_of = array(); // Antilog lookup table
public $genpoly = array(); // Generator polynomial
public $nroots; // Number of generator roots = number of parity symbols
public $fcr; // First consecutive root, index form
public $prim; // Primitive element, index form
public $iprim; // prim-th root of 1, index form
public $pad; // Padding bytes in shortened block
public $gfpoly;
//----------------------------------------------------------------------
public function modnn($x)
{
while ($x >= $this->nn) {
$x -= $this->nn;
$x = ($x >> $this->mm) + ($x & $this->nn);
}
return $x;
}
//----------------------------------------------------------------------
public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
{
// Common code for intializing a Reed-Solomon control block (char or int symbols)
// Copyright 2004 Phil Karn, KA9Q
// May be used under the terms of the GNU Lesser General Public License (LGPL)
$rs = null;
// Check parameter ranges
if($symsize < 0 || $symsize > 8) return $rs;
if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs;
if($prim <= 0 || $prim >= (1<<$symsize)) return $rs;
if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values!
if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding
$rs = new QRrsItem();
$rs->mm = $symsize;
$rs->nn = (1<<$symsize)-1;
$rs->pad = $pad;
$rs->alpha_to = array_fill(0, $rs->nn+1, 0);
$rs->index_of = array_fill(0, $rs->nn+1, 0);
// PHP style macro replacement ;)
$NN =& $rs->nn;
$A0 =& $NN;
// Generate Galois field lookup tables
$rs->index_of[0] = $A0; // log(zero) = -inf
$rs->alpha_to[$A0] = 0; // alpha**-inf = 0
$sr = 1;
for($i=0; $i<$rs->nn; $i++) {
$rs->index_of[$sr] = $i;
$rs->alpha_to[$i] = $sr;
$sr <<= 1;
if($sr & (1<<$symsize)) {
$sr ^= $gfpoly;
}
$sr &= $rs->nn;
}
if($sr != 1){
// field generator polynomial is not primitive!
$rs = NULL;
return $rs;
}
/* Form RS code generator polynomial from its roots */
$rs->genpoly = array_fill(0, $nroots+1, 0);
$rs->fcr = $fcr;
$rs->prim = $prim;
$rs->nroots = $nroots;
$rs->gfpoly = $gfpoly;
/* Find prim-th root of 1, used in decoding */
for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn)
; // intentional empty-body loop!
$rs->iprim = (int)($iprim / $prim);
$rs->genpoly[0] = 1;
for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) {
$rs->genpoly[$i+1] = 1;
// Multiply rs->genpoly[] by @**(root + x)
for ($j = $i; $j > 0; $j--) {
if ($rs->genpoly[$j] != 0) {
$rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)];
} else {
$rs->genpoly[$j] = $rs->genpoly[$j-1];
}
}
// rs->genpoly[0] can never be zero
$rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)];
}
// convert rs->genpoly[] to index form for quicker encoding
for ($i = 0; $i <= $nroots; $i++)
$rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]];
return $rs;
}
//----------------------------------------------------------------------
public function encode_rs_char($data, &$parity)
{
$MM =& $this->mm;
$NN =& $this->nn;
$ALPHA_TO =& $this->alpha_to;
$INDEX_OF =& $this->index_of;
$GENPOLY =& $this->genpoly;
$NROOTS =& $this->nroots;
$FCR =& $this->fcr;
$PRIM =& $this->prim;
$IPRIM =& $this->iprim;
$PAD =& $this->pad;
$A0 =& $NN;
$parity = array_fill(0, $NROOTS, 0);
for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) {
$feedback = $INDEX_OF[$data[$i] ^ $parity[0]];
if($feedback != $A0) {
// feedback term is non-zero
// This line is unnecessary when GENPOLY[NROOTS] is unity, as it must
// always be for the polynomials constructed by init_rs()
$feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback);
for($j=1;$j<$NROOTS;$j++) {
$parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])];
}
}
// Shift
array_shift($parity);
if($feedback != $A0) {
array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]);
} else {
array_push($parity, 0);
}
}
}
}
//##########################################################################
class QRrs {
public static $items = array();
//----------------------------------------------------------------------
public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad)
{
foreach(self::$items as $rs) {
if($rs->pad != $pad) continue;
if($rs->nroots != $nroots) continue;
if($rs->mm != $symsize) continue;
if($rs->gfpoly != $gfpoly) continue;
if($rs->fcr != $fcr) continue;
if($rs->prim != $prim) continue;
return $rs;
}
$rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad);
array_unshift(self::$items, $rs);
return $rs;
}
}

View File

@@ -0,0 +1,592 @@
<?php
/*
* PHP QR Code encoder
*
* QR Code specifications
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* The following data / specifications are taken from
* "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
* or
* "Automatic identification and data capture techniques --
* QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('QRSPEC_VERSION_MAX', 40);
define('QRSPEC_WIDTH_MAX', 177);
define('QRCAP_WIDTH', 0);
define('QRCAP_WORDS', 1);
define('QRCAP_REMINDER', 2);
define('QRCAP_EC', 3);
class QRspec {
public static $capacity = array(
array( 0, 0, 0, array( 0, 0, 0, 0)),
array( 21, 26, 0, array( 7, 10, 13, 17)), // 1
array( 25, 44, 7, array( 10, 16, 22, 28)),
array( 29, 70, 7, array( 15, 26, 36, 44)),
array( 33, 100, 7, array( 20, 36, 52, 64)),
array( 37, 134, 7, array( 26, 48, 72, 88)), // 5
array( 41, 172, 7, array( 36, 64, 96, 112)),
array( 45, 196, 0, array( 40, 72, 108, 130)),
array( 49, 242, 0, array( 48, 88, 132, 156)),
array( 53, 292, 0, array( 60, 110, 160, 192)),
array( 57, 346, 0, array( 72, 130, 192, 224)), //10
array( 61, 404, 0, array( 80, 150, 224, 264)),
array( 65, 466, 0, array( 96, 176, 260, 308)),
array( 69, 532, 0, array( 104, 198, 288, 352)),
array( 73, 581, 3, array( 120, 216, 320, 384)),
array( 77, 655, 3, array( 132, 240, 360, 432)), //15
array( 81, 733, 3, array( 144, 280, 408, 480)),
array( 85, 815, 3, array( 168, 308, 448, 532)),
array( 89, 901, 3, array( 180, 338, 504, 588)),
array( 93, 991, 3, array( 196, 364, 546, 650)),
array( 97, 1085, 3, array( 224, 416, 600, 700)), //20
array(101, 1156, 4, array( 224, 442, 644, 750)),
array(105, 1258, 4, array( 252, 476, 690, 816)),
array(109, 1364, 4, array( 270, 504, 750, 900)),
array(113, 1474, 4, array( 300, 560, 810, 960)),
array(117, 1588, 4, array( 312, 588, 870, 1050)), //25
array(121, 1706, 4, array( 336, 644, 952, 1110)),
array(125, 1828, 4, array( 360, 700, 1020, 1200)),
array(129, 1921, 3, array( 390, 728, 1050, 1260)),
array(133, 2051, 3, array( 420, 784, 1140, 1350)),
array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30
array(141, 2323, 3, array( 480, 868, 1290, 1530)),
array(145, 2465, 3, array( 510, 924, 1350, 1620)),
array(149, 2611, 3, array( 540, 980, 1440, 1710)),
array(153, 2761, 3, array( 570, 1036, 1530, 1800)),
array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35
array(161, 3034, 0, array( 600, 1120, 1680, 1980)),
array(165, 3196, 0, array( 630, 1204, 1770, 2100)),
array(169, 3362, 0, array( 660, 1260, 1860, 2220)),
array(173, 3532, 0, array( 720, 1316, 1950, 2310)),
array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40
);
//----------------------------------------------------------------------
public static function getDataLength($version, $level)
{
return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level];
}
//----------------------------------------------------------------------
public static function getECCLength($version, $level)
{
return self::$capacity[$version][QRCAP_EC][$level];
}
//----------------------------------------------------------------------
public static function getWidth($version)
{
return self::$capacity[$version][QRCAP_WIDTH];
}
//----------------------------------------------------------------------
public static function getRemainder($version)
{
return self::$capacity[$version][QRCAP_REMINDER];
}
//----------------------------------------------------------------------
public static function getMinimumVersion($size, $level)
{
for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) {
$words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level];
if($words >= $size)
return $i;
}
return -1;
}
//######################################################################
public static $lengthTableBits = array(
array(10, 12, 14),
array( 9, 11, 13),
array( 8, 16, 16),
array( 8, 10, 12)
);
//----------------------------------------------------------------------
public static function lengthIndicator($mode, $version)
{
if ($mode == QR_MODE_STRUCTURE)
return 0;
if ($version <= 9) {
$l = 0;
} else if ($version <= 26) {
$l = 1;
} else {
$l = 2;
}
return self::$lengthTableBits[$mode][$l];
}
//----------------------------------------------------------------------
public static function maximumWords($mode, $version)
{
if($mode == QR_MODE_STRUCTURE)
return 3;
if($version <= 9) {
$l = 0;
} else if($version <= 26) {
$l = 1;
} else {
$l = 2;
}
$bits = self::$lengthTableBits[$mode][$l];
$words = (1 << $bits) - 1;
if($mode == QR_MODE_KANJI) {
$words *= 2; // the number of bytes is required
}
return $words;
}
// Error correction code -----------------------------------------------
// Table of the error correction code (Reed-Solomon block)
// See Table 12-16 (pp.30-36), JIS X0510:2004.
public static $eccTable = array(
array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)),
array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1
array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)),
array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)),
array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)),
array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5
array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)),
array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)),
array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)),
array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)),
array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10
array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)),
array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)),
array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)),
array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)),
array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15
array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)),
array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)),
array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)),
array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)),
array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20
array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)),
array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)),
array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)),
array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)),
array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25
array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)),
array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)),
array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)),
array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)),
array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30
array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)),
array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)),
array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)),
array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)),
array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35
array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)),
array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)),
array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)),
array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)),
array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40
);
//----------------------------------------------------------------------
// CACHEABLE!!!
public static function getEccSpec($version, $level, array &$spec)
{
if (count($spec) < 5) {
$spec = array(0,0,0,0,0);
}
$b1 = self::$eccTable[$version][$level][0];
$b2 = self::$eccTable[$version][$level][1];
$data = self::getDataLength($version, $level);
$ecc = self::getECCLength($version, $level);
if($b2 == 0) {
$spec[0] = $b1;
$spec[1] = (int)($data / $b1);
$spec[2] = (int)($ecc / $b1);
$spec[3] = 0;
$spec[4] = 0;
} else {
$spec[0] = $b1;
$spec[1] = (int)($data / ($b1 + $b2));
$spec[2] = (int)($ecc / ($b1 + $b2));
$spec[3] = $b2;
$spec[4] = $spec[1] + 1;
}
}
// Alignment pattern ---------------------------------------------------
// Positions of alignment patterns.
// This array includes only the second and the third position of the
// alignment patterns. Rest of them can be calculated from the distance
// between them.
// See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
public static $alignmentPattern = array(
array( 0, 0),
array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5
array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10
array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15
array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20
array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25
array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30
array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35
array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40
);
/** --------------------------------------------------------------------
* Put an alignment marker.
* @param frame
* @param width
* @param ox,oy center coordinate of the pattern
*/
public static function putAlignmentMarker(array &$frame, $ox, $oy)
{
$finder = array(
"\xa1\xa1\xa1\xa1\xa1",
"\xa1\xa0\xa0\xa0\xa1",
"\xa1\xa0\xa1\xa0\xa1",
"\xa1\xa0\xa0\xa0\xa1",
"\xa1\xa1\xa1\xa1\xa1"
);
$yStart = $oy-2;
$xStart = $ox-2;
for($y=0; $y<5; $y++) {
QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]);
}
}
//----------------------------------------------------------------------
public static function putAlignmentPattern($version, &$frame, $width)
{
if($version < 2)
return;
$d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0];
if($d < 0) {
$w = 2;
} else {
$w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2);
}
if($w * $w - 3 == 1) {
$x = self::$alignmentPattern[$version][0];
$y = self::$alignmentPattern[$version][0];
self::putAlignmentMarker($frame, $x, $y);
return;
}
$cx = self::$alignmentPattern[$version][0];
for($x=1; $x<$w - 1; $x++) {
self::putAlignmentMarker($frame, 6, $cx);
self::putAlignmentMarker($frame, $cx, 6);
$cx += $d;
}
$cy = self::$alignmentPattern[$version][0];
for($y=0; $y<$w-1; $y++) {
$cx = self::$alignmentPattern[$version][0];
for($x=0; $x<$w-1; $x++) {
self::putAlignmentMarker($frame, $cx, $cy);
$cx += $d;
}
$cy += $d;
}
}
// Version information pattern -----------------------------------------
// Version information pattern (BCH coded).
// See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
// size: [QRSPEC_VERSION_MAX - 6]
public static $versionPattern = array(
0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d,
0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9,
0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,
0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64,
0x27541, 0x28c69
);
//----------------------------------------------------------------------
public static function getVersionPattern($version)
{
if($version < 7 || $version > QRSPEC_VERSION_MAX)
return 0;
return self::$versionPattern[$version -7];
}
// Format information --------------------------------------------------
// See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib)
public static $formatInfo = array(
array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976),
array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0),
array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed),
array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)
);
public static function getFormatInfo($mask, $level)
{
if($mask < 0 || $mask > 7)
return 0;
if($level < 0 || $level > 3)
return 0;
return self::$formatInfo[$level][$mask];
}
// Frame ---------------------------------------------------------------
// Cache of initial frames.
public static $frames = array();
/** --------------------------------------------------------------------
* Put a finder pattern.
* @param frame
* @param width
* @param ox,oy upper-left coordinate of the pattern
*/
public static function putFinderPattern(&$frame, $ox, $oy)
{
$finder = array(
"\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
"\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
"\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
"\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
);
for($y=0; $y<7; $y++) {
QRstr::set($frame, $ox, $oy+$y, $finder[$y]);
}
}
//----------------------------------------------------------------------
public static function createFrame($version)
{
$width = self::$capacity[$version][QRCAP_WIDTH];
$frameLine = str_repeat ("\0", $width);
$frame = array_fill(0, $width, $frameLine);
// Finder pattern
self::putFinderPattern($frame, 0, 0);
self::putFinderPattern($frame, $width - 7, 0);
self::putFinderPattern($frame, 0, $width - 7);
// Separator
$yOffset = $width - 7;
for($y=0; $y<7; $y++) {
$frame[$y][7] = "\xc0";
$frame[$y][$width - 8] = "\xc0";
$frame[$yOffset][7] = "\xc0";
$yOffset++;
}
$setPattern = str_repeat("\xc0", 8);
QRstr::set($frame, 0, 7, $setPattern);
QRstr::set($frame, $width-8, 7, $setPattern);
QRstr::set($frame, 0, $width - 8, $setPattern);
// Format info
$setPattern = str_repeat("\x84", 9);
QRstr::set($frame, 0, 8, $setPattern);
QRstr::set($frame, $width - 8, 8, $setPattern, 8);
$yOffset = $width - 8;
for($y=0; $y<8; $y++,$yOffset++) {
$frame[$y][8] = "\x84";
$frame[$yOffset][8] = "\x84";
}
// Timing pattern
for($i=1; $i<$width-15; $i++) {
$frame[6][7+$i] = chr(0x90 | ($i & 1));
$frame[7+$i][6] = chr(0x90 | ($i & 1));
}
// Alignment pattern
self::putAlignmentPattern($version, $frame, $width);
// Version information
if($version >= 7) {
$vinf = self::getVersionPattern($version);
$v = $vinf;
for($x=0; $x<6; $x++) {
for($y=0; $y<3; $y++) {
$frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
$v = $v >> 1;
}
}
$v = $vinf;
for($y=0; $y<6; $y++) {
for($x=0; $x<3; $x++) {
$frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
$v = $v >> 1;
}
}
}
// and a little bit...
$frame[$width - 8][8] = "\x81";
return $frame;
}
//----------------------------------------------------------------------
public static function debug($frame, $binary_mode = false)
{
if ($binary_mode) {
foreach ($frame as &$frameLine) {
$frameLine = join('<span class="m">&nbsp;&nbsp;</span>', explode('0', $frameLine));
$frameLine = join('&#9608;&#9608;', explode('1', $frameLine));
}
?>
<style>
.m { background-color: white; }
</style>
<?php
echo '<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
echo join("<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $frame);
echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >';
} else {
foreach ($frame as &$frameLine) {
$frameLine = join('<span class="m">&nbsp;</span>', explode("\xc0", $frameLine));
$frameLine = join('<span class="m">&#9618;</span>', explode("\xc1", $frameLine));
$frameLine = join('<span class="p">&nbsp;</span>', explode("\xa0", $frameLine));
$frameLine = join('<span class="p">&#9618;</span>', explode("\xa1", $frameLine));
$frameLine = join('<span class="s">&#9671;</span>', explode("\x84", $frameLine)); //format 0
$frameLine = join('<span class="s">&#9670;</span>', explode("\x85", $frameLine)); //format 1
$frameLine = join('<span class="x">&#9762;</span>', explode("\x81", $frameLine)); //special bit
$frameLine = join('<span class="c">&nbsp;</span>', explode("\x90", $frameLine)); //clock 0
$frameLine = join('<span class="c">&#9719;</span>', explode("\x91", $frameLine)); //clock 1
$frameLine = join('<span class="f">&nbsp;</span>', explode("\x88", $frameLine)); //version
$frameLine = join('<span class="f">&#9618;</span>', explode("\x89", $frameLine)); //version
$frameLine = join('&#9830;', explode("\x01", $frameLine));
$frameLine = join('&#8901;', explode("\0", $frameLine));
}
?>
<style>
.p { background-color: yellow; }
.m { background-color: #00FF00; }
.s { background-color: #FF0000; }
.c { background-color: aqua; }
.x { background-color: pink; }
.f { background-color: gold; }
</style>
<?php
echo "<pre><tt>";
echo join("<br/ >", $frame);
echo "</tt></pre>";
}
}
//----------------------------------------------------------------------
public static function serial($frame)
{
return gzcompress(join("\n", $frame), 9);
}
//----------------------------------------------------------------------
public static function unserial($code)
{
return explode("\n", gzuncompress($code));
}
//----------------------------------------------------------------------
public static function newFrame($version)
{
if($version < 1 || $version > QRSPEC_VERSION_MAX)
return null;
if(!isset(self::$frames[$version])) {
$fileName = QR_CACHE_DIR.'frame_'.$version.'.dat';
if (QR_CACHEABLE) {
if (file_exists($fileName)) {
self::$frames[$version] = self::unserial(file_get_contents($fileName));
} else {
self::$frames[$version] = self::createFrame($version);
file_put_contents($fileName, self::serial(self::$frames[$version]));
}
} else {
self::$frames[$version] = self::createFrame($version);
}
}
if(is_null(self::$frames[$version]))
return null;
return self::$frames[$version];
}
//----------------------------------------------------------------------
public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; }
public static function rsBlockNum1($spec) { return $spec[0]; }
public static function rsDataCodes1($spec) { return $spec[1]; }
public static function rsEccCodes1($spec) { return $spec[2]; }
public static function rsBlockNum2($spec) { return $spec[3]; }
public static function rsDataCodes2($spec) { return $spec[4]; }
public static function rsEccCodes2($spec) { return $spec[2]; }
public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); }
public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; }
}

View File

@@ -0,0 +1,311 @@
<?php
/*
* PHP QR Code encoder
*
* Input splitting classes
*
* Based on libqrencode C library distributed under LGPL 2.1
* Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* The following data / specifications are taken from
* "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
* or
* "Automatic identification and data capture techniques --
* QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class QRsplit {
public $dataStr = '';
public $input;
public $modeHint;
//----------------------------------------------------------------------
public function __construct($dataStr, $input, $modeHint)
{
$this->dataStr = $dataStr;
$this->input = $input;
$this->modeHint = $modeHint;
}
//----------------------------------------------------------------------
public static function isdigitat($str, $pos)
{
if ($pos >= strlen($str))
return false;
return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9')));
}
//----------------------------------------------------------------------
public static function isalnumat($str, $pos)
{
if ($pos >= strlen($str))
return false;
return (QRinput::lookAnTable(ord($str[$pos])) >= 0);
}
//----------------------------------------------------------------------
public function identifyMode($pos)
{
if ($pos >= strlen($this->dataStr))
return QR_MODE_NUL;
$c = $this->dataStr[$pos];
if(self::isdigitat($this->dataStr, $pos)) {
return QR_MODE_NUM;
} else if(self::isalnumat($this->dataStr, $pos)) {
return QR_MODE_AN;
} else if($this->modeHint == QR_MODE_KANJI) {
if ($pos+1 < strlen($this->dataStr))
{
$d = $this->dataStr[$pos+1];
$word = (ord($c) << 8) | ord($d);
if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) {
return QR_MODE_KANJI;
}
}
}
return QR_MODE_8;
}
//----------------------------------------------------------------------
public function eatNum()
{
$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
$p = 0;
while(self::isdigitat($this->dataStr, $p)) {
$p++;
}
$run = $p;
$mode = $this->identifyMode($p);
if($mode == QR_MODE_8) {
$dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ QRinput::estimateBitsMode8(1) // + 4 + l8
- QRinput::estimateBitsMode8($run + 1); // - 4 - l8
if($dif > 0) {
return $this->eat8();
}
}
if($mode == QR_MODE_AN) {
$dif = QRinput::estimateBitsModeNum($run) + 4 + $ln
+ QRinput::estimateBitsModeAn(1) // + 4 + la
- QRinput::estimateBitsModeAn($run + 1);// - 4 - la
if($dif > 0) {
return $this->eatAn();
}
}
$ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr));
if($ret < 0)
return -1;
return $run;
}
//----------------------------------------------------------------------
public function eatAn()
{
$la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
$p = 0;
while(self::isalnumat($this->dataStr, $p)) {
if(self::isdigitat($this->dataStr, $p)) {
$q = $p;
while(self::isdigitat($this->dataStr, $q)) {
$q++;
}
$dif = QRinput::estimateBitsModeAn($p) // + 4 + la
+ QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
- QRinput::estimateBitsModeAn($q); // - 4 - la
if($dif < 0) {
break;
} else {
$p = $q;
}
} else {
$p++;
}
}
$run = $p;
if(!self::isalnumat($this->dataStr, $p)) {
$dif = QRinput::estimateBitsModeAn($run) + 4 + $la
+ QRinput::estimateBitsMode8(1) // + 4 + l8
- QRinput::estimateBitsMode8($run + 1); // - 4 - l8
if($dif > 0) {
return $this->eat8();
}
}
$ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr));
if($ret < 0)
return -1;
return $run;
}
//----------------------------------------------------------------------
public function eatKanji()
{
$p = 0;
while($this->identifyMode($p) == QR_MODE_KANJI) {
$p += 2;
}
$ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr));
if($ret < 0)
return -1;
return $run;
}
//----------------------------------------------------------------------
public function eat8()
{
$la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion());
$ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion());
$p = 1;
$dataStrLen = strlen($this->dataStr);
while($p < $dataStrLen) {
$mode = $this->identifyMode($p);
if($mode == QR_MODE_KANJI) {
break;
}
if($mode == QR_MODE_NUM) {
$q = $p;
while(self::isdigitat($this->dataStr, $q)) {
$q++;
}
$dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ QRinput::estimateBitsModeNum($q - $p) + 4 + $ln
- QRinput::estimateBitsMode8($q); // - 4 - l8
if($dif < 0) {
break;
} else {
$p = $q;
}
} else if($mode == QR_MODE_AN) {
$q = $p;
while(self::isalnumat($this->dataStr, $q)) {
$q++;
}
$dif = QRinput::estimateBitsMode8($p) // + 4 + l8
+ QRinput::estimateBitsModeAn($q - $p) + 4 + $la
- QRinput::estimateBitsMode8($q); // - 4 - l8
if($dif < 0) {
break;
} else {
$p = $q;
}
} else {
$p++;
}
}
$run = $p;
$ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr));
if($ret < 0)
return -1;
return $run;
}
//----------------------------------------------------------------------
public function splitString()
{
while (strlen($this->dataStr) > 0)
{
if($this->dataStr == '')
return 0;
$mode = $this->identifyMode(0);
switch ($mode) {
case QR_MODE_NUM: $length = $this->eatNum(); break;
case QR_MODE_AN: $length = $this->eatAn(); break;
case QR_MODE_KANJI:
if ($hint == QR_MODE_KANJI)
$length = $this->eatKanji();
else $length = $this->eat8();
break;
default: $length = $this->eat8(); break;
}
if($length == 0) return 0;
if($length < 0) return -1;
$this->dataStr = substr($this->dataStr, $length);
}
}
//----------------------------------------------------------------------
public function toUpper()
{
$stringLen = strlen($this->dataStr);
$p = 0;
while ($p<$stringLen) {
$mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint);
if($mode == QR_MODE_KANJI) {
$p += 2;
} else {
if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) {
$this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32);
}
$p++;
}
}
return $this->dataStr;
}
//----------------------------------------------------------------------
public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true)
{
if(is_null($string) || $string == '\0' || $string == '') {
throw new Exception('empty string!!!');
}
$split = new QRsplit($string, $input, $modeHint);
if(!$casesensitive)
$split->toUpper();
return $split->splitString();
}
}

View File

@@ -0,0 +1,172 @@
<?php
/*
* PHP QR Code encoder
*
* Toolset, handy and debug utilites.
*
* PHP QR Code is distributed under LGPL 3
* Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class QRtools {
//----------------------------------------------------------------------
public static function binarize($frame)
{
$len = count($frame);
foreach ($frame as &$frameLine) {
for($i=0; $i<$len; $i++) {
$frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
}
}
return $frame;
}
//----------------------------------------------------------------------
public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037')
{
$barcode_array = array();
if (!is_array($mode))
$mode = explode(',', $mode);
$eccLevel = 'L';
if (count($mode) > 1) {
$eccLevel = $mode[1];
}
$qrTab = QRcode::text($code, false, $eccLevel);
$size = count($qrTab);
$barcode_array['num_rows'] = $size;
$barcode_array['num_cols'] = $size;
$barcode_array['bcode'] = array();
foreach ($qrTab as $line) {
$arrAdd = array();
foreach(str_split($line) as $char)
$arrAdd[] = ($char=='1')?1:0;
$barcode_array['bcode'][] = $arrAdd;
}
return $barcode_array;
}
//----------------------------------------------------------------------
public static function clearCache()
{
self::$frames = array();
}
//----------------------------------------------------------------------
public static function buildCache()
{
QRtools::markTime('before_build_cache');
$mask = new QRmask();
for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) {
$frame = QRspec::newFrame($a);
if (QR_IMAGE) {
$fileName = QR_CACHE_DIR.'frame_'.$a.'.png';
QRimage::png(self::binarize($frame), $fileName, 1, 0);
}
$width = count($frame);
$bitMask = array_fill(0, $width, array_fill(0, $width, 0));
for ($maskNo=0; $maskNo<8; $maskNo++)
$mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true);
}
QRtools::markTime('after_build_cache');
}
//----------------------------------------------------------------------
public static function log($outfile, $err)
{
if (QR_LOG_DIR !== false) {
if ($err != '') {
if ($outfile !== false) {
file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
} else {
file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
}
}
}
}
//----------------------------------------------------------------------
public static function dumpMask($frame)
{
$width = count($frame);
for($y=0;$y<$width;$y++) {
for($x=0;$x<$width;$x++) {
echo ord($frame[$y][$x]).',';
}
}
}
//----------------------------------------------------------------------
public static function markTime($markerId)
{
list($usec, $sec) = explode(" ", microtime());
$time = ((float)$usec + (float)$sec);
if (!isset($GLOBALS['qr_time_bench']))
$GLOBALS['qr_time_bench'] = array();
$GLOBALS['qr_time_bench'][$markerId] = $time;
}
//----------------------------------------------------------------------
public static function timeBenchmark()
{
self::markTime('finish');
$lastTime = 0;
$startTime = 0;
$p = 0;
echo '<table cellpadding="3" cellspacing="1">
<thead><tr style="border-bottom:1px solid silver"><td colspan="2" style="text-align:center">BENCHMARK</td></tr></thead>
<tbody>';
foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) {
if ($p > 0) {
echo '<tr><th style="text-align:right">till '.$markerId.': </th><td>'.number_format($thisTime-$lastTime, 6).'s</td></tr>';
} else {
$startTime = $thisTime;
}
$p++;
$lastTime = $thisTime;
}
echo '</tbody><tfoot>
<tr style="border-top:2px solid black"><th style="text-align:right">TOTAL: </th><td>'.number_format($lastTime-$startTime, 6).'s</td></tr>
</tfoot>
</table>';
}
}
//##########################################################################
QRtools::markTime('start');