TicketService.php 1.9 KB

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