| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284 |
- <?php
- namespace App\Module\Notification\Services;
- use App\Module\Notification\Contracts\NotificationHookInterface;
- use App\Module\Notification\Enums\NOTIFICATION_CHANNEL;
- use App\Module\Notification\Enums\NOTIFICATION_STATUS;
- use App\Module\Notification\Models\NotificationTemplate;
- use App\Module\Notification\Models\NotificationLog;
- use App\Module\Notification\Queues\SendNotificationQueue;
- use Illuminate\Support\Facades\Log;
- use App\Module\Notification\Hook\HookManager;
- class NotificationService
- {
- protected HookManager $hookManager;
- public function __construct(HookManager $hookManager)
- {
- $this->hookManager = $hookManager;
- }
- /**
- * 发送通知
- *
- * @param array $data
- * @return bool
- */
- public function send(array $data): bool
- {
- try {
- // 验证数据
- $this->validateData($data);
- // 获取模板
- $template = $this->getTemplate($data['template_id']);
- if (!$template) {
- throw new \Exception('通知模板不存在');
- }
- // 获取用户信息
- $data['user'] = $this->getUserInfo($data['user_id']);
- $data['template'] = $template;
- // 执行发送前钩子
- $data = $this->hookManager->executeBeforeSend($data);
- // 如果没有可用渠道,直接返回
- if (empty($data['channels'])) {
- Log::warning('没有可用的通知渠道', [
- 'user_id' => $data['user_id'],
- 'template_id' => $data['template_id']
- ]);
- return false;
- }
- // 创建通知记录
- $notification = $this->createNotificationLog($template, $data);
- // 发送到队列
- SendNotificationQueue::dispatch($notification);
- // 执行发送后钩子
- $this->hookManager->executeAfterSend($data, true);
- return true;
- } catch (\Exception $e) {
- // 执行错误钩子
- $this->hookManager->executeOnError($data ?? [], $e);
- Log::error('发送通知失败', [
- 'error' => $e->getMessage(),
- 'data' => $data ?? []
- ]);
- return false;
- }
- }
- /**
- * 批量发送通知
- *
- * @param array $data
- * @return bool
- */
- public function sendBatch(array $data): bool
- {
- try {
- foreach ($data as $item) {
- $this->send($item);
- }
- return true;
- } catch (\Exception $e) {
- Log::error('批量发送通知失败', [
- 'error' => $e->getMessage(),
- 'data' => $data
- ]);
- return false;
- }
- }
- /**
- * 获取模板
- *
- * @param int $id
- * @return NotificationTemplate|null
- */
- public function getTemplate(int $id): ?NotificationTemplate
- {
- return NotificationTemplate::find($id);
- }
- /**
- * 创建模板
- *
- * @param array $data
- * @return NotificationTemplate
- */
- public function createTemplate(array $data): NotificationTemplate
- {
- return NotificationTemplate::create($data);
- }
- /**
- * 更新模板
- *
- * @param int $id
- * @param array $data
- * @return bool
- */
- public function updateTemplate(int $id, array $data): bool
- {
- $template = $this->getTemplate($id);
- if (!$template) {
- return false;
- }
- return $template->update($data);
- }
- /**
- * 删除模板
- *
- * @param int $id
- * @return bool
- */
- public function deleteTemplate(int $id): bool
- {
- $template = $this->getTemplate($id);
- if (!$template) {
- return false;
- }
- return $template->delete();
- }
- /**
- * 验证数据
- *
- * @param array $data
- * @throws \Exception
- */
- protected function validateData(array $data): void
- {
- if (empty($data['template_id'])) {
- throw new \Exception('模板ID不能为空');
- }
- if (empty($data['user_id'])) {
- throw new \Exception('用户ID不能为空');
- }
- if (empty($data['channels'])) {
- throw new \Exception('通知渠道不能为空');
- }
- if (!is_array($data['channels'])) {
- throw new \Exception('通知渠道必须是数组');
- }
- foreach ($data['channels'] as $channel) {
- if (!in_array($channel, NOTIFICATION_CHANNEL::values())) {
- throw new \Exception('无效的通知渠道');
- }
- }
- }
- /**
- * 获取用户信息
- *
- * @param int $userId
- * @return array
- */
- protected function getUserInfo(int $userId): array
- {
- // TODO: 实现用户信息获取
- return [
- 'id' => $userId,
- 'phone' => '',
- 'email' => '',
- 'device_token' => ''
- ];
- }
- /**
- * 创建通知记录
- *
- * @param NotificationTemplate $template
- * @param array $data
- * @return NotificationLog
- */
- protected function createNotificationLog(NotificationTemplate $template, array $data): NotificationLog
- {
- return NotificationLog::create([
- 'template_id' => $template->id,
- 'user_id' => $data['user_id'],
- 'channels' => $data['channels'],
- 'title' => $template->title,
- 'content' => $template->content,
- 'data' => $data['data'] ?? [],
- 'status' => NOTIFICATION_STATUS::PENDING
- ]);
- }
- /**
- * 处理通知发送
- *
- * @param NotificationLog $notification
- * @return void
- */
- public function handleNotification(NotificationLog $notification): void
- {
- try {
- $notification->update(['status' => NOTIFICATION_STATUS::SENDING]);
- // 获取用户信息
- $data = [
- 'user' => $this->getUserInfo($notification->user_id),
- 'template' => $this->getTemplate($notification->template_id),
- 'channels' => $notification->channels,
- 'data' => $notification->data
- ];
- // 执行发送前钩子
- $data = $this->hookManager->executeBeforeSend($data);
- foreach ($data['channels'] as $channel) {
- $this->sendByChannel($notification, $channel, $data);
- }
- $notification->update([
- 'status' => NOTIFICATION_STATUS::SENT,
- 'sent_at' => now()
- ]);
- // 执行发送后钩子
- $this->hookManager->executeAfterSend($data, true);
- } catch (\Exception $e) {
- $notification->update([
- 'status' => NOTIFICATION_STATUS::FAILED,
- 'message' => $e->getMessage()
- ]);
- // 执行错误钩子
- $this->hookManager->executeOnError($data ?? [], $e);
- Log::error('处理通知发送失败', [
- 'notification_id' => $notification->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- /**
- * 通过指定渠道发送通知
- *
- * @param NotificationLog $notification
- * @param string $channel
- * @param array $data
- * @return void
- */
- protected function sendByChannel(NotificationLog $notification, string $channel, array $data): void
- {
- // 具体的发送逻辑由各个模块的Hook处理
- // 这里只需要调用Hook的beforeSend方法即可
- }
- }
|