73 lines
2.5 KiB
PHP
73 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Setting;
|
|
|
|
use App\Models\ReferenceUnit;
|
|
use App\Models\ReferenceUnitConversion;
|
|
use App\Services\SigdCrudService;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class UnitConversionService extends SigdCrudService
|
|
{
|
|
public function __construct(ReferenceUnitConversion $model)
|
|
{
|
|
parent::__construct($model);
|
|
}
|
|
|
|
public function getCategories()
|
|
{
|
|
return ReferenceUnit::distinct()->rowActive()->pluck('category');
|
|
}
|
|
|
|
public function getUnitsByCategory($category)
|
|
{
|
|
return ReferenceUnit::where('category', $category)->rowActive()->orderByRowNum()->get();
|
|
}
|
|
|
|
public function getConversionsByCategory($category)
|
|
{
|
|
return ReferenceUnitConversion::where('category', $category)
|
|
->rowActive()->get()
|
|
->groupBy('from_unit_code')->map(function ($item) {
|
|
return $item->keyBy('to_unit_code');
|
|
});
|
|
}
|
|
|
|
public function save($category, array $conversions)
|
|
{
|
|
DB::transaction(function () use ($category, $conversions) {
|
|
foreach ($conversions as $fromUnitCode => $values) {
|
|
foreach ($values as $toUnitCode => $value) {
|
|
$isExist = ReferenceUnitConversion::where('category', $category)
|
|
->where('from_unit_code', $fromUnitCode)
|
|
->where('to_unit_code', $toUnitCode)
|
|
->rowActive()
|
|
->first();
|
|
|
|
if (!empty($value)) {
|
|
$newValue = getOriginalValue($value);
|
|
if ($isExist) {
|
|
$oldValue = (float) rtrim(rtrim($isExist->value, '0'), ',');
|
|
if ($oldValue != $newValue) {
|
|
$this->update($isExist, ['value' => $newValue]);
|
|
}
|
|
} else {
|
|
// Create new record
|
|
$this->create([
|
|
'category' => $category,
|
|
'from_unit_code' => $fromUnitCode,
|
|
'to_unit_code' => $toUnitCode,
|
|
'value' => $newValue,
|
|
]);
|
|
}
|
|
} else {
|
|
if ($isExist) {
|
|
$this->delete($isExist);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|