1
0

Giant Update

This commit is contained in:
Wian Drs
2026-07-31 13:57:11 +07:00
parent f68d967c8b
commit b0d08211ec
112 changed files with 6674 additions and 3 deletions
@@ -0,0 +1,81 @@
<?php
namespace App\Services\Billing;
use App\Models\BillingProfile;
use App\Models\User;
use Illuminate\Validation\ValidationException;
class BillingProfileService
{
public function list(array $filters, User $actor, ?int $tenantId)
{
return BillingProfile::query()->with('tenant:id,tenant_code,tenant_name')
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
->when(! empty($filters['search']), fn ($q) => $q->where('name', 'ILIKE', "%{$filters['search']}%"))
->orderBy($filters['sort_by'] ?? 'id', $filters['sort_direction'] ?? 'desc')
->paginate($filters['per_page'] ?? 10);
}
public function find(int $id): BillingProfile
{
return BillingProfile::with('tenant:id,tenant_code,tenant_name')->findOrFail($id);
}
public function create(array $data, User $actor, ?int $tenantId): BillingProfile
{
$data['tenant_id'] = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $data['tenant_id']) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
$data['tax_rate'] = $data['tax_type'] === 'non_tax' ? 0 : ($data['tax_rate'] ?? 11);
$data['status'] ??= 'active';
$data = $this->normalizeSchedule($data);
return BillingProfile::create($data)->load('tenant:id,tenant_code,tenant_name');
}
public function update(BillingProfile $profile, array $data, User $actor): BillingProfile
{
if (! $actor->isMasterAdmin()) {
unset($data['tenant_id']);
}
if (($data['tax_type'] ?? $profile->tax_type) === 'non_tax') {
$data['tax_rate'] = 0;
}
$data = $this->normalizeSchedule($data, $profile);
$profile->update($data);
return $profile->fresh()->load('tenant:id,tenant_code,tenant_name');
}
public function delete(BillingProfile $profile): void
{
if ($profile->customers()->exists() || $profile->invoices()->exists()) {
throw ValidationException::withMessages(['profile' => 'Profile tagihan masih digunakan customer atau invoice.']);
}
$profile->delete();
}
private function normalizeSchedule(array $data, ?BillingProfile $profile = null): array
{
$type = $data['schedule_type'] ?? $profile?->schedule_type ?? 'fixed_date';
$data['schedule_type'] = $type;
if ($type === 'installation_date') {
$data['invoice_day'] = $profile?->invoice_day ?? 1;
$data['send_day'] = $profile?->send_day ?? 1;
$data['warning_day'] = $profile?->warning_day ?? 1;
$data['isolation_day'] = $profile?->isolation_day ?? 1;
} else {
$data['invoice_days_before'] = null;
$data['send_days_before'] = null;
$data['warning_days_before'] = null;
$data['isolation_days_after'] = null;
}
return $data;
}
}
+346
View File
@@ -0,0 +1,346 @@
<?php
namespace App\Services\Billing;
use App\Models\BillingProfile;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\User;
use App\Services\Notification\NotificationManager;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Validation\ValidationException;
class InvoiceService
{
public function __construct(protected NotificationManager $notifications) {}
private const RELATIONS = [
'tenant:id,tenant_code,tenant_name',
'customer:id,tenant_id,customer_code,name,whatsapp_number,email,status',
'billingProfile:id,tenant_id,name,schedule_type,invoice_day,send_day,warning_day,isolation_day,invoice_days_before,send_days_before,warning_days_before,isolation_days_after,tax_type,tax_rate',
];
public function list(string $scope, array $filters, User $actor, ?int $tenantId)
{
$query = Invoice::query()->with(self::RELATIONS);
if ($scope === 'running') {
$query->whereIn('status', ['draft', 'published', 'sent', 'warning']);
} elseif ($scope === 'overdue') {
$query->where('status', 'overdue');
} elseif ($scope === 'paid') {
$query->where('status', 'paid');
}
return $query
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
->when(! empty($filters['date_from']), fn ($q) => $q->whereDate('issue_date', '>=', $filters['date_from']))
->when(! empty($filters['date_to']), fn ($q) => $q->whereDate('issue_date', '<=', $filters['date_to']))
->when(! empty($filters['search']), fn ($q) => $q->where(function ($search) use ($filters) {
$term = "%{$filters['search']}%";
$search->where('invoice_number', 'ILIKE', $term)
->orWhere('customer_name_snapshot', 'ILIKE', $term)
->orWhere('customer_code_snapshot', 'ILIKE', $term);
}))
->orderBy($filters['sort_by'] ?? 'id', $filters['sort_direction'] ?? 'desc')
->paginate($filters['per_page'] ?? 10);
}
public function find(int $id): Invoice
{
return Invoice::with(self::RELATIONS)->findOrFail($id);
}
public function options(User $actor, ?int $tenantId): array
{
$tenantScope = fn ($q) => $q
->when(! $actor->isMasterAdmin(), fn ($x) => $x->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($x) => $x->where('tenant_id', $tenantId));
return [
'customers' => $tenantScope(Customer::query())
->with('billingProfile')
->whereIn('status', ['active', 'order'])
->orderBy('name')
->get(['id', 'tenant_id', 'customer_code', 'name', 'billing_profile_id', 'package_profile_id', 'activated_at']),
];
}
public function create(array $data, ?User $actor, ?int $tenantId): Invoice
{
$data['tenant_id'] = $actor?->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $data['tenant_id']) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
$customer = Customer::with('packageProfile')->whereKey($data['customer_id'])->where('tenant_id', $data['tenant_id'])->first();
if (! $customer) {
throw ValidationException::withMessages(['customer_id' => 'Customer bukan milik tenant aktif.']);
}
$profile = BillingProfile::whereKey($customer->billing_profile_id)
->where('tenant_id', $data['tenant_id'])
->where('status', 'active')
->first();
if (! $profile) {
throw ValidationException::withMessages([
'customer_id' => 'Customer belum memiliki profile tagihan aktif.',
]);
}
$data = [...$data, ...$this->scheduleDates($profile, $customer, $data)];
$amounts = $this->amounts((float) $data['subtotal'], $profile->tax_type, (float) $profile->tax_rate);
$data = [
...$data,
...$amounts,
'billing_profile_id' => $profile->id,
'invoice_number' => filled($data['invoice_number'] ?? null) ? $data['invoice_number'] : $this->nextNumber((int) $data['tenant_id']),
'status' => $data['status'] ?? $this->statusByDate($data),
'payment_status' => 'unpaid',
'created_by' => $actor?->id,
'updated_by' => $actor?->id,
'customer_code_snapshot' => $customer->customer_code,
'customer_name_snapshot' => $customer->name,
'customer_address_snapshot' => $customer->full_installation_address ?? $customer->installation_address,
'package_name_snapshot' => $customer->packageProfile?->name,
'profile_snapshot' => $profile->only([
'name', 'schedule_type', 'invoice_day', 'send_day', 'warning_day', 'isolation_day',
'invoice_days_before', 'send_days_before', 'warning_days_before',
'isolation_days_after', 'tax_type', 'tax_rate',
]),
];
$invoice = Invoice::create($data)->load(self::RELATIONS);
$this->emitDueNotifications($invoice);
return $invoice;
}
public function processSchedules(): array
{
$created = 0;
$today = now()->startOfDay();
$periods = [
$today->copy()->startOfMonth(),
$today->copy()->addMonthNoOverflow()->startOfMonth(),
];
Customer::query()
->with(['billingProfile', 'packageProfile'])
->where('status', 'active')
->whereNotNull('billing_profile_id')
->whereNotNull('package_profile_id')
->chunkById(200, function ($customers) use (&$created, $periods, $today) {
foreach ($customers as $customer) {
if (! $customer->billingProfile || $customer->billingProfile->status !== 'active') {
continue;
}
if ($customer->billingProfile->schedule_type === 'installation_date' && ! $customer->activated_at) {
continue;
}
foreach ($periods as $period) {
$schedule = $this->scheduleDates(
$customer->billingProfile,
$customer,
['period_start' => $period->toDateString()],
);
if (Carbon::parse($schedule['issue_date'])->startOfDay()->gt($today)) {
continue;
}
$periodEnd = $period->copy()->endOfMonth()->toDateString();
if (Invoice::withTrashed()
->where('customer_id', $customer->id)
->whereDate('period_start', $period->toDateString())
->whereDate('period_end', $periodEnd)
->exists()) {
continue;
}
try {
$this->create([
'tenant_id' => $customer->tenant_id,
'customer_id' => $customer->id,
'period_start' => $period->toDateString(),
'period_end' => $periodEnd,
'subtotal' => (float) $customer->packageProfile->price,
...$schedule,
], null, $customer->tenant_id);
$created++;
} catch (QueryException $exception) {
if (! $this->isDuplicateKey($exception)) {
throw $exception;
}
}
}
}
});
return ['created' => $created, 'updated' => $this->refreshStatuses()];
}
public function update(Invoice $invoice, array $data, User $actor): Invoice
{
unset($data['tenant_id'], $data['customer_id'], $data['billing_profile_id'], $data['invoice_number']);
if (array_key_exists('subtotal', $data)) {
$data = [...$data, ...$this->amounts((float) $data['subtotal'], $invoice->tax_type, (float) $invoice->tax_rate, (float) $invoice->paid_amount)];
}
$data['updated_by'] = $actor->id;
$invoice->update($data);
return $invoice->fresh()->load(self::RELATIONS);
}
public function pay(Invoice $invoice, array $data, User $actor): Invoice
{
if ($invoice->status === 'cancelled') {
throw ValidationException::withMessages(['invoice' => 'Invoice dibatalkan tidak dapat dibayar.']);
}
$paidAmount = min((float) $invoice->total, (float) $invoice->paid_amount + (float) $data['amount']);
$balance = max(0, (float) $invoice->total - $paidAmount);
$invoice->update([
'paid_amount' => $paidAmount,
'balance' => $balance,
'payment_status' => $balance <= 0 ? 'paid' : 'partial',
'status' => $balance <= 0 ? 'paid' : $this->statusByDate($invoice->toArray()),
'paid_at' => $balance <= 0 ? ($data['paid_at'] ?? now()) : null,
'payment_method' => $data['payment_method'] ?? $invoice->payment_method,
'payment_reference' => $data['payment_reference'] ?? $invoice->payment_reference,
'paid_by' => $actor->id,
'updated_by' => $actor->id,
'notes' => $data['notes'] ?? $invoice->notes,
]);
return $invoice->fresh()->load(self::RELATIONS);
}
public function cancel(Invoice $invoice, User $actor): Invoice
{
if ((float) $invoice->paid_amount > 0) {
throw ValidationException::withMessages(['invoice' => 'Invoice yang sudah memiliki pembayaran tidak dapat dibatalkan.']);
}
$invoice->update(['status' => 'cancelled', 'updated_by' => $actor->id]);
return $invoice->fresh()->load(self::RELATIONS);
}
private function amounts(float $subtotal, string $type, float $rate, float $paid = 0): array
{
$tax = match ($type) {
'inclusive' => $rate > 0 ? round($subtotal * $rate / (100 + $rate), 2) : 0,
'exclusive' => round($subtotal * $rate / 100, 2),
default => 0,
};
$total = $type === 'exclusive' ? $subtotal + $tax : $subtotal;
return ['tax_type' => $type, 'tax_rate' => $rate, 'tax_amount' => $tax, 'total' => $total, 'balance' => max(0, $total - $paid)];
}
private function scheduleDates(BillingProfile $profile, Customer $customer, array $data): array
{
$periodDate = Carbon::parse($data['period_start'])->startOfMonth();
if ($profile->schedule_type !== 'installation_date') {
return [
'issue_date' => $periodDate->copy()->day((int) $profile->invoice_day)->toDateString(),
'send_date' => $periodDate->copy()->day((int) $profile->send_day)->toDateString(),
'warning_date' => $periodDate->copy()->day((int) $profile->warning_day)->toDateString(),
'isolation_date' => $periodDate->copy()->day((int) $profile->isolation_day)->toDateString(),
];
}
if (! $customer->activated_at) {
throw ValidationException::withMessages([
'customer_id' => 'Tanggal pemasangan customer belum tersedia untuk profile tagihan ini.',
]);
}
$installationDay = $customer->activated_at->day;
$anchor = $periodDate->copy()->day(min($installationDay, $periodDate->daysInMonth));
return [
'issue_date' => $anchor->copy()->subDays((int) $profile->invoice_days_before)->toDateString(),
'send_date' => $anchor->copy()->subDays((int) $profile->send_days_before)->toDateString(),
'warning_date' => $anchor->copy()->subDays((int) $profile->warning_days_before)->toDateString(),
'isolation_date' => $anchor->copy()->addDays((int) $profile->isolation_days_after)->toDateString(),
];
}
private function statusByDate(array $data): string
{
$today = now()->startOfDay();
if (! empty($data['isolation_date']) && Carbon::parse($data['isolation_date'])->startOfDay()->lte($today)) {
return 'overdue';
}
if (! empty($data['warning_date']) && Carbon::parse($data['warning_date'])->startOfDay()->lte($today)) {
return 'warning';
}
if (! empty($data['send_date']) && Carbon::parse($data['send_date'])->startOfDay()->lte($today)) {
return 'sent';
}
if (! empty($data['issue_date']) && Carbon::parse($data['issue_date'])->startOfDay()->lte($today)) {
return 'published';
}
return 'draft';
}
private function refreshStatuses(?User $actor = null, ?int $tenantId = null): int
{
$updated = 0;
Invoice::query()->whereNotIn('status', ['paid', 'cancelled'])
->when($actor && (! $actor->isMasterAdmin() || $tenantId), fn ($q) => $q->where('tenant_id', $tenantId))
->chunkById(500, function ($invoices) use (&$updated) {
$invoices->each(function (Invoice $invoice) use (&$updated) {
$status = $this->statusByDate($invoice->toArray());
if ($status !== $invoice->status) {
$invoice->updateQuietly(['status' => $status]);
$updated++;
}
$this->emitDueNotifications($invoice->fresh(self::RELATIONS));
});
});
return $updated;
}
private function isDuplicateKey(QueryException $exception): bool
{
return in_array((string) $exception->getCode(), ['23000', '23505'], true);
}
private function emitDueNotifications(Invoice $invoice): void
{
if (in_array($invoice->status, ['paid', 'cancelled'], true) || ! $invoice->customer) {
return;
}
$payload = [
'tenant' => $invoice->tenant?->toArray() ?? [],
'customer' => $invoice->customer->toArray(),
'invoice' => [
...$invoice->toArray(),
'total' => 'Rp '.number_format((float) $invoice->total, 0, ',', '.'),
'balance' => 'Rp '.number_format((float) $invoice->balance, 0, ',', '.'),
],
];
foreach ([
'billing.invoice_sent' => $invoice->send_date,
'billing.warning' => $invoice->warning_date,
'billing.isolated' => $invoice->isolation_date,
] as $event => $date) {
if ($date && $date->copy()->startOfDay()->lte(now()->startOfDay())) {
$this->notifications->emit(
$event,
$invoice->customer,
$invoice,
$payload,
$event.'-'.$invoice->period_start->format('Ym'),
['action_url' => "/billing/running?invoice={$invoice->id}"],
);
}
}
}
private function nextNumber(int $tenantId): string
{
$sequence = Invoice::withTrashed()->where('tenant_id', $tenantId)->whereYear('created_at', now()->year)->count() + 1;
return 'INV-'.now()->format('Ym').'-'.str_pad((string) $sequence, 5, '0', STR_PAD_LEFT);
}
}
+283
View File
@@ -0,0 +1,283 @@
<?php
namespace App\Services\Customer;
use App\Models\BillingProfile;
use App\Models\Customer;
use App\Models\CustomerContact;
use App\Models\NasMikrotik;
use App\Models\NasPackageProfile;
use App\Models\StoredFile;
use App\Models\User;
use App\Models\WilayahDesa;
use App\Services\Notification\NotificationManager;
use Illuminate\Validation\ValidationException;
class CustomerService
{
public function __construct(protected NotificationManager $notifications) {}
private const BASE_RELATIONS = [
'tenant:id,tenant_code,tenant_name',
'provinsi:id,kode,nama',
'kabupaten:id,provinsi_id,kode,nama',
'kecamatan:id,kabupaten_id,kode,nama',
'desa:id,kecamatan_id,kode,nama',
'packageProfile:id,tenant_id,name,service_type,download_kbps,upload_kbps,price',
'nasMikrotik:id,tenant_id,name,connection_type,host,status',
'billingProfile:id,tenant_id,name,schedule_type,invoice_day,send_day,warning_day,isolation_day,invoice_days_before,send_days_before,warning_days_before,isolation_days_after,tax_type,tax_rate,status',
];
private const DETAIL_RELATIONS = [
...self::BASE_RELATIONS,
'images.file:id,uuid,tenant_id,uploaded_by,original_name,mime_type,size,category',
];
private const LIST_RELATIONS = [
...self::BASE_RELATIONS,
'coverImage.file:id,uuid,original_name,mime_type,size',
];
public function list(string $scope, array $filters, User $actor, ?int $tenantId)
{
$query = Customer::query()->with(self::LIST_RELATIONS);
if ($scope === 'trash') {
$query->onlyTrashed();
} else {
$query->where('status', $scope === 'orders' ? 'order' : $scope);
}
return $query
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->when(! empty($filters['source']), fn ($q) => $q->where('source', $filters['source']))
->when(! empty($filters['search']), fn ($q) => $q->where(function ($search) use ($filters) {
$term = "%{$filters['search']}%";
$search->where('customer_code', 'ILIKE', $term)
->orWhere('name', 'ILIKE', $term)
->orWhere('email', 'ILIKE', $term)
->orWhere('whatsapp_number', 'ILIKE', $term)
->orWhere('external_username', 'ILIKE', $term);
}))
->orderBy($filters['sort_by'] ?? 'id', $filters['sort_direction'] ?? 'desc')
->paginate($filters['per_page'] ?? 10);
}
public function find(int $id, bool $trashed = false): Customer
{
return Customer::query()
->when($trashed, fn ($q) => $q->withTrashed())
->with(self::DETAIL_RELATIONS)
->findOrFail($id);
}
public function create(array $data, User $actor, ?int $tenantId): Customer
{
$images = $data['images'] ?? [];
unset($data['images']);
$data['tenant_id'] = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $data['tenant_id']) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
$data['customer_code'] = filled($data['customer_code'] ?? null)
? $data['customer_code']
: $this->nextCode((int) $data['tenant_id']);
$data['source'] ??= 'manual';
$data['status'] = $data['source'] === 'manual' ? 'order' : 'unmanaged';
$data['order_stage'] ??= 'registration';
$this->validateTenantRelations($data);
$this->validateWilayah($data);
$customer = Customer::create($data);
$this->syncImages($customer, $images, $actor);
$this->syncPrimaryContacts($customer);
$customer->load('tenant:id,tenant_name');
$this->notifications->emit(
'customer.registration',
$customer,
$customer,
['customer' => $customer->toArray(), 'tenant' => $customer->tenant?->toArray() ?? []],
'registration',
['action_url' => "/customers/orders/{$customer->id}/detail"],
);
return $customer->load(self::DETAIL_RELATIONS);
}
public function update(Customer $customer, array $data, User $actor): Customer
{
$hasImages = array_key_exists('images', $data);
$images = $data['images'] ?? [];
unset($data['images']);
if (! $actor->isMasterAdmin()) {
unset($data['tenant_id']);
}
$data['tenant_id'] ??= $customer->tenant_id;
$this->validateTenantRelations($data);
$this->validateWilayah($data);
unset($data['status']);
$customer->update($data);
$this->syncPrimaryContacts($customer);
if ($hasImages) {
$this->syncImages($customer, $images, $actor);
}
return $customer->fresh()->load(self::DETAIL_RELATIONS);
}
public function activate(Customer $customer, array $data): Customer
{
$data['tenant_id'] = $customer->tenant_id;
$this->validateTenantRelations($data);
if (! $customer->desa_id || ! $customer->installation_address) {
throw ValidationException::withMessages([
'installation_address' => 'Alamat pemasangan dan wilayah desa wajib lengkap sebelum aktivasi.',
]);
}
$customer->update([
...$data,
'status' => 'active',
'order_stage' => 'ready_activation',
'activated_at' => now(),
'inactivated_at' => null,
]);
$customer->load('tenant:id,tenant_name');
$this->notifications->emit(
'customer.activation',
$customer,
$customer,
['customer' => $customer->toArray(), 'tenant' => $customer->tenant?->toArray() ?? []],
'activation-'.$customer->activated_at->format('YmdHis'),
['action_url' => "/customers/active/{$customer->id}/detail"],
);
return $customer->fresh()->load(self::DETAIL_RELATIONS);
}
public function deactivate(Customer $customer): Customer
{
$customer->update(['status' => 'inactive', 'inactivated_at' => now()]);
return $customer->fresh()->load(self::DETAIL_RELATIONS);
}
public function trash(Customer $customer): void
{
$customer->delete();
}
public function restore(Customer $customer): Customer
{
$customer->restore();
return $customer->fresh()->load(self::DETAIL_RELATIONS);
}
public function forceDelete(Customer $customer): void
{
$customer->forceDelete();
}
public function options(User $actor, ?int $tenantId): array
{
$scope = fn ($query) => $query
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->where('status', 'active')
->orderBy('name');
return [
'package_profiles' => $scope(NasPackageProfile::query())
->get(['id', 'tenant_id', 'name', 'service_type', 'download_kbps', 'upload_kbps', 'price']),
'nas_mikrotiks' => $scope(NasMikrotik::query())
->get(['id', 'tenant_id', 'name', 'connection_type', 'host']),
'billing_profiles' => $scope(BillingProfile::query())
->get(['id', 'tenant_id', 'name', 'schedule_type', 'invoice_day', 'send_day', 'warning_day', 'isolation_day', 'invoice_days_before', 'send_days_before', 'warning_days_before', 'isolation_days_after', 'tax_type', 'tax_rate']),
];
}
private function nextCode(int $tenantId): string
{
$next = ((int) Customer::withTrashed()->where('tenant_id', $tenantId)->max('id')) + 1;
return 'CUST-'.str_pad((string) $next, 6, '0', STR_PAD_LEFT);
}
private function validateTenantRelations(array $data): void
{
$tenantId = (int) $data['tenant_id'];
if (! empty($data['package_profile_id']) && ! NasPackageProfile::whereKey($data['package_profile_id'])->where('tenant_id', $tenantId)->exists()) {
throw ValidationException::withMessages(['package_profile_id' => 'Profile paket bukan milik tenant customer.']);
}
if (! empty($data['nas_mikrotik_id']) && ! NasMikrotik::whereKey($data['nas_mikrotik_id'])->where('tenant_id', $tenantId)->exists()) {
throw ValidationException::withMessages(['nas_mikrotik_id' => 'NAS Mikrotik bukan milik tenant customer.']);
}
if (! empty($data['billing_profile_id']) && ! BillingProfile::whereKey($data['billing_profile_id'])->where('tenant_id', $tenantId)->exists()) {
throw ValidationException::withMessages(['billing_profile_id' => 'Profile tagihan bukan milik tenant customer.']);
}
}
private function validateWilayah(array $data): void
{
if (empty($data['desa_id'])) {
return;
}
$desa = WilayahDesa::with('kecamatan.kabupaten')->find($data['desa_id']);
if (! $desa
|| (! empty($data['kecamatan_id']) && (int) $desa->kecamatan_id !== (int) $data['kecamatan_id'])
|| (! empty($data['kabupaten_id']) && (int) $desa->kecamatan->kabupaten_id !== (int) $data['kabupaten_id'])
|| (! empty($data['provinsi_id']) && (int) $desa->kecamatan->kabupaten->provinsi_id !== (int) $data['provinsi_id'])) {
throw ValidationException::withMessages(['desa_id' => 'Hierarki wilayah pemasangan tidak sesuai.']);
}
}
private function syncImages(Customer $customer, array $images, User $actor): void
{
$coverAssigned = false;
$rows = collect($images)->map(function (array $image, int $index) use ($customer, $actor, &$coverAssigned) {
$file = StoredFile::findOrFail($image['stored_file_id']);
$allowed = $actor->isMasterAdmin()
|| $file->uploaded_by === $actor->id
|| ((int) $file->tenant_id === (int) $customer->tenant_id);
if (! $allowed || $file->category !== 'customer-image' || ! str_starts_with((string) $file->mime_type, 'image/')) {
throw ValidationException::withMessages(['images' => 'File galeri customer tidak valid atau tidak dapat diakses.']);
}
$isCover = ! $coverAssigned && (bool) ($image['is_cover'] ?? $index === 0);
$coverAssigned = $coverAssigned || $isCover;
return [
'stored_file_id' => $file->id,
'category' => $image['category'],
'caption' => $image['caption'] ?? null,
'is_cover' => $isCover,
'sort_order' => $image['sort_order'] ?? $index,
];
})->all();
$customer->images()->delete();
if ($rows) {
$customer->images()->createMany($rows);
}
}
private function syncPrimaryContacts(Customer $customer): void
{
foreach (['email' => $customer->email, 'whatsapp' => $customer->whatsapp_number] as $type => $value) {
if (! $value) {
continue;
}
CustomerContact::where('customer_id', $customer->id)->where('type', $type)->where('value', '!=', $value)
->update(['is_primary' => false]);
CustomerContact::updateOrCreate(
['customer_id' => $customer->id, 'type' => $type, 'value' => $value],
[
'tenant_id' => $customer->tenant_id,
'label' => 'Kontak utama',
'is_primary' => true,
'can_receive_transactional' => true,
'can_receive_broadcast' => true,
],
);
}
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Services\Notification\Adapters;
use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class EmailAdapter implements NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array
{
$config = $delivery->channelConfig;
$credentials = $config?->credentials ?? [];
$settings = $config?->settings ?? [];
if (! $delivery->destination || empty($settings['host'])) {
throw ValidationException::withMessages(['channel' => 'Alamat penerima atau konfigurasi SMTP belum lengkap.']);
}
$original = Config::get('mail.mailers.smtp');
$originalFrom = Config::get('mail.from');
try {
Config::set('mail.mailers.smtp', [
'transport' => 'smtp',
'host' => $settings['host'],
'port' => $settings['port'] ?? 587,
'encryption' => $settings['encryption'] ?? 'tls',
'username' => $credentials['username'] ?? null,
'password' => $credentials['password'] ?? null,
'timeout' => 30,
]);
Config::set('mail.from', [
'address' => $settings['from_address'],
'name' => $settings['from_name'] ?? null,
]);
Mail::purge('smtp');
Mail::raw($delivery->rendered_body, function ($mail) use ($delivery) {
$mail->to($delivery->destination)->subject($delivery->rendered_subject ?: 'Notifikasi');
});
} finally {
Config::set('mail.mailers.smtp', $original);
Config::set('mail.from', $originalFrom);
Mail::purge('smtp');
}
return ['provider_message_id' => (string) Str::uuid(), 'response' => ['accepted' => true]];
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Services\Notification\Adapters;
use App\Models\NotificationChannel;
use App\Models\NotificationDelivery;
use App\Models\User;
use App\Models\UserNotification;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class SystemAdapter implements NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array
{
$message = $delivery->message;
$user = $message->recipient instanceof User
? $message->recipient
: ($message->recipient?->user ?? null);
if (! $user) {
throw ValidationException::withMessages(['recipient' => 'Penerima tidak memiliki akun aplikasi.']);
}
$notification = UserNotification::create([
'uuid' => Str::uuid(),
'tenant_id' => $message->tenant_id,
'user_id' => $user->id,
'notification_message_id' => $message->id,
'title' => $delivery->rendered_subject ?: 'Notifikasi',
'body' => $delivery->rendered_body,
'action_url' => data_get($message->context, 'action_url'),
'icon' => data_get($message->context, 'icon', 'cil-bell'),
]);
$settings = NotificationChannel::where('tenant_id', $message->tenant_id)
->where('channel', 'system')->where('enabled', true)->where('is_default', true)
->first()?->settings ?? [];
$maximum = max(20, (int) ($settings['maximum_notifications_per_user'] ?? 500));
UserNotification::where('user_id', $user->id)
->whereNotIn('id', UserNotification::where('user_id', $user->id)->latest('id')->limit($maximum)->pluck('id'))
->delete();
return ['provider_message_id' => $notification->uuid, 'response' => ['stored' => true]];
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Services\Notification\Adapters;
use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
class TelegramAdapter implements NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array
{
$token = data_get($delivery->channelConfig?->credentials, 'bot_token');
if (! $token) {
throw ValidationException::withMessages(['channel' => 'Bot token Telegram belum diatur.']);
}
$response = Http::timeout(30)->post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $delivery->destination,
'text' => $delivery->rendered_body,
'parse_mode' => data_get($delivery->channelConfig?->settings, 'parse_mode'),
])->throw()->json();
return ['provider_message_id' => (string) data_get($response, 'result.message_id'), 'response' => $response];
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Services\Notification\Adapters;
use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
class WhatsAppOfficialAdapter implements NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array
{
$config = $delivery->channelConfig;
$credentials = $config?->credentials ?? [];
$settings = $config?->settings ?? [];
$phoneId = $credentials['phone_number_id'] ?? null;
$token = $credentials['access_token'] ?? null;
$templateName = data_get($delivery->provider_response, 'request_context.provider_template_name');
if (! $phoneId || ! $token || ! $templateName) {
throw ValidationException::withMessages(['channel' => 'Phone Number ID, access token, dan template WhatsApp Official wajib tersedia.']);
}
$baseUrl = rtrim($settings['base_url'] ?? 'https://graph.facebook.com/v22.0', '/');
$parameters = collect(data_get($delivery->provider_response, 'request_context.template_parameters', []))
->map(fn ($value) => ['type' => 'text', 'text' => (string) $value])->values()->all();
$response = Http::withToken($token)->timeout(30)->post("{$baseUrl}/{$phoneId}/messages", [
'messaging_product' => 'whatsapp',
'to' => $delivery->destination,
'type' => 'template',
'template' => [
'name' => $templateName,
'language' => ['code' => data_get($delivery->provider_response, 'request_context.language', 'id')],
'components' => $parameters ? [['type' => 'body', 'parameters' => $parameters]] : [],
],
])->throw()->json();
return ['provider_message_id' => data_get($response, 'messages.0.id'), 'response' => $response];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Services\Notification\Adapters;
use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
class WhatsAppUnofficialAdapter implements NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array
{
$config = $delivery->channelConfig;
$credentials = $config?->credentials ?? [];
$settings = $config?->settings ?? [];
$url = $settings['send_url'] ?? null;
if (! $url) {
throw ValidationException::withMessages(['channel' => 'URL pengiriman gateway unofficial belum diatur.']);
}
$headers = [];
if ($apiKey = $credentials['api_key'] ?? null) {
$headers[$settings['api_key_header'] ?? 'X-API-Key'] = $apiKey;
}
$payload = [
$settings['destination_field'] ?? 'number' => $delivery->destination,
$settings['message_field'] ?? 'message' => $delivery->rendered_body,
'instance_id' => $credentials['instance_id'] ?? null,
];
$response = Http::withHeaders($headers)->timeout(30)->post($url, $payload)->throw()->json();
return ['provider_message_id' => data_get($response, $settings['message_id_path'] ?? 'id'), 'response' => $response];
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Services\Notification\Contracts;
use App\Models\NotificationDelivery;
interface NotificationChannelAdapter
{
public function send(NotificationDelivery $delivery): array;
}
@@ -0,0 +1,294 @@
<?php
namespace App\Services\Notification;
use App\Jobs\ProcessNotificationDelivery;
use App\Models\Customer;
use App\Models\NotificationBroadcastRecipient;
use App\Models\NotificationChannel;
use App\Models\NotificationDelivery;
use App\Models\NotificationEvent;
use App\Models\NotificationEventOccurrence;
use App\Models\NotificationMessage;
use App\Models\NotificationPreference;
use App\Models\NotificationTemplate;
use App\Models\User;
use App\Services\Notification\Adapters\EmailAdapter;
use App\Services\Notification\Adapters\SystemAdapter;
use App\Services\Notification\Adapters\TelegramAdapter;
use App\Services\Notification\Adapters\WhatsAppOfficialAdapter;
use App\Services\Notification\Adapters\WhatsAppUnofficialAdapter;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class NotificationManager
{
public function emit(
string $eventCode,
Model $recipient,
Model $subject,
array $payload,
string $occurrenceKey,
array $context = [],
): ?NotificationMessage {
$event = NotificationEvent::where('code', $eventCode)->where('enabled', true)->first();
$tenantId = (int) ($recipient->tenant_id ?? $subject->tenant_id);
if (! $event || ! $tenantId) {
return null;
}
return DB::transaction(function () use ($event, $recipient, $subject, $payload, $occurrenceKey, $context, $tenantId) {
$occurrence = NotificationEventOccurrence::firstOrCreate([
'tenant_id' => $tenantId,
'notification_event_id' => $event->id,
'subjectable_type' => $subject->getMorphClass(),
'subjectable_id' => $subject->getKey(),
'occurrence_key' => $occurrenceKey,
]);
if (! $occurrence->wasRecentlyCreated) {
return null;
}
$preferences = NotificationPreference::with('channelConfig')
->where('tenant_id', $tenantId)
->where('notification_event_id', $event->id)
->where('enabled', true)
->orderBy('priority')
->get();
if ($preferences->isEmpty()) {
$occurrence->update(['processed_at' => now()]);
return null;
}
$message = NotificationMessage::create([
'uuid' => Str::uuid(),
'tenant_id' => $tenantId,
'notification_event_id' => $event->id,
'recipient_type' => $recipient->getMorphClass(),
'recipient_id' => $recipient->getKey(),
'subjectable_type' => $subject->getMorphClass(),
'subjectable_id' => $subject->getKey(),
'payload' => $payload,
'context' => $context,
'priority' => 5,
'status' => 'queued',
]);
foreach ($preferences as $preference) {
$template = $this->template($tenantId, $event->id, $preference->channel);
$channelConfig = $preference->channelConfig
?: NotificationChannel::where('tenant_id', $tenantId)->where('channel', $preference->channel)->where('enabled', true)->where('is_default', true)->first();
$destination = $this->destination($recipient, $preference->channel);
if (! $template || ($preference->channel !== 'system' && ! $channelConfig) || ! $destination) {
NotificationDelivery::create([
'uuid' => Str::uuid(),
'notification_message_id' => $message->id,
'notification_channel_id' => $channelConfig?->id,
'channel' => $preference->channel,
'destination' => $destination,
'rendered_subject' => $template?->subject,
'rendered_body' => $template?->body ?? '',
'status' => 'skipped',
'error_message' => 'Template, channel, atau tujuan penerima belum tersedia.',
]);
continue;
}
$delivery = NotificationDelivery::create([
'uuid' => Str::uuid(),
'notification_message_id' => $message->id,
'notification_channel_id' => $channelConfig?->id,
'channel' => $preference->channel,
'destination' => $destination,
'rendered_subject' => $this->render($template->subject, $payload),
'rendered_body' => $this->render($template->body, $payload),
'status' => 'queued',
'queued_at' => now(),
'provider_response' => [
'request_context' => [
'provider_template_name' => $template->provider_template_name,
'language' => $template->language,
'template_parameters' => collect($template->variables ?? [])->map(fn ($key) => data_get($payload, $key))->values()->all(),
],
],
]);
$scheduledAt = $this->scheduledAt($preference);
$message->update([
'notification_template_id' => $message->notification_template_id ?: $template->id,
'scheduled_at' => $scheduledAt,
]);
ProcessNotificationDelivery::dispatch($delivery->id)
->delay($scheduledAt)
->onQueue('notifications-'.$this->queueName($preference->channel))
->afterCommit();
}
$occurrence->update(['processed_at' => now()]);
return $message->load('deliveries');
});
}
public function deliver(NotificationDelivery $delivery): void
{
$delivery->load(['message.recipient', 'channelConfig']);
$delivery->update(['status' => 'processing', 'attempt_count' => $delivery->attempt_count + 1]);
try {
$result = $this->adapter($delivery->channel)->send($delivery);
$delivery->update([
'status' => $delivery->channel === 'system' ? 'delivered' : 'sent',
'provider_message_id' => $result['provider_message_id'] ?? null,
'provider_response' => $result['response'] ?? null,
'sent_at' => now(),
'delivered_at' => $delivery->channel === 'system' ? now() : null,
'error_code' => null,
'error_message' => null,
]);
} catch (\Throwable $exception) {
$delivery->update([
'status' => 'failed',
'failed_at' => now(),
'next_retry_at' => now()->addMinutes(min(60, 2 ** $delivery->attempt_count)),
'error_code' => (string) $exception->getCode(),
'error_message' => Str::limit($exception->getMessage(), 2000),
]);
throw $exception;
} finally {
$this->refreshMessageStatus($delivery->message);
$this->refreshBroadcast($delivery->message);
}
}
public function render(?string $template, array $payload): ?string
{
if ($template === null) {
return null;
}
return preg_replace_callback(
'/{{\s*([a-zA-Z0-9_.]+)\s*}}/',
function ($matches) use ($payload) {
$value = data_get($payload, $matches[1]);
if ($value === null && $matches[1] === 'tenant.name') {
$value = data_get($payload, 'tenant.tenant_name');
}
return (string) ($value ?? '');
},
$template,
);
}
public function destination(Model $recipient, string $channel, bool $broadcast = false): ?string
{
if ($channel === 'system') {
return (string) ($recipient instanceof User ? $recipient->id : $recipient->user_id);
}
if (! $recipient instanceof Customer) {
return $channel === 'email' ? $recipient->email : null;
}
$type = match ($channel) {
'whatsapp_official', 'whatsapp_unofficial' => 'whatsapp',
'email' => 'email',
'telegram' => 'telegram',
};
$contact = $recipient->contacts()
->where('type', $type)
->whereNull('opted_out_at')
->when($broadcast, fn ($q) => $q->where('can_receive_broadcast', true))
->orderByDesc('is_primary')
->first();
if ($contact) {
return $contact->value;
}
return match ($channel) {
'whatsapp_official', 'whatsapp_unofficial' => $broadcast ? null : $recipient->whatsapp_number,
'email' => $broadcast ? null : $recipient->email,
default => null,
};
}
private function template(int $tenantId, int $eventId, string $channel): ?NotificationTemplate
{
return NotificationTemplate::where('notification_event_id', $eventId)
->where('channel', $channel)
->where('enabled', true)
->when($channel === 'whatsapp_official', fn ($q) => $q->where('approval_status', 'approved')->whereNotNull('provider_template_name'))
->where(fn ($q) => $q->where('tenant_id', $tenantId)->orWhereNull('tenant_id'))
->orderByRaw('tenant_id IS NULL')
->orderByDesc('version')
->first();
}
private function adapter(string $channel)
{
return match ($channel) {
'system' => app(SystemAdapter::class),
'whatsapp_official' => app(WhatsAppOfficialAdapter::class),
'whatsapp_unofficial' => app(WhatsAppUnofficialAdapter::class),
'email' => app(EmailAdapter::class),
'telegram' => app(TelegramAdapter::class),
};
}
private function queueName(string $channel): string
{
return str_starts_with($channel, 'whatsapp') ? 'whatsapp' : $channel;
}
private function scheduledAt(NotificationPreference $preference): Carbon
{
$scheduled = now()->addMinutes($preference->send_delay_minutes);
if (! $preference->quiet_hours_start || ! $preference->quiet_hours_end) {
return $scheduled;
}
$start = $scheduled->copy()->setTimeFromTimeString($preference->quiet_hours_start);
$end = $scheduled->copy()->setTimeFromTimeString($preference->quiet_hours_end);
if ($end->lte($start)) {
$end->addDay();
if ($scheduled->lt($start)) {
$start->subDay();
}
}
return $scheduled->between($start, $end) ? $end : $scheduled;
}
private function refreshMessageStatus(NotificationMessage $message): void
{
$statuses = $message->deliveries()->pluck('status');
$status = $statuses->contains(fn ($value) => in_array($value, ['queued', 'processing', 'pending'], true))
? 'processing'
: ($statuses->contains(fn ($value) => in_array($value, ['sent', 'delivered', 'read'], true)) ? 'sent' : 'failed');
$message->update(['status' => $status]);
}
private function refreshBroadcast(NotificationMessage $message): void
{
if (! $message->notification_broadcast_id) {
return;
}
$recipient = NotificationBroadcastRecipient::where('notification_message_id', $message->id)->first();
$messageStatus = $message->fresh()->status;
if ($recipient) {
$recipient->update([
'status' => $messageStatus === 'sent' ? 'sent' : ($messageStatus === 'failed' ? 'failed' : 'queued'),
]);
}
$broadcast = $message->broadcast;
if (! $broadcast) {
return;
}
$pending = $broadcast->recipients()->whereIn('status', ['pending', 'queued'])->count();
$broadcast->update([
'processed_recipients' => $broadcast->recipients()->count(),
'success_count' => $broadcast->recipients()->where('status', 'sent')->count(),
'failed_count' => $broadcast->recipients()->whereIn('status', ['failed', 'skipped'])->count(),
'status' => $pending === 0 ? 'completed' : 'processing',
]);
}
}
@@ -0,0 +1,395 @@
<?php
namespace App\Services\Notification;
use App\Jobs\ProcessBroadcast;
use App\Jobs\ProcessNotificationDelivery;
use App\Models\Customer;
use App\Models\CustomerContact;
use App\Models\NotificationBroadcast;
use App\Models\NotificationBroadcastRecipient;
use App\Models\NotificationChannel;
use App\Models\NotificationDelivery;
use App\Models\NotificationEvent;
use App\Models\NotificationMessage;
use App\Models\NotificationPreference;
use App\Models\NotificationTemplate;
use App\Models\TopologyLink;
use App\Models\User;
use App\Models\UserNotification;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class NotificationService
{
public function __construct(protected NotificationManager $manager) {}
public function channels(string $channel, User $actor, ?int $tenantId)
{
return NotificationChannel::with('tenant:id,tenant_code,tenant_name')
->where('channel', $channel)
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->orderByDesc('is_default')->orderBy('name')->get()
->each(fn ($item) => $item->setAttribute('credentials_configured', ! empty($item->getRawOriginal('credentials'))));
}
public function saveChannel(array $data, User $actor, ?int $tenantId, ?NotificationChannel $channel = null): NotificationChannel
{
$effectiveTenant = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $channel?->tenant_id ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
if ($channel && (int) $channel->tenant_id !== (int) $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Konfigurasi bukan milik tenant tersebut.']);
}
$credentials = array_filter($data['credentials'] ?? [], fn ($value) => $value !== '' && $value !== null);
if ($channel && $credentials) {
$credentials = [...($channel->credentials ?? []), ...$credentials];
}
if (($data['is_default'] ?? false) === true) {
NotificationChannel::where('tenant_id', $effectiveTenant)->where('channel', $data['channel'])
->when($channel, fn ($q) => $q->whereKeyNot($channel->id))
->update(['is_default' => false]);
}
$payload = [
...$data,
'tenant_id' => $effectiveTenant,
'provider' => $data['provider'] ?? $data['channel'],
'settings' => $data['settings'] ?? [],
];
if ($credentials) {
$payload['credentials'] = $credentials;
} else {
unset($payload['credentials']);
}
$channel ? $channel->update($payload) : $channel = NotificationChannel::create($payload);
return $channel->fresh('tenant:id,tenant_code,tenant_name')
->setAttribute('credentials_configured', ! empty($channel->getRawOriginal('credentials')));
}
public function templates(string $channel, User $actor, ?int $tenantId)
{
return NotificationTemplate::with(['event:id,code,name,category,variables', 'channelConfig:id,name'])
->where('channel', $channel)
->where(function ($q) use ($actor, $tenantId) {
$q->whereNull('tenant_id')
->when(! $actor->isMasterAdmin() || $tenantId, fn ($x) => $x->orWhere('tenant_id', $tenantId));
})
->orderBy('notification_event_id')->orderByDesc('tenant_id')->orderByDesc('version')->get();
}
public function saveTemplate(array $data, User $actor, ?int $tenantId, ?NotificationTemplate $template = null): NotificationTemplate
{
$effectiveTenant = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $template?->tenant_id ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih untuk membuat override template.']);
}
if ($template?->tenant_id === null) {
$template = null;
}
$variables = $this->extractVariables(($data['subject'] ?? '').' '.($data['body'] ?? ''));
$payload = [...$data, 'tenant_id' => $effectiveTenant, 'variables' => $variables];
if (! $template) {
$payload['version'] = ((int) NotificationTemplate::where('tenant_id', $effectiveTenant)
->where('notification_event_id', $data['notification_event_id'])
->where('channel', $data['channel'])->max('version')) + 1;
$template = NotificationTemplate::create($payload);
} else {
$template->update($payload);
}
return $template->fresh(['event:id,code,name,category,variables', 'channelConfig:id,name']);
}
public function preferences(User $actor, ?int $tenantId): array
{
$effectiveTenant = $actor->isMasterAdmin() ? $tenantId : $tenantId;
return [
'events' => NotificationEvent::where('enabled', true)->orderBy('category')->orderBy('name')->get(),
'preferences' => $effectiveTenant
? NotificationPreference::with(['event:id,code,name', 'channelConfig:id,name'])->where('tenant_id', $effectiveTenant)->get()
: [],
];
}
public function savePreferences(array $rows, User $actor, ?int $tenantId): void
{
DB::transaction(function () use ($rows, $actor, $tenantId) {
foreach ($rows as $row) {
$effectiveTenant = $actor->isMasterAdmin() ? ($row['tenant_id'] ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
if (! empty($row['notification_channel_id']) && ! NotificationChannel::whereKey($row['notification_channel_id'])
->where('tenant_id', $effectiveTenant)->where('channel', $row['channel'])->exists()) {
throw ValidationException::withMessages(['notification_channel_id' => 'Konfigurasi channel bukan milik tenant atau channel tersebut.']);
}
NotificationPreference::updateOrCreate(
[
'tenant_id' => $effectiveTenant,
'notification_event_id' => $row['notification_event_id'],
'channel' => $row['channel'],
],
[
'notification_channel_id' => $row['notification_channel_id'] ?? null,
'enabled' => $row['enabled'] ?? false,
'priority' => $row['priority'] ?? 1,
'send_delay_minutes' => $row['send_delay_minutes'] ?? 0,
'quiet_hours_start' => $row['quiet_hours_start'] ?? null,
'quiet_hours_end' => $row['quiet_hours_end'] ?? null,
],
);
}
});
}
public function deliveries(string $channel, array $filters, User $actor, ?int $tenantId)
{
return NotificationDelivery::with(['message:id,tenant_id,uuid,notification_event_id,recipient_type,recipient_id,created_at', 'message.event:id,code,name', 'channelConfig:id,name'])
->where('channel', $channel)
->whereHas('message', fn ($q) => $q
->when(! $actor->isMasterAdmin(), fn ($x) => $x->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($x) => $x->where('tenant_id', $tenantId)))
->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
->when(! empty($filters['search']), fn ($q) => $q->where(fn ($x) => $x->where('destination', 'ILIKE', "%{$filters['search']}%")->orWhere('rendered_body', 'ILIKE', "%{$filters['search']}%")))
->orderByDesc('id')->paginate($filters['per_page'] ?? 10);
}
public function testChannel(NotificationChannel $channel): NotificationChannel
{
try {
$credentials = $channel->credentials ?? [];
$settings = $channel->settings ?? [];
$message = match ($channel->channel) {
'system' => 'Penyimpanan notifikasi aplikasi siap.',
'telegram' => data_get(Http::timeout(15)->get('https://api.telegram.org/bot'.$credentials['bot_token'].'/getMe')->throw()->json(), 'result.username', 'Bot Telegram terhubung.'),
'whatsapp_official' => data_get(Http::withToken($credentials['access_token'])->timeout(15)->get(rtrim($settings['base_url'] ?? 'https://graph.facebook.com/v22.0', '/').'/'.$credentials['phone_number_id'])->throw()->json(), 'display_phone_number', 'WhatsApp Official terhubung.'),
'whatsapp_unofficial' => data_get(Http::withHeaders(isset($credentials['api_key']) ? [($settings['api_key_header'] ?? 'X-API-Key') => $credentials['api_key']] : [])->timeout(15)->get($settings['health_url'])->throw()->json(), 'status', 'Gateway terhubung.'),
'email' => ! empty($settings['host']) && ! empty($settings['from_address']) ? 'Konfigurasi SMTP lengkap.' : throw new \RuntimeException('Host dan alamat pengirim SMTP wajib diisi.'),
};
$channel->update(['last_health_status' => 'healthy', 'last_health_message' => (string) $message, 'last_health_check_at' => now()]);
} catch (\Throwable $exception) {
$channel->update(['last_health_status' => 'unhealthy', 'last_health_message' => Str::limit($exception->getMessage(), 1000), 'last_health_check_at' => now()]);
}
return $channel->fresh();
}
public function broadcasts(array $filters, User $actor, ?int $tenantId)
{
return NotificationBroadcast::with(['tenant:id,tenant_code,tenant_name', 'template:id,name', 'channelConfig:id,name'])
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
->when(! empty($filters['search']), fn ($q) => $q->where('name', 'ILIKE', "%{$filters['search']}%"))
->orderByDesc('id')->paginate($filters['per_page'] ?? 10);
}
public function previewBroadcast(array $data, User $actor, ?int $tenantId): array
{
$effectiveTenant = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
$query = $this->recipientQuery($effectiveTenant, $data['filters'] ?? []);
$estimated = (clone $query)->count();
$sample = $query->limit(10)->get(['id', 'customer_code', 'name', 'email', 'whatsapp_number']);
return ['estimated_recipients' => $estimated, 'sample' => $sample];
}
public function createBroadcast(array $data, User $actor, ?int $tenantId): NotificationBroadcast
{
$effectiveTenant = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
$channelConfig = NotificationChannel::whereKey($data['notification_channel_id'] ?? null)
->where('tenant_id', $effectiveTenant)->where('channel', $data['channel'])->where('enabled', true)->first();
if ($data['channel'] !== 'system' && ! $channelConfig) {
throw ValidationException::withMessages(['notification_channel_id' => 'Konfigurasi channel aktif wajib dipilih.']);
}
$template = null;
if (! empty($data['notification_template_id'])) {
$template = NotificationTemplate::whereKey($data['notification_template_id'])
->where('channel', $data['channel'])
->where('enabled', true)
->where(fn ($q) => $q->whereNull('tenant_id')->orWhere('tenant_id', $effectiveTenant))
->first();
if (! $template) {
throw ValidationException::withMessages(['notification_template_id' => 'Template tidak tersedia untuk tenant dan channel ini.']);
}
}
if ($data['channel'] === 'whatsapp_official'
&& (! $template || $template->approval_status !== 'approved' || ! $template->provider_template_name)) {
throw ValidationException::withMessages(['notification_template_id' => 'WhatsApp Official wajib memakai template provider berstatus approved.']);
}
$estimated = $this->recipientQuery($effectiveTenant, $data['filters'] ?? [])->count();
$filters = $data['filters'] ?? [];
unset($data['filters']);
$requiresApproval = $estimated >= 1000;
$broadcast = NotificationBroadcast::create([
...$data,
'uuid' => Str::uuid(),
'tenant_id' => $effectiveTenant,
'filter_snapshot' => $filters,
'estimated_recipients' => $estimated,
'status' => $requiresApproval
? 'pending_approval'
: (! empty($data['scheduled_at']) && now()->lt($data['scheduled_at']) ? 'scheduled' : 'queued'),
'created_by' => $actor->id,
]);
if (! $requiresApproval) {
$this->dispatchBroadcast($broadcast);
}
return $broadcast->load(['tenant:id,tenant_code,tenant_name', 'template:id,name', 'channelConfig:id,name']);
}
public function approveBroadcast(NotificationBroadcast $broadcast, User $actor): NotificationBroadcast
{
if ($broadcast->status !== 'pending_approval') {
throw ValidationException::withMessages(['broadcast' => 'Siaran ini tidak sedang menunggu persetujuan.']);
}
$broadcast->update([
'approved_by' => $actor->id,
'status' => $broadcast->scheduled_at?->isFuture() ? 'scheduled' : 'queued',
]);
$this->dispatchBroadcast($broadcast);
return $broadcast->fresh(['tenant:id,tenant_code,tenant_name', 'template:id,name', 'channelConfig:id,name']);
}
public function processBroadcast(NotificationBroadcast $broadcast): void
{
if (in_array($broadcast->status, ['processing', 'completed', 'cancelled'], true)) {
return;
}
$broadcast->update(['status' => 'processing']);
$template = $broadcast->template;
$channelConfig = $broadcast->channelConfig;
$this->recipientQuery($broadcast->tenant_id, $broadcast->filter_snapshot)
->with('contacts')
->chunkById(200, function ($customers) use ($broadcast, $template, $channelConfig) {
foreach ($customers as $customer) {
$destination = $this->manager->destination($customer, $broadcast->channel, true);
$recipient = NotificationBroadcastRecipient::firstOrCreate(
['notification_broadcast_id' => $broadcast->id, 'customer_id' => $customer->id],
['destination' => $destination, 'status' => $destination ? 'pending' : 'skipped', 'reason' => $destination ? null : 'Kontak broadcast tidak tersedia.'],
);
if (! $destination || $recipient->notification_message_id) {
continue;
}
$payload = ['customer' => $customer->toArray(), 'tenant' => $broadcast->tenant->toArray()];
$body = $this->manager->render($template?->body ?? $broadcast->body, $payload);
$subject = $this->manager->render($template?->subject ?? $broadcast->subject, $payload);
$message = NotificationMessage::create([
'uuid' => Str::uuid(), 'tenant_id' => $broadcast->tenant_id,
'notification_template_id' => $template?->id, 'notification_broadcast_id' => $broadcast->id,
'recipient_type' => $customer->getMorphClass(), 'recipient_id' => $customer->id,
'subject' => $subject, 'payload' => $payload, 'status' => 'queued', 'scheduled_at' => now(),
'context' => ['provider_template_name' => $template?->provider_template_name, 'language' => $template?->language],
]);
$delivery = NotificationDelivery::create([
'uuid' => Str::uuid(), 'notification_message_id' => $message->id,
'notification_channel_id' => $channelConfig?->id, 'channel' => $broadcast->channel,
'destination' => $destination, 'rendered_subject' => $subject, 'rendered_body' => $body,
'status' => 'queued', 'queued_at' => now(),
'provider_response' => ['request_context' => [
'provider_template_name' => $template?->provider_template_name,
'language' => $template?->language,
'template_parameters' => collect($template?->variables ?? [])->map(fn ($key) => data_get($payload, $key))->values()->all(),
]],
]);
$recipient->update(['notification_message_id' => $message->id, 'status' => 'queued']);
$queue = str_starts_with($broadcast->channel, 'whatsapp') ? 'whatsapp' : $broadcast->channel;
ProcessNotificationDelivery::dispatch($delivery->id)->onQueue('notifications-'.$queue);
}
});
$pending = $broadcast->recipients()->whereIn('status', ['pending', 'queued'])->count();
$broadcast->update([
'status' => $pending === 0 ? 'completed' : 'processing',
'processed_recipients' => $broadcast->recipients()->count(),
'success_count' => $broadcast->recipients()->where('status', 'sent')->count(),
'failed_count' => $broadcast->recipients()->whereIn('status', ['failed', 'skipped'])->count(),
]);
}
public function userNotifications(User $user, array $filters)
{
return UserNotification::where('user_id', $user->id)
->when(($filters['unread'] ?? false), fn ($q) => $q->whereNull('read_at'))
->orderByDesc('id')->paginate($filters['per_page'] ?? 20);
}
public function saveContact(Customer $customer, array $data, ?CustomerContact $contact = null): CustomerContact
{
if ($contact && (int) $contact->customer_id !== (int) $customer->id) {
throw ValidationException::withMessages(['contact' => 'Kontak bukan milik customer tersebut.']);
}
if (($data['is_primary'] ?? false) === true) {
$customer->contacts()->where('type', $data['type'])->when($contact, fn ($q) => $q->whereKeyNot($contact->id))
->update(['is_primary' => false]);
}
$data = [...$data, 'tenant_id' => $customer->tenant_id];
if (($data['is_verified'] ?? false) && ! $contact?->verified_at) {
$data['verified_at'] = now();
}
$contact ? $contact->update($data) : $contact = $customer->contacts()->create($data);
return $contact->fresh();
}
private function recipientQuery(int $tenantId, array $filters): Builder
{
$query = Customer::query()->where('tenant_id', $tenantId)->whereNull('deleted_at');
$query->when(! empty($filters['customer_status']), fn ($q) => $q->whereIn('status', (array) $filters['customer_status']))
->when(! empty($filters['source']), fn ($q) => $q->where('source', $filters['source']))
->when(! empty($filters['package_profile_id']), fn ($q) => $q->where('package_profile_id', $filters['package_profile_id']))
->when(! empty($filters['billing_profile_id']), fn ($q) => $q->where('billing_profile_id', $filters['billing_profile_id']))
->when(! empty($filters['provinsi_id']), fn ($q) => $q->where('provinsi_id', $filters['provinsi_id']))
->when(! empty($filters['kabupaten_id']), fn ($q) => $q->where('kabupaten_id', $filters['kabupaten_id']))
->when(! empty($filters['kecamatan_id']), fn ($q) => $q->where('kecamatan_id', $filters['kecamatan_id']))
->when(! empty($filters['desa_id']), fn ($q) => $q->where('desa_id', $filters['desa_id']));
if (! empty($filters['topology_node_id'])) {
$nodeIds = $this->downstreamNodeIds((int) $filters['topology_node_id'], $tenantId);
$query->whereHas('activeTopologyConnection', fn ($q) => $q->whereIn('odp_node_id', $nodeIds));
}
return $query;
}
private function downstreamNodeIds(int $rootId, int $tenantId): array
{
$ids = [$rootId];
$frontier = [$rootId];
while ($frontier && count($ids) < 10000) {
$frontier = TopologyLink::where('tenant_id', $tenantId)->whereIn('source_node_id', $frontier)
->pluck('target_node_id')->diff($ids)->values()->all();
$ids = [...$ids, ...$frontier];
}
return array_values(array_unique($ids));
}
private function extractVariables(string $value): array
{
preg_match_all('/{{\s*([a-zA-Z0-9_.]+)\s*}}/', $value, $matches);
return array_values(array_unique($matches[1]));
}
private function dispatchBroadcast(NotificationBroadcast $broadcast): void
{
ProcessBroadcast::dispatch($broadcast->id)
->delay($broadcast->scheduled_at)
->onQueue('notifications-broadcast')
->afterCommit();
}
}
@@ -0,0 +1,138 @@
<?php
namespace App\Services\Payment;
use App\Models\PaymentGatewayAccount;
use App\Models\PaymentProvider;
use App\Models\PaymentTransaction;
use App\Models\TenantPaymentSetting;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class PaymentGatewayService
{
public function providers()
{
return PaymentProvider::where('enabled', true)->orderBy('name')->get();
}
public function settings(User $actor, ?int $tenantId): array
{
$accounts = PaymentGatewayAccount::with('provider:id,code,name,scope,capabilities,credential_schema')
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where(fn ($x) => $x->where('tenant_id', $tenantId)->orWhere('scope', 'platform')))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where(fn ($x) => $x->where('tenant_id', $tenantId)->orWhere('scope', 'platform')))
->orderBy('scope')->orderBy('name')->get()
->map(fn ($account) => $this->maskedAccount($account));
$setting = $tenantId ? TenantPaymentSetting::with(['tenantGateway.provider', 'platformGateway.provider'])->firstOrCreate(
['tenant_id' => $tenantId],
['payment_mode' => 'disabled', 'fee_bearer' => 'customer', 'default_expiry_minutes' => 1440]
) : null;
return compact('accounts', 'setting');
}
public function saveAccount(array $data, User $actor, ?int $tenantId, ?PaymentGatewayAccount $account = null): PaymentGatewayAccount
{
$scope = $data['scope'];
if ($scope === 'platform' && ! $actor->isMasterAdmin()) {
abort(403, 'Hanya Master Admin yang dapat mengelola gateway platform.');
}
$effectiveTenant = $scope === 'platform' ? null : ($actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId);
if ($scope === 'tenant' && ! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
if ($account && ($account->scope !== $scope || ($scope === 'tenant' && (int) $account->tenant_id !== (int) $effectiveTenant))) {
abort(403);
}
return DB::transaction(function () use ($data, $account, $scope, $effectiveTenant) {
if (($data['enabled'] ?? false) && $scope === 'tenant') {
PaymentGatewayAccount::where('tenant_id', $effectiveTenant)->where('scope', 'tenant')
->when($account, fn ($q) => $q->whereKeyNot($account->id))->update(['enabled' => false, 'is_default' => false]);
}
if (($data['is_default'] ?? false) && $scope === 'platform') {
PaymentGatewayAccount::where('scope', 'platform')
->when($account, fn ($q) => $q->whereKeyNot($account->id))->update(['is_default' => false]);
}
$payload = [
'uuid' => $account?->uuid ?? Str::uuid(),
'payment_provider_id' => $data['payment_provider_id'],
'tenant_id' => $effectiveTenant,
'scope' => $scope,
'name' => $data['name'],
'environment' => $data['environment'],
'settings' => $data['settings'] ?? [],
'enabled' => $data['enabled'] ?? false,
'is_default' => $data['is_default'] ?? false,
];
if (! empty($data['credentials'])) {
$payload['credentials'] = $data['credentials'];
}
if (filled($data['webhook_secret'] ?? null)) {
$payload['webhook_secret'] = $data['webhook_secret'];
}
$model = $account ?: new PaymentGatewayAccount;
$model->fill($payload)->save();
return $model->load('provider');
});
}
public function saveTenantSetting(array $data, User $actor, ?int $tenantId): TenantPaymentSetting
{
$effectiveTenant = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $effectiveTenant) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
if ($data['payment_mode'] === 'tenant_gateway') {
$valid = PaymentGatewayAccount::whereKey($data['tenant_gateway_account_id'] ?? 0)
->where('tenant_id', $effectiveTenant)->where('scope', 'tenant')->where('enabled', true)->exists();
if (! $valid) {
throw ValidationException::withMessages(['tenant_gateway_account_id' => 'Gateway tenant aktif tidak valid.']);
}
}
if ($data['payment_mode'] === 'platform_gateway') {
$valid = PaymentGatewayAccount::whereKey($data['platform_gateway_account_id'] ?? 0)
->whereNull('tenant_id')->where('scope', 'platform')->where('enabled', true)->exists();
if (! $valid) {
throw ValidationException::withMessages(['platform_gateway_account_id' => 'Gateway platform aktif tidak valid.']);
}
}
return TenantPaymentSetting::updateOrCreate(['tenant_id' => $effectiveTenant], [
...$data,
'tenant_id' => $effectiveTenant,
'tenant_gateway_account_id' => $data['payment_mode'] === 'tenant_gateway' ? $data['tenant_gateway_account_id'] : null,
'platform_gateway_account_id' => $data['payment_mode'] === 'platform_gateway' ? $data['platform_gateway_account_id'] : null,
])->load(['tenantGateway.provider', 'platformGateway.provider']);
}
public function transactions(array $filters, User $actor, ?int $tenantId)
{
return PaymentTransaction::with(['tenant:id,tenant_name', 'user:id,name', 'customer:id,name,customer_code', 'invoice:id,invoice_number', 'account.provider:id,code,name'])
->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId))
->when($filters['search'] ?? null, fn ($q, $search) => $q->where(fn ($x) => $x->where('transaction_number', 'ilike', "%{$search}%")->orWhere('provider_reference', 'ilike', "%{$search}%")))
->when($filters['status'] ?? null, fn ($q, $value) => $q->where('status', $value))
->when($filters['provider_code'] ?? null, fn ($q, $value) => $q->where('provider_code', $value))
->when($filters['purpose'] ?? null, fn ($q, $value) => $q->where('purpose', $value))
->when($filters['date_from'] ?? null, fn ($q, $value) => $q->whereDate('created_at', '>=', $value))
->when($filters['date_to'] ?? null, fn ($q, $value) => $q->whereDate('created_at', '<=', $value))
->orderBy($filters['sort_by'] ?? 'id', $filters['sort_direction'] ?? 'desc')
->paginate($filters['per_page'] ?? 10);
}
private function maskedAccount(PaymentGatewayAccount $account): PaymentGatewayAccount
{
$account->setAttribute('has_credentials', ! empty($account->getRawOriginal('credentials')));
$account->setAttribute('has_webhook_secret', ! empty($account->getRawOriginal('webhook_secret')));
return $account;
}
}
+421
View File
@@ -0,0 +1,421 @@
<?php
namespace App\Services\Topology;
use App\Models\Customer;
use App\Models\TopologyConnectionRule;
use App\Models\TopologyCustomerConnection;
use App\Models\TopologyDeviceType;
use App\Models\TopologyLink;
use App\Models\TopologyNode;
use App\Models\TopologyPort;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class TopologyService
{
private const RELATIONS = [
'device-type' => [],
'node' => ['tenant:id,tenant_code,tenant_name', 'deviceType:id,tenant_id,code,name,category,color,icon', 'parent:id,code,name'],
'link' => ['tenant:id,tenant_code,tenant_name', 'sourceNode.deviceType:id,code,name,color', 'targetNode.deviceType:id,code,name,color', 'sourcePort:id,node_id,name,port_number', 'targetPort:id,node_id,name,port_number'],
];
public function list(string $resource, array $filters, User $actor, ?int $tenantId)
{
$query = $this->model($resource)::query()->with(self::RELATIONS[$resource]);
$this->scopeTenant($query, $resource, $actor, $tenantId);
$sortable = [
'device-type' => ['id', 'code', 'name', 'category', 'status', 'created_at'],
'node' => ['id', 'code', 'name', 'status', 'installed_at', 'created_at'],
'link' => ['id', 'code', 'name', 'link_type', 'status', 'installed_at', 'created_at'],
][$resource];
$sortBy = in_array($filters['sort_by'] ?? null, $sortable, true) ? $filters['sort_by'] : 'id';
return $query
->when(! empty($filters['status']), fn ($q) => $q->where('status', $filters['status']))
->when(! empty($filters['device_type_id']) && $resource === 'node', fn ($q) => $q->where('device_type_id', $filters['device_type_id']))
->when(! empty($filters['link_type']) && $resource === 'link', fn ($q) => $q->where('link_type', $filters['link_type']))
->when(! empty($filters['search']), fn ($q) => $q->where(function ($search) use ($filters) {
$term = "%{$filters['search']}%";
$search->where('code', 'ILIKE', $term)->orWhere('name', 'ILIKE', $term);
}))
->orderBy($sortBy, $filters['sort_direction'] ?? 'desc')
->paginate($filters['per_page'] ?? 10);
}
public function find(string $resource, int $id): Model
{
$relations = self::RELATIONS[$resource];
if ($resource === 'node') {
$relations = [...$relations, 'ports'];
}
return $this->model($resource)::with($relations)->findOrFail($id);
}
public function create(string $resource, array $data, User $actor, ?int $tenantId): Model
{
return DB::transaction(function () use ($resource, $data, $actor, $tenantId) {
$data = $this->prepare($resource, $data, $actor, $tenantId);
$model = $this->model($resource)::create($data);
return $this->find($resource, $model->id);
});
}
public function update(string $resource, Model $model, array $data, User $actor): Model
{
return DB::transaction(function () use ($resource, $model, $data, $actor) {
if (! $actor->isMasterAdmin()) {
unset($data['tenant_id']);
}
$data['tenant_id'] ??= $model->tenant_id;
$data = $this->prepare($resource, $data, $actor, $model->tenant_id, $model);
$model->update($data);
return $this->find($resource, $model->id);
});
}
public function delete(string $resource, Model $model): void
{
if ($resource === 'device-type' && ($model->is_system || $model->nodes()->exists())) {
throw ValidationException::withMessages(['device_type' => 'Kategori sistem atau kategori yang digunakan tidak dapat dihapus.']);
}
if ($resource === 'node' && ($model->incomingLinks()->exists() || $model->outgoingLinks()->exists())) {
throw ValidationException::withMessages(['node' => 'Perangkat masih terhubung dengan jalur jaringan.']);
}
if ($resource === 'node' && TopologyCustomerConnection::where('odp_node_id', $model->id)->where('status', 'active')->exists()) {
throw ValidationException::withMessages(['node' => 'Perangkat masih melayani customer aktif.']);
}
$model->delete();
}
public function options(User $actor, ?int $tenantId): array
{
$types = TopologyDeviceType::query();
$nodes = TopologyNode::query()->with('deviceType:id,code,name,color');
$this->scopeTenant($types, 'device-type', $actor, $tenantId);
$this->scopeTenant($nodes, 'node', $actor, $tenantId);
return [
'device_types' => $types->where('status', 'active')->orderBy('name')->get(),
'nodes' => $nodes->where('status', 'active')->orderBy('name')->get(),
];
}
public function ports(TopologyNode $node): Collection
{
return $node->ports()->get();
}
public function createPort(TopologyNode $node, array $data): TopologyPort
{
if (! $node->deviceType->can_have_ports) {
throw ValidationException::withMessages(['node_id' => 'Kategori perangkat ini tidak mendukung port.']);
}
return $node->ports()->create([...$data, 'tenant_id' => $node->tenant_id]);
}
public function updatePort(TopologyPort $port, array $data): TopologyPort
{
$port->update($data);
return $port->fresh();
}
public function deletePort(TopologyPort $port): void
{
if (TopologyLink::where('source_port_id', $port->id)->orWhere('target_port_id', $port->id)->exists()) {
throw ValidationException::withMessages(['port' => 'Port masih digunakan oleh jalur jaringan.']);
}
$port->delete();
}
public function map(array $filters, User $actor, ?int $tenantId): array
{
$nodes = TopologyNode::query()->with('deviceType:id,code,name,color,icon');
$links = TopologyLink::query()->with(['sourceNode:id,latitude,longitude', 'targetNode:id,latitude,longitude']);
$this->scopeTenant($nodes, 'node', $actor, $tenantId);
$this->scopeTenant($links, 'link', $actor, $tenantId);
if (! empty($filters['bbox'])) {
[$minLng, $minLat, $maxLng, $maxLat] = array_map('floatval', explode(',', $filters['bbox']));
$nodes->whereBetween('longitude', [$minLng, $maxLng])->whereBetween('latitude', [$minLat, $maxLat]);
$links->where(function ($query) use ($minLng, $minLat, $maxLng, $maxLat) {
$query->whereHas('sourceNode', fn ($q) => $q->whereBetween('longitude', [$minLng, $maxLng])->whereBetween('latitude', [$minLat, $maxLat]))
->orWhereHas('targetNode', fn ($q) => $q->whereBetween('longitude', [$minLng, $maxLng])->whereBetween('latitude', [$minLat, $maxLat]));
});
}
$nodeRows = $nodes->where('status', '!=', 'inactive')->get();
$linkRows = $links->where('status', '!=', 'inactive')->get();
return [
'nodes' => [
'type' => 'FeatureCollection',
'features' => $nodeRows->map(fn ($node) => [
'type' => 'Feature',
'id' => $node->id,
'geometry' => ['type' => 'Point', 'coordinates' => [(float) $node->longitude, (float) $node->latitude]],
'properties' => [
'id' => $node->id,
'code' => $node->code,
'name' => $node->name,
'status' => $node->status,
'device_type' => $node->deviceType?->code,
'color' => $node->deviceType?->color ?? '#2f74c0',
],
])->values(),
],
'links' => [
'type' => 'FeatureCollection',
'features' => $linkRows->map(function ($link) {
$geometry = $link->path_geojson ?: [
'type' => 'LineString',
'coordinates' => [
[(float) $link->sourceNode->longitude, (float) $link->sourceNode->latitude],
[(float) $link->targetNode->longitude, (float) $link->targetNode->latitude],
],
];
return [
'type' => 'Feature',
'id' => $link->id,
'geometry' => $geometry,
'properties' => [
'id' => $link->id,
'code' => $link->code,
'name' => $link->name,
'status' => $link->status,
'link_type' => $link->link_type,
'core_count' => $link->core_count,
],
];
})->values(),
],
];
}
public function trace(TopologyNode $node, string $direction): array
{
$visited = [];
$levels = [[$node->id]];
while ($levels[count($levels) - 1] && count($levels) <= 100) {
$ids = $levels[count($levels) - 1];
$visited = [...$visited, ...$ids];
$column = $direction === 'upstream' ? 'target_node_id' : 'source_node_id';
$select = $direction === 'upstream' ? 'source_node_id' : 'target_node_id';
$next = TopologyLink::where('tenant_id', $node->tenant_id)
->whereIn($column, $ids)
->where('status', 'active')
->pluck($select)
->reject(fn ($id) => in_array($id, $visited))
->unique()
->values()
->all();
if (! $next) {
break;
}
$levels[] = $next;
}
$nodes = TopologyNode::with('deviceType:id,code,name,color')
->whereIn('id', collect($levels)->flatten()->unique())
->get()->keyBy('id');
return collect($levels)->map(fn ($ids, $level) => [
'level' => $level,
'nodes' => collect($ids)->map(fn ($id) => $nodes->get($id))->filter()->values(),
])->all();
}
public function connectCustomer(array $data, User $actor, ?int $tenantId): TopologyCustomerConnection
{
$customer = Customer::findOrFail($data['customer_id']);
$node = TopologyNode::with('deviceType')->findOrFail($data['odp_node_id']);
$effectiveTenant = $actor->isMasterAdmin() ? $customer->tenant_id : $tenantId;
if ((int) $customer->tenant_id !== (int) $effectiveTenant || (int) $node->tenant_id !== (int) $effectiveTenant || $node->deviceType?->code !== 'ODP') {
throw ValidationException::withMessages(['odp_node_id' => 'Customer dan ODP harus berasal dari tenant yang sama dan perangkat harus bertipe ODP.']);
}
if (! empty($data['odp_port_id']) && ! TopologyPort::whereKey($data['odp_port_id'])->where('node_id', $node->id)->exists()) {
throw ValidationException::withMessages(['odp_port_id' => 'Port bukan milik ODP yang dipilih.']);
}
TopologyCustomerConnection::where('customer_id', $customer->id)->where('status', 'active')
->update(['status' => 'inactive', 'disconnected_at' => now()]);
$customer->update(['topology_id' => $node->id]);
return TopologyCustomerConnection::create([
...$data,
'tenant_id' => $effectiveTenant,
'connected_at' => $data['connected_at'] ?? now(),
'status' => 'active',
])->load(['customer:id,customer_code,name', 'odpNode:id,code,name', 'odpPort:id,name,port_number']);
}
public function customerPath(Customer $customer): array
{
$connection = TopologyCustomerConnection::with(['odpNode.deviceType', 'odpPort'])
->where('customer_id', $customer->id)
->where('status', 'active')
->first();
if (! $connection) {
throw ValidationException::withMessages(['customer_id' => 'Customer belum terhubung ke ODP.']);
}
return [
'customer' => $customer->only(['id', 'customer_code', 'name']),
'connection' => $connection,
'path' => $this->trace($connection->odpNode, 'upstream'),
];
}
private function prepare(string $resource, array $data, User $actor, ?int $tenantId, ?Model $existing = null): array
{
if ($resource === 'device-type') {
$data['tenant_id'] = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? null) : $tenantId;
$data['is_system'] = $existing?->is_system ?? false;
return $data;
}
$data['tenant_id'] = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
if (! $data['tenant_id']) {
throw ValidationException::withMessages(['tenant_id' => 'Tenant wajib dipilih.']);
}
if ($resource === 'node') {
$type = TopologyDeviceType::whereKey($data['device_type_id'] ?? $existing?->device_type_id)
->where(fn ($q) => $q->whereNull('tenant_id')->orWhere('tenant_id', $data['tenant_id']))
->first();
if (! $type) {
throw ValidationException::withMessages(['device_type_id' => 'Kategori perangkat tidak tersedia untuk tenant ini.']);
}
if (! empty($data['parent_node_id']) && ! TopologyNode::whereKey($data['parent_node_id'])->where('tenant_id', $data['tenant_id'])->exists()) {
throw ValidationException::withMessages(['parent_node_id' => 'Parent perangkat bukan milik tenant yang sama.']);
}
}
if ($resource === 'link') {
$this->validateLink($data, $existing);
}
$data['updated_by'] = $actor->id;
if (! $existing) {
$data['created_by'] = $actor->id;
}
return $data;
}
private function validateLink(array $data, ?Model $existing): void
{
$sourceId = (int) ($data['source_node_id'] ?? $existing?->source_node_id);
$targetId = (int) ($data['target_node_id'] ?? $existing?->target_node_id);
$tenantId = (int) $data['tenant_id'];
$nodes = TopologyNode::with('deviceType')->whereIn('id', [$sourceId, $targetId])->where('tenant_id', $tenantId)->get()->keyBy('id');
if ($sourceId === $targetId || $nodes->count() !== 2) {
throw ValidationException::withMessages(['target_node_id' => 'Node asal dan tujuan harus berbeda dan berasal dari tenant yang sama.']);
}
$rule = TopologyConnectionRule::where(fn ($q) => $q->whereNull('tenant_id')->orWhere('tenant_id', $tenantId))
->where('source_device_type_id', $nodes[$sourceId]->device_type_id)
->where('target_device_type_id', $nodes[$targetId]->device_type_id)
->orderByDesc('tenant_id')
->first();
if ($rule && ! $rule->allowed) {
throw ValidationException::withMessages(['target_node_id' => 'Hubungan antar kategori perangkat ini tidak diizinkan.']);
}
if ($rule?->max_connections) {
$connectionCount = TopologyLink::where('source_node_id', $sourceId)
->when($existing, fn ($q) => $q->whereKeyNot($existing->id))
->count();
if ($connectionCount >= $rule->max_connections) {
throw ValidationException::withMessages(['source_node_id' => 'Batas maksimal koneksi perangkat asal sudah tercapai.']);
}
}
$duplicate = TopologyLink::where('source_node_id', $sourceId)
->where('target_node_id', $targetId)
->when($existing, fn ($q) => $q->whereKeyNot($existing->id))
->where(function ($query) use ($data, $existing) {
$sourcePortId = $data['source_port_id'] ?? $existing?->source_port_id;
$targetPortId = $data['target_port_id'] ?? $existing?->target_port_id;
$sourcePortId ? $query->where('source_port_id', $sourcePortId) : $query->whereNull('source_port_id');
$targetPortId ? $query->where('target_port_id', $targetPortId) : $query->whereNull('target_port_id');
})
->exists();
if ($duplicate) {
throw ValidationException::withMessages(['target_node_id' => 'Jalur dengan endpoint yang sama sudah tersedia.']);
}
foreach (['source_port_id' => $sourceId, 'target_port_id' => $targetId] as $field => $nodeId) {
$portId = $data[$field] ?? $existing?->{$field};
if ($portId) {
$port = TopologyPort::whereKey($portId)->where('node_id', $nodeId)->where('tenant_id', $tenantId)->first();
if (! $port) {
throw ValidationException::withMessages([$field => 'Port tidak sesuai dengan node yang dipilih.']);
}
$used = TopologyLink::where(fn ($q) => $q->where('source_port_id', $portId)->orWhere('target_port_id', $portId))
->when($existing, fn ($q) => $q->whereKeyNot($existing->id))
->count();
if ($used >= $port->capacity) {
throw ValidationException::withMessages([$field => 'Kapasitas port sudah terpakai penuh.']);
}
}
}
if ($this->hasDirectedPath($targetId, $sourceId, $tenantId, $existing?->id)) {
throw ValidationException::withMessages(['target_node_id' => 'Jalur ini membentuk loop topologi.']);
}
}
private function hasDirectedPath(int $from, int $to, int $tenantId, ?int $ignoreLink): bool
{
$queue = [$from];
$visited = [];
while ($queue) {
$current = array_shift($queue);
if ($current === $to) {
return true;
}
if (isset($visited[$current])) {
continue;
}
$visited[$current] = true;
$next = TopologyLink::where('tenant_id', $tenantId)
->where('source_node_id', $current)
->when($ignoreLink, fn ($q) => $q->whereKeyNot($ignoreLink))
->pluck('target_node_id')
->all();
$queue = [...$queue, ...$next];
}
return false;
}
private function scopeTenant($query, string $resource, User $actor, ?int $tenantId): void
{
if ($resource === 'device-type') {
if ($actor->isMasterAdmin() && ! $tenantId) {
return;
}
$query->where(function ($q) use ($tenantId) {
$q->whereNull('tenant_id')
->orWhere('tenant_id', $tenantId);
});
return;
}
$query->when(! $actor->isMasterAdmin(), fn ($q) => $q->where('tenant_id', $tenantId))
->when($actor->isMasterAdmin() && $tenantId, fn ($q) => $q->where('tenant_id', $tenantId));
}
private function model(string $resource): string
{
return match ($resource) {
'device-type' => TopologyDeviceType::class,
'node' => TopologyNode::class,
'link' => TopologyLink::class,
default => throw ValidationException::withMessages(['resource' => 'Resource topologi tidak valid.']),
};
}
}
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace App\Services\Wallet;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Wallet;
use App\Models\WalletLedgerEntry;
use App\Models\WalletTransaction;
use App\Models\WalletWithdrawal;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class WalletService
{
public function wallets(User $user, ?int $tenantId)
{
$wallets = collect([$this->walletFor($user, 'user')]);
if ($tenantId && ($user->isMasterAdmin() || $user->isTenantOwner())) {
$wallets->push($this->walletFor(Tenant::findOrFail($tenantId), 'tenant'));
}
return $wallets->values();
}
public function ledger(Wallet $wallet, User $actor, ?int $tenantId, array $filters)
{
$this->authorizeWallet($wallet, $actor, $tenantId);
return $wallet->ledgerEntries()->with('transaction:id,uuid,transaction_number,type,status,description,created_at')
->latest('id')->paginate($filters['per_page'] ?? 10);
}
public function transfer(Wallet $source, Wallet $destination, float $amount, User $actor, ?int $tenantId): WalletTransaction
{
$this->authorizeWallet($source, $actor, $tenantId);
$this->authorizeWallet($destination, $actor, $tenantId);
if ($source->is($destination)) {
throw ValidationException::withMessages(['destination_wallet_id' => 'Dompet tujuan harus berbeda.']);
}
if ($amount <= 0) {
throw ValidationException::withMessages(['amount' => 'Nominal harus lebih dari nol.']);
}
return DB::transaction(function () use ($source, $destination, $amount, $actor) {
$wallets = Wallet::whereIn('id', [$source->id, $destination->id])->lockForUpdate()->get()->keyBy('id');
$from = $wallets[$source->id];
$to = $wallets[$destination->id];
if ((float) $from->available_balance < $amount) {
throw ValidationException::withMessages(['amount' => 'Saldo tidak mencukupi.']);
}
$transaction = $this->newTransaction('transfer', $amount, $actor, 'Pindah saldo antar dompet');
$this->post($from, $transaction, 'debit', $amount);
$this->post($to, $transaction, 'credit', $amount);
$transaction->update(['status' => 'completed', 'completed_at' => now()]);
return $transaction->load('entries.wallet');
});
}
public function requestWithdrawal(Wallet $wallet, array $data, User $actor, ?int $tenantId): WalletWithdrawal
{
$this->authorizeWallet($wallet, $actor, $tenantId);
return DB::transaction(function () use ($wallet, $data, $actor) {
$locked = Wallet::lockForUpdate()->findOrFail($wallet->id);
$total = (float) $data['amount'] + (float) ($data['fee'] ?? 0);
if ((float) $locked->available_balance < $total) {
throw ValidationException::withMessages(['amount' => 'Saldo tidak mencukupi.']);
}
$transaction = $this->newTransaction('withdrawal', $data['amount'], $actor, 'Permintaan penarikan saldo', $data['fee'] ?? 0);
$this->post($locked, $transaction, 'debit', $total);
return WalletWithdrawal::create([
'uuid' => Str::uuid(), 'wallet_id' => $locked->id, 'wallet_transaction_id' => $transaction->id,
'requested_by' => $actor->id, 'amount' => $data['amount'], 'fee' => $data['fee'] ?? 0,
'bank_code' => $data['bank_code'], 'account_number' => $data['account_number'],
'account_name' => $data['account_name'], 'status' => 'pending_approval',
]);
});
}
private function walletFor(Model $owner, string $type): Wallet
{
return Wallet::firstOrCreate(
['owner_type' => $owner->getMorphClass(), 'owner_id' => $owner->getKey(), 'wallet_type' => $type, 'currency' => 'IDR'],
['uuid' => Str::uuid(), 'status' => 'active']
);
}
private function newTransaction(string $type, float $amount, User $actor, string $description, float $fee = 0): WalletTransaction
{
return WalletTransaction::create([
'uuid' => Str::uuid(), 'transaction_number' => 'WLT-'.now()->format('YmdHis').'-'.Str::upper(Str::random(6)),
'type' => $type, 'status' => 'processing', 'initiated_by' => $actor->id, 'amount' => $amount,
'fee' => $fee, 'idempotency_key' => (string) Str::uuid(), 'description' => $description,
]);
}
private function post(Wallet $wallet, WalletTransaction $transaction, string $type, float $amount): void
{
$before = (float) $wallet->available_balance;
$after = $type === 'credit' ? $before + $amount : $before - $amount;
WalletLedgerEntry::create([
'wallet_id' => $wallet->id, 'wallet_transaction_id' => $transaction->id, 'entry_type' => $type,
'balance_bucket' => 'available', 'amount' => $amount, 'balance_before' => $before,
'balance_after' => $after, 'description' => $transaction->description,
]);
$wallet->update(['available_balance' => $after, 'version' => $wallet->version + 1]);
}
private function authorizeWallet(Wallet $wallet, User $actor, ?int $tenantId): void
{
if ($actor->isMasterAdmin()) {
return;
}
$allowed = ($wallet->owner_type === $actor->getMorphClass() && (int) $wallet->owner_id === (int) $actor->id)
|| ($actor->isTenantOwner() && $wallet->owner_type === (new Tenant)->getMorphClass() && (int) $wallet->owner_id === (int) $tenantId);
abort_unless($allowed, 403, 'Dompet tidak dapat diakses.');
}
}