Files
BE_IBL/application/controllers/etl/Upload_danone.php
2026-04-15 15:23:57 +07:00

105 lines
3.1 KiB
PHP

<?php
defined('BASEPATH') or exit('No direct script access allowed');
set_time_limit(500);
class Upload_danone extends MY_Controller
{
var $url_nas;
public function __construct()
{
parent::__construct();
$this->url_nas = "http://192.168.250.42/one-api/etl/r_danone/saveData";
}
function getBranch()
{
$sql = "select M_BranchCode from m_branch where M_BranchIsActive='Y' and M_BranchIsDefault ='Y'";
$qry = $this->db->query($sql);
if (!$qry) {
$this->sendError("Err get default branch");
exit;
}
$rows = $qry->result_array();
if (count($rows) == 0) {
$this->sendError("Err get default branch");
exit;
}
return $rows[0]["M_BranchCode"];
}
public function process($mgmMcuID, $start_date, $end_date, $companyID, $mouID)
{
$defaultBranch = $this->getBranch();
// Fetch data from the database
$sql = "call sp_rpt_pengelolaan_mcu(?,?,?,?,'')";
$query = $this->db->query($sql, [$start_date, $end_date, $companyID, $mouID]);
if (!$query) {
$this->sendError("Database error while fetching records: " . $this->db->error()['message']);
}
$data = $query->result_array();
foreach ($data as $idx => $d) {
$d["Mgm_McuID"] = $mgmMcuID;
$d["M_BranchCode"] = $defaultBranch;
$data[$idx] = $d;
}
if (empty($data)) {
$this->sendError("No data available to upload.\n" . $this->db->last_query());
}
$send_records = count($data);
// Convert data to JSON
$jsonData = json_encode($data);
if (!$jsonData) {
$this->sendError("Failed to encode JSON data.");
}
// Compress JSON data using gzcompress
$compressedData = gzcompress($jsonData);
if (!$compressedData) {
$this->sendError("Failed to compress data.");
}
// Initialize cURL l
$ch = curl_init($this->url_nas);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 500); // Timeout for the request (in seconds)
curl_setopt($ch, CURLOPT_POSTFIELDS, $compressedData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/octet-stream",
"Content-Encoding: gzip"
]);
// Execute cURL request
$response = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($response === false) {
$this->sendError("Failed to upload data. cURL Error: " . $curlError);
}
// Decode response
$responseJson = json_decode($response, true);
if (!$responseJson || !isset($responseJson['status'])) {
$this->sendError("Invalid response from server.\nRaw: $response");
}
if ($responseJson['status'] == 'ERR') {
$this->sendError("Server error: " . $responseJson['message']);
}
header("Content-Type: application/json");
echo json_encode([
"status" => "OK",
"message" => "Data uploaded successfully",
"server_response" => $responseJson,
"send_records" => $send_records
]);
}
private function sendError($message)
{
header("Content-Type: application/json");
echo json_encode(["status" => "ERR", "message" => $message]);
exit;
}
}