Files
x-server-mobile/backend/app/service/FeishuNotificationService.php
T

549 lines
16 KiB
PHP
Raw Normal View History

<?php
namespace app\service;
use app\model\User;
use app\model\Company;
use app\util\FeishuUtil;
use app\util\HttpClient;
use Exception;
/**
* 飞书通知服务
* 提供多种卡片类型的消息通知功能
*/
class FeishuNotificationService
{
private ?int $companyId = null;
private ?int $appId = null;
/**
* 设置当前操作的公司
*/
public function setCompany(int $companyId): self
{
$this->companyId = $companyId;
return $this;
}
/**
* 设置飞书应用ID(必须指定)
*/
public function setApp(int $appId): self
{
$this->appId = $appId;
return $this;
}
/**
* 根据用户ID自动设置其最后登录的应用
*/
public function setAppByUser(int $userId): self
{
$user = \app\model\User::find($userId);
if (!$user) {
throw new Exception('用户不存在');
}
$this->setCompany($user->company_id);
// 使用用户最后登录的应用
if ($user->feishu_app_id) {
$this->appId = $user->feishu_app_id;
} else {
throw new Exception('用户未绑定飞书应用,请先通过飞书登录');
}
return $this;
}
/**
* 获取飞书应用配置(必须先通过 setApp 或 setAppByUser 指定)
*/
private function getAppConfig(): array
{
if (!$this->companyId) {
throw new Exception('未设置公司ID');
}
if (!$this->appId) {
throw new Exception('未指定飞书应用,请通过 setApp() 或 setAppByUser() 指定');
}
$app = \app\model\CompanyFeishuApp::where('company_id', $this->companyId)
->where('id', $this->appId)
->where('status', 1)
->first();
if (!$app) {
throw new Exception('指定的飞书应用不存在或未启用');
}
return $app->toArray();
}
/**
* 获取 access_token
*/
private function getAccessToken(): string
{
$app = $this->getAppConfig();
return FeishuUtil::getAppAccessToken($app['id']);
}
/**
* 获取用户在指定飞书应用下的 feishu_user_id
*/
private function getFeishuUserId(int $userId, int $companyId): ?string
{
if (!$this->appId) {
throw new Exception('未指定飞书应用,请先调用 setApp() 或 setAppByUser()');
}
$binding = \app\model\UserFeishuApp::where('user_id', $userId)
->where('company_id', $companyId)
->where('feishu_app_id', $this->appId)
->first();
return $binding ? $binding->feishu_user_id : null;
}
/**
* 发送审批通知
*
* @param array $params
* - user_id: 接收人ID
* - title: 通知标题
* - applicant: 申请人姓名
* - type: 申请类型
* - content: 申请内容摘要
* - url: 详情链接
2026-02-26 18:57:59 +08:00
* - order_id: 审批单ID(用于构建审批操作按钮)
* @return bool
*/
public function sendApprovalNotification(array $params): bool
{
$userId = $params['user_id'] ?? null;
if (!$userId) {
error_log('❌ sendApprovalNotification: 缺少 user_id');
return false;
}
try {
$user = User::find($userId);
if (!$user) {
error_log("❌ sendApprovalNotification: 用户不存在, user_id={$userId}");
return false;
}
// 从 user_feishu_apps 获取指定应用下的 feishu_user_id
$feishuUserId = $this->getFeishuUserId($userId, $user->company_id);
if (!$feishuUserId) {
error_log("❌ sendApprovalNotification: 用户未绑定飞书应用, user_id={$userId}");
return false;
}
$card = $this->buildApprovalCard($params);
return $this->sendMessage($feishuUserId, $card);
} catch (Exception $e) {
error_log('❌ sendApprovalNotification 失败: ' . $e->getMessage());
return false;
}
}
/**
* 发送系统通知
*
* @param array $params
* - user_ids: 接收人ID数组
* - title: 通知标题
* - content: 通知内容
* - url: 跳转链接(可选)
* @return array 返回每个用户的发送结果
*/
public function sendSystemNotification(array $params): array
{
$userIds = $params['user_ids'] ?? [];
if (empty($userIds)) {
error_log('❌ sendSystemNotification: 缺少 user_ids');
return [];
}
$results = [];
foreach ($userIds as $userId) {
try {
$user = User::find($userId);
if (!$user) {
$results[$userId] = false;
continue;
}
// 从 user_feishu_apps 获取指定应用下的 feishu_user_id
$feishuUserId = $this->getFeishuUserId($userId, $user->company_id);
if (!$feishuUserId) {
$results[$userId] = false;
continue;
}
$card = $this->buildSystemCard($params);
$results[$userId] = $this->sendMessage($feishuUserId, $card);
} catch (Exception $e) {
error_log("❌ sendSystemNotification 失败: user_id={$userId}, error=" . $e->getMessage());
$results[$userId] = false;
}
}
return $results;
}
/**
* 发送提醒通知
*
* @param array $params
* - user_id: 接收人ID
* - title: 提醒标题
* - content: 提醒内容
* - level: 提醒级别 (info/warning/urgent)
* - url: 跳转链接(可选)
* @return bool
*/
public function sendReminderNotification(array $params): bool
{
$userId = $params['user_id'] ?? null;
if (!$userId) {
error_log('❌ sendReminderNotification: 缺少 user_id');
return false;
}
try {
$user = User::find($userId);
if (!$user) {
error_log("❌ sendReminderNotification: 用户不存在, user_id={$userId}");
return false;
}
// 从 user_feishu_apps 获取指定应用下的 feishu_user_id
$feishuUserId = $this->getFeishuUserId($userId, $user->company_id);
if (!$feishuUserId) {
error_log("❌ sendReminderNotification: 用户未绑定飞书应用, user_id={$userId}");
return false;
}
$card = $this->buildReminderCard($params);
return $this->sendMessage($feishuUserId, $card);
} catch (Exception $e) {
error_log('❌ sendReminderNotification 失败: ' . $e->getMessage());
return false;
}
}
/**
* 批量发送通知
*
* @param array $params
* - user_ids: 接收人ID数组
* - type: 通知类型 (approval/system/reminder)
* - 其他参数根据类型不同而不同
* @return array
*/
public function sendBatchNotification(array $params): array
{
$userIds = $params['user_ids'] ?? [];
$type = $params['type'] ?? 'system';
$results = [];
foreach ($userIds as $userId) {
$notifyParams = array_merge($params, ['user_id' => $userId]);
unset($notifyParams['user_ids']);
switch ($type) {
case 'approval':
$results[$userId] = $this->sendApprovalNotification($notifyParams);
break;
case 'reminder':
$results[$userId] = $this->sendReminderNotification($notifyParams);
break;
case 'system':
default:
$results[$userId] = $this->sendSystemNotification(['user_ids' => [$userId]] + $params)[$userId] ?? false;
break;
}
}
return $results;
}
/**
* 构建审批通知卡片
*/
private function buildApprovalCard(array $params): array
{
$title = $params['title'] ?? '新的审批申请';
$applicant = $params['applicant'] ?? '未知';
$type = $params['type'] ?? '申请';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
2026-02-26 18:57:59 +08:00
$orderId = $params['order_id'] ?? null;
2026-02-26 18:57:59 +08:00
// 构建卡片元素
$elements = [];
2026-02-26 18:57:59 +08:00
// 内容区域
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => "**申请人**: {$applicant}\n**申请类型**: {$type}\n\n{$content}",
'tag' => 'lark_md',
],
];
} else {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => "**申请人**: {$applicant}\n**申请类型**: {$type}",
'tag' => 'lark_md',
],
];
}
2026-02-26 18:57:59 +08:00
// 操作按钮区域
$actions = [];
2026-02-26 19:30:12 +08:00
// 如果有审批单ID,添加审批操作按钮(使用快速审批页面,无感操作)
2026-02-26 18:57:59 +08:00
if ($orderId) {
2026-02-26 19:30:12 +08:00
// 通过按钮(绿色)- 快速审批页面
2026-02-26 18:57:59 +08:00
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '✓ 通过',
'tag' => 'plain_text',
],
'type' => 'primary',
'size' => 'medium',
2026-02-26 19:30:12 +08:00
'url' => "https://xsm.dev.hnxinyouhe.com/approval/quick-action?action=approve&order_id={$orderId}",
2026-02-26 18:57:59 +08:00
];
2026-02-26 19:30:12 +08:00
// 拒绝按钮(红色)- 快速审批页面
2026-02-26 18:57:59 +08:00
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '✗ 拒绝',
'tag' => 'plain_text',
],
'type' => 'danger',
'size' => 'medium',
2026-02-26 19:30:12 +08:00
'url' => "https://xsm.dev.hnxinyouhe.com/approval/quick-action?action=reject&order_id={$orderId}",
2026-02-26 18:57:59 +08:00
];
}
// 查看详情按钮
if ($url) {
2026-02-26 18:57:59 +08:00
$actions[] = [
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'size' => 'medium',
'url' => $url,
];
}
if (!empty($actions)) {
$elements[] = [
'tag' => 'action',
2026-02-26 18:57:59 +08:00
'actions' => $actions,
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "📋 {$title}",
'tag' => 'plain_text',
],
'template' => 'blue',
],
'elements' => $elements,
];
}
/**
* 构建系统通知卡片
*/
private function buildSystemCard(array $params): array
{
$title = $params['title'] ?? '系统通知';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
$elements = [];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => $content,
'tag' => 'lark_md',
],
];
}
if ($url) {
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => $url,
],
],
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "🔔 {$title}",
'tag' => 'plain_text',
],
'template' => 'gray',
],
'elements' => $elements,
];
}
/**
* 构建提醒通知卡片
*/
private function buildReminderCard(array $params): array
{
$title = $params['title'] ?? '提醒';
$content = $params['content'] ?? '';
$level = $params['level'] ?? 'info'; // info, warning, urgent
$url = $params['url'] ?? '';
// 根据级别选择模板颜色
$templateMap = [
'info' => 'blue',
'warning' => 'orange',
'urgent' => 'red',
];
$template = $templateMap[$level] ?? 'blue';
// 根据级别选择图标
$iconMap = [
'info' => '💡',
'warning' => '⚠️',
'urgent' => '🚨',
];
$icon = $iconMap[$level] ?? '💡';
$elements = [];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => $content,
'tag' => 'plain_text',
],
];
}
if ($url) {
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看',
'tag' => 'plain_text',
],
'type' => 'primary',
'url' => $url,
],
],
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "{$icon} {$title}",
'tag' => 'plain_text',
],
'template' => $template,
],
'elements' => $elements,
];
}
/**
* 发送消息到飞书
*/
private function sendMessage(string $feishuUserId, array $card): bool
{
try {
$app = $this->getAppConfig();
$token = $this->getAccessToken();
$body = [
'receive_id_type' => 'user_id',
'receive_id' => $feishuUserId,
'msg_type' => 'interactive',
'content' => json_encode(['card' => $card]),
];
error_log('📤 发送飞书消息: app_id=' . $app['app_id'] . ', feishu_user_id=' . $feishuUserId);
error_log('📦 消息卡片: ' . json_encode($card, JSON_UNESCAPED_UNICODE));
$content = json_encode($card);
error_log('📤 发送的content: ' . $content);
$response = HttpClient::httpPost(
"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id",
[
'receive_id' => $feishuUserId,
'msg_type' => 'interactive',
'content' => $content,
],
[
'Authorization: Bearer ' . $token,
]
);
$code = $response['code'] ?? -1;
error_log('📥 飞书响应: code=' . $code . ', msg=' . ($response['msg'] ?? 'null'));
if ($code !== 0) {
error_log('❌ 飞书消息发送失败: ' . json_encode($response));
} else {
error_log('✅ 飞书消息发送成功');
}
return $code === 0;
} catch (Exception $e) {
error_log('❌ sendMessage 异常: ' . $e->getMessage());
return false;
}
}
}