97 lines
3.0 KiB
PHP
97 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Admin;
|
|
|
|
use App\Models\Position;
|
|
use App\Models\PositionQuota;
|
|
use App\Models\PusatMengundi;
|
|
use App\Models\SaluranMengundi;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class PusatOperationalSetupService
|
|
{
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
*/
|
|
public function configure(PusatMengundi $pusatMengundi, array $data): void
|
|
{
|
|
DB::transaction(function () use ($pusatMengundi, $data): void {
|
|
$salurans = collect();
|
|
|
|
foreach (range(1, (int) $data['saluran_count']) as $number) {
|
|
$salurans->push(SaluranMengundi::query()->updateOrCreate(
|
|
[
|
|
'pusat_mengundi_id' => $pusatMengundi->id,
|
|
'number' => (string) $number,
|
|
],
|
|
[
|
|
'election_id' => $pusatMengundi->election_id,
|
|
'name' => null,
|
|
],
|
|
));
|
|
}
|
|
|
|
$this->upsertPusatQuotas($pusatMengundi, $data);
|
|
|
|
foreach ($salurans as $saluran) {
|
|
$this->upsertSaluranQuotas($pusatMengundi, $saluran, $data);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
*/
|
|
private function upsertPusatQuotas(PusatMengundi $pusatMengundi, array $data): void
|
|
{
|
|
foreach ([
|
|
'PPM' => 'ppm_count',
|
|
'PAPM' => 'papm_count',
|
|
'JKM' => 'jkm_count',
|
|
'KKM' => 'kkm_count',
|
|
] as $code => $field) {
|
|
$this->upsertQuota($pusatMengundi, null, $code, (int) $data[$field]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $data
|
|
*/
|
|
private function upsertSaluranQuotas(PusatMengundi $pusatMengundi, SaluranMengundi $saluran, array $data): void
|
|
{
|
|
foreach ([
|
|
'KTM' => 'ktm_count',
|
|
'POLIS' => 'polis_iring_count',
|
|
'KP' => 'kp_count',
|
|
'KPDP' => 'kpdp_count',
|
|
'CALON_TAMBAHAN' => 'calon_tambahan_count',
|
|
] as $code => $field) {
|
|
$this->upsertQuota($pusatMengundi, $saluran, $code, (int) $data[$field]);
|
|
}
|
|
}
|
|
|
|
private function upsertQuota(PusatMengundi $pusatMengundi, ?SaluranMengundi $saluran, string $positionCode, int $quota): void
|
|
{
|
|
$position = Position::query()->where('code', $positionCode)->first();
|
|
|
|
if (! $position instanceof Position) {
|
|
throw ValidationException::withMessages([
|
|
'positions' => 'Jawatan '.$positionCode.' belum dikonfigurasi.',
|
|
]);
|
|
}
|
|
|
|
PositionQuota::query()->updateOrCreate(
|
|
[
|
|
'election_id' => $pusatMengundi->election_id,
|
|
'pusat_mengundi_id' => $pusatMengundi->id,
|
|
'saluran_mengundi_id' => $saluran?->id,
|
|
'position_id' => $position->id,
|
|
],
|
|
[
|
|
'quota' => $quota,
|
|
],
|
|
);
|
|
}
|
|
}
|