feat: 添加消息卡片更新功能,支持或签/单人审批场景

新增功能:
1. 创建 feishu_message 表,存储消息与审批订单/节点/用户的映射关系
2. 发送审批通知时保存 message_id
3. 审批完成后自动更新其他审批人的消息卡片

使用场景:
- 或签(or_approve):一人通过后,更新其他审批人的消息卡片
- 单人审批(approver):一人通过后,更新其他审批人的消息卡片
- 拒绝(reject):拒绝后更新所有其他审批人的消息卡片

技术细节:
- FeishuMessage 模型:管理消息映射
- FeishuNotificationService::updateMessageCards():更新消息卡片
- ApprovalService:审批完成后调用消息更新逻辑

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-28 18:06:40 +08:00
parent aeff21aec6
commit 1f72da9ec4
6 changed files with 273 additions and 15 deletions
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace app\model;
use support\Model;
/**
* 飞书审批消息映射模型
*/
class FeishuMessage extends Model
{
protected $table = 'feishu_message';
protected $fillable = [
'order_id',
'node_id',
'user_id',
'message_id',
'msg_token',
'status',
];
const STATUS_ACTIVE = 'active';
const STATUS_UPDATED = 'updated';
const STATUS_DELETED = 'deleted';
/**
* 根据订单和节点获取消息列表
*/
public static function getMessagesByOrderAndNode(int $orderId, int $nodeId): array
{
return self::where('order_id', $orderId)
->where('node_id', $nodeId)
->where('status', self::STATUS_ACTIVE)
->get()
->toArray();
}
/**
* 保存消息映射
*/
public static function saveMessage(
int $orderId,
int $nodeId,
int $userId,
string $messageId,
?string $msgToken = null
): self {
return self::updateOrCreate(
[
'order_id' => $orderId,
'node_id' => $nodeId,
'user_id' => $userId,
],
[
'message_id' => $messageId,
'msg_token' => $msgToken,
'status' => self::STATUS_ACTIVE,
]
);
}
/**
* 标记消息为已更新
*/
public static function markAsUpdated(int $orderId, int $nodeId): bool
{
return self::where('order_id', $orderId)
->where('node_id', $nodeId)
->update(['status' => self::STATUS_UPDATED]) > 0;
}
}
+34
View File
@@ -111,6 +111,22 @@ class ApprovalService
// 判断节点是否完成
if ($this->isNodeCompleted($order->id, $currentNode->id)) {
// 对于或签和单人审批,更新其他审批人的消息卡片
if ($currentNode->type === ApprovalNode::TYPE_OR_APPROVE || $currentNode->type === 'approver') {
$approver = User::find($approverId);
$approverName = $approver ? $approver->name : '未知';
if ($this->notificationService) {
$this->notificationService->updateMessageCards(
$order->id,
$currentNode->id,
$approverId,
'approved',
$approverName
);
}
}
// 移动到下一节点
$nextNodes = $this->getNextNodes($order->flow, $currentNode->order);
@@ -178,6 +194,20 @@ class ApprovalService
'comment' => $comment,
]);
// 更新其他审批人的消息卡片(拒绝时所有人都需要更新)
$approver = User::find($approverId);
$approverName = $approver ? $approver->name : '未知';
if ($this->notificationService && $currentNode) {
$this->notificationService->updateMessageCards(
$order->id,
$currentNode->id,
$approverId,
'rejected',
$approverName
);
}
// 更新状态为已拒绝
$order->status = ApprovalOrder::STATUS_REJECTED;
$order->current_nodes = [];
@@ -498,6 +528,9 @@ class ApprovalService
error_log("🔔 通知下一节点审批人: order_id={$order->id}, approverIds=" . json_encode($approverIds));
// 获取第一个下一节点的 ID(用于消息映射)
$nextNodeId = $nextNodes[0]['id'] ?? null;
// 为每个审批人发送通知
foreach ($approverIds as $approverId) {
try {
@@ -511,6 +544,7 @@ class ApprovalService
'content' => "**申请标题**: {$order->title}\n**申请人**: {$order->applicant->name}",
'url' => $detailUrl,
'order_id' => $order->id,
'node_id' => $nextNodeId, // 添加节点ID用于保存消息映射
]);
error_log("✅ 审批人通知成功: approver_id={$approverId}");
} catch (\Exception $e) {
@@ -318,6 +318,7 @@ class BusinessTripService
'content' => $content,
'url' => $approvalUrl,
'order_id' => $approvalOrder->id,
'node_id' => $node->id, // 添加节点ID用于保存消息映射
]);
error_log("✅ 审批人通知成功: approver_id={$approverId}");
} catch (\Exception $e) {
+110 -15
View File
@@ -119,14 +119,17 @@ class FeishuNotificationService
* - 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'));
error_log("📧 sendApprovalNotification 被调用: user_id={$userId}, applicant_id=" . ($applicantId ?? 'null') . ", order_id={$orderId}, node_id={$nodeId}");
if (!$userId) {
error_log('❌ sendApprovalNotification: 缺少 user_id');
@@ -157,7 +160,15 @@ class FeishuNotificationService
error_log("📨 发送卡片消息: 不是自审批");
$card = $this->buildApprovalCard($params, $user->company_id);
return $this->sendMessage($feishuUserId, $card);
$messageId = $this->sendMessage($feishuUserId, $card);
if ($messageId && $orderId && $nodeId) {
// 保存消息映射
\app\model\FeishuMessage::saveMessage($orderId, $nodeId, $userId, $messageId);
error_log("💾 保存消息映射: order_id={$orderId}, node_id={$nodeId}, user_id={$userId}, message_id={$messageId}");
}
return $messageId !== false;
} catch (Exception $e) {
error_log('❌ sendApprovalNotification 失败: ' . $e->getMessage());
return false;
@@ -539,26 +550,19 @@ class FeishuNotificationService
/**
* 发送消息到飞书
* @return string|false 返回 message_id 或 false
*/
private function sendMessage(string $feishuUserId, array $card): bool
private function sendMessage(string $feishuUserId, array $card)
{
try {
$app = $this->getAppConfig();
$token = $this->getAccessToken();
$body = [
'receive_id_type' => 'user_id',
'receive_id' => $feishuUserId,
'msg_type' => 'interactive',
'content' => json_encode(['card' => $card]),
];
$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",
[
@@ -576,17 +580,108 @@ class FeishuNotificationService
if ($code !== 0) {
error_log('❌ 飞书消息发送失败: ' . json_encode($response));
} else {
error_log('✅ 飞书消息发送成功');
return false;
}
return $code === 0;
$messageId = $response['data']['message_id'] ?? null;
if ($messageId) {
error_log('✅ 飞书消息发送成功, message_id=' . $messageId);
return $messageId;
}
return false;
} catch (Exception $e) {
error_log('❌ sendMessage 异常: ' . $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;
}
$token = $this->getAccessToken();
$statusText = $status === 'approved' ? '已通过' : '已拒绝';
$statusColor = $status === 'approved' ? 'green' : 'red';
foreach ($messages as $message) {
try {
// 构建更新后的卡片(移除操作按钮)
$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',
],
],
],
];
$response = HttpClient::httpPost(
"https://open.feishu.cn/open-apis/im/v1/messages/{$message->message_id}/update",
[
'msg_type' => 'interactive',
'content' => json_encode(['card' => $updatedCard]),
],
[
'Authorization: Bearer ' . $token,
]
);
$code = $response['code'] ?? -1;
if ($code === 0) {
error_log("✅ 消息卡片更新成功: message_id={$message->message_id}");
// 标记消息为已更新
$message->status = \app\model\FeishuMessage::STATUS_UPDATED;
$message->save();
} else {
error_log("❌ 消息卡片更新失败: message_id={$message->message_id}, 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;
}
}
/**
* 发送文本消息(用于自审批场景)
*/
@@ -0,0 +1,32 @@
<?php
use support\Db;
return new class
{
public function up(): void
{
Db::statement('
CREATE TABLE IF NOT EXISTS `feishu_message` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`order_id` bigint unsigned NOT NULL COMMENT \'审批订单ID\',
`node_id` bigint unsigned NOT NULL COMMENT \'审批节点ID\',
`user_id` bigint unsigned NOT NULL COMMENT \'审批人ID\',
`message_id` varchar(64) NOT NULL COMMENT \'飞书消息ID\',
`msg_token` varchar(128) DEFAULT NULL COMMENT \'消息Token(用于更新卡片)\',
`status` varchar(20) NOT NULL DEFAULT \'active\' COMMENT \'active: 有效, updated: 已更新, deleted: 已删除\',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_order_node_user` (`order_id`, `node_id`, `user_id`),
KEY `idx_message_id` (`message_id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=\'飞书审批消息映射表\'
');
}
public function down(): void
{
Db::statement('DROP TABLE IF EXISTS `feishu_message`');
}
};