95 lines
3.0 KiB
PHP
95 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
use Throwable;
|
|
|
|
class CommodityCertificate
|
|
{
|
|
/**
|
|
* Certificate fields for a SAG. Shoraka is used when that order exists,
|
|
* otherwise the BSAS order, otherwise the legacy daily commodity stock.
|
|
*/
|
|
public function forReference(string $reference, $pinjaman = null): array
|
|
{
|
|
$shoraka = $this->shorakaPrint($reference);
|
|
if ($shoraka) {
|
|
return $this->normalize($shoraka['komoditi'], $shoraka['product'], $shoraka['kuantiti']);
|
|
}
|
|
|
|
$bsas = Http::withOptions(['verify' => config('app.api_verify')])
|
|
->get(rtrim((string) config('api.url'), '/') . '/api/komuditi/bsas/order/norujukan/' . urlencode($reference));
|
|
|
|
if ($bsas->successful() && is_array($bsas->json())) {
|
|
$payload = $bsas->json();
|
|
return $this->normalize(
|
|
$payload['komoditi'] ?? [],
|
|
$payload['product'] ?? [],
|
|
(float) ($payload['kuantiti'] ?? 0)
|
|
);
|
|
}
|
|
|
|
return $this->legacy($pinjaman);
|
|
}
|
|
|
|
private function shorakaPrint(string $reference): ?array
|
|
{
|
|
try {
|
|
return app(ShorakaFinancingService::class)->printData($reference);
|
|
} catch (HttpException $exception) {
|
|
if ($exception->getStatusCode() === 409) {
|
|
throw $exception;
|
|
}
|
|
return null;
|
|
} catch (Throwable $exception) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private function legacy($pinjaman): array
|
|
{
|
|
$api = rtrim((string) config('api.url'), '/');
|
|
$komoditi = Http::withOptions(['verify' => config('app.api_verify')])
|
|
->get($api . '/api/komuditi/check')
|
|
->json();
|
|
if (!is_array($komoditi)) {
|
|
$komoditi = [];
|
|
}
|
|
|
|
$product = Http::withOptions(['verify' => config('app.api_verify')])
|
|
->get($api . '/api/komuditi/description', [
|
|
'kodproduk' => $komoditi['kodproduct'] ?? '',
|
|
])
|
|
->json();
|
|
|
|
$nilai = (float) ($komoditi['nilai'] ?? 0);
|
|
$kuantiti = $nilai > 0 ? ((float) $pinjaman / $nilai) : 0;
|
|
|
|
return $this->normalize($komoditi, is_array($product) ? $product : [], $kuantiti);
|
|
}
|
|
|
|
private function normalize($komoditi, $product, $kuantiti): array
|
|
{
|
|
if (!is_array($komoditi)) {
|
|
$komoditi = [];
|
|
}
|
|
if (!is_array($product)) {
|
|
$product = [];
|
|
}
|
|
|
|
$code = $product['product_code'] ?? $product['kodproduk'] ?? ($komoditi['kodproduct'] ?? '');
|
|
$product['product_code'] = $product['product_code'] ?? $code;
|
|
$product['kodproduk'] = $product['kodproduk'] ?? $code;
|
|
$product['description'] = $product['description'] ?? '';
|
|
$product['unit'] = $product['unit'] ?? 'TAN';
|
|
|
|
return [
|
|
'komoditi' => $komoditi,
|
|
'product' => $product,
|
|
'kuantiti' => $kuantiti,
|
|
];
|
|
}
|
|
}
|