327 lines
14 KiB
PHP
327 lines
14 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\ImportDatasourceStatus;
|
|
use App\Models\BigdataResume;
|
|
use App\Models\GlobalSetting;
|
|
use App\Models\ImportDatasource;
|
|
use App\Models\PbgTaskIndexIntegrations;
|
|
use App\Models\PbgTaskPrasarana;
|
|
use App\Models\PbgTaskRetributions;
|
|
use Exception;
|
|
use App\Models\PbgTask;
|
|
use App\Traits\GlobalApiResponse;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Carbon\Carbon;
|
|
use App\Services\ServiceClient;
|
|
|
|
class ServiceSIMBG
|
|
{
|
|
use GlobalApiResponse;
|
|
private $email;
|
|
private $password;
|
|
private $simbg_host;
|
|
private $fetch_per_page;
|
|
private $service_client;
|
|
/**
|
|
* Create a new class instance.
|
|
*/
|
|
public function __construct()
|
|
{
|
|
$settings = GlobalSetting::whereIn('key', [
|
|
'SIMBG_EMAIL', 'SIMBG_PASSWORD', 'SIMBG_HOST', 'FETCH_PER_PAGE'
|
|
])->pluck('value', 'key');
|
|
|
|
$this->email = trim((string) ($settings['SIMBG_EMAIL'] ?? ""));
|
|
$this->password = trim((string) ($settings['SIMBG_PASSWORD'] ?? ""));
|
|
$this->simbg_host = trim((string) ($settings['SIMBG_HOST'] ?? ""));
|
|
$this->fetch_per_page = trim((string) ($settings['FETCH_PER_PAGE'] ?? ""));
|
|
|
|
$this->service_client = new ServiceClient($this->simbg_host);
|
|
}
|
|
|
|
public function getToken(){
|
|
try{
|
|
$url = "/api/user/v1/auth/login/";
|
|
$body = [
|
|
'email' => $this->email,
|
|
'password' => $this->password,
|
|
];
|
|
|
|
$res = $this->service_client->post($url, $body);
|
|
if(!$res->original['success']){
|
|
Log::error("Token not retrieved ", ['response' => $res]);
|
|
throw new Exception("Token not retrieved.");
|
|
}
|
|
return $res;
|
|
}catch(Exception $e){
|
|
Log::error("Error on method get token ", ['response' => $e->getMessage()]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
public function syncIndexIntegration($uuids, $token)
|
|
{
|
|
try{
|
|
if(empty($uuids)){
|
|
return false;
|
|
}
|
|
|
|
$integrations = [];
|
|
foreach($uuids as $uuid){
|
|
$url = "/api/pbg/v1/detail/" . $uuid . "/retribution/indeks-terintegrasi/";
|
|
|
|
$headers = [
|
|
'Authorization' => "Bearer " . $token,
|
|
];
|
|
|
|
$res = $this->service_client->get($url, $headers);
|
|
|
|
if (empty($res->original['success']) || !$res->original['success']) {
|
|
// Log error
|
|
Log::error("API response indicates failure", ['url' => $url, 'uuid' => $uuid]);
|
|
continue;
|
|
}
|
|
|
|
$data = $res->original['data']['data'] ?? null;
|
|
if (!$data) {
|
|
Log::error("No valid data returned from API", ['url' => $url, 'uuid' => $uuid]);
|
|
continue;
|
|
}
|
|
|
|
$integrations[] = [
|
|
'pbg_task_uid' => $uuid,
|
|
'indeks_fungsi_bangunan' => $data['indeks_fungsi_bangunan'] ?? null,
|
|
'indeks_parameter_kompleksitas' => $data['indeks_parameter_kompleksitas'] ?? null,
|
|
'indeks_parameter_permanensi' => $data['indeks_parameter_permanensi'] ?? null,
|
|
'indeks_parameter_ketinggian' => $data['indeks_parameter_ketinggian'] ?? null,
|
|
'faktor_kepemilikan' => $data['faktor_kepemilikan'] ?? null,
|
|
'indeks_terintegrasi' => $data['indeks_terintegrasi'] ?? null,
|
|
'total' => $data['total'] ?? null,
|
|
];
|
|
}
|
|
|
|
PbgTaskIndexIntegrations::upsert($integrations, ['pbg_task_uid'], ['indeks_fungsi_bangunan',
|
|
'indeks_parameter_kompleksitas', 'indeks_parameter_permanensi', 'indeks_parameter_ketinggian', 'faktor_kepemilikan', 'indeks_terintegrasi', 'total']);
|
|
|
|
return true;
|
|
}catch (Exception $e){
|
|
Log::error('error when sync index integration ', ['index integration'=> $e->getMessage()]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
public function syncTaskList()
|
|
{
|
|
try {
|
|
$importDatasource = ImportDatasource::create([
|
|
'status' => ImportDatasourceStatus::Processing->value,
|
|
]);
|
|
|
|
$initResToken = $this->getToken();
|
|
if (empty($initResToken->original['data']['token']['access'])) {
|
|
$importDatasource->update([
|
|
'status' => ImportDatasourceStatus::Failed->value,
|
|
'message' => 'Failed to retrieve token'
|
|
]);
|
|
return $this->resError("Failed to retrieve token");
|
|
}
|
|
$apiToken = $initResToken->original['data']['token']['access'];
|
|
$headers = ['Authorization' => "Bearer " . $apiToken];
|
|
|
|
$url = "/api/pbg/v1/list/?page=1&size={$this->fetch_per_page}&sort=ASC";
|
|
$initialResponse = $this->service_client->get($url, $headers);
|
|
|
|
$totalPage = $initialResponse->original['data']['total_page'] ?? 0;
|
|
if ($totalPage == 0) {
|
|
$importDatasource->update([
|
|
'status' => ImportDatasourceStatus::Failed->value,
|
|
'message' => 'Invalid response: no total_page'
|
|
]);
|
|
return $this->resError("Invalid response from API");
|
|
}
|
|
|
|
$savedCount = $failedCount = 0;
|
|
|
|
for ($currentPage = 1; $currentPage <= $totalPage; $currentPage++) {
|
|
try {
|
|
$pageUrl = "/api/pbg/v1/list/?page={$currentPage}&size={$this->fetch_per_page}&sort=ASC";
|
|
|
|
Log::info("Fetching tasks", ['currentPage' => $currentPage]);
|
|
|
|
$response = $this->service_client->get($pageUrl, $headers);
|
|
$tasks = $response->original['data']['data'] ?? [];
|
|
|
|
if (empty($tasks)) {
|
|
Log::warning("No data found on page", ['page' => $currentPage]);
|
|
continue;
|
|
}
|
|
|
|
$tasksCollective = [];
|
|
foreach ($tasks as $item) {
|
|
try {
|
|
$tasksCollective[] = [
|
|
'uuid' => $item['uid'],
|
|
'name' => $item['name'],
|
|
'owner_name' => $item['owner_name'],
|
|
'application_type' => $item['application_type'],
|
|
'application_type_name' => $item['application_type_name'],
|
|
'condition' => $item['condition'],
|
|
'registration_number' => $item['registration_number'],
|
|
'document_number' => $item['document_number'],
|
|
'address' => $item['address'],
|
|
'status' => $item['status'],
|
|
'status_name' => $item['status_name'],
|
|
'slf_status' => $item['slf_status'] ?? null,
|
|
'slf_status_name' => $item['slf_status_name'] ?? null,
|
|
'function_type' => $item['function_type'],
|
|
'consultation_type' => $item['consultation_type'],
|
|
'due_date' => $item['due_date'],
|
|
'land_certificate_phase' => $item['land_certificate_phase'],
|
|
'task_created_at' => isset($item['created_at']) ? Carbon::parse($item['created_at'])->format('Y-m-d H:i:s') : null,
|
|
'updated_at' => now(),
|
|
'created_at' => now(),
|
|
];
|
|
|
|
$this->syncTaskDetailSubmit($item['uid'], $apiToken);
|
|
$savedCount++;
|
|
} catch (Exception $e) {
|
|
$failedCount++;
|
|
Log::error("Failed to process task", [
|
|
'error' => $e->getMessage(),
|
|
'task' => $item,
|
|
]);
|
|
continue; // Skip failed task, continue processing the rest
|
|
}
|
|
}
|
|
|
|
if (!empty($tasksCollective)) {
|
|
PbgTask::upsert($tasksCollective, ['uuid'], [
|
|
'name', 'owner_name', 'application_type', 'application_type_name', 'condition',
|
|
'registration_number', 'document_number', 'address', 'status', 'status_name',
|
|
'slf_status', 'slf_status_name', 'function_type', 'consultation_type', 'due_date',
|
|
'land_certificate_phase', 'task_created_at', 'updated_at'
|
|
]);
|
|
|
|
$uuids = array_column($tasksCollective, 'uuid');
|
|
$this->syncIndexIntegration($uuids, $apiToken);
|
|
}
|
|
} catch (Exception $e) {
|
|
Log::error("Failed to process page", [
|
|
'error' => $e->getMessage(),
|
|
'page' => $currentPage,
|
|
]);
|
|
continue; // Skip the failed page and move to the next
|
|
}
|
|
}
|
|
|
|
BigdataResume::generateResumeData($importDatasource->id, "all");
|
|
BigdataResume::generateResumeData($importDatasource->id, now()->year);
|
|
|
|
// Final update after processing all pages
|
|
$importDatasource->update([
|
|
'status' => ImportDatasourceStatus::Success->value,
|
|
'message' => "Successfully processed: $savedCount, Failed: $failedCount"
|
|
]);
|
|
|
|
Log::info("syncTaskList completed", ['savedCount' => $savedCount, 'failedCount' => $failedCount]);
|
|
|
|
return $this->resSuccess(['savedCount' => $savedCount, 'failedCount' => $failedCount]);
|
|
|
|
} catch (Exception $e) {
|
|
Log::error("syncTaskList failed", ['error' => $e->getMessage()]);
|
|
if (isset($importDatasource)) {
|
|
$importDatasource->update([
|
|
'status' => ImportDatasourceStatus::Failed->value,
|
|
'message' => 'Critical failure: ' . $e->getMessage()
|
|
]);
|
|
}
|
|
return $this->resError("Critical failure occurred: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function syncTaskDetailSubmit($uuid, $token)
|
|
{
|
|
try{
|
|
$url = "/api/pbg/v1/detail/" . $uuid . "/retribution/submit/";
|
|
$headers = [
|
|
'Authorization' => "Bearer " . $token,
|
|
];
|
|
|
|
$res = $this->service_client->get($url, $headers);
|
|
|
|
if (empty($res->original['success']) || !$res->original['success']) {
|
|
// Log error
|
|
Log::error("API response indicates failure", ['url' => $url, 'uuid' => $uuid]);
|
|
return false;
|
|
}
|
|
|
|
$data = $res->original['data']['data'] ?? [];
|
|
if (empty($data)) {
|
|
Log::error("No data returned from API", ['url' => $url, 'uuid' => $uuid]);
|
|
return false;
|
|
}
|
|
|
|
$detailCreatedAt = isset($data['created_at'])
|
|
? Carbon::parse($data['created_at'])->format('Y-m-d H:i:s')
|
|
: null;
|
|
|
|
$detailUpdatedAt = isset($data['updated_at'])
|
|
? Carbon::parse($data['updated_at'])->format('Y-m-d H:i:s')
|
|
: null;
|
|
|
|
$pbg_task_retributions = PbgTaskRetributions::updateOrCreate(
|
|
['detail_id' => $data['id']],
|
|
[
|
|
'detail_uid' => $data['uid'] ?? null,
|
|
'detail_created_at' => $detailCreatedAt ?? null,
|
|
'detail_updated_at' => $detailUpdatedAt ?? null,
|
|
'luas_bangunan' => $data['luas_bangunan'] ?? null,
|
|
'indeks_lokalitas' => $data['indeks_lokalitas'] ?? null,
|
|
'wilayah_shst' => $data['wilayah_shst'] ?? null,
|
|
'kegiatan_id' => $data['kegiatan']['id'] ?? null,
|
|
'kegiatan_name' => $data['kegiatan']['name'] ?? null,
|
|
'nilai_shst' => $data['nilai_shst'] ?? null,
|
|
'indeks_terintegrasi' => $data['indeks_terintegrasi'] ?? null,
|
|
'indeks_bg_terbangun' => $data['indeks_bg_terbangun'] ?? null,
|
|
'nilai_retribusi_bangunan' => $data['nilai_retribusi_bangunan'] ?? null,
|
|
'nilai_prasarana' => $data['nilai_prasarana'] ?? null,
|
|
'created_by' => $data['created_by'] ?? null,
|
|
'pbg_document' => $data['pbg_document'] ?? null,
|
|
'underpayment' => $data['underpayment'] ?? null,
|
|
'skrd_amount' => $data['skrd_amount'] ?? null,
|
|
'pbg_task_uid' => $uuid,
|
|
]
|
|
);
|
|
|
|
$pbg_task_retribution_id = $pbg_task_retributions->id;
|
|
|
|
$prasaranaData = $data['prasarana'] ?? [];
|
|
if (!empty($prasaranaData)) {
|
|
$insertData = array_map(fn($item) => [
|
|
'pbg_task_uid' => $uuid,
|
|
'pbg_task_retribution_id' => $pbg_task_retribution_id,
|
|
'prasarana_id' => $item['id'] ?? null,
|
|
'prasarana_type' => $item['prasarana_type'] ?? null,
|
|
'building_type' => $item['building_type'] ?? null,
|
|
'total' => $item['total'] ?? null,
|
|
'quantity' => $item['quantity'] ?? null,
|
|
'unit' => $item['unit'] ?? null,
|
|
'index_prasarana' => $item['index_prasarana'] ?? null,
|
|
], $prasaranaData);
|
|
|
|
// Use bulk insert or upsert for faster database operation
|
|
PbgTaskPrasarana::upsert($insertData, ['prasarana_id']);
|
|
}
|
|
return true;
|
|
|
|
}catch(Exception $e){
|
|
Log::error("Failed to sync task detail submit", ['error' => $e->getMessage(), 'uuid' => $uuid]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
} |