TicketService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 reply($ticket, $message, $userId)
  11. {
  12. DB::beginTransaction();
  13. $ticketMessage = TicketMessage::create([
  14. 'user_id' => $userId,
  15. 'ticket_id' => $ticket->id,
  16. 'message' => $message
  17. ]);
  18. if ($userId !== $ticket->user_id) {
  19. $ticket->reply_status = 0;
  20. } else {
  21. $ticket->reply_status = 1;
  22. }
  23. if (!$ticketMessage || !$ticket->save()) {
  24. DB::rollback();
  25. return false;
  26. }
  27. DB::commit();
  28. return $ticketMessage;
  29. }
  30. public function replyByAdmin($ticketId, $message, $userId):void
  31. {
  32. $ticket = Ticket::where('id', $ticketId)
  33. ->first();
  34. if (!$ticket) {
  35. abort(500, '工单不存在');
  36. }
  37. $ticket->status = 0;
  38. DB::beginTransaction();
  39. $ticketMessage = TicketMessage::create([
  40. 'user_id' => $userId,
  41. 'ticket_id' => $ticket->id,
  42. 'message' => $message
  43. ]);
  44. if ($userId !== $ticket->user_id) {
  45. $ticket->reply_status = 0;
  46. } else {
  47. $ticket->reply_status = 1;
  48. }
  49. if (!$ticketMessage || !$ticket->save()) {
  50. DB::rollback();
  51. abort(500, '工单回复失败');
  52. }
  53. DB::commit();
  54. $this->sendEmailNotify($ticket, $ticketMessage);
  55. }
  56. // 半小时内不再重复通知
  57. private function sendEmailNotify(Ticket $ticket, TicketMessage $ticketMessage)
  58. {
  59. $user = User::find($ticket->user_id);
  60. $cacheKey = 'ticket_sendEmailNotify_' . $ticket->user_id;
  61. if (!Cache::get($cacheKey)) {
  62. Cache::put($cacheKey, 1, 1800);
  63. SendEmailJob::dispatch([
  64. 'email' => $user->email,
  65. 'subject' => '您在' . config('v2board.app_name', 'V2Board') . '的工单得到了回复',
  66. 'template_name' => 'notify',
  67. 'template_value' => [
  68. 'name' => config('v2board.app_name', 'V2Board'),
  69. 'url' => config('v2board.app_url'),
  70. 'content' => "主题:{$ticket->subject}\r\n回复内容:{$ticketMessage->message}"
  71. ]
  72. ]);
  73. }
  74. }
  75. }