NotificationService.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace App\Module\Notification\Services;
  3. use App\Module\Notification\Contracts\NotificationHookInterface;
  4. use App\Module\Notification\Enums\NOTIFICATION_CHANNEL;
  5. use App\Module\Notification\Enums\NOTIFICATION_STATUS;
  6. use App\Module\Notification\Models\NotificationTemplate;
  7. use App\Module\Notification\Models\NotificationLog;
  8. use App\Module\Notification\Queues\SendNotificationQueue;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Module\Notification\Hook\HookManager;
  11. class NotificationService
  12. {
  13. protected HookManager $hookManager;
  14. public function __construct(HookManager $hookManager)
  15. {
  16. $this->hookManager = $hookManager;
  17. }
  18. /**
  19. * 发送通知
  20. *
  21. * @param array $data
  22. * @return bool
  23. */
  24. public function send(array $data): bool
  25. {
  26. try {
  27. // 验证数据
  28. $this->validateData($data);
  29. // 获取模板
  30. $template = $this->getTemplate($data['template_id']);
  31. if (!$template) {
  32. throw new \Exception('通知模板不存在');
  33. }
  34. // 获取用户信息
  35. $data['user'] = $this->getUserInfo($data['user_id']);
  36. $data['template'] = $template;
  37. // 执行发送前钩子
  38. $data = $this->hookManager->executeBeforeSend($data);
  39. // 如果没有可用渠道,直接返回
  40. if (empty($data['channels'])) {
  41. Log::warning('没有可用的通知渠道', [
  42. 'user_id' => $data['user_id'],
  43. 'template_id' => $data['template_id']
  44. ]);
  45. return false;
  46. }
  47. // 创建通知记录
  48. $notification = $this->createNotificationLog($template, $data);
  49. // 发送到队列
  50. SendNotificationQueue::dispatch($notification);
  51. // 执行发送后钩子
  52. $this->hookManager->executeAfterSend($data, true);
  53. return true;
  54. } catch (\Exception $e) {
  55. // 执行错误钩子
  56. $this->hookManager->executeOnError($data ?? [], $e);
  57. Log::error('发送通知失败', [
  58. 'error' => $e->getMessage(),
  59. 'data' => $data ?? []
  60. ]);
  61. return false;
  62. }
  63. }
  64. /**
  65. * 批量发送通知
  66. *
  67. * @param array $data
  68. * @return bool
  69. */
  70. public function sendBatch(array $data): bool
  71. {
  72. try {
  73. foreach ($data as $item) {
  74. $this->send($item);
  75. }
  76. return true;
  77. } catch (\Exception $e) {
  78. Log::error('批量发送通知失败', [
  79. 'error' => $e->getMessage(),
  80. 'data' => $data
  81. ]);
  82. return false;
  83. }
  84. }
  85. /**
  86. * 获取模板
  87. *
  88. * @param int $id
  89. * @return NotificationTemplate|null
  90. */
  91. public function getTemplate(int $id): ?NotificationTemplate
  92. {
  93. return NotificationTemplate::find($id);
  94. }
  95. /**
  96. * 创建模板
  97. *
  98. * @param array $data
  99. * @return NotificationTemplate
  100. */
  101. public function createTemplate(array $data): NotificationTemplate
  102. {
  103. return NotificationTemplate::create($data);
  104. }
  105. /**
  106. * 更新模板
  107. *
  108. * @param int $id
  109. * @param array $data
  110. * @return bool
  111. */
  112. public function updateTemplate(int $id, array $data): bool
  113. {
  114. $template = $this->getTemplate($id);
  115. if (!$template) {
  116. return false;
  117. }
  118. return $template->update($data);
  119. }
  120. /**
  121. * 删除模板
  122. *
  123. * @param int $id
  124. * @return bool
  125. */
  126. public function deleteTemplate(int $id): bool
  127. {
  128. $template = $this->getTemplate($id);
  129. if (!$template) {
  130. return false;
  131. }
  132. return $template->delete();
  133. }
  134. /**
  135. * 验证数据
  136. *
  137. * @param array $data
  138. * @throws \Exception
  139. */
  140. protected function validateData(array $data): void
  141. {
  142. if (empty($data['template_id'])) {
  143. throw new \Exception('模板ID不能为空');
  144. }
  145. if (empty($data['user_id'])) {
  146. throw new \Exception('用户ID不能为空');
  147. }
  148. if (empty($data['channels'])) {
  149. throw new \Exception('通知渠道不能为空');
  150. }
  151. if (!is_array($data['channels'])) {
  152. throw new \Exception('通知渠道必须是数组');
  153. }
  154. foreach ($data['channels'] as $channel) {
  155. if (!in_array($channel, NOTIFICATION_CHANNEL::values())) {
  156. throw new \Exception('无效的通知渠道');
  157. }
  158. }
  159. }
  160. /**
  161. * 获取用户信息
  162. *
  163. * @param int $userId
  164. * @return array
  165. */
  166. protected function getUserInfo(int $userId): array
  167. {
  168. // TODO: 实现用户信息获取
  169. return [
  170. 'id' => $userId,
  171. 'phone' => '',
  172. 'email' => '',
  173. 'device_token' => ''
  174. ];
  175. }
  176. /**
  177. * 创建通知记录
  178. *
  179. * @param NotificationTemplate $template
  180. * @param array $data
  181. * @return NotificationLog
  182. */
  183. protected function createNotificationLog(NotificationTemplate $template, array $data): NotificationLog
  184. {
  185. return NotificationLog::create([
  186. 'template_id' => $template->id,
  187. 'user_id' => $data['user_id'],
  188. 'channels' => $data['channels'],
  189. 'title' => $template->title,
  190. 'content' => $template->content,
  191. 'data' => $data['data'] ?? [],
  192. 'status' => NOTIFICATION_STATUS::PENDING
  193. ]);
  194. }
  195. /**
  196. * 处理通知发送
  197. *
  198. * @param NotificationLog $notification
  199. * @return void
  200. */
  201. public function handleNotification(NotificationLog $notification): void
  202. {
  203. try {
  204. $notification->update(['status' => NOTIFICATION_STATUS::SENDING]);
  205. // 获取用户信息
  206. $data = [
  207. 'user' => $this->getUserInfo($notification->user_id),
  208. 'template' => $this->getTemplate($notification->template_id),
  209. 'channels' => $notification->channels,
  210. 'data' => $notification->data
  211. ];
  212. // 执行发送前钩子
  213. $data = $this->hookManager->executeBeforeSend($data);
  214. foreach ($data['channels'] as $channel) {
  215. $this->sendByChannel($notification, $channel, $data);
  216. }
  217. $notification->update([
  218. 'status' => NOTIFICATION_STATUS::SENT,
  219. 'sent_at' => now()
  220. ]);
  221. // 执行发送后钩子
  222. $this->hookManager->executeAfterSend($data, true);
  223. } catch (\Exception $e) {
  224. $notification->update([
  225. 'status' => NOTIFICATION_STATUS::FAILED,
  226. 'message' => $e->getMessage()
  227. ]);
  228. // 执行错误钩子
  229. $this->hookManager->executeOnError($data ?? [], $e);
  230. Log::error('处理通知发送失败', [
  231. 'notification_id' => $notification->id,
  232. 'error' => $e->getMessage()
  233. ]);
  234. }
  235. }
  236. /**
  237. * 通过指定渠道发送通知
  238. *
  239. * @param NotificationLog $notification
  240. * @param string $channel
  241. * @param array $data
  242. * @return void
  243. */
  244. protected function sendByChannel(NotificationLog $notification, string $channel, array $data): void
  245. {
  246. // 具体的发送逻辑由各个模块的Hook处理
  247. // 这里只需要调用Hook的beforeSend方法即可
  248. }
  249. }