TicketService.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. if ($ticket->status) {
  18. abort(500, '工单已关闭,无法回复');
  19. }
  20. DB::beginTransaction();
  21. $ticketMessage = TicketMessage::create([
  22. 'user_id' => $userId,
  23. 'ticket_id' => $ticket->id,
  24. 'message' => $message
  25. ]);
  26. $ticket->last_reply_user_id = $userId;
  27. if (!$ticketMessage || !$ticket->save()) {
  28. DB::rollback();
  29. abort(500, '工单回复失败');
  30. }
  31. DB::commit();
  32. $this->sendEmailNotify($ticket, $ticketMessage);
  33. }
  34. // 半小时内不再重复通知
  35. private function sendEmailNotify(Ticket $ticket, TicketMessage $ticketMessage)
  36. {
  37. $user = User::find($ticket->user_id);
  38. $cacheKey = 'ticket_sendEmailNotify_' . $ticket->user_id;
  39. if (!Cache::get($cacheKey)) {
  40. Cache::put($cacheKey, 1, 1800);
  41. SendEmailJob::dispatch([
  42. 'email' => $user->email,
  43. 'subject' => '您在' . config('v2board.app_name', 'V2Board') . '的工单得到了回复',
  44. 'template_name' => 'notify',
  45. 'template_value' => [
  46. 'name' => config('v2board.app_name', 'V2Board'),
  47. 'url' => config('v2board.app_url'),
  48. 'content' => "主题:{$ticket->subject}\r\n回复内容:{$ticketMessage->message}"
  49. ]
  50. ]);
  51. }
  52. }
  53. }