TicketService.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Services;
  3. use App\Jobs\SendEmailJob;
  4. use App\Models\Ticket;
  5. use App\Models\TicketMessage;
  6. use App\Models\User;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. class TicketService {
  10. public function replyByAdmin($ticketId, $message, $userId):void
  11. {
  12. $ticket = Ticket::where('id', $ticketId)
  13. ->first();
  14. if (!$ticket) {
  15. abort(500, '工单不存在');
  16. }
  17. $ticket->status = 0;
  18. DB::beginTransaction();
  19. $ticketMessage = TicketMessage::create([
  20. 'user_id' => $userId,
  21. 'ticket_id' => $ticket->id,
  22. 'message' => $message
  23. ]);
  24. $ticket->last_reply_user_id = $userId;
  25. if (!$ticketMessage || !$ticket->save()) {
  26. DB::rollback();
  27. abort(500, '工单回复失败');
  28. }
  29. DB::commit();
  30. $this->sendEmailNotify($ticket, $ticketMessage);
  31. }
  32. // 半小时内不再重复通知
  33. private function sendEmailNotify(Ticket $ticket, TicketMessage $ticketMessage)
  34. {
  35. $user = User::find($ticket->user_id);
  36. $cacheKey = 'ticket_sendEmailNotify_' . $ticket->user_id;
  37. if (!Cache::get($cacheKey)) {
  38. Cache::put($cacheKey, 1, 1800);
  39. SendEmailJob::dispatch([
  40. 'email' => $user->email,
  41. 'subject' => '您在' . config('v2board.app_name', 'V2Board') . '的工单得到了回复',
  42. 'template_name' => 'notify',
  43. 'template_value' => [
  44. 'name' => config('v2board.app_name', 'V2Board'),
  45. 'url' => config('v2board.app_url'),
  46. 'content' => "主题:{$ticket->subject}\r\n回复内容:{$ticketMessage->message}"
  47. ]
  48. ]);
  49. }
  50. }
  51. }