sigd/app/Services/Emisi/Waste4APreService.php

108 lines
3.5 KiB
PHP

<?php
namespace App\Services\Emisi;
use App\Models\ActivityFormDetail;
use App\Models\Waste4APre;
use App\Services\SigdCrudService;
class Waste4APreService extends SigdCrudService
{
private $sectorCode = 'waste';
private $formCode = 'sampah';
public function __construct(Waste4APre $model)
{
$this->model = $model;
}
public function save($code, $inventoryYear)
{
try {
$dataBatch = [];
$ws = $this->getWs($code);
$years = activityYearRange($inventoryYear);
if ($ws && class_basename($ws->model) == 'Waste4APre') {
foreach ($years as $year) {
$dataBatch = array_merge($dataBatch, $this->calcAndSave($inventoryYear, $year, $ws));
}
} else {
throw new \Exception("Forbidden");
}
return $dataBatch;
} catch (\Exception $e) {
throw $e;
}
}
public function calcAndSave($inventoryYear, $activityYear, $ws)
{
// Initialize variables
$dataForms = [];
$sector = $this->sectorCode;
$code = $this->formCode;
$wsCode = $ws->ws_code;
$items = ['sisa_makanan', 'kertas', 'nappies', 'taman', 'kayu', 'tekstil', 'karet_kulit', 'plastik', 'logam', 'kaca', 'anorganik_lainnya'];
$activities = [];
$total_waste = 0;
try {
$activity = 'timbulan_sampah';
$value = ActivityFormDetail::getValue($inventoryYear, $activityYear, $sector, $code, $activity);
$total_waste = $value / 1000;
foreach ($items as $item) {
$activities['composition'][$item] = 0;
$activities['dry_matter'][$item] = 0;
$activities['amount'][$item] = 0;
}
$formBahanSampah = $this->getActivityFormDetailsByYear($inventoryYear, $activityYear, $this->sectorCode, 'bahan_kering_sampah');
foreach ($formBahanSampah as $row) {
if (!preg_match('/_bahan_kering$/', $row->activity_code)) {
$activities['composition'][$row->activity_code] = $row->activity_value;
$activities['amount'][$row->activity_code] = $total_waste * $row->activity_value / 100;
} else {
$strCode = str_replace('_bahan_kering', '', $row->activity_code);
$activities['dry_matter'][$strCode] = $row->activity_value;
}
}
# hitung emisi
$no = 1;
foreach ($activities as $activity => $row) {
$dataForm = [
'inventory_year' => $inventoryYear,
'activity_year' => $activityYear,
// 'category' => $wsCode,
'activity' => $activity,
'value' => $value,
'total_waste' => $total_waste,
'row_num' => $no++,
];
foreach ($items as $item) {
$dataForm[$item] = $row[$item];
}
$this->createOrUpdate([
'inventory_year' => $inventoryYear,
'activity_year' => $activityYear,
// 'category' => $wsCode,
'activity' => $activity,
'row_status' => 1,
], $dataForm);
$dataForms[] = $dataForm;
}
return $dataForms;
} catch (\Exception $e) {
throw $e;
}
}
}