93 lines
2.8 KiB
PHP
93 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Ticket;
|
|
|
|
use App\Models\Ticket;
|
|
use App\Models\TicketLog;
|
|
use App\Models\TicketType;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class TicketService
|
|
{
|
|
public function create(array $data, User $actor, ?int $tenantId): Ticket
|
|
{
|
|
return DB::transaction(function () use ($data, $actor, $tenantId) {
|
|
|
|
$tenantId = $actor->isMasterAdmin() ? ($data['tenant_id'] ?? $tenantId) : $tenantId;
|
|
abort_unless($tenantId, 422, 'Tenant wajib dipilih.');
|
|
if (! empty($data['customer_id'])) abort_unless(\App\Models\Customer::whereKey($data['customer_id'])->where('tenant_id', $tenantId)->exists(), 422, 'Customer bukan milik tenant aktif.');
|
|
$type = TicketType::findOrFail($data['ticket_type_id']);
|
|
|
|
$ticket = Ticket::create([
|
|
'ticket_no' => $this->generateTicketNo(),
|
|
'ticket_type_id' => $data['ticket_type_id'],
|
|
'customer_id' => $data['customer_id'] ?? null,
|
|
'tenant_id' => $tenantId,
|
|
'title' => $data['title'],
|
|
'description' => $data['description'] ?? null,
|
|
'priority' => $data['priority'],
|
|
'status' => $type->need_approval ? 'open' : 'approved',
|
|
'sla_minutes' => $type->sla_minutes,
|
|
'created_by' => $actor->id
|
|
,'approved_by' => $type->need_approval ? null : $actor->id
|
|
,'approved_at' => $type->need_approval ? null : now()
|
|
]);
|
|
|
|
TicketLog::create([
|
|
'ticket_id' => $ticket->id,
|
|
'user_id' => $actor->id,
|
|
'activity' => 'Ticket Created',
|
|
'notes' => 'Ticket dibuat oleh '.$actor->name,
|
|
'created_at'=> now()
|
|
]);
|
|
|
|
return $ticket->load(['ticketType','customer','tenant','creator','assignments.user']);
|
|
});
|
|
}
|
|
|
|
public function update(Ticket $ticket, array $data): Ticket
|
|
{
|
|
$ticket->update($data);
|
|
|
|
return $ticket->fresh();
|
|
}
|
|
|
|
public function delete(Ticket $ticket): Ticket
|
|
{
|
|
$ticket->update([
|
|
'status' => 'cancelled'
|
|
]);
|
|
|
|
return $ticket;
|
|
}
|
|
|
|
private function generateTicketNo(): string
|
|
{
|
|
$prefix = 'TCK-' . now()->format('Ym');
|
|
|
|
$lastTicket = Ticket::where(
|
|
'ticket_no',
|
|
'like',
|
|
$prefix . '%'
|
|
)
|
|
->latest('id')
|
|
->first();
|
|
|
|
$number = 1;
|
|
|
|
if ($lastTicket) {
|
|
$number = ((int) substr($lastTicket->ticket_no, -6)) + 1;
|
|
}
|
|
|
|
return $prefix . '-' . str_pad(
|
|
$number,
|
|
6,
|
|
'0',
|
|
STR_PAD_LEFT
|
|
);
|
|
}
|
|
|
|
public function generateNo(): string { return $this->generateTicketNo(); }
|
|
}
|