Files
x-server-mobile/backend/app/service/FeishuNotificationService.php
T
2026-03-01 12:58:43 +08:00

1175 lines
42 KiB
PHP

<?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
{
error_log("🔧 setAppByUser 被调用: userId={$userId}");
$user = \app\model\User::find($userId);
if (!$user) {
throw new Exception('用户不存在');
}
error_log("🔧 setAppByUser: 找到用户, company_id={$user->company_id}, feishu_app_id={$user->feishu_app_id}");
$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: 详情链接
* - order_id: 审批单ID(用于构建审批操作按钮)
* - node_id: 审批节点ID(用于保存消息映射)
* @return bool
*/
public function sendApprovalNotification(array $params): bool
{
$userId = $params['user_id'] ?? null;
$applicantId = $params['applicant_id'] ?? null;
$orderId = $params['order_id'] ?? null;
$nodeId = $params['node_id'] ?? null;
error_log("📧 sendApprovalNotification 被调用: user_id={$userId}, applicant_id=" . ($applicantId ?? 'null') . ", order_id={$orderId}, node_id={$nodeId}");
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;
}
// 检查是否是申请人自己 - 发送文本消息而不是卡片
error_log("🔍 自审批检查前: applicant_id=" . var_export($applicantId, true) . ", user_id=" . var_export($userId, true));
if ($applicantId && (int)$applicantId === (int)$userId) {
error_log("🔄 检测到自审批,发送文本通知而不是卡片");
return $this->sendTextNotification($feishuUserId, $params);
}
error_log("📨 发送卡片消息: 不是自审批");
$card = $this->buildApprovalCard($params, $user->company_id);
$messageId = $this->sendMessage($feishuUserId, $card, $orderId, $nodeId, $userId);
if ($messageId && $orderId && $nodeId) {
// 保存消息映射(包含公司ID和飞书应用ID)
\app\model\FeishuMessage::saveMessage(
$orderId,
$nodeId,
$userId,
$messageId,
null,
$user->company_id,
$this->appId
);
error_log("💾 保存消息映射: order_id={$orderId}, node_id={$nodeId}, user_id={$userId}, company_id={$user->company_id}, feishu_app_id={$this->appId}, message_id={$messageId}");
}
return $messageId !== false;
} 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, $user->company_id);
$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, $user->company_id);
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, int $recipientCompanyId): array
{
$title = $params['title'] ?? '新的审批申请';
$applicant = $params['applicant'] ?? '未知';
$type = $params['type'] ?? '申请';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
$orderId = $params['order_id'] ?? null;
// 构建卡片元素
$elements = [];
// 内容区域
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',
],
];
}
// 提示信息(如需备注请去详情页)
if ($orderId) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => "_如需添加备注,请点击「查看详情」进入详情页操作_",
'tag' => 'lark_md',
],
];
}
// 按钮区域:三个按钮在一行
$buttonActions = [];
// 通过按钮
if ($orderId) {
$buttonActions[] = [
'tag' => 'button',
'text' => [
'content' => '通过',
'tag' => 'plain_text',
],
'type' => 'primary',
'size' => 'medium',
'value' => [
'action_type' => 'approve',
'order_id' => (int)$orderId,
],
];
// 拒绝按钮
$buttonActions[] = [
'tag' => 'button',
'text' => [
'content' => '拒绝',
'tag' => 'plain_text',
],
'type' => 'danger',
'size' => 'medium',
'value' => [
'action_type' => 'reject',
'order_id' => (int)$orderId,
],
];
}
// 查看详情按钮(跳转链接)
if ($url) {
$separator = strpos($url, '?') !== false ? '&' : '?';
$urlWithCompany = $url . $separator . 'company=' . $recipientCompanyId;
$buttonActions[] = [
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'size' => 'medium',
'url' => $urlWithCompany,
];
}
// 将所有按钮放在一个 action 元素中(会横向排列)
if (!empty($buttonActions)) {
$elements[] = [
'tag' => 'action',
'actions' => $buttonActions,
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "📋 {$title}",
'tag' => 'plain_text',
],
'template' => 'blue',
],
'elements' => $elements,
];
}
/**
* 构建系统通知卡片
*/
private function buildSystemCard(array $params, int $recipientCompanyId): array
{
$title = $params['title'] ?? '系统通知';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
$elements = [];
if ($content) {
$elements[] = [
'tag' => 'div',
'text' => [
'content' => $content,
'tag' => 'lark_md',
],
];
}
if ($url) {
// 在 URL 后面添加公司参数
$separator = strpos($url, '?') !== false ? '&' : '?';
$urlWithCompany = $url . $separator . 'company=' . $recipientCompanyId;
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => $urlWithCompany,
],
],
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "🔔 {$title}",
'tag' => 'plain_text',
],
'template' => 'gray',
],
'elements' => $elements,
];
}
/**
* 构建提醒通知卡片
*/
private function buildReminderCard(array $params, int $recipientCompanyId): 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) {
// 在 URL 后面添加公司参数
$separator = strpos($url, '?') !== false ? '&' : '?';
$urlWithCompany = $url . $separator . 'company=' . $recipientCompanyId;
$elements[] = [
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看',
'tag' => 'plain_text',
],
'type' => 'primary',
'url' => $urlWithCompany,
],
],
];
}
return [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "{$icon} {$title}",
'tag' => 'plain_text',
],
'template' => $template,
],
'elements' => $elements,
];
}
/**
* 发送消息到飞书
* @return string|false 返回 message_id 或 false
*/
private function sendMessage(string $feishuUserId, array $card, ?int $orderId = null, ?int $nodeId = null, ?int $userId = null)
{
$requestData = [
'feishu_user_id' => $feishuUserId,
'card' => $card,
];
try {
$app = $this->getAppConfig();
$token = $this->getAccessToken();
error_log('📤 发送飞书消息: app_id=' . $app['app_id'] . ', feishu_user_id=' . $feishuUserId);
error_log('📦 消息卡片: ' . json_encode($card, JSON_UNESCAPED_UNICODE));
// content 必须是 card 对象的 JSON 字符串,不是 {"card":{...}}
// JSON_UNESCAPED_UNICODE 保留 emoji
// JSON_UNESCAPED_SLASHES 避免 URL 中的 / 被转义为 \/
$contentJson = json_encode($card, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response = HttpClient::httpPostJson(
"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id",
[
'receive_id' => $feishuUserId,
'msg_type' => 'interactive',
'content' => $contentJson,
],
['content'], // content 字段是预编码的 JSON 字符串
[
'Authorization: Bearer ' . $token,
]
);
$code = $response['code'] ?? -1;
error_log('📥 飞书响应: code=' . $code . ', msg=' . ($response['msg'] ?? 'null'));
if ($code !== 0) {
error_log('❌ 飞书消息发送失败: ' . json_encode($response));
// 记录失败日志
if ($orderId) {
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_SEND,
$orderId,
$nodeId,
$userId,
null,
\app\model\FeishuMessageLog::STATUS_FAILED,
$requestData,
$response,
$response['msg'] ?? 'Unknown error'
);
}
return false;
}
$messageId = $response['data']['message_id'] ?? null;
if ($messageId) {
error_log('✅ 飞书消息发送成功, message_id=' . $messageId);
// 记录成功日志
if ($orderId) {
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_SEND,
$orderId,
$nodeId,
$userId,
$messageId,
\app\model\FeishuMessageLog::STATUS_SUCCESS,
$requestData,
$response
);
}
return $messageId;
}
return false;
} catch (Exception $e) {
error_log('❌ sendMessage 异常: ' . $e->getMessage());
// 记录异常日志
if ($orderId) {
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_SEND,
$orderId,
$nodeId,
$userId,
null,
\app\model\FeishuMessageLog::STATUS_FAILED,
$requestData,
null,
$e->getMessage()
);
}
return false;
}
}
/**
* 更新消息卡片(用于或签/单人审批完成后,更新其他审批人的消息)
*
* @param int $orderId 审批订单ID
* @param int $nodeId 节点ID
* @param int $excludeUserId 排除的用户ID(已经操作过的用户)
* @param string $status 审批状态 (approved/rejected)
* @param string $operatorName 操作人姓名
* @return bool
*/
/**
* 更新操作人自己的消息卡片(审批完成后显示查看详情按钮)
*
* @param int $orderId 订单ID
* @param int $nodeId 节点ID
* @param int $actorUserId 操作人ID(刚刚完成审批的用户)
* @param string $status 审批状态 (approved/rejected)
* @return bool
*/
public function updateActorMessageCard(int $orderId, int $nodeId, int $actorUserId, string $status): bool
{
error_log("🔧 updateActorMessageCard 被调用: order_id={$orderId}, node_id={$nodeId}, actorUserId={$actorUserId}, status={$status}");
try {
// 获取该操作人的消息
$message = \app\model\FeishuMessage::where('order_id', $orderId)
->where('node_id', $nodeId)
->where('user_id', $actorUserId)
->where('status', \app\model\FeishuMessage::STATUS_ACTIVE)
->first();
if (!$message) {
error_log("📭 没有找到操作人的消息: order_id={$orderId}, node_id={$nodeId}, user_id={$actorUserId}");
return true;
}
$companyId = $message->company_id;
$feishuAppId = $message->feishu_app_id;
if (!$companyId || !$feishuAppId) {
error_log("❌ 消息记录缺少 company_id 或 feishu_app_id: message_id={$message->message_id}");
return false;
}
error_log("🔍 准备更新操作人消息: message_id={$message->message_id}, company_id={$companyId}, feishu_app_id={$feishuAppId}");
// 使用该消息对应的飞书应用配置
$this->companyId = $companyId;
$this->appId = $feishuAppId;
// 获取订单信息
$order = \app\model\ApprovalOrder::find($orderId);
$orderTitle = $order ? $order->title : '审批单';
// 构建操作人自己的卡片(显示操作结果和查看详情按钮)
$statusText = $status === 'approved' ? '已通过' : '已拒绝';
$statusColor = $status === 'approved' ? 'green' : 'red';
$statusEmoji = $status === 'approved' ? '✅' : '❌';
$updatedCard = [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => "{$statusEmoji} 已操作",
'tag' => 'plain_text',
],
'template' => $statusColor,
],
'elements' => [
[
'tag' => 'div',
'text' => [
'content' => "**审批单**: {$orderTitle}\n\n**您的操作**: {$statusText}\n\n您已完成此审批操作。",
'tag' => 'lark_md',
],
],
[
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => "https://uniservice-mobile.hnxinyouhe.com/approval/detail/{$orderId}?company={$companyId}",
],
],
],
],
];
$contentJson = json_encode($updatedCard, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response = HttpClient::httpPatchJson(
"https://open.feishu.cn/open-apis/im/v1/messages/{$message->message_id}",
[
'msg_type' => 'interactive',
'content' => $contentJson,
],
['content'],
[
'Authorization: Bearer ' . $this->getAccessToken(),
]
);
$code = $response['code'] ?? -1;
if ($code === 0) {
error_log("✅ 操作人消息卡片更新成功: message_id={$message->message_id}, user_id={$actorUserId}, status={$status}");
// 标记消息为已更新
$message->status = \app\model\FeishuMessage::STATUS_UPDATED;
$message->save();
} else {
error_log("❌ 操作人消息卡片更新失败: message_id={$message->message_id}, error=" . json_encode($response));
return false;
}
return true;
} catch (Exception $e) {
error_log("❌ updateActorMessageCard 异常: " . $e->getMessage());
return false;
}
}
/**
* 更新其他审批人的消息卡片
* 多公司多飞书应用场景:使用每个消息对应的原始飞书应用去更新
*
* @param int $orderId 订单ID
* @param int $nodeId 节点ID
* @param int $excludeUserId 排除的用户ID(已经操作过的用户)
* @param string $status 审批状态 (approved/rejected)
* @param string $operatorName 操作人姓名
* @return bool
*/
public function updateMessageCards(int $orderId, int $nodeId, int $excludeUserId, string $status, string $operatorName): bool
{
try {
// 获取该节点的所有消息(排除已操作的用户)
$messages = \app\model\FeishuMessage::where('order_id', $orderId)
->where('node_id', $nodeId)
->where('user_id', '!=', $excludeUserId)
->where('status', \app\model\FeishuMessage::STATUS_ACTIVE)
->get();
if ($messages->isEmpty()) {
error_log("📭 没有需要更新的消息: order_id={$orderId}, node_id={$nodeId}");
return true;
}
$statusText = $status === 'approved' ? '已通过' : '已拒绝';
$statusColor = $status === 'approved' ? 'green' : 'red';
// 为每个消息使用其对应的飞书应用去更新
foreach ($messages as $message) {
try {
$companyId = $message->company_id;
$feishuAppId = $message->feishu_app_id;
if (!$companyId || !$feishuAppId) {
error_log("❌ 消息记录缺少 company_id 或 feishu_app_id: message_id={$message->message_id}");
continue;
}
error_log("🔍 准备更新消息: message_id={$message->message_id}, company_id={$companyId}, feishu_app_id={$feishuAppId}");
// 使用该消息对应的飞书应用配置
$this->companyId = $companyId;
$this->appId = $feishuAppId;
// 构建更新后的卡片(移除操作按钮)
$updatedCard = [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => '📋 审批已完成',
'tag' => 'plain_text',
],
'template' => $statusColor,
],
'elements' => [
[
'tag' => 'div',
'text' => [
'content' => "**操作人**: {$operatorName}\n**操作结果**: {$statusText}\n\n此审批已被处理,无需重复操作。",
'tag' => 'lark_md',
],
],
[
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '查看详情',
'tag' => 'plain_text',
],
'type' => 'default',
'url' => "https://uniservice-mobile.hnxinyouhe.com/approval/detail/{$orderId}?company={$companyId}",
],
],
],
],
];
$contentJson = json_encode($updatedCard, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response = HttpClient::httpPatchJson(
"https://open.feishu.cn/open-apis/im/v1/messages/{$message->message_id}",
[
'msg_type' => 'interactive',
'content' => $contentJson,
],
['content'],
[
'Authorization: Bearer ' . $this->getAccessToken(),
]
);
$code = $response['code'] ?? -1;
if ($code === 0) {
error_log("✅ 消息卡片更新成功: message_id={$message->message_id}, company_id={$companyId}");
// 标记消息为已更新
$message->status = \app\model\FeishuMessage::STATUS_UPDATED;
$message->save();
} else {
error_log("❌ 消息卡片更新失败: message_id={$message->message_id}, company_id={$companyId}, error=" . json_encode($response));
}
} catch (Exception $e) {
error_log("❌ 更新消息卡片异常: message_id={$message->message_id}, error=" . $e->getMessage());
}
}
return true;
} catch (Exception $e) {
error_log('❌ updateMessageCards 异常: ' . $e->getMessage());
return false;
}
}
/**
* 更新会签节点的消息卡片(部分审批人已通过)
* 用于会签场景:一人通过后,更新其他人的消息卡片,显示等待其他人审批
*
* @param int $orderId 订单ID
* @param int $nodeId 节点ID
* @param int $excludeUserId 排除的用户ID(已经操作过的用户)
* @param string $operatorName 操作人姓名
* @param int $approvedCount 已通过人数
* @param int $totalCount 总审批人数
* @return bool
*/
public function updateMessageCardsForPartialApprove(int $orderId, int $nodeId, int $excludeUserId, string $operatorName, int $approvedCount, int $totalCount): bool
{
try {
// 获取该节点的所有消息(排除已操作的用户)
$messages = \app\model\FeishuMessage::where('order_id', $orderId)
->where('node_id', $nodeId)
->where('user_id', '!=', $excludeUserId)
->where('status', \app\model\FeishuMessage::STATUS_ACTIVE)
->get();
if ($messages->isEmpty()) {
error_log("📭 没有需要更新的消息: order_id={$orderId}, node_id={$nodeId}");
return true;
}
// 获取订单申请人信息,从用户中获取公司ID
$order = \app\model\ApprovalOrder::find($orderId);
$companyId = null;
$applicantIdForLog = 'null';
if ($order) {
$applicantIdForLog = $order->applicant_id;
$applicant = \app\model\User::find($order->applicant_id);
if ($applicant && !empty($applicant->company_id)) {
$companyId = $applicant->company_id;
}
}
error_log("🔍 updateMessageCards: order_id={$orderId}, applicant_id={$applicantIdForLog}, company_id={$companyId}");
// 如果获取到公司ID,设置飞书应用配置
if ($companyId) {
$this->setAppByUser($excludeUserId, $companyId);
error_log("✅ setAppByUser called: user_id={$excludeUserId}, company_id={$companyId}");
} else {
error_log("❌ company_id is empty or order not found");
}
$token = $this->getAccessToken();
$remainingCount = $totalCount - $approvedCount;
foreach ($messages as $message) {
try {
// 构建更新后的卡片(保留操作按钮,但更新状态提示)
$updatedCard = [
'config' => [
'wide_screen_mode' => false,
],
'header' => [
'title' => [
'content' => '⏳ 会签进行中',
'tag' => 'plain_text',
],
'template' => 'blue',
],
'elements' => [
[
'tag' => 'div',
'text' => [
'content' => "**{$operatorName}** 已通过审批\n\n📊 进度: {$approvedCount}/{$totalCount} 人已通过,还剩 {$remainingCount} 人等待审批",
'tag' => 'lark_md',
],
],
[
'tag' => 'action',
'actions' => [
[
'tag' => 'button',
'text' => [
'content' => '通过',
'tag' => 'plain_text',
],
'type' => 'primary',
'size' => 'medium',
'value' => [
'action_type' => 'approve',
'order_id' => (int)$orderId,
],
],
[
'tag' => 'button',
'text' => [
'content' => '拒绝',
'tag' => 'plain_text',
],
'type' => 'danger',
'size' => 'medium',
'value' => [
'action_type' => 'reject',
'order_id' => (int)$orderId,
],
],
],
],
],
];
$requestData = [
'message_id' => $message->message_id,
'card' => $updatedCard,
'approved_count' => $approvedCount,
'total_count' => $totalCount,
];
$contentJson = json_encode($updatedCard, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response = HttpClient::httpPatchJson(
"https://open.feishu.cn/open-apis/im/v1/messages/{$message->message_id}",
[
'msg_type' => 'interactive',
'content' => $contentJson,
],
['content'],
[
'Authorization: Bearer ' . $token,
]
);
$code = $response['code'] ?? -1;
if ($code === 0) {
error_log("✅ 会签消息卡片更新成功: message_id={$message->message_id}, approved={$approvedCount}/{$totalCount}");
// 记录成功日志
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_UPDATE_CARD,
$orderId,
$nodeId,
$message->user_id,
$message->message_id,
\app\model\FeishuMessageLog::STATUS_SUCCESS,
$requestData,
$response
);
} else {
error_log("❌ 会签消息卡片更新失败: message_id={$message->message_id}, error=" . json_encode($response));
// 记录失败日志
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_UPDATE_CARD,
$orderId,
$nodeId,
$message->user_id,
$message->message_id,
\app\model\FeishuMessageLog::STATUS_FAILED,
$requestData,
$response,
$response['msg'] ?? 'Unknown error'
);
}
} catch (Exception $e) {
error_log("❌ 更新会签消息卡片异常: message_id={$message->message_id}, error=" . $e->getMessage());
// 记录异常日志
\app\model\FeishuMessageLog::log(
\app\model\FeishuMessageLog::ACTION_UPDATE_CARD,
$orderId,
$nodeId,
$message->user_id,
$message->message_id,
\app\model\FeishuMessageLog::STATUS_FAILED,
null,
null,
$e->getMessage()
);
}
}
return true;
} catch (Exception $e) {
error_log('❌ updateMessageCardsForPartialApprove 异常: ' . $e->getMessage());
return false;
}
}
/**
* 发送文本消息(用于自审批场景)
*/
private function sendTextNotification(string $feishuUserId, array $params): bool
{
try {
$title = $params['title'] ?? '审批申请';
$type = $params['type'] ?? '申请';
$content = $params['content'] ?? '';
$url = $params['url'] ?? '';
// 构建文本内容
$text = "【{$title}】\n";
$text .= "申请类型:{$type}\n";
if ($content) {
// 清理 markdown 格式,转为纯文本
$content = preg_replace('/\*\*(.*?)\*\*/', '$1', $content);
$content = str_replace('**', '', $content);
$text .= "\n{$content}\n";
}
if ($url) {
$text .= "\n👉 点击查看详情:{$url}";
}
// 发送文本消息
return $this->sendText($feishuUserId, $text);
} catch (Exception $e) {
error_log('❌ sendTextNotification 异常: ' . $e->getMessage());
return false;
}
}
/**
* 发送纯文本消息
*/
private function sendText(string $feishuUserId, string $text): bool
{
try {
$accessToken = $this->getAccessToken();
if (!$accessToken) {
error_log('❌ sendText: 获取 access_token 失败');
return false;
}
$apiUrl = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id";
// content 必须是 JSON 字符串,使用 httpPostJson 避免二次编码
$contentJson = json_encode(['text' => $text], JSON_UNESCAPED_UNICODE);
$requestData = [
'receive_id' => $feishuUserId,
'msg_type' => 'text',
'content' => $contentJson,
];
error_log('📤 发送文本消息: feishu_user_id=' . $feishuUserId . ', text=' . substr($text, 0, 100));
$responseData = \app\util\HttpClient::httpPostJson($apiUrl, $requestData, ['content'], [
'Authorization: Bearer ' . $accessToken,
]);
$code = $responseData['code'] ?? -1;
if ($code !== 0) {
error_log('❌ 发送文本消息失败: ' . json_encode($responseData));
} else {
error_log('✅ 文本消息发送成功');
}
return $code === 0;
} catch (Exception $e) {
error_log('❌ sendText 异常: ' . $e->getMessage());
return false;
}
}
}