fix: 修复页面间状态丢失问题并优化选择页面
- 修复选择审批人后再选择抄送人导致状态丢失的问题 - 使用独立的 sessionStorage key (selectedApprovers, selectedCc) - 组件每次挂载时从 sessionStorage 恢复状态 - 只在提交/保存成功后清除 sessionStorage - 优化人员选择页面布局和样式 - 更新 CLAUDE.md 文档记录问题和解决方案 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,301 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\ApprovalFlow;
|
||||
use App\Model\ApprovalNode;
|
||||
use App\Model\ApprovalOrder;
|
||||
use App\Model\ApprovalRecord;
|
||||
use App\Model\User;
|
||||
use App\Util\Db;
|
||||
use Illuminate\Database\Connection;
|
||||
|
||||
class ApprovalService
|
||||
{
|
||||
private Connection $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// Initialize database if not already initialized
|
||||
Db::init();
|
||||
$this->db = Db::connection();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交审批
|
||||
*/
|
||||
public function submit(array $data): ApprovalOrder
|
||||
{
|
||||
return $this->db->transaction(function () use ($data) {
|
||||
// 1. 获取审批流程
|
||||
$flow = ApprovalFlow::active()
|
||||
->byBusinessType($data['business_type'])
|
||||
->with('nodes')
|
||||
->findOrFail($data['flow_id']);
|
||||
|
||||
// 2. 创建审批单
|
||||
$order = ApprovalOrder::create([
|
||||
'business_type' => $data['business_type'],
|
||||
'business_id' => $data['business_id'],
|
||||
'title' => $data['title'],
|
||||
'applicant_id' => $data['applicant_id'],
|
||||
'status' => ApprovalOrder::STATUS_PENDING,
|
||||
'current_nodes' => $this->getFirstNodeIds($flow),
|
||||
'flow_id' => $flow->id,
|
||||
'form_data' => $data['form_data'] ?? [],
|
||||
'attachments' => $data['attachments'] ?? [],
|
||||
]);
|
||||
|
||||
// 3. 记录提交操作
|
||||
ApprovalRecord::create([
|
||||
'order_id' => $order->id,
|
||||
'node_id' => $flow->nodes->first()->id ?? 0,
|
||||
'node_type' => 'submit',
|
||||
'approver_id' => $data['applicant_id'],
|
||||
'action' => ApprovalRecord::ACTION_SUBMIT,
|
||||
'comment' => $data['comment'] ?? null,
|
||||
]);
|
||||
|
||||
return $order->load(['flow', 'applicant']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批通过
|
||||
*/
|
||||
public function approve(int $orderId, int $approverId, ?string $comment = null): ApprovalOrder
|
||||
{
|
||||
return $this->db->transaction(function () use ($orderId, $approverId, $comment) {
|
||||
$order = ApprovalOrder::with(['flow.nodes'])->findOrFail($orderId);
|
||||
|
||||
if (!$order->canApprove()) {
|
||||
throw new \Exception('当前状态无法审批');
|
||||
}
|
||||
|
||||
$currentNodeIds = $order->current_nodes ?? [];
|
||||
$currentNode = ApprovalNode::whereIn('id', $currentNodeIds)->first();
|
||||
|
||||
if (!$currentNode) {
|
||||
throw new \Exception('当前节点不存在');
|
||||
}
|
||||
|
||||
// 记录审批操作
|
||||
ApprovalRecord::create([
|
||||
'order_id' => $order->id,
|
||||
'node_id' => $currentNode->id,
|
||||
'node_type' => $currentNode->type,
|
||||
'approver_id' => $approverId,
|
||||
'action' => ApprovalRecord::ACTION_APPROVE,
|
||||
'comment' => $comment,
|
||||
]);
|
||||
|
||||
// 判断节点是否完成
|
||||
if ($this->isNodeCompleted($order->id, $currentNode->id)) {
|
||||
// 移动到下一节点
|
||||
$nextNodes = $this->getNextNodes($order->flow, $currentNode->order);
|
||||
|
||||
if (empty($nextNodes)) {
|
||||
// 审批完成
|
||||
$order->status = ApprovalOrder::STATUS_APPROVED;
|
||||
$order->current_nodes = [];
|
||||
} else {
|
||||
$order->current_nodes = collect($nextNodes)->pluck('id')->toArray();
|
||||
}
|
||||
|
||||
$order->save();
|
||||
}
|
||||
|
||||
return $order->fresh(['flow', 'applicant', 'records']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批拒绝
|
||||
*/
|
||||
public function reject(int $orderId, int $approverId, ?string $comment = null): ApprovalOrder
|
||||
{
|
||||
return $this->db->transaction(function () use ($orderId, $approverId, $comment) {
|
||||
$order = ApprovalOrder::findOrFail($orderId);
|
||||
|
||||
if (!$order->canApprove()) {
|
||||
throw new \Exception('当前状态无法审批');
|
||||
}
|
||||
|
||||
$currentNodeIds = $order->current_nodes ?? [];
|
||||
$currentNode = ApprovalNode::whereIn('id', $currentNodeIds)->first();
|
||||
|
||||
// 记录拒绝操作
|
||||
ApprovalRecord::create([
|
||||
'order_id' => $order->id,
|
||||
'node_id' => $currentNode->id ?? 0,
|
||||
'node_type' => $currentNode->type ?? 'unknown',
|
||||
'approver_id' => $approverId,
|
||||
'action' => ApprovalRecord::ACTION_REJECT,
|
||||
'comment' => $comment,
|
||||
]);
|
||||
|
||||
// 更新状态为已拒绝
|
||||
$order->status = ApprovalOrder::STATUS_REJECTED;
|
||||
$order->current_nodes = [];
|
||||
$order->save();
|
||||
|
||||
return $order->fresh(['flow', 'applicant', 'records']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 撤销申请
|
||||
*/
|
||||
public function cancel(int $orderId, int $userId): ApprovalOrder
|
||||
{
|
||||
$order = ApprovalOrder::findOrFail($orderId);
|
||||
|
||||
if ($order->applicant_id !== $userId) {
|
||||
throw new \Exception('只有申请人可以撤销');
|
||||
}
|
||||
|
||||
if (!$order->canEdit() && !$order->canApprove()) {
|
||||
throw new \Exception('当前状态无法撤销');
|
||||
}
|
||||
|
||||
// 记录撤销操作
|
||||
ApprovalRecord::create([
|
||||
'order_id' => $order->id,
|
||||
'node_id' => 0,
|
||||
'node_type' => 'cancel',
|
||||
'approver_id' => $userId,
|
||||
'action' => ApprovalRecord::ACTION_CANCEL,
|
||||
'comment' => '申请人撤销',
|
||||
]);
|
||||
|
||||
$order->status = ApprovalOrder::STATUS_CANCELLED;
|
||||
$order->current_nodes = [];
|
||||
$order->save();
|
||||
|
||||
return $order->fresh(['flow', 'applicant', 'records']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取审批列表
|
||||
*/
|
||||
public function getList(int $userId, string $type = 'my', int $page = 1, int $pageSize = 20): array
|
||||
{
|
||||
$query = ApprovalOrder::with(['flow', 'applicant']);
|
||||
|
||||
switch ($type) {
|
||||
case 'my':
|
||||
$query->where('applicant_id', $userId);
|
||||
break;
|
||||
case 'pending':
|
||||
// 获取用户待审批的订单
|
||||
$pendingOrderIds = $this->getPendingOrderIds($userId);
|
||||
$query->whereIn('id', $pendingOrderIds);
|
||||
break;
|
||||
case 'approved':
|
||||
// 获取用户已审批的订单
|
||||
$approvedOrderIds = ApprovalRecord::where('approver_id', $userId)
|
||||
->where('action', '!=', ApprovalRecord::ACTION_SUBMIT)
|
||||
->pluck('order_id')
|
||||
->unique()
|
||||
->toArray();
|
||||
$query->whereIn('id', $approvedOrderIds);
|
||||
break;
|
||||
}
|
||||
|
||||
$total = $query->count();
|
||||
$list = $query->orderBy('created_at', 'desc')
|
||||
->offset(($page - 1) * $pageSize)
|
||||
->limit($pageSize)
|
||||
->get();
|
||||
|
||||
return [
|
||||
'list' => $list,
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取第一个节点ID列表
|
||||
*/
|
||||
private function getFirstNodeIds(ApprovalFlow $flow): array
|
||||
{
|
||||
return $flow->nodes
|
||||
->where('order', 0)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断节点是否完成
|
||||
*/
|
||||
private function isNodeCompleted(int $orderId, int $nodeId): bool
|
||||
{
|
||||
$node = ApprovalNode::findOrFail($nodeId);
|
||||
$records = ApprovalRecord::where('order_id', $orderId)
|
||||
->where('node_id', $nodeId)
|
||||
->where('action', ApprovalRecord::ACTION_APPROVE)
|
||||
->get();
|
||||
|
||||
$approvers = $node->approvers ?? [];
|
||||
|
||||
if ($node->type === ApprovalNode::TYPE_AND_APPROVE) {
|
||||
// 会签:需要所有人通过
|
||||
return count($records) >= count($approvers);
|
||||
} elseif ($node->type === ApprovalNode::TYPE_OR_APPROVE) {
|
||||
// 或签:任一人通过即可
|
||||
return count($records) >= 1;
|
||||
} else {
|
||||
// 单人审批:需要一人通过
|
||||
return count($records) >= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一节点
|
||||
*/
|
||||
private function getNextNodes(ApprovalFlow $flow, int $currentOrder): array
|
||||
{
|
||||
return $flow->nodes
|
||||
->where('order', '>', $currentOrder)
|
||||
->sortBy('order')
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户待审批的订单ID列表
|
||||
*/
|
||||
private function getPendingOrderIds(int $userId): array
|
||||
{
|
||||
// 获取用户参与的待审批订单
|
||||
$pendingOrders = ApprovalOrder::where('status', ApprovalOrder::STATUS_PENDING)
|
||||
->whereNotNull('current_nodes')
|
||||
->get();
|
||||
|
||||
$result = [];
|
||||
foreach ($pendingOrders as $order) {
|
||||
$currentNodeIds = $order->current_nodes ?? [];
|
||||
$nodes = ApprovalNode::whereIn('id', $currentNodeIds)->get();
|
||||
|
||||
foreach ($nodes as $node) {
|
||||
$approvers = $node->approvers ?? [];
|
||||
if (in_array($userId, $approvers)) {
|
||||
// 检查是否已审批
|
||||
$hasApproved = ApprovalRecord::where('order_id', $order->id)
|
||||
->where('node_id', $node->id)
|
||||
->where('approver_id', $userId)
|
||||
->exists();
|
||||
|
||||
if (!$hasApproved) {
|
||||
$result[] = $order->id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\BusinessTrip;
|
||||
use App\Model\BusinessTripItinerary;
|
||||
use App\Model\ApprovalOrder;
|
||||
use App\Model\ApprovalFlow;
|
||||
use App\Model\ApprovalRecord;
|
||||
use App\Model\User;
|
||||
use App\Util\Db;
|
||||
use Illuminate\Database\Connection;
|
||||
|
||||
class BusinessTripService
|
||||
{
|
||||
private Connection $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
Db::init();
|
||||
$this->db = Db::connection();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建出差申请(草稿)
|
||||
*/
|
||||
public function createDraft(int $userId, array $data): BusinessTrip
|
||||
{
|
||||
return $this->db->transaction(function () use ($userId, $data) {
|
||||
try {
|
||||
// 计算最早和最晚时间
|
||||
$itineraries = $data['itineraries'] ?? [];
|
||||
if (empty($itineraries)) {
|
||||
throw new \Exception('请至少添加一条行程');
|
||||
}
|
||||
|
||||
$startDate = null;
|
||||
$endDate = null;
|
||||
$destinations = [];
|
||||
|
||||
foreach ($itineraries as $itinerary) {
|
||||
if ($itinerary['start_time']) {
|
||||
if (!$startDate || $itinerary['start_time'] < $startDate) {
|
||||
$startDate = $itinerary['start_time'];
|
||||
}
|
||||
}
|
||||
if ($itinerary['end_time']) {
|
||||
if (!$endDate || $itinerary['end_time'] > $endDate) {
|
||||
$endDate = $itinerary['end_time'];
|
||||
}
|
||||
}
|
||||
if (!empty($itinerary['destination'])) {
|
||||
$destinations[] = $itinerary['destination'];
|
||||
}
|
||||
}
|
||||
|
||||
// 创建出差申请
|
||||
$businessTrip = BusinessTrip::create([
|
||||
'user_id' => $userId,
|
||||
'reason' => $data['reason'] ?? '',
|
||||
'start_date' => $startDate ? date('Y-m-d', strtotime($startDate)) : null,
|
||||
'end_date' => $endDate ? date('Y-m-d', strtotime($endDate)) : null,
|
||||
'destination' => implode(', ', array_unique($destinations)),
|
||||
'estimated_cost' => $data['estimated_cost'] ?? 0,
|
||||
'status' => BusinessTrip::STATUS_DRAFT,
|
||||
]);
|
||||
|
||||
// 创建行程明细
|
||||
foreach ($itineraries as $itinerary) {
|
||||
BusinessTripItinerary::create([
|
||||
'business_trip_id' => $businessTrip->id,
|
||||
'start_time' => $itinerary['start_time'],
|
||||
'end_time' => $itinerary['end_time'] ?? null,
|
||||
'departure' => $itinerary['departure'] ?? '',
|
||||
'destination' => $itinerary['destination'] ?? '',
|
||||
'transport' => $itinerary['transport'] ?? '',
|
||||
'trip_type' => $itinerary['trip_type'] ?? 'oneway',
|
||||
'remark' => $itinerary['remark'] ?? '',
|
||||
]);
|
||||
}
|
||||
|
||||
return $businessTrip->load('itineraries');
|
||||
} catch (\Exception $e) {
|
||||
error_log('BusinessTripService::createDraft error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
|
||||
throw $e;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交出差申请
|
||||
*/
|
||||
public function submit(int $userId, int $businessTripId, array $approvers, array $ccUsers = []): BusinessTrip
|
||||
{
|
||||
return $this->db->transaction(function () use ($userId, $businessTripId, $approvers, $ccUsers) {
|
||||
$businessTrip = BusinessTrip::with('itineraries')->findOrFail($businessTripId);
|
||||
|
||||
if ($businessTrip->user_id !== $userId) {
|
||||
throw new \Exception('无权操作此申请');
|
||||
}
|
||||
|
||||
if (!$businessTrip->canSubmit()) {
|
||||
throw new \Exception('当前状态无法提交');
|
||||
}
|
||||
|
||||
// 获取审批流程(简化版:直接使用第一个审批人作为单人审批)
|
||||
$flow = ApprovalFlow::where('business_type', 'business_trip')
|
||||
->where('status', 1)
|
||||
->first();
|
||||
|
||||
if (!$flow) {
|
||||
// 创建默认流程
|
||||
$flow = ApprovalFlow::create([
|
||||
'business_type' => 'business_trip',
|
||||
'name' => '出差审批',
|
||||
'description' => '出差申请审批流程',
|
||||
'status' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
// 创建审批单
|
||||
$approvalOrder = ApprovalOrder::create([
|
||||
'business_type' => 'business_trip',
|
||||
'business_id' => $businessTrip->id,
|
||||
'title' => '出差申请 - ' . $businessTrip->user->name,
|
||||
'applicant_id' => $userId,
|
||||
'status' => ApprovalOrder::STATUS_PENDING,
|
||||
'current_nodes' => [1], // 简化:使用节点1
|
||||
'flow_id' => $flow->id,
|
||||
'form_data' => [
|
||||
'reason' => $businessTrip->reason,
|
||||
'start_date' => $businessTrip->start_date,
|
||||
'end_date' => $businessTrip->end_date,
|
||||
'destination' => $businessTrip->destination,
|
||||
'approvers' => $approvers,
|
||||
'cc_users' => $ccUsers,
|
||||
],
|
||||
]);
|
||||
|
||||
// 更新出差申请状态
|
||||
$businessTrip->status = BusinessTrip::STATUS_PENDING;
|
||||
$businessTrip->approval_order_id = $approvalOrder->id;
|
||||
$businessTrip->save();
|
||||
|
||||
// 记录提交操作
|
||||
ApprovalRecord::create([
|
||||
'order_id' => $approvalOrder->id,
|
||||
'node_id' => 1,
|
||||
'node_type' => 'single_approve',
|
||||
'approver_id' => $userId,
|
||||
'action' => 'submit',
|
||||
'comment' => null,
|
||||
]);
|
||||
|
||||
return $businessTrip->fresh(['itineraries', 'approvalOrder']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取出差申请列表
|
||||
*/
|
||||
public function getList(int $userId, string $type = 'my', int $page = 1, int $pageSize = 20): array
|
||||
{
|
||||
$query = BusinessTrip::with(['user', 'itineraries']);
|
||||
|
||||
switch ($type) {
|
||||
case 'my':
|
||||
$query->where('user_id', $userId);
|
||||
break;
|
||||
case 'pending':
|
||||
// 获取待审批的申请
|
||||
$pendingOrderIds = ApprovalOrder::where('status', ApprovalOrder::STATUS_PENDING)
|
||||
->where('business_type', 'business_trip')
|
||||
->pluck('business_id')
|
||||
->toArray();
|
||||
$query->whereIn('id', $pendingOrderIds);
|
||||
break;
|
||||
}
|
||||
|
||||
$total = $query->count();
|
||||
$list = $query->orderBy('created_at', 'desc')
|
||||
->offset(($page - 1) * $pageSize)
|
||||
->limit($pageSize)
|
||||
->get();
|
||||
|
||||
return [
|
||||
'list' => $list,
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取出差申请详情
|
||||
*/
|
||||
public function getDetail(int $id): BusinessTrip
|
||||
{
|
||||
return BusinessTrip::with(['user', 'itineraries'])
|
||||
->findOrFail($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新出差申请
|
||||
*/
|
||||
public function update(int $userId, int $id, array $data): BusinessTrip
|
||||
{
|
||||
$businessTrip = BusinessTrip::findOrFail($id);
|
||||
|
||||
if ($businessTrip->user_id !== $userId) {
|
||||
throw new \Exception('无权操作此申请');
|
||||
}
|
||||
|
||||
if (!$businessTrip->canEdit()) {
|
||||
throw new \Exception('当前状态无法编辑');
|
||||
}
|
||||
|
||||
return $this->db->transaction(function () use ($businessTrip, $data) {
|
||||
// 更新基本信息
|
||||
if (isset($data['reason'])) {
|
||||
$businessTrip->reason = $data['reason'];
|
||||
}
|
||||
|
||||
// 更新行程
|
||||
if (isset($data['itineraries'])) {
|
||||
// 删除旧行程
|
||||
BusinessTripItinerary::where('business_trip_id', $businessTrip->id)->delete();
|
||||
|
||||
// 创建新行程
|
||||
$startDate = null;
|
||||
$endDate = null;
|
||||
$destinations = [];
|
||||
|
||||
foreach ($data['itineraries'] as $itinerary) {
|
||||
BusinessTripItinerary::create([
|
||||
'business_trip_id' => $businessTrip->id,
|
||||
'start_time' => $itinerary['start_time'],
|
||||
'end_time' => $itinerary['end_time'] ?? null,
|
||||
'departure' => $itinerary['departure'] ?? '',
|
||||
'destination' => $itinerary['destination'] ?? '',
|
||||
'transport' => $itinerary['transport'] ?? '',
|
||||
'trip_type' => $itinerary['trip_type'] ?? 'oneway',
|
||||
'remark' => $itinerary['remark'] ?? '',
|
||||
]);
|
||||
|
||||
if ($itinerary['start_time']) {
|
||||
if (!$startDate || $itinerary['start_time'] < $startDate) {
|
||||
$startDate = $itinerary['start_time'];
|
||||
}
|
||||
}
|
||||
if ($itinerary['end_time']) {
|
||||
if (!$endDate || $itinerary['end_time'] > $endDate) {
|
||||
$endDate = $itinerary['end_time'];
|
||||
}
|
||||
}
|
||||
if (!empty($itinerary['destination'])) {
|
||||
$destinations[] = $itinerary['destination'];
|
||||
}
|
||||
}
|
||||
|
||||
// 更新日期和目的地
|
||||
$businessTrip->start_date = $startDate ? date('Y-m-d', strtotime($startDate)) : null;
|
||||
$businessTrip->end_date = $endDate ? date('Y-m-d', strtotime($endDate)) : null;
|
||||
$businessTrip->destination = implode(', ', array_unique($destinations));
|
||||
}
|
||||
|
||||
$businessTrip->save();
|
||||
|
||||
return $businessTrip->fresh('itineraries');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消出差申请
|
||||
*/
|
||||
public function cancel(int $userId, int $id): BusinessTrip
|
||||
{
|
||||
$businessTrip = BusinessTrip::findOrFail($id);
|
||||
|
||||
if ($businessTrip->user_id !== $userId) {
|
||||
throw new \Exception('无权操作此申请');
|
||||
}
|
||||
|
||||
if (!$businessTrip->canCancel()) {
|
||||
throw new \Exception('当前状态无法取消');
|
||||
}
|
||||
|
||||
$businessTrip->status = BusinessTrip::STATUS_CANCELLED;
|
||||
$businessTrip->save();
|
||||
|
||||
// 同时取消审批单
|
||||
if ($businessTrip->approval_order_id) {
|
||||
$approvalOrder = ApprovalOrder::find($businessTrip->approval_order_id);
|
||||
if ($approvalOrder) {
|
||||
$approvalOrder->status = ApprovalOrder::STATUS_CANCELLED;
|
||||
$approvalOrder->current_nodes = [];
|
||||
$approvalOrder->save();
|
||||
}
|
||||
}
|
||||
|
||||
return $businessTrip->fresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\Company;
|
||||
use App\Model\CompanyFeishuApp;
|
||||
use App\Model\User;
|
||||
use App\Util\Db;
|
||||
|
||||
class FeishuService
|
||||
{
|
||||
private ?string $accessToken = null;
|
||||
private ?int $companyId = null;
|
||||
private ?int $appId = null;
|
||||
|
||||
// 简单的内存缓存(生产环境应使用 Redis)
|
||||
private static array $tokenCache = [];
|
||||
|
||||
/**
|
||||
* 设置当前操作的公司
|
||||
*/
|
||||
public function setCompany(int $companyId): self
|
||||
{
|
||||
$this->companyId = $companyId;
|
||||
$this->accessToken = null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置飞书应用ID(支持多应用)
|
||||
*/
|
||||
public function setApp(int $appId): self
|
||||
{
|
||||
$this->appId = $appId;
|
||||
$this->accessToken = null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 tenant_key 获取公司配置
|
||||
*/
|
||||
public function getCompanyByTenantKey(string $tenantKey): ?Company
|
||||
{
|
||||
return Company::active()->byTenantKey($tenantKey)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公司的飞书应用配置
|
||||
*/
|
||||
private function getFeishuApp(int $appId): array
|
||||
{
|
||||
$app = CompanyFeishuApp::find($appId);
|
||||
|
||||
if (!$app || $app->status !== 1) {
|
||||
throw new \Exception('飞书应用配置不存在');
|
||||
}
|
||||
|
||||
return $app->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公司的默认飞书应用
|
||||
*/
|
||||
private function getDefaultFeishuApp(int $companyId): array
|
||||
{
|
||||
$app = CompanyFeishuApp::where('company_id', $companyId)
|
||||
->where('system_id', 1)
|
||||
->where('status', 1)
|
||||
->orderBy('sort')
|
||||
->first();
|
||||
|
||||
if (!$app) {
|
||||
throw new \Exception('未配置飞书应用');
|
||||
}
|
||||
|
||||
return $app->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取飞书应用配置(优先使用指定应用,否则使用默认应用)
|
||||
*/
|
||||
private function getAppConfig(): array
|
||||
{
|
||||
if (!$this->companyId) {
|
||||
throw new \Exception('未设置公司ID');
|
||||
}
|
||||
|
||||
if ($this->appId) {
|
||||
return $this->getFeishuApp($this->appId);
|
||||
}
|
||||
|
||||
return $this->getDefaultFeishuApp($this->companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取飞书 access_token
|
||||
*/
|
||||
public function getAccessToken(): string
|
||||
{
|
||||
if ($this->accessToken) {
|
||||
return $this->accessToken;
|
||||
}
|
||||
|
||||
$app = $this->getAppConfig();
|
||||
$cacheKey = "feishu:access_token:{$app['id']}";
|
||||
|
||||
// 从内存缓存获取
|
||||
if (isset(self::$tokenCache[$cacheKey]) && self::$tokenCache[$cacheKey]['expire'] > time()) {
|
||||
$this->accessToken = self::$tokenCache[$cacheKey]['token'];
|
||||
return $this->accessToken;
|
||||
}
|
||||
|
||||
// 请求新的 token
|
||||
$response = $this->httpPost('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', [
|
||||
'app_id' => $app['app_id'],
|
||||
'app_secret' => $app['app_secret'],
|
||||
]);
|
||||
|
||||
if ($response['code'] !== 0) {
|
||||
throw new \Exception('获取飞书 token 失败: ' . ($response['msg'] ?? '未知错误'));
|
||||
}
|
||||
|
||||
$token = $response['tenant_access_token'];
|
||||
$expire = $response['expire'] ?? 7200;
|
||||
|
||||
// 缓存 token(提前5分钟过期)
|
||||
self::$tokenCache[$cacheKey] = [
|
||||
'token' => $token,
|
||||
'expire' => time() + $expire - 300,
|
||||
];
|
||||
|
||||
$this->accessToken = $token;
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 auth_code 获取用户信息
|
||||
*/
|
||||
public function getUserInfo(string $authCode): array
|
||||
{
|
||||
$app = $this->getAppConfig();
|
||||
$token = $this->getAccessToken();
|
||||
|
||||
// 获取用户 access_token
|
||||
$response = $this->httpPost('https://open.feishu.cn/open-apis/authen/v1/oidc/access_token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'client_id' => $app['app_id'],
|
||||
'client_secret' => $app['app_secret'],
|
||||
'code' => $authCode,
|
||||
], [
|
||||
'Authorization: Bearer ' . $token,
|
||||
]);
|
||||
|
||||
if ($response['code'] !== 0) {
|
||||
throw new \Exception('获取用户信息失败: ' . ($response['msg'] ?? '未知错误'));
|
||||
}
|
||||
|
||||
return $response['data'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建或更新用户
|
||||
*/
|
||||
public function createOrUpdateUser(array $feishuData, int $companyId): User
|
||||
{
|
||||
$unionId = $feishuData['union_id'] ?? null;
|
||||
$userId = $feishuData['user_id'] ?? null;
|
||||
$name = $feishuData['name'] ?? '未知';
|
||||
$avatar = $feishuData['avatar_url'] ?? null;
|
||||
$email = $feishuData['email'] ?? null;
|
||||
|
||||
if (!$unionId) {
|
||||
throw new \Exception('缺少 union_id');
|
||||
}
|
||||
|
||||
// 查找或创建用户
|
||||
$user = User::byFeishuUnionId($unionId)->first();
|
||||
|
||||
if (!$user) {
|
||||
$user = User::create([
|
||||
'company_id' => $companyId,
|
||||
'feishu_user_id' => $userId,
|
||||
'feishu_union_id' => $unionId,
|
||||
'name' => $name,
|
||||
'email' => $email,
|
||||
'avatar' => $avatar,
|
||||
'status' => 1,
|
||||
]);
|
||||
} else {
|
||||
// 更新用户信息
|
||||
$user->update([
|
||||
'feishu_user_id' => $userId,
|
||||
'name' => $name,
|
||||
'avatar' => $avatar,
|
||||
'email' => $email,
|
||||
]);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送审批消息通知
|
||||
*/
|
||||
public function sendApprovalMessage(int $userId, string $title, string $url): bool
|
||||
{
|
||||
try {
|
||||
$user = User::findOrFail($userId);
|
||||
$company = Company::findOrFail($user->company_id);
|
||||
|
||||
$this->setCompany($company->id);
|
||||
$token = $this->getAccessToken();
|
||||
|
||||
// 构建消息内容
|
||||
$message = [
|
||||
'msg_type' => 'interactive',
|
||||
'card' => [
|
||||
'header' => [
|
||||
'title' => [
|
||||
'content' => '审批通知',
|
||||
'tag' => 'plain_text',
|
||||
],
|
||||
'template' => 'blue',
|
||||
],
|
||||
'elements' => [
|
||||
[
|
||||
'tag' => 'div',
|
||||
'text' => [
|
||||
'content' => $title,
|
||||
'tag' => 'plain_text',
|
||||
],
|
||||
],
|
||||
[
|
||||
'tag' => 'action',
|
||||
'actions' => [
|
||||
[
|
||||
'tag' => 'button',
|
||||
'text' => [
|
||||
'content' => '查看详情',
|
||||
'tag' => 'plain_text',
|
||||
],
|
||||
'type' => 'default',
|
||||
'url' => $url,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// 发送消息
|
||||
$response = $this->httpPost(
|
||||
"https://open.feishu.cn/open-apis/message/v4/send_messages",
|
||||
[
|
||||
'receive_id_type' => 'user_id',
|
||||
'receive_id' => $user->feishu_user_id,
|
||||
'msg_type' => 'interactive',
|
||||
'content' => json_encode(['card' => $message['card']]),
|
||||
],
|
||||
[
|
||||
'Authorization: Bearer ' . $token,
|
||||
]
|
||||
);
|
||||
|
||||
return ($response['code'] ?? -1) === 0;
|
||||
} catch (\Exception $e) {
|
||||
// 记录错误但不中断流程
|
||||
error_log('发送飞书消息失败: ' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP POST 请求
|
||||
*/
|
||||
private function httpPost(string $url, array $data, array $headers = []): array
|
||||
{
|
||||
$ch = curl_init();
|
||||
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
|
||||
$defaultHeaders = [
|
||||
'Content-Type: application/json',
|
||||
];
|
||||
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($defaultHeaders, $headers));
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
// curl_close($ch); // 不再需要,PHP 8.5+ 自动关闭
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
throw new \Exception("HTTP 请求失败: {$httpCode}");
|
||||
}
|
||||
|
||||
$result = json_decode($response, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new \Exception('JSON 解析失败');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user