@php $title = $page['title']; $bodyClass = ''; $mainClass = ''; $contentClass = 'portal-content--campaign-report'; $isTargeted = $menu === 'targeted'; $listDetail = is_array($campaignRow['report_detail'] ?? null) ? $campaignRow['report_detail'] : []; $rawCampaign = (array) ($campaignRow['raw'] ?? []); $campaignReport = is_array($campaignReport ?? null) ? $campaignReport : []; $campaignListReport = is_array($campaignListReport ?? null) ? $campaignListReport : []; $reportData = data_get($campaignReport, 'data.data') ?? data_get($campaignReport, 'data') ?? []; $reportData = is_array($reportData) ? $reportData : []; // Metode Pengiriman: the campaign's table and campaign_type in the API database, e.g. campaign_mms + lba = "MMS LBA". $methodChannel = strtolower((string) ($reportData['channel'] ?? ($channel === 'wa-business' ? 'waba' : $channel))); $methodType = strtolower((string) ($reportData['campaign_type'] ?? match ($menu) { 'targeted' => 'targeted', 'broadcast' => 'broadcast', default => 'lba' })); $deliveryMethod = strtoupper($methodChannel).' '.match ($methodType) { 'lba' => 'LBA', 'targeted' => 'Targeted', 'broadcast' => 'Broadcast', default => ucfirst($methodType) }; $listReportData = []; $decodeNestedJson = function ($value) use (&$decodeNestedJson) { if (is_string($value)) { $trimmed = trim($value); if ($trimmed !== '' && in_array($trimmed[0], ['{', '['], true)) { $decoded = json_decode($trimmed, true); if (json_last_error() === JSON_ERROR_NONE) { return $decodeNestedJson($decoded); } } return $value; } if (is_array($value)) { foreach ($value as $key => $item) { $value[$key] = $decodeNestedJson($item); } } return $value; }; $rawCampaign = $decodeNestedJson($rawCampaign); $reportData = $decodeNestedJson($reportData); $formatNumber = function ($value, $default = '-') { if ($value === null || $value === '') { return $default; } return is_numeric($value) ? number_format((float) $value, 0, ',', '.') : $value; }; $formatMoney = function ($value, $default = '-') { if ($value === null || $value === '') { return $default; } if (is_string($value) && str_starts_with(trim($value), 'Rp')) { return $value; } return is_numeric($value) ? 'Rp ' . number_format((float) $value, 0, ',', '.') : $value; }; $formatDate = function ($value, $default = '-') { $value = trim((string) $value); if ($value === '') { return $default; } try { if (preg_match('/^\d{8}$/', $value)) { return \Illuminate\Support\Carbon::createFromFormat('Ymd', $value)->translatedFormat('d M Y'); } if (is_numeric($value) && strlen($value) >= 12) { return \Illuminate\Support\Carbon::createFromTimestamp((int) ($value / 1000))->translatedFormat('d M Y'); } return \Illuminate\Support\Carbon::parse($value)->translatedFormat('d M Y'); } catch (Throwable) { return $value; } }; $formatTime = function ($value, $default = '-') { $value = trim((string) $value); if ($value === '') { return $default; } if (preg_match('/^\d{4}-\d{2}-\d{2}/', $value)) { try { return \Illuminate\Support\Carbon::parse($value)->format('H.i'); } catch (Throwable) { return $value; } } if (preg_match('/^\d{4}$/', $value)) { return substr($value, 0, 2) . '.' . substr($value, 2, 2); } return str_replace(':', '.', $value); }; $normalizeKey = function (string $key): string { if (str_contains($key, '.')) { $key = substr(strrchr($key, '.'), 1); } return strtolower((string) preg_replace('/[^a-z0-9]/i', '', $key)); }; $findNestedValue = function ($source, array $keys) use (&$findNestedValue, $normalizeKey) { if (! is_array($source)) { return null; } $targets = array_map($normalizeKey, $keys); foreach ($source as $key => $value) { if (in_array($normalizeKey((string) $key), $targets, true) && $value !== null && $value !== '') { return $value; } if (is_array($value)) { $nested = $findNestedValue($value, $keys); if ($nested !== null && $nested !== '') { return $nested; } } } return null; }; $firstValue = function (array $keys, $default = null) use ($listDetail, $reportData, $rawCampaign, $campaignRow, $findNestedValue) { foreach ($keys as $key) { foreach ([$reportData, $campaignRow, $listDetail, $rawCampaign] as $source) { $value = data_get($source, $key); if ($value !== null && $value !== '') { return $value; } } } foreach ([$reportData, $campaignRow, $listDetail, $rawCampaign] as $source) { $value = $findNestedValue($source, $keys); if ($value !== null && $value !== '') { return $value; } } return $default; }; $listReportData = \App\Services\CampaignReportContent::listItem($campaignListReport, (string) ($campaignRow['id'] ?? '')); $firstListValue = function (array $keys, $default = null) use ($listReportData, $listDetail, $reportData, $rawCampaign, $campaignRow, $findNestedValue) { foreach ($keys as $key) { foreach ([$listReportData, $campaignRow, $listDetail, $rawCampaign, $reportData] as $source) { $value = data_get($source, $key); if ($value !== null && $value !== '') { return $value; } } } foreach ([$listReportData, $campaignRow, $listDetail, $rawCampaign, $reportData] as $source) { $value = $findNestedValue($source, $keys); if ($value !== null && $value !== '') { return $value; } } return $default; }; $firstAssoc = function (array $keys) use ($firstValue): array { $value = $firstValue($keys, []); if (! is_array($value)) { return []; } if (array_is_list($value)) { return is_array($value[0] ?? null) ? $value[0] : []; } return $value; }; $listValue = function (array $keys) use ($firstValue): array { $value = $firstValue($keys, []); if (! is_array($value)) { return []; } return array_is_list($value) ? $value : [$value]; }; preg_match('/Sukses:\s*([\d\.,]+)/i', $campaignRow['status_detail'] ?? '', $successMatch); preg_match('/Gagal:\s*([\d\.,]+)/i', $campaignRow['status_detail'] ?? '', $failedMatch); $campaignId = $firstListValue(['id', 'campaignId'], $campaignRow['id'] ?? '-'); $campaignTitle = $firstListValue(['campaignName', 'title', 'name'], $campaignRow['title'] ?? 'Belum diisi'); $campaignDate = $formatDate($firstListValue(['startDate', 'deliveryDate', 'deliveryStartDate', 'createdDate', 'createdAt'], $campaignRow['date'] ?? ''), '-'); $categoryLabel = match ($menu) { 'targeted' => 'Targeted', 'broadcast' => 'Broadcast', default => 'Location Based Advertising' }; $channelLabel = $channel === 'wa-business' ? 'WhatsApp Business' : $firstListValue(['inventoryType', 'channel', 'channel_type'], $campaignRow['channel_type'] ?? 'SMS'); $senderName = $firstListValue(['sender_name', 'senderName', 'senderId', 'sender_id', 'sender', 'from'], '-'); $messageText = \App\Services\CampaignReportContent::message($campaignRow, $campaignReport, $campaignListReport); // Biaya Pembayaran from the API database (campaign_billing.billing): Saldo Utama payment or membership quota, and refunds. $billing = is_array($reportData['billing'] ?? null) ? $reportData['billing'] : null; // Pengiriman awal: the campaign's recipient count, else the billed recipients (Jumlah Penerima), else "-". $totalRecipient = $formatNumber($firstListValue(['totalTarget', 'recipient_total', 'recepientTotal', 'recipientTotal', 'totalRecipient', 'totalRecepient', 'totalMessage'], $billing['recipients'] ?? null), '-'); // The schedule we sent to DigitalCore (the API's request_payload deliveries), not loosely matched // report fields. DigitalCore sends to every recipient on each day of a window. $sentPayload = is_array($reportData['request_payload'] ?? null) ? $reportData['request_payload'] : []; $sentDeliveries = \App\Support\CampaignSchedule::deliveries($sentPayload); $deliveryDays = \App\Support\CampaignSchedule::days($sentDeliveries); // Tanggal Penayangan Iklan: first start date to last end date of that schedule. $campaignDate = \App\Support\CampaignSchedule::label($sentDeliveries) ?? $campaignDate; // Pengiriman awal: DigitalCore's totalTarget already counts every day, so it is the total as-is // (never multiplied again); without it, the per-day recipients we sent x the days. $perDayRecipients = $sentPayload['recepientTotal'] ?? $reportData['total_recipient'] ?? null; $perDayRecipients = is_numeric($perDayRecipients) ? (int) $perDayRecipients : null; $digitalCoreTotal = $firstListValue(['totalTarget'], null); $totalSends = is_numeric($digitalCoreTotal) ? (int) $digitalCoreTotal : ($perDayRecipients !== null ? $perDayRecipients * $deliveryDays : null); if ($totalSends !== null) { $totalRecipient = $formatNumber($totalSends, '-'); } $totalRecipientBreakdown = $perDayRecipients !== null && $deliveryDays > 1 ? ' ('.$formatNumber($perDayRecipients, '-').' penerima x '.$deliveryDays.' hari)' : ''; $successRaw = $firstValue(['success_message', 'successMessage', 'success', 'successCount', 'totalSuccess', 'delivered', 'deliveredCount', 'sent', 'sentCount'], $successMatch[1] ?? null); $successCount = $formatNumber($successRaw, '0'); $failedCount = $formatNumber($firstValue(['failed_message', 'failedMessage', 'failed', 'failedCount', 'totalFailed', 'undelivered', 'undeliveredCount', 'fail', 'failCount'], $failedMatch[1] ?? null), '0'); $totalClick = $formatNumber($firstValue(['totalClick', 'clickTotal', 'clicks', 'clickCount'], 0), '0'); $clickRateRaw = $firstValue(['clickRate', 'ctr', 'click_rate'], null); $clickRate = is_numeric($clickRateRaw) ? number_format((float) $clickRateRaw, 2, ',', '.') . '%' : ($clickRateRaw ?: '0%'); $shortUrl = $firstValue(['short_url', 'shortUrl', 'url.shortUrl', 'content.shortUrl', 'contents.shortUrl'], '-'); $location = $firstAssoc(['location', 'content.locations', 'contents.locations', 'locations']); $locationName = data_get($location, 'locationNameUser') ?? data_get($location, 'locationNameMap') ?? data_get($location, 'locationName') ?? data_get($location, 'name') ?? '-'; $locationAddress = data_get($location, 'address') ?? '-'; $radius = $formatNumber(data_get($location, 'radius') ?? $firstValue(['radius'], null), '-'); $locationType = data_get($location, 'locationType') ?? $firstValue(['locationType'], '-'); $estimatedPotential = $formatNumber($firstValue(['estimatedRecipient', 'estimatedRecepient', 'potentialRecipient', 'potentialRecepient'], null), '-'); // LBA: the estimate the API stored for this campaign; without one, the page asks the API once, // which asks DigitalCore for the campaign's own location and stores the answer. $storedEstimate = is_array($reportData['estimate'] ?? null) ? $reportData['estimate'] : null; if ($storedEstimate && is_numeric($storedEstimate['population'] ?? null)) { [$low, $high] = [$storedEstimate['min_population'] ?? null, $storedEstimate['max_population'] ?? null]; $estimatedPotential = is_numeric($low) && is_numeric($high) && (int) $low !== (int) $high ? $formatNumber($low, '-').'–'.$formatNumber($high, '-').' orang' : $formatNumber($storedEstimate['population'], '-').' orang'; } $lbaEstimateUrl = $menu === 'location-based-area' && $estimatedPotential === '-' && ! empty($reportData['local_id']) && in_array($methodChannel, ['sms', 'mms', 'waba'], true) ? route('campaign.report.estimate', ['channel' => $methodChannel, 'localId' => $reportData['local_id']]) : null; $profile = $firstAssoc(['profile', 'profiles', 'targetProfile']); $gender = data_get($profile, 'gender') ?? data_get($profile, 'profileGender') ?? $firstValue(['profile_gender', 'gender'], 'Semua'); // DigitalCore's M/F as words. $genderLabel = static fn ($value) => match (strtoupper(trim((string) $value))) { 'M', 'MALE' => 'Laki-laki', 'F', 'FEMALE' => 'Perempuan', default => $value }; $gender = is_array($gender) ? array_map($genderLabel, $gender) : implode(', ', array_map($genderLabel, explode('|', (string) $gender))); $age = data_get($profile, 'age') ?? data_get($profile, 'profileAge') ?? $firstValue(['profile_age', 'age'], 'Semua'); $religion = data_get($profile, 'religion') ?? data_get($profile, 'profileReligion') ?? $firstValue(['profile_religion', 'religion'], 'Semua'); $device = data_get($profile, 'device') ?? data_get($profile, 'os') ?? data_get($profile, 'profileOs') ?? $firstValue(['profile_os', 'device', 'os'], 'Semua'); // First non-empty value of the keys, in order, from one schedule entry (deliveryDate or delivery_date alike). $pickDelivery = function ($delivery, array $keys) use ($findNestedValue) { foreach ($keys as $key) { $value = $findNestedValue(is_array($delivery) ? $delivery : [], [$key]); if (is_scalar($value) && trim((string) $value) !== '') { return $value; } } return null; }; $deliveries = $sentDeliveries !== [] ? $sentDeliveries : $listValue(['deliveries', 'delivery', 'schedules', 'schedule']); if ($deliveries === []) { $deliveries = [[ 'deliveryDate' => $firstListValue(['deliveryDate', 'startDate'], ''), 'deliveryStartDate' => $firstListValue(['deliveryStartDate', 'startDate'], ''), 'deliveryEndDate' => $firstListValue(['deliveryEndDate', 'endDate'], ''), 'deliveryTime' => $firstListValue(['deliveryTime', 'startDatetime'], ''), 'deliveryStartTime' => $firstListValue(['deliveryStartTime', 'startDatetime'], ''), 'deliveryEndTime' => $firstListValue(['deliveryEndTime', 'endDatetime'], ''), 'deliveryMethod' => $deliveryMethod, ]]; } $controlNumbersRaw = $firstValue(['control_numbers', 'controlNumbers', 'controlNumber', 'testNumbers', 'testNumber'], []); if (is_string($controlNumbersRaw)) { $controlNumbers = array_filter(array_map('trim', preg_split('/[,;\n]+/', $controlNumbersRaw))); } elseif (is_array($controlNumbersRaw)) { $controlNumbers = array_values(array_filter($controlNumbersRaw, fn ($number) => trim((string) $number) !== '')); } else { $controlNumbers = []; } $unitPrice = $formatMoney($firstListValue(['basePriceProduct', 'unit_price', 'unitPrice', 'pricePerMessage', 'price'], null), '-'); $grandTotal = $formatMoney($firstListValue(['bucketMain', 'grand_total', 'grandTotal', 'totalPrice', 'totalCost'], $campaignRow['total_price'] ?? null), '-'); if ($billing) { $unitPrice = is_numeric($billing['unit_price'] ?? null) ? $formatMoney($billing['unit_price'], '-').' / pesan' : '-'; $grandTotal = $formatMoney($billing['amount'] ?? null, '-'); } $balanceMain = $formatMoney($firstValue(['balanceMain', 'mainBalance', 'saldoUmum'], null), '-'); $balanceMonetary = $formatMoney($firstValue(['balanceMonetary', 'monetaryBalance', 'saldoMonetary'], null), '-'); $quota = $formatNumber($firstValue(['quota', 'quotaPackage', 'kuotaPaket'], 0), '0') . ' Pesan'; $navMenus = \App\Support\PortalNavigation::menus(); $activeNav = $channel ?? 'sms'; $activeSubnav = $activeNav.'-'.$menu; $reportSections = [ ['key' => 'message', 'icon' => 'message', 'title' => 'Konten Pesan Iklan'], ['key' => 'schedule', 'icon' => 'schedule', 'title' => 'Jadwal Pengiriman'], ['key' => 'test', 'icon' => 'profile', 'title' => 'Nomor Test Iklan'], ['key' => 'billing', 'icon' => 'billing', 'title' => 'Biaya Pembayaran'], ]; @endphp @extends('layouts.portal') @section('content') @include('partials.campaign-report-header')
@include('partials.report-icon', ['name' => 'send'])

Pengiriman

{{ $totalRecipient }} Pengiriman awal{{ $totalRecipientBreakdown }}

{{ $successCount }} Pesan Berhasil Dikirim

{{ $failedCount }} pesan tidak terkirim

Menampilkan 1 - {{ count($deliveries) }} dari {{ count($deliveries) }} Jadwal

Jadwal Pengiriman 1

Lihat Detil Pengiriman {{-- Click: clicks on the campaign's tracked short links; "-" with an (i) hint without one. --}} Sukses: {{ $successCount }} | Gagal: {{ $failedCount }} | Click@if ($shortUrl === '-')i@endif: {{ $shortUrl === '-' ? '-' : $totalClick }}
{{-- Flow chart: Pengiriman awal -> Terkirim -> Sukses / Gagal, and the delivery and click rates. --}} @include('partials.campaign-delivery-chart', [ 'input' => $totalSends ?? $firstListValue(['totalTarget', 'recipient_total', 'recepientTotal', 'recipientTotal', 'totalRecipient', 'totalRecepient', 'totalMessage'], $billing['recipients'] ?? null), 'success' => $firstValue(['success_message', 'successMessage', 'success', 'successCount', 'totalSuccess', 'delivered', 'deliveredCount', 'sent', 'sentCount'], $successMatch[1] ?? null), 'failed' => $firstValue(['failed_message', 'failedMessage', 'failed', 'failedCount', 'totalFailed', 'undelivered', 'undeliveredCount', 'fail', 'failCount'], $failedMatch[1] ?? null), 'clicks' => $shortUrl === '-' ? null : $firstValue(['totalClick', 'clickTotal', 'clicks', 'clickCount'], 0), 'status' => $firstValue(['campaign_status', 'status'], ''), 'lba' => $menu === 'location-based-area', 'estimate' => $storedEstimate, 'estimatePending' => (bool) $lbaEstimateUrl, ]) @if ($shortUrl !== '-') {{-- Tracked short links in the message (API short_links.py): clicks counted by the /{code} redirect. --}} @endif
@foreach ($reportSections as $section)
@if ($section['key'] === 'message')
Pengirim {{ $senderName }}
Isi Pesan (1 Pesan {{ $channel === 'wa-business' ? $channelLabel : strtoupper((string) $channelLabel) }}) {{ $messageText }}
@if ($menu === 'location-based-area')
Lokasi {{ $locationName }} @if ($locationAddress !== '-' && $locationAddress !== $locationName)

{{ $locationAddress }}

@endif
Radius{{ $radius }} meter
Tipe Lokasi{{ $locationType }}
Estimasi Penerima Potensial{{ $lbaEstimateUrl ? 'Menghitung…' : $estimatedPotential }}
@endif @if ($menu !== 'broadcast')

Profil

Jenis Kelamin{{ is_array($gender) ? implode(', ', $gender) : $gender }}
Rentang Umur{{ is_array($age) ? implode(', ', $age) : $age }}
Agama{{ is_array($religion) ? implode(', ', $religion) : $religion }}
Jenis Handphone{{ is_array($device) ? implode(', ', $device) : $device }}
@endif
@elseif ($section['key'] === 'schedule')
@foreach ($deliveries as $deliveryIndex => $delivery) @php // First non-empty key of the schedule (blank keys are skipped), else the campaign's own fields. $startDate = $pickDelivery($delivery, ['deliveryStartDate', 'deliveryDate', 'startDate']) ?? $firstListValue(['deliveryStartDate', 'deliveryDate', 'startDate'], ''); $endDate = $pickDelivery($delivery, ['deliveryEndDate', 'endDate']) ?? $firstListValue(['deliveryEndDate', 'endDate'], null) ?? $startDate; $startTime = $pickDelivery($delivery, ['deliveryStartTime', 'deliveryTime', 'startTime']) ?? $firstListValue(['deliveryStartTime', 'deliveryTime', 'startTime', 'startDatetime'], ''); $endTime = $pickDelivery($delivery, ['deliveryEndTime', 'endTime']) ?? $firstListValue(['deliveryEndTime', 'endTime', 'endDatetime'], ''); // One day (broadcast): the date once, not "13 Nov 2026 - 13 Nov 2026". $dateRange = $formatDate($startDate) === $formatDate($endDate) ? $formatDate($startDate) : $formatDate($startDate).' - '.$formatDate($endDate); $method = $deliveryMethod; @endphp
Jadwal Pengiriman {{ $deliveryIndex + 1 }} {{ $dateRange }}
Jam Kirim {{ $formatTime($startTime) }}{{ $endTime ? ' - ' . $formatTime($endTime) : '' }} WIB
Metode Pengiriman {{ $method }}
@endforeach
@elseif ($section['key'] === 'test')
@forelse ($controlNumbers as $index => $number) {{ $index + 1 }}) {{ $number }} @empty Nomor test tidak tersedia. @endforelse
Total Pesan yang akan dikirim {{ $totalRecipient }} Pesan{{ $totalRecipientBreakdown }}
@else @include('partials.campaign-report-billing') @endif
@endforeach
@endsection @push('scripts') @endpush