新增生成pdf
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\approval\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class ApprovalCcs extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'approval_ccs';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 允许自动填充模型字段
|
||||
*/
|
||||
protected $fillable = ['id', 'instance_id', 'user_id', 'notified_at', 'read_at', 'created_at', 'updated_at'];
|
||||
|
||||
/**
|
||||
* 不允许自动填充模型字段
|
||||
*/
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\approval\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class ApprovalFlows extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'approval_flows';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 允许自动填充模型字段
|
||||
*/
|
||||
protected $fillable = ['id', 'name', 'type', 'steps', 'is_active', 'timeout_hours', 'timeout_action', 'created_at', 'updated_at'];
|
||||
|
||||
/**
|
||||
* 不允许自动填充模型字段
|
||||
*/
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\approval\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class ApprovalInstances extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'approval_instances';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 允许自动填充模型字段
|
||||
*/
|
||||
protected $fillable = ['id', 'flow_type', 'biz_id', 'biz_type', 'form_data', 'initiator_id', 'status', 'current_step', 'finished_at', 'deadline_at', 'created_at', 'updated_at'];
|
||||
|
||||
/**
|
||||
* 不允许自动填充模型字段
|
||||
*/
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\approval\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class ApprovalRecords extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'approval_records';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = true;
|
||||
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 允许自动填充模型字段
|
||||
*/
|
||||
protected $fillable = ['id', 'instance_id', 'approver_id', 'step_index', 'action', 'comment', 'approved_at', 'created_at', 'updated_at'];
|
||||
|
||||
/**
|
||||
* 不允许自动填充模型字段
|
||||
*/
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
<?php
|
||||
namespace app\common\approval\service;
|
||||
|
||||
use DateTime;
|
||||
use support\exception\BusinessException;
|
||||
use support\Db;
|
||||
|
||||
use app\common\approval\model\ApprovalCcs;
|
||||
use app\common\approval\model\ApprovalFlows;
|
||||
use app\common\approval\model\ApprovalInstances;
|
||||
use app\common\approval\model\ApprovalRecords;
|
||||
|
||||
class ApprovalFlowService
|
||||
{
|
||||
// --- 公共方法 ---
|
||||
|
||||
/**
|
||||
* 启动审批流程
|
||||
*/
|
||||
public function start(string $flowType, string $bizType, string $bizId, array $formData, int $initiatorId): array
|
||||
{
|
||||
// 1. 获取流程定义
|
||||
$flow = Db::table('approval_flows')
|
||||
->where('type', $flowType)
|
||||
->where('is_active', 1)
|
||||
->first();
|
||||
|
||||
if (!$flow) {
|
||||
throw new BusinessException("审批流程未找到或已停用: {$flowType}");
|
||||
}
|
||||
|
||||
$steps = json_decode($flow->steps, true);
|
||||
if (!is_array($steps) || empty($steps)) {
|
||||
throw new BusinessException("流程步骤配置错误");
|
||||
}
|
||||
|
||||
// 2. 查找第一个有效步骤(考虑 condition)
|
||||
$firstStep = $this->getNextValidStep($steps, $formData);
|
||||
if (!$firstStep) {
|
||||
throw new BusinessException("未找到可执行的审批步骤");
|
||||
}
|
||||
|
||||
// 3. 创建审批实例
|
||||
$instanceId = Db::table('approval_instances')->insertGetId([
|
||||
'flow_type' => $flowType,
|
||||
'biz_type' => $bizType,
|
||||
'biz_id' => $bizId,
|
||||
'form_data' => json_encode($formData, JSON_UNESCAPED_UNICODE),
|
||||
'initiator_id' => $initiatorId,
|
||||
'status' => 'processing',
|
||||
'current_step' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 4. 创建审批记录(待办)
|
||||
$approverIds = $this->resolveApprovers($firstStep, (object)['initiator_id' => $initiatorId]);
|
||||
foreach ($approverIds as $approverId) {
|
||||
Db::table('approval_records')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'step_name' => $firstStep['name'],
|
||||
'approver_id' => $approverId,
|
||||
'status' => 'pending',
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
// 5. 通知审批人
|
||||
$this->sendNotification($approverIds, (object)['id' => $instanceId, 'flow_type' => $flowType], 'pending', false);
|
||||
|
||||
// 6. 通知抄送人(当前步骤)
|
||||
$this->notifyCCs($firstStep, (object)['id' => $instanceId, 'flow_type' => $flowType, 'form_data' => json_encode($formData)], 'pending');
|
||||
|
||||
return ['instance_id' => $instanceId];
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行审批
|
||||
*/
|
||||
public function approve(int $instanceId, int $approverId, string $action, string $comment = '')
|
||||
{
|
||||
$instance = Db::table('approval_instances')->where('id', $instanceId)->first();
|
||||
if (!$instance) {
|
||||
throw new BusinessException("审批实例未找到");
|
||||
}
|
||||
|
||||
$steps = json_decode($instance->steps, true) ?: json_decode(Db::table('approval_flows')->where('type', $instance->flow_type)->value('steps'), true);
|
||||
$currentStep = $steps[$instance->current_step] ?? null;
|
||||
|
||||
if (!$currentStep) {
|
||||
throw new BusinessException("当前步骤配置错误");
|
||||
}
|
||||
|
||||
// 检查用户是否有权限审批
|
||||
if (!$this->canUserApproveStep($currentStep, $approverId, $instance)) {
|
||||
throw new BusinessException("您无权审批此步骤");
|
||||
}
|
||||
|
||||
// 更新审批记录
|
||||
Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('approver_id', $approverId)
|
||||
->where('status', 'pending')
|
||||
->update([
|
||||
'status' => $action,
|
||||
'comment' => $comment,
|
||||
'approved_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 检查当前步骤是否完成(根据 type: any, all, sequential)
|
||||
$stepCompleted = $this->isStepCompleted($instanceId, $instance->current_step, $currentStep['type']);
|
||||
|
||||
if (!$stepCompleted) {
|
||||
// 步骤未完成,不进入下一步
|
||||
return ['status' => 'step_pending'];
|
||||
}
|
||||
|
||||
// 步骤已完成,进入下一步或结束
|
||||
$nextStep = $this->getNextValidStep($steps, json_decode($instance->form_data, true), $instance->current_step + 1);
|
||||
|
||||
if ($nextStep === null) {
|
||||
// 流程结束
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update([
|
||||
'status' => $action === 'approve' ? 'approved' : 'rejected',
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 通知发起人结果
|
||||
$this->sendNotification([$instance->initiator_id], $instance, $action, false);
|
||||
|
||||
return ['status' => 'completed', 'result' => $action];
|
||||
}
|
||||
|
||||
// 进入下一步
|
||||
$nextStepIndex = array_search($nextStep, $steps);
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update([
|
||||
'current_step' => $nextStepIndex,
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 创建下一步的审批记录
|
||||
$nextApprovers = $this->resolveApprovers($nextStep, $instance);
|
||||
foreach ($nextApprovers as $approverId) {
|
||||
Db::table('approval_records')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'step_name' => $nextStep['name'],
|
||||
'approver_id' => $approverId,
|
||||
'status' => 'pending',
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
// 通知下一步审批人
|
||||
$this->sendNotification($nextApprovers, $instance, 'pending', false);
|
||||
|
||||
// 通知下一步抄送人
|
||||
$this->notifyCCs($nextStep, $instance, 'pending');
|
||||
|
||||
return ['status' => 'next_step', 'step_name' => $nextStep['name']];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析审批人
|
||||
*/
|
||||
private function resolveApprovers(array $step, object $instance): array
|
||||
{
|
||||
$resolved = [];
|
||||
$formData = json_decode($instance->form_data ?? '{}', true);
|
||||
|
||||
foreach ($step['approvers'] as $approverConfig) {
|
||||
$approverIds = [];
|
||||
|
||||
switch ($approverConfig['type']) {
|
||||
case 'role':
|
||||
$approverIds = $this->getUserIdsByRole($approverConfig['value']);
|
||||
break;
|
||||
case 'user':
|
||||
$approverIds = [(int)$approverConfig['value']];
|
||||
break;
|
||||
case 'initiator_leader':
|
||||
$leaderId = $this->getLeaderIdByUserId($instance->initiator_id);
|
||||
if ($leaderId) $approverIds = [$leaderId];
|
||||
break;
|
||||
case 'field_user':
|
||||
if (isset($formData[$approverConfig['value']])) {
|
||||
$approverIds = [(int)$formData[$approverConfig['value']]];
|
||||
}
|
||||
break;
|
||||
case 'dept_head':
|
||||
$approverIds = $this->getDeptHeadId($approverConfig['value']);
|
||||
if ($approverIds) $approverIds = [$approverIds];
|
||||
break;
|
||||
default:
|
||||
throw new BusinessException("不支持的审批人类型: {$approverConfig['type']}");
|
||||
}
|
||||
|
||||
$resolved = array_merge($resolved, $approverIds);
|
||||
}
|
||||
|
||||
return array_unique(array_filter($resolved));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知抄送人
|
||||
*/
|
||||
private function notifyCCs(array $step, object $instance, string $action = 'pending')
|
||||
{
|
||||
$ccConfig = $step['cc'] ?? [];
|
||||
$ccUserIds = [];
|
||||
$formData = json_decode($instance->form_data ?? '{}', true);
|
||||
|
||||
foreach ($ccConfig as $cc) {
|
||||
switch ($cc['type']) {
|
||||
case 'role':
|
||||
$ccUserIds = array_merge($ccUserIds, $this->getUserIdsByRole($cc['value']));
|
||||
break;
|
||||
case 'user':
|
||||
$ccUserIds[] = (int)$cc['value'];
|
||||
break;
|
||||
case 'initiator_leader':
|
||||
$leaderId = $this->getLeaderIdByUserId($instance->initiator_id);
|
||||
if ($leaderId) $ccUserIds[] = $leaderId;
|
||||
break;
|
||||
case 'field_user':
|
||||
if (isset($formData[$cc['value']])) {
|
||||
$ccUserIds[] = (int)$formData[$cc['value']];
|
||||
}
|
||||
break;
|
||||
case 'dept_head':
|
||||
$deptHeadId = $this->getDeptHeadId($cc['value']);
|
||||
if ($deptHeadId) $ccUserIds[] = $deptHeadId;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$ccUserIds = array_unique(array_filter($ccUserIds));
|
||||
|
||||
if (!empty($ccUserIds)) {
|
||||
$this->sendNotification($ccUserIds, $instance, $action, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估条件
|
||||
*/
|
||||
private function evaluateCondition(?string $condition, array $formData): bool
|
||||
{
|
||||
if (!$condition) return true;
|
||||
|
||||
$pattern = '/^(\w+)\s*(==|!=|>|<|>=|<=)\s*(.+)$/';
|
||||
if (!preg_match($pattern, $condition, $matches)) {
|
||||
throw new BusinessException("条件格式错误: {$condition}");
|
||||
}
|
||||
|
||||
$field = $matches[1];
|
||||
$op = $matches[2];
|
||||
$value = trim($matches[3], "\"'");
|
||||
|
||||
$actualValue = $formData[$field] ?? null;
|
||||
|
||||
if (is_numeric($value) && is_numeric($actualValue)) {
|
||||
$value = (float)$value;
|
||||
$actualValue = (float)$actualValue;
|
||||
}
|
||||
|
||||
switch ($op) {
|
||||
case '==': return $actualValue == $value;
|
||||
case '!=': return $actualValue != $value;
|
||||
case '>': return $actualValue > $value;
|
||||
case '<': $actualValue < $value;
|
||||
case '>=': return $actualValue >= $value;
|
||||
case '<=': return $actualValue <= $value;
|
||||
default: throw new BusinessException("不支持的操作符: {$op}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个有效步骤(考虑 condition)
|
||||
*/
|
||||
private function getNextValidStep(array $steps, array $formData, int $startIndex = 0): ?array
|
||||
{
|
||||
for ($i = $startIndex; $i < count($steps); $i++) {
|
||||
$step = $steps[$i];
|
||||
if (!isset($step['condition']) || $this->evaluateCondition($step['condition'], $formData)) {
|
||||
return $step;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否有权限审批
|
||||
*/
|
||||
private function canUserApproveStep(array $step, int $userId, object $instance): bool
|
||||
{
|
||||
$approvers = $this->resolveApprovers($step, $instance);
|
||||
return in_array($userId, $approvers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前步骤是否完成
|
||||
*/
|
||||
private function isStepCompleted(int $instanceId, int $stepIndex, string $type): bool
|
||||
{
|
||||
$pendingCount = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('status', 'pending')
|
||||
->count();
|
||||
|
||||
if ($type === 'any') {
|
||||
return $pendingCount === 0; // 任一通过即可
|
||||
}
|
||||
|
||||
if ($type === 'all' || $type === 'sequential') {
|
||||
return $pendingCount === 0; // 所有人都必须审批
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送通知(你可以替换为你的通知系统)
|
||||
*/
|
||||
private function sendNotification(array $userIds, object $instance, string $action, bool $isCC)
|
||||
{
|
||||
$actionText = [
|
||||
'pending' => '待审批',
|
||||
'approve' => '已通过',
|
||||
'reject' => '已拒绝'
|
||||
][$action] ?? $action;
|
||||
|
||||
$prefix = $isCC ? '[抄送]' : '';
|
||||
$message = "{$prefix}您有一条审批 {$actionText}:流程ID {$instance->id},类型 {$instance->flow_type}";
|
||||
|
||||
// TODO: 调用你的消息系统,如邮件、站内信、企业微信等
|
||||
// 示例:MessageService::send($userIds, $message);
|
||||
echo "通知用户 " . implode(',', $userIds) . ":$message\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户待审批列表
|
||||
* @param int $userId 用户ID
|
||||
* @return array
|
||||
*/
|
||||
public function getPendingApprovals(int $userId): array
|
||||
{
|
||||
// 简化查询:找到用户需要审批的实例ID
|
||||
// 更复杂的逻辑(如并行会签)需要更精细的查询
|
||||
$instanceIds = Db::table('approval_records')
|
||||
->where('approver_id', $userId)
|
||||
->pluck('instance_id')
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
if (empty($instanceIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Db::table('approval_instances')
|
||||
->whereIn('id', $instanceIds)
|
||||
->where('status', 'processing')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取审批历史记录
|
||||
* @param int $instanceId
|
||||
* @return array
|
||||
*/
|
||||
public function getApprovalHistory(int $instanceId): array
|
||||
{
|
||||
return Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->orderBy('step_index')
|
||||
->orderBy('approved_at')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取审批流程图数据 (简化版)
|
||||
* @param int $instanceId
|
||||
* @return array
|
||||
*/
|
||||
public function getFlowDiagramData(int $instanceId): array
|
||||
{
|
||||
$instance = Db::table('approval_instances')->find($instanceId);
|
||||
if (!$instance) return [];
|
||||
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if (!$flow) return [];
|
||||
|
||||
$steps = json_decode($flow->steps, true);
|
||||
$records = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->orderBy('step_index')
|
||||
->orderBy('approved_at')
|
||||
->get()
|
||||
->groupBy('step_index');
|
||||
|
||||
$diagramData = [];
|
||||
foreach ($steps as $index => $step) {
|
||||
$status = 'pending';
|
||||
$actions = $records->get($index, collect())->toArray();
|
||||
|
||||
if (!empty($actions)) {
|
||||
$hasReject = collect($actions)->contains('action', 'reject');
|
||||
if ($hasReject) {
|
||||
$status = 'rejected';
|
||||
} else {
|
||||
if ($step['type'] === 'parallel') {
|
||||
// 简化处理
|
||||
$status = 'approved';
|
||||
} else {
|
||||
$status = 'approved';
|
||||
}
|
||||
}
|
||||
} elseif ($index < $instance->current_step) {
|
||||
$status = 'approved';
|
||||
} elseif ($index == $instance->current_step) {
|
||||
$status = 'processing';
|
||||
}
|
||||
|
||||
$diagramData[] = [
|
||||
'index' => $index,
|
||||
'name' => $step['name'],
|
||||
'type' => $step['type'],
|
||||
'status' => $status,
|
||||
'actions' => $actions
|
||||
];
|
||||
}
|
||||
return $diagramData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理超时的审批实例 (定时任务调用)
|
||||
*/
|
||||
public function handleTimeouts()
|
||||
{
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$expiredInstances = Db::table('approval_instances')
|
||||
->where('status', 'processing')
|
||||
->where('deadline_at', '<=', $now)
|
||||
->get();
|
||||
|
||||
foreach ($expiredInstances as $instance) {
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if ($flow && $flow->timeout_action) {
|
||||
$updateData = [
|
||||
'finished_at' => $now,
|
||||
'updated_at' => $now
|
||||
];
|
||||
if ($flow->timeout_action === 'auto_reject') {
|
||||
$updateData['status'] = 'rejected';
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'rejected_timeout');
|
||||
} elseif ($flow->timeout_action === 'auto_approve') {
|
||||
$updateData['status'] = 'approved';
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'approved_timeout');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 辅助方法 ---
|
||||
|
||||
// private function canUserApproveStep(array $step, int $userId, object $instance): bool
|
||||
// {
|
||||
// $approvers = $this->resolveApprovers($step, $instance);
|
||||
// return in_array($userId, $approvers);
|
||||
// }
|
||||
|
||||
// private function resolveApprovers(array $step, object $instance): array
|
||||
// {
|
||||
// $resolved = [];
|
||||
// foreach ($step['approvers'] as $approver) {
|
||||
// if ($approver['type'] === 'role') {
|
||||
// // 示例:根据角色查找用户ID,你需要替换为实际逻辑
|
||||
// if ($approver['value'] === 'admin') {
|
||||
// $resolved[] = 1; // 假设 admin 角色的用户ID是1
|
||||
// } elseif ($approver['value'] === 'manager') {
|
||||
// $resolved[] = 2; $resolved[] = 3; // 假设有多个manager
|
||||
// }
|
||||
// } elseif ($approver['type'] === 'user') {
|
||||
// $resolved[] = (int)$approver['value'];
|
||||
// } elseif ($approver['type'] === 'initiator_leader') {
|
||||
// // 示例:获取发起人的领导
|
||||
// $resolved[] = 4; // 假设领导ID是4
|
||||
// }
|
||||
// }
|
||||
// return array_unique($resolved);
|
||||
// }
|
||||
|
||||
// private function resolveApprovers(array $step, object $instance): array
|
||||
// {
|
||||
// $resolved = [];
|
||||
|
||||
// foreach ($step['approvers'] as $approverConfig) {
|
||||
// $approverIds = [];
|
||||
|
||||
// switch ($approverConfig['type']) {
|
||||
// // 1. 按角色查找
|
||||
// case 'role':
|
||||
// $roleCode = $approverConfig['value'];
|
||||
// // 所有拥有该角色的用户ID
|
||||
// $approverIds = $this->getUserIdsByRole($roleCode);
|
||||
// break;
|
||||
|
||||
// // 2. 按具体用户ID
|
||||
// case 'user':
|
||||
// $approverIds = [(int)$approverConfig['value']];
|
||||
// break;
|
||||
|
||||
// // 3. 按发起人的直属领导 (业务一般是组长)
|
||||
// case 'initiator_leader':
|
||||
// // 用户表中 report_to 字段
|
||||
// $approverIds = $this->getLeaderIdByUserId($instance->initiator_id);
|
||||
// if ($approverIds) {
|
||||
// $approverIds = [$approverIds];
|
||||
// } else {
|
||||
// $approverIds = []; // 没有领导,跳过
|
||||
// }
|
||||
// break;
|
||||
|
||||
// // 4. 按业务字段关联的用户 (高级功能)
|
||||
// case 'field_user':
|
||||
// $fieldName = $approverConfig['value']; // 如 'project_manager_id'
|
||||
// $formData = json_decode($instance->form_data, true);
|
||||
// if (isset($formData[$fieldName])) {
|
||||
// $approverIds = [(int)$formData[$fieldName]];
|
||||
// } else {
|
||||
// $approverIds = [];
|
||||
// }
|
||||
// break;
|
||||
|
||||
// // 5. 按组织架构层级 (如发起人所在部门的负责人)
|
||||
// case 'dept_head':
|
||||
// $deptId = $approverConfig['value']; // 也可以从 instance 或 formData 中获取
|
||||
// $approverIds = $this->getDeptHeadId($deptId);
|
||||
// if ($approverIds) {
|
||||
// $approverIds = [$approverIds];
|
||||
// } else {
|
||||
// $approverIds = [];
|
||||
// }
|
||||
// break;
|
||||
|
||||
// default:
|
||||
// throw new BusinessException("不支持的审批人类型: {$approverConfig['type']}");
|
||||
// }
|
||||
|
||||
// $resolved = array_merge($resolved, $approverIds);
|
||||
// }
|
||||
|
||||
// return array_unique($resolved);
|
||||
// }
|
||||
|
||||
// 角色层
|
||||
private function getUserIdsByRole(string $roleCode): array
|
||||
{
|
||||
// user_roles 表和 roles 表
|
||||
return Db::table('user_roles as ur')
|
||||
->join('roles as r', 'ur.role_id', '=', 'r.id')
|
||||
->where('r.code', $roleCode) // 假设 roles 表有 code 字段
|
||||
->pluck('ur.user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
// 领导层
|
||||
private function getLeaderIdByUserId(int $userId): ?int
|
||||
{
|
||||
// users 表 report_to 字段
|
||||
return Db::table('user')->where('id', $userId)->value('report_to');
|
||||
}
|
||||
|
||||
// 组织架构层
|
||||
private function getDeptHeadId(int $deptId): ?int
|
||||
{
|
||||
// departments 表 head_user_id 字段(部门逻辑暂时不用,根据后续业务实际情况开发)
|
||||
return Db::table('departments')->where('id', $deptId)->value('head_user_id');
|
||||
}
|
||||
|
||||
private function calculateNextStepIndex(int $instanceId, int $currentStepIndex, array $currentStep): int
|
||||
{
|
||||
// 对于 sequential 和 any,单次 approve 即进入下一步
|
||||
if ($currentStep['type'] === 'sequential' || $currentStep['type'] === 'any') {
|
||||
return $currentStepIndex + 1;
|
||||
} elseif ($currentStep['type'] === 'parallel') {
|
||||
// 对于并行会签,需要检查是否所有审批人都已 approve
|
||||
// 这里简化处理,实际需要精确计算
|
||||
// 假设只要有一次 approve 就算完成(不准确,仅为示例)
|
||||
// 正确做法是查询所有 approvers 是否都 approve 了
|
||||
return $currentStepIndex + 1;
|
||||
}
|
||||
return $currentStepIndex + 1;
|
||||
}
|
||||
|
||||
private function notifyNextApprovers(int $instanceId)
|
||||
{
|
||||
// 实现你的通知逻辑,如发送站内信、邮件、企业微信等
|
||||
// 可以查询 instance_id 对应的当前步骤审批人
|
||||
echo "通知下一个审批人 (Instance ID: {$instanceId})\n";
|
||||
}
|
||||
|
||||
private function notifyInitiator(object $instance, string $result)
|
||||
{
|
||||
// 通知发起人审批结果
|
||||
echo "通知发起人 {$instance->initiator_id} 审批结果: {$result}\n";
|
||||
}
|
||||
|
||||
private function notifyAllApprovers(object $instance, string $status)
|
||||
{
|
||||
// 通知所有相关审批人(如撤回时)
|
||||
echo "通知所有审批人,实例 {$instance->id} 状态变为: {$status}\n";
|
||||
}
|
||||
|
||||
private function notifyCc(int $instanceId)
|
||||
{
|
||||
// 通知抄送人
|
||||
echo "通知抄送人 (Instance ID: {$instanceId})\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
namespace app\common\approval\service;
|
||||
|
||||
use DateTime;
|
||||
use support\exception\BusinessException;
|
||||
use support\Db;
|
||||
|
||||
use app\common\approval\model\ApprovalCcs;
|
||||
use app\common\approval\model\ApprovalFlows;
|
||||
use app\common\approval\model\ApprovalInstances;
|
||||
use app\common\approval\model\ApprovalRecords;
|
||||
|
||||
class ApprovalFlowService_bak
|
||||
{
|
||||
// --- 公共方法 ---
|
||||
|
||||
/**
|
||||
* 启动一个审批实例
|
||||
* @param string $flowType 流程类型标识 (approval_flows.type)
|
||||
* @param string $bizType 业务类型标识 (如 'leave_application')
|
||||
* @param string $bizId 业务数据ID (如 leave_applications 表的 ID)
|
||||
* @param array $formData 提交的表单数据快照
|
||||
* @param int $initiatorId 发起人ID
|
||||
* @return array ['success' => true, 'instance_id' => ...] 或抛出异常
|
||||
*/
|
||||
public function start(string $flowType, string $bizType, string $bizId, array $formData, int $initiatorId): array
|
||||
{
|
||||
// 1. 获取流程定义
|
||||
$flow = Db::table('approval_flows')
|
||||
->where('type', $flowType)
|
||||
->where('is_active', 1)
|
||||
->first();
|
||||
|
||||
if (!$flow) {
|
||||
throw new BusinessException("审批流程 '{$flowType}' 不存在或已停用");
|
||||
}
|
||||
|
||||
// 2. 创建审批实例
|
||||
$instanceId = Db::table('approval_instances')->insertGetId([
|
||||
'flow_type' => $flowType,
|
||||
'biz_id' => $bizId,
|
||||
'biz_type' => $bizType,
|
||||
'form_data' => json_encode($formData),
|
||||
'initiator_id' => $initiatorId,
|
||||
'status' => 'processing',
|
||||
'current_step' => 0,
|
||||
'deadline_at' => $flow->timeout_hours > 0 ?
|
||||
(new DateTime())->modify("+{$flow->timeout_hours} hours")->format('Y-m-d H:i:s') : null,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 3. 通知下一个审批人
|
||||
$this->notifyNextApprovers($instanceId);
|
||||
|
||||
return ['success' => true, 'instance_id' => $instanceId];
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行审批操作
|
||||
* @param int $instanceId 审批实例ID
|
||||
* @param int $approverId 审批人ID
|
||||
* @param string $action 操作 (approve, reject, revoke)
|
||||
* @param string $comment 审批意见
|
||||
* @return array 操作结果
|
||||
*/
|
||||
public function approve(int $instanceId, int $approverId, string $action, string $comment = ''): array
|
||||
{
|
||||
// 1. 获取实例和流程
|
||||
$instance = Db::table('approval_instances')->find($instanceId);
|
||||
if (!$instance) {
|
||||
throw new BusinessException("审批实例不存在");
|
||||
}
|
||||
if ($instance->status !== 'processing') {
|
||||
throw new BusinessException("审批实例状态不正确");
|
||||
}
|
||||
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if (!$flow) {
|
||||
throw new BusinessException("关联的审批流程不存在");
|
||||
}
|
||||
|
||||
$steps = json_decode($flow->steps, true);
|
||||
$currentStepIndex = $instance->current_step;
|
||||
|
||||
if ($currentStepIndex >= count($steps)) {
|
||||
throw new BusinessException("审批流程已结束");
|
||||
}
|
||||
|
||||
$currentStep = $steps[$currentStepIndex];
|
||||
|
||||
// 2. 验证权限和条件
|
||||
if (!$this->canUserApproveStep($currentStep, $approverId, $instance)) {
|
||||
throw new BusinessException("您无权审批此步骤");
|
||||
}
|
||||
|
||||
// 3. 记录审批行为
|
||||
Db::table('approval_records')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'approver_id' => $approverId,
|
||||
'step_index' => $currentStepIndex,
|
||||
'action' => $action,
|
||||
'comment' => $comment,
|
||||
'approved_at' => date('Y-m-d H:i:s'),
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
|
||||
// 4. 处理审批结果
|
||||
$updateData = ['updated_at' => date('Y-m-d H:i:s')];
|
||||
if ($action === 'reject') {
|
||||
$updateData['status'] = 'rejected';
|
||||
$updateData['finished_at'] = date('Y-m-d H:i:s');
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'rejected');
|
||||
return ['result' => 'rejected'];
|
||||
}
|
||||
|
||||
if ($action === 'revoke') {
|
||||
if ($instance->initiator_id !== $approverId || $instance->status !== 'processing') {
|
||||
throw new BusinessException("无权撤回或状态不允许");
|
||||
}
|
||||
$updateData['status'] = 'revoked';
|
||||
$updateData['finished_at'] = date('Y-m-d H:i:s');
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update($updateData);
|
||||
$this->notifyAllApprovers($instance, 'revoked');
|
||||
return ['result' => 'revoked'];
|
||||
}
|
||||
|
||||
// 5. 处理 approve 逻辑
|
||||
$nextStepIndex = $this->calculateNextStepIndex($instanceId, $currentStepIndex, $currentStep);
|
||||
$updateData['current_step'] = $nextStepIndex;
|
||||
|
||||
if ($nextStepIndex >= count($steps)) {
|
||||
$updateData['status'] = 'approved';
|
||||
$updateData['finished_at'] = date('Y-m-d H:i:s');
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'approved');
|
||||
$this->notifyCc($instanceId);
|
||||
} else {
|
||||
Db::table('approval_instances')->where('id', $instanceId)->update($updateData);
|
||||
$this->notifyNextApprovers($instanceId);
|
||||
}
|
||||
|
||||
return ['result' => 'approved', 'next_step' => $nextStepIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户待审批列表
|
||||
* @param int $userId 用户ID
|
||||
* @return array
|
||||
*/
|
||||
public function getPendingApprovals(int $userId): array
|
||||
{
|
||||
// 简化查询:找到用户需要审批的实例ID
|
||||
// 更复杂的逻辑(如并行会签)需要更精细的查询
|
||||
$instanceIds = Db::table('approval_records')
|
||||
->where('approver_id', $userId)
|
||||
->pluck('instance_id')
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
if (empty($instanceIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Db::table('approval_instances')
|
||||
->whereIn('id', $instanceIds)
|
||||
->where('status', 'processing')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取审批历史记录
|
||||
* @param int $instanceId
|
||||
* @return array
|
||||
*/
|
||||
public function getApprovalHistory(int $instanceId): array
|
||||
{
|
||||
return Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->orderBy('step_index')
|
||||
->orderBy('approved_at')
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取审批流程图数据 (简化版)
|
||||
* @param int $instanceId
|
||||
* @return array
|
||||
*/
|
||||
public function getFlowDiagramData(int $instanceId): array
|
||||
{
|
||||
$instance = Db::table('approval_instances')->find($instanceId);
|
||||
if (!$instance) return [];
|
||||
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if (!$flow) return [];
|
||||
|
||||
$steps = json_decode($flow->steps, true);
|
||||
$records = Db::table('approval_records')
|
||||
->where('instance_id', $instanceId)
|
||||
->orderBy('step_index')
|
||||
->orderBy('approved_at')
|
||||
->get()
|
||||
->groupBy('step_index');
|
||||
|
||||
$diagramData = [];
|
||||
foreach ($steps as $index => $step) {
|
||||
$status = 'pending';
|
||||
$actions = $records->get($index, collect())->toArray();
|
||||
|
||||
if (!empty($actions)) {
|
||||
$hasReject = collect($actions)->contains('action', 'reject');
|
||||
if ($hasReject) {
|
||||
$status = 'rejected';
|
||||
} else {
|
||||
if ($step['type'] === 'parallel') {
|
||||
// 简化处理
|
||||
$status = 'approved';
|
||||
} else {
|
||||
$status = 'approved';
|
||||
}
|
||||
}
|
||||
} elseif ($index < $instance->current_step) {
|
||||
$status = 'approved';
|
||||
} elseif ($index == $instance->current_step) {
|
||||
$status = 'processing';
|
||||
}
|
||||
|
||||
$diagramData[] = [
|
||||
'index' => $index,
|
||||
'name' => $step['name'],
|
||||
'type' => $step['type'],
|
||||
'status' => $status,
|
||||
'actions' => $actions
|
||||
];
|
||||
}
|
||||
return $diagramData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理超时的审批实例 (定时任务调用)
|
||||
*/
|
||||
public function handleTimeouts()
|
||||
{
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$expiredInstances = Db::table('approval_instances')
|
||||
->where('status', 'processing')
|
||||
->where('deadline_at', '<=', $now)
|
||||
->get();
|
||||
|
||||
foreach ($expiredInstances as $instance) {
|
||||
$flow = Db::table('approval_flows')->where('type', $instance->flow_type)->first();
|
||||
if ($flow && $flow->timeout_action) {
|
||||
$updateData = [
|
||||
'finished_at' => $now,
|
||||
'updated_at' => $now
|
||||
];
|
||||
if ($flow->timeout_action === 'auto_reject') {
|
||||
$updateData['status'] = 'rejected';
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'rejected_timeout');
|
||||
} elseif ($flow->timeout_action === 'auto_approve') {
|
||||
$updateData['status'] = 'approved';
|
||||
Db::table('approval_instances')->where('id', $instance->id)->update($updateData);
|
||||
$this->notifyInitiator($instance, 'approved_timeout');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 辅助方法 ---
|
||||
|
||||
private function canUserApproveStep(array $step, int $userId, object $instance): bool
|
||||
{
|
||||
$approvers = $this->resolveApprovers($step, $instance);
|
||||
return in_array($userId, $approvers);
|
||||
}
|
||||
|
||||
// private function resolveApprovers(array $step, object $instance): array
|
||||
// {
|
||||
// $resolved = [];
|
||||
// foreach ($step['approvers'] as $approver) {
|
||||
// if ($approver['type'] === 'role') {
|
||||
// // 示例:根据角色查找用户ID,你需要替换为实际逻辑
|
||||
// if ($approver['value'] === 'admin') {
|
||||
// $resolved[] = 1; // 假设 admin 角色的用户ID是1
|
||||
// } elseif ($approver['value'] === 'manager') {
|
||||
// $resolved[] = 2; $resolved[] = 3; // 假设有多个manager
|
||||
// }
|
||||
// } elseif ($approver['type'] === 'user') {
|
||||
// $resolved[] = (int)$approver['value'];
|
||||
// } elseif ($approver['type'] === 'initiator_leader') {
|
||||
// // 示例:获取发起人的领导
|
||||
// $resolved[] = 4; // 假设领导ID是4
|
||||
// }
|
||||
// }
|
||||
// return array_unique($resolved);
|
||||
// }
|
||||
|
||||
private function resolveApprovers(array $step, object $instance): array
|
||||
{
|
||||
$resolved = [];
|
||||
|
||||
foreach ($step['approvers'] as $approverConfig) {
|
||||
$approverIds = [];
|
||||
|
||||
switch ($approverConfig['type']) {
|
||||
// 1. 按角色查找
|
||||
case 'role':
|
||||
$roleCode = $approverConfig['value'];
|
||||
// 所有拥有该角色的用户ID
|
||||
$approverIds = $this->getUserIdsByRole($roleCode);
|
||||
break;
|
||||
|
||||
// 2. 按具体用户ID
|
||||
case 'user':
|
||||
$approverIds = [(int)$approverConfig['value']];
|
||||
break;
|
||||
|
||||
// 3. 按发起人的直属领导 (业务一般是组长)
|
||||
case 'initiator_leader':
|
||||
// 用户表中 report_to 字段
|
||||
$approverIds = $this->getLeaderIdByUserId($instance->initiator_id);
|
||||
if ($approverIds) {
|
||||
$approverIds = [$approverIds];
|
||||
} else {
|
||||
$approverIds = []; // 没有领导,跳过
|
||||
}
|
||||
break;
|
||||
|
||||
// 4. 按业务字段关联的用户 (高级功能)
|
||||
case 'field_user':
|
||||
$fieldName = $approverConfig['value']; // 如 'project_manager_id'
|
||||
$formData = json_decode($instance->form_data, true);
|
||||
if (isset($formData[$fieldName])) {
|
||||
$approverIds = [(int)$formData[$fieldName]];
|
||||
} else {
|
||||
$approverIds = [];
|
||||
}
|
||||
break;
|
||||
|
||||
// 5. 按组织架构层级 (如发起人所在部门的负责人)
|
||||
case 'dept_head':
|
||||
$deptId = $approverConfig['value']; // 也可以从 instance 或 formData 中获取
|
||||
$approverIds = $this->getDeptHeadId($deptId);
|
||||
if ($approverIds) {
|
||||
$approverIds = [$approverIds];
|
||||
} else {
|
||||
$approverIds = [];
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new BusinessException("不支持的审批人类型: {$approverConfig['type']}");
|
||||
}
|
||||
|
||||
$resolved = array_merge($resolved, $approverIds);
|
||||
}
|
||||
|
||||
return array_unique($resolved);
|
||||
}
|
||||
|
||||
// 角色层
|
||||
private function getUserIdsByRole(string $roleCode): array
|
||||
{
|
||||
// user_roles 表和 roles 表
|
||||
return Db::table('user_roles as ur')
|
||||
->join('roles as r', 'ur.role_id', '=', 'r.id')
|
||||
->where('r.code', $roleCode) // 假设 roles 表有 code 字段
|
||||
->pluck('ur.user_id')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
// 领导层
|
||||
private function getLeaderIdByUserId(int $userId): ?int
|
||||
{
|
||||
// users 表 report_to 字段
|
||||
return Db::table('user')->where('id', $userId)->value('report_to');
|
||||
}
|
||||
|
||||
// 组织架构层
|
||||
private function getDeptHeadId(int $deptId): ?int
|
||||
{
|
||||
// departments 表 head_user_id 字段(部门逻辑暂时不用,根据后续业务实际情况开发)
|
||||
return Db::table('departments')->where('id', $deptId)->value('head_user_id');
|
||||
}
|
||||
|
||||
private function calculateNextStepIndex(int $instanceId, int $currentStepIndex, array $currentStep): int
|
||||
{
|
||||
// 对于 sequential 和 any,单次 approve 即进入下一步
|
||||
if ($currentStep['type'] === 'sequential' || $currentStep['type'] === 'any') {
|
||||
return $currentStepIndex + 1;
|
||||
} elseif ($currentStep['type'] === 'parallel') {
|
||||
// 对于并行会签,需要检查是否所有审批人都已 approve
|
||||
// 这里简化处理,实际需要精确计算
|
||||
// 假设只要有一次 approve 就算完成(不准确,仅为示例)
|
||||
// 正确做法是查询所有 approvers 是否都 approve 了
|
||||
return $currentStepIndex + 1;
|
||||
}
|
||||
return $currentStepIndex + 1;
|
||||
}
|
||||
|
||||
private function notifyNextApprovers(int $instanceId)
|
||||
{
|
||||
// 实现你的通知逻辑,如发送站内信、邮件、企业微信等
|
||||
// 可以查询 instance_id 对应的当前步骤审批人
|
||||
echo "通知下一个审批人 (Instance ID: {$instanceId})\n";
|
||||
}
|
||||
|
||||
private function notifyInitiator(object $instance, string $result)
|
||||
{
|
||||
// 通知发起人审批结果
|
||||
echo "通知发起人 {$instance->initiator_id} 审批结果: {$result}\n";
|
||||
}
|
||||
|
||||
private function notifyAllApprovers(object $instance, string $status)
|
||||
{
|
||||
// 通知所有相关审批人(如撤回时)
|
||||
echo "通知所有审批人,实例 {$instance->id} 状态变为: {$status}\n";
|
||||
}
|
||||
|
||||
private function notifyCc(int $instanceId)
|
||||
{
|
||||
// 通知抄送人
|
||||
echo "通知抄送人 (Instance ID: {$instanceId})\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
namespace app\common\utils\pdf\controller;
|
||||
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
use app\common\utils\pdf\service\document\ReimbursementDocumentService;
|
||||
use app\common\utils\pdf\service\PdfGeneratorService; // 用于通用 HTML 生成
|
||||
use Exception;
|
||||
|
||||
class DocumentController
|
||||
{
|
||||
|
||||
protected $noNeedLogin = ['downloadReimbursementPdf', 'viewReimbursementPdf'];
|
||||
|
||||
protected $noNeedHeaderData = ['downloadReimbursementPdf', 'viewReimbursementPdf'];
|
||||
|
||||
/**
|
||||
* 下载报销单 PDF
|
||||
* 访问路由: GET /document/reimbursement/{id}
|
||||
* 示例: /document/reimbursement/123
|
||||
*/
|
||||
public function downloadReimbursementPdf(Request $request, int $id)
|
||||
{
|
||||
try {
|
||||
$service = new ReimbursementDocumentService();
|
||||
$pdfData = $service->generatePdfById($id);
|
||||
|
||||
$filename = 'reimbursement_' . $id . '_' . date('Ymd_His') . '.pdf';
|
||||
return response($pdfData, 200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
// 记录日志
|
||||
// \support\Log::error("Failed to generate reimbursement PDF: " . $e->getMessage());
|
||||
return json(['code' => 1, 'msg' => 'Failed to generate PDF: ' . $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在浏览器中查看报销单 PDF
|
||||
* 访问路由: GET /document/reimbursement/view/{id}
|
||||
* 示例: /document/reimbursement/view/123
|
||||
*/
|
||||
public function viewReimbursementPdf(Request $request, int $id)
|
||||
{
|
||||
try {
|
||||
$service = new ReimbursementDocumentService();
|
||||
$pdfData = $service->generatePdfById($id);
|
||||
|
||||
return response($pdfData, 200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'inline; filename="reimbursement_view_' . $id . '.pdf"', // 'inline' 关键
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
return json(['code' => 1, 'msg' => 'Failed to view PDF: ' . $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存报销单 PDF 到服务器
|
||||
* 访问路由: POST /document/reimbursement/save
|
||||
* 参数: id (POST)
|
||||
*/
|
||||
public function saveReimbursementPdf(Request $request)
|
||||
{
|
||||
$id = $request->post('id');
|
||||
if (!$id || !is_numeric($id)) {
|
||||
return json(['code' => 1, 'msg' => 'Invalid ID']);
|
||||
}
|
||||
|
||||
try {
|
||||
// 指定保存路径
|
||||
$savePath = runtime_path() . '/generated_pdfs/reimbursements/';
|
||||
$service = new ReimbursementDocumentService();
|
||||
$service->savePdfToFile((int)$id, $savePath);
|
||||
|
||||
return json(['code' => 0, 'msg' => 'PDF saved successfully', 'path' => $savePath]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
return json(['code' => 1, 'msg' => 'Failed to save PDF: ' . $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用 HTML 到 PDF 生成接口 (示例)
|
||||
* 访问路由: POST /document/generate-from-html
|
||||
* 参数: html_content (POST)
|
||||
*/
|
||||
public function generateFromHtml(Request $request)
|
||||
{
|
||||
$htmlContent = $request->post('html_content');
|
||||
if (!$htmlContent) {
|
||||
return json(['code' => 1, 'msg' => 'HTML content is required']);
|
||||
}
|
||||
|
||||
try {
|
||||
$generator = new PdfGeneratorService();
|
||||
// 这里直接传入 HTML,不需要模板。可以创建一个简单的 'html_wrapper' 模板来应用样式。
|
||||
// 或者直接处理 HTML 字符串。
|
||||
// 为简化,我们假设传入的 HTML 已经包含所需样式。
|
||||
// 注意:TCPDF 对复杂 CSS 支持有限,内联样式通常更可靠。
|
||||
|
||||
// 创建一个临时数据结构
|
||||
$tempData = ['content' => $htmlContent];
|
||||
// 创建一个简单的模板 app/view/pdf/html_wrapper.php
|
||||
/* 内容示例: <?php echo $data['content']; ?> */
|
||||
// 但更简单的是直接使用 TCPDF 的 writeHTMLCell 或类似方法处理原始 HTML 片段
|
||||
// 这里我们直接调用 TCPDF (绕过服务的模板机制)
|
||||
|
||||
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
|
||||
$pdf->SetCreator('Your System');
|
||||
$pdf->SetTitle('Generated from HTML');
|
||||
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
|
||||
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
|
||||
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
|
||||
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
|
||||
$pdf->setFontSubsetting(true);
|
||||
$pdf->SetFont('dejavusans', '', 10, '', true);
|
||||
$pdf->AddPage();
|
||||
// 直接写入 HTML
|
||||
$pdf->writeHTML($htmlContent, true, false, true, false, '');
|
||||
$pdf->endPage();
|
||||
$pdfData = $pdf->Output('', 'S');
|
||||
|
||||
$filename = 'custom_html_' . date('Ymd_His') . '.pdf';
|
||||
return response($pdfData, 200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
return json(['code' => 1, 'msg' => 'Failed to generate PDF from HTML: ' . $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
namespace app\common\utils\pdf\service;
|
||||
|
||||
use TCPDF;
|
||||
use Exception;
|
||||
|
||||
class PdfGeneratorService
|
||||
{
|
||||
private $templatePath;
|
||||
private $defaultOptions;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// 设置模板基础路径
|
||||
$this->templatePath = app_path() . '/common/utils/pdf/template/';
|
||||
// 设置 TCPDF 默认选项
|
||||
$this->defaultOptions = [
|
||||
'page_orientation' => 'P', // PDF_PAGE_ORIENTATION
|
||||
'unit' => 'mm', // PDF_UNIT
|
||||
'page_format' => 'A4', // PDF_PAGE_FORMAT
|
||||
'unicode' => true,
|
||||
'encoding' => 'UTF-8',
|
||||
// --- 修改字体设置 ---
|
||||
// 'font' => 'dejavusans', // DejaVu 字体有时可能需要额外配置
|
||||
'font' => 'stsongstdlight', // 使用 TCPDF 内置的简体中文支持字体
|
||||
'font_style' => '', // 字体样式 (e.g., 'B' for bold)
|
||||
'font_size' => 10,
|
||||
// --- 字体设置结束 ---
|
||||
'creator' => 'Your Company Internal System',
|
||||
'author' => 'Your Company',
|
||||
'margin_left' => 15,
|
||||
'margin_right' => 15,
|
||||
'margin_top' => 20,
|
||||
'margin_bottom' => 20,
|
||||
'margin_header' => 5,
|
||||
'margin_footer' => 10,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染模板并返回 HTML 字符串
|
||||
*
|
||||
* @param string $templateName 模板文件名 (不含 .php)
|
||||
* @param array $data 注入模板的数据
|
||||
* @return string 渲染后的 HTML
|
||||
* @throws Exception
|
||||
*/
|
||||
private function renderTemplate(string $templateName, array $data): string
|
||||
{
|
||||
$templateFile = $this->templatePath . $templateName . '.php';
|
||||
|
||||
if (!file_exists($templateFile)) {
|
||||
throw new Exception("PDF template file not found: {$templateFile}");
|
||||
}
|
||||
|
||||
// 提取数据变量到当前作用域,供模板使用
|
||||
extract($data);
|
||||
|
||||
// 开启输出缓冲
|
||||
ob_start();
|
||||
// 包含模板文件
|
||||
include $templateFile;
|
||||
// 获取缓冲区内容并清理缓冲区
|
||||
$htmlContent = ob_get_clean();
|
||||
|
||||
if ($htmlContent === false) {
|
||||
throw new Exception("Failed to render PDF template: {$templateName}");
|
||||
}
|
||||
|
||||
return $htmlContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 PDF
|
||||
*
|
||||
* @param string $templateName 模板文件名 (不含 .php)
|
||||
* @param array $data 注入模板的数据
|
||||
* @param array $options (可选)覆盖默认的 TCPDF 选项
|
||||
* @return string PDF 二进制数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public function generate(string $templateName, array $data, array $options = []): string
|
||||
{
|
||||
// 合并选项
|
||||
$options = array_merge($this->defaultOptions, $options);
|
||||
|
||||
// 渲染 HTML
|
||||
$html = $this->renderTemplate($templateName, $data);
|
||||
|
||||
// 创建 TCPDF 实例
|
||||
$pdf = new TCPDF(
|
||||
$options['page_orientation'],
|
||||
$options['unit'],
|
||||
$options['page_format'],
|
||||
$options['unicode'],
|
||||
$options['encoding']
|
||||
);
|
||||
|
||||
// 设置文档信息
|
||||
$pdf->SetCreator($options['creator']);
|
||||
$pdf->SetAuthor($options['author']);
|
||||
$pdf->SetTitle($templateName . ' - Generated PDF');
|
||||
|
||||
// --- 修改字体设置 ---
|
||||
// 使用支持中文的字体
|
||||
// 'stsongstdlight' 是 TCPDF 内置的简体中文 CJK 字体
|
||||
// 'cid0cs' 也是支持中文的字体,可以尝试
|
||||
$pdf->SetFont($options['font'], $options['font_style'], $options['font_size'], '', true);
|
||||
// --- 字体设置结束 ---
|
||||
|
||||
// 设置页边距
|
||||
$pdf->SetMargins($options['margin_left'], $options['margin_top'], $options['margin_right']);
|
||||
$pdf->SetHeaderMargin($options['margin_header']);
|
||||
$pdf->SetFooterMargin($options['margin_footer']);
|
||||
|
||||
// 设置自动分页
|
||||
$pdf->SetAutoPageBreak(TRUE, $options['margin_bottom']);
|
||||
|
||||
// 设置图像比例因子
|
||||
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
|
||||
|
||||
// 添加首页
|
||||
$pdf->AddPage();
|
||||
|
||||
// 写入 HTML 内容
|
||||
$pdf->writeHTML($html, true, false, true, false, '');
|
||||
|
||||
// 结束最后一页
|
||||
$pdf->endPage();
|
||||
|
||||
// 返回 PDF 字符串
|
||||
return $pdf->Output('', 'S'); // 'S' 返回字符串
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 PDF 到文件
|
||||
*
|
||||
* @param string $templateName 模板文件名
|
||||
* @param array $data 注入模板的数据
|
||||
* @param string $filePath 保存的完整文件路径
|
||||
* @param array $options (可选)TCPDF 选项
|
||||
* @throws Exception
|
||||
*/
|
||||
public function saveToFile(string $templateName, array $data, string $filePath, array $options = [])
|
||||
{
|
||||
$options = array_merge($this->defaultOptions, $options);
|
||||
$html = $this->renderTemplate($templateName, $data);
|
||||
|
||||
$pdf = new TCPDF(
|
||||
$options['page_orientation'],
|
||||
$options['unit'],
|
||||
$options['page_format'],
|
||||
$options['unicode'],
|
||||
$options['encoding']
|
||||
);
|
||||
$pdf->SetCreator($options['creator']);
|
||||
$pdf->SetAuthor($options['author']);
|
||||
$pdf->SetTitle($templateName . ' - Saved PDF');
|
||||
|
||||
// --- 修改字体设置 ---
|
||||
$pdf->SetFont($options['font'], $options['font_style'], $options['font_size'], '', true);
|
||||
// --- 字体设置结束 ---
|
||||
|
||||
$pdf->SetMargins($options['margin_left'], $options['margin_top'], $options['margin_right']);
|
||||
$pdf->SetAutoPageBreak(TRUE, $options['margin_bottom']);
|
||||
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
|
||||
$pdf->AddPage();
|
||||
$pdf->writeHTML($html, true, false, true, false, '');
|
||||
$pdf->endPage();
|
||||
|
||||
// 确保目录存在
|
||||
$dir = dirname($filePath);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
|
||||
$pdf->Output($filePath, 'F'); // 'F' 保存到文件
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
namespace app\common\utils\pdf\service\document;
|
||||
|
||||
use app\common\utils\pdf\service\PdfGeneratorService;
|
||||
use Exception;
|
||||
|
||||
class ReimbursementDocumentService
|
||||
{
|
||||
private $pdfGenerator;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->pdfGenerator = new PdfGeneratorService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据报销单 ID 生成 PDF 数据
|
||||
* (这里模拟从数据库获取数据)
|
||||
*
|
||||
* @param int $reimbursementId
|
||||
* @return string PDF 二进制数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public function generatePdfById(int $reimbursementId): string
|
||||
{
|
||||
// --- 模拟从数据库获取数据 ---
|
||||
// 实际应用中,这里应该是查询数据库
|
||||
$reimbursementData = $this->getMockReimbursementData($reimbursementId);
|
||||
|
||||
if (!$reimbursementData) {
|
||||
throw new Exception("Reimbursement record not found for ID: {$reimbursementId}");
|
||||
}
|
||||
// --- 数据获取结束 ---
|
||||
|
||||
// 调用核心 PDF 服务生成 PDF
|
||||
// 'reimbursement_template' 对应 app/view/pdf/reimbursement_template.php
|
||||
return $this->pdfGenerator->generate('reimbursement', $reimbursementData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟获取报销单数据
|
||||
* @param int $id
|
||||
* @return array|null
|
||||
*/
|
||||
private function getMockReimbursementData(int $id)
|
||||
{
|
||||
if ($id <= 0) return null;
|
||||
|
||||
return [
|
||||
'reimbursement_id' => 'REIM-' . str_pad($id, 5, '0', STR_PAD_LEFT),
|
||||
'applicant_name' => '张三',
|
||||
'department' => '技术部',
|
||||
'application_date' => '2023-10-26',
|
||||
'total_amount' => 1250.75,
|
||||
'reason' => "参加北京技术研讨会的差旅费用。\n包括交通、住宿和餐饮。",
|
||||
'items' => [
|
||||
['date' => '2023-10-20', 'category' => '交通费', 'description' => '高铁二等座', 'amount' => 520.00, 'remark' => ''],
|
||||
['date' => '2023-10-21', 'category' => '住宿费', 'description' => 'XX酒店 2 晚', 'amount' => 680.00, 'remark' => '含早餐'],
|
||||
['date' => '2023-10-21', 'category' => '餐饮费', 'description' => '午餐晚餐', 'amount' => 50.75, 'remark' => '发票已附'],
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存报销单 PDF 到服务器
|
||||
* @param int $reimbursementId
|
||||
* @param string $savePath 保存路径 (目录)
|
||||
* @throws Exception
|
||||
*/
|
||||
public function savePdfToFile(int $reimbursementId, string $savePath)
|
||||
{
|
||||
$reimbursementData = $this->getMockReimbursementData($reimbursementId);
|
||||
if (!$reimbursementData) {
|
||||
throw new Exception("Reimbursement record not found for ID: {$reimbursementId}");
|
||||
}
|
||||
|
||||
$filename = 'reimbursement_' . $reimbursementData['reimbursement_id'] . '_' . date('Ymd_His') . '.pdf';
|
||||
$fullPath = rtrim($savePath, '/') . '/' . $filename;
|
||||
|
||||
$this->pdfGenerator->saveToFile('reimbursement_template', $reimbursementData, $fullPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<!-- app/view/pdf/delivery_template.php -->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<title>出货单 - <?php echo htmlspecialchars($data['delivery_id'] ?? 'N/A'); ?></title>
|
||||
<style>
|
||||
/* styles.css */
|
||||
body {
|
||||
font-family: "DejaVu Sans", sans-serif; /* TCPDF 支持的字体 */
|
||||
font-size: 10pt;
|
||||
color: #333;
|
||||
margin: 20mm 15mm 20mm 15mm; /* 页边距 */
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
border-bottom: 2px solid #000;
|
||||
padding-bottom: 5mm;
|
||||
margin-bottom: 8mm;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 16pt;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.header p {
|
||||
margin: 2mm 0;
|
||||
}
|
||||
|
||||
.company-info {
|
||||
font-size: 9pt;
|
||||
text-align: right;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details {
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.document-details th, .document-details td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.document-details th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.items-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.items-table th, .items-table td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.items-table th {
|
||||
background-color: #eaeaea;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.items-table tfoot td {
|
||||
font-weight: bold;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.footer {
|
||||
border-top: 1px solid #ccc;
|
||||
padding-top: 5mm;
|
||||
font-size: 9pt;
|
||||
text-align: center;
|
||||
}
|
||||
/* 特定于出货单的样式 */
|
||||
.delivery-address {
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="header">
|
||||
<h1>商品出货单</h1>
|
||||
<p>出货编号: <?php echo htmlspecialchars($data['delivery_id'] ?? 'N/A'); ?></p>
|
||||
</div>
|
||||
|
||||
<div class="company-info">
|
||||
<p>发货方: Your Company Ltd.</p>
|
||||
<p>地址: 123 Main Street, City</p>
|
||||
<p>电话: (123) 456-7890</p>
|
||||
</div>
|
||||
|
||||
<div class="document-details">
|
||||
<table>
|
||||
<tr>
|
||||
<th width="20%">客户名称</th>
|
||||
<td width="30%"><?php echo htmlspecialchars($data['customer_name'] ?? ''); ?></td>
|
||||
<th width="20%">出货日期</th>
|
||||
<td width="30%"><?php echo htmlspecialchars($data['delivery_date'] ?? ''); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>订单编号</th>
|
||||
<td><?php echo htmlspecialchars($data['order_id'] ?? ''); ?></td>
|
||||
<th>运输方式</th>
|
||||
<td><?php echo htmlspecialchars($data['shipping_method'] ?? ''); ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="delivery-address">
|
||||
<h3>收货地址</h3>
|
||||
<p><?php echo nl2br(htmlspecialchars($data['recipient_address'] ?? '')); ?></p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>出货明细</h3>
|
||||
<table class="items-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th width="5%">序号</th>
|
||||
<th width="15%">产品编码</th>
|
||||
<th width="30%">产品名称</th>
|
||||
<th width="10%">规格</th>
|
||||
<th width="10%">单位</th>
|
||||
<th width="15%">数量</th>
|
||||
<th width="15%">备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (!empty($data['items'])): ?>
|
||||
<?php foreach ($data['items'] as $index => $item): ?>
|
||||
<tr>
|
||||
<td><?php echo $index + 1; ?></td>
|
||||
<td><?php echo htmlspecialchars($item['product_code'] ?? ''); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['product_name'] ?? ''); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['specification'] ?? ''); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['unit'] ?? ''); ?></td>
|
||||
<td style="text-align: right;"><?php echo number_format($item['quantity'] ?? 0, 2); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['remark'] ?? ''); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<tr>
|
||||
<td colspan="7" style="text-align: center;">无出货明细</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>仓库经办人: _________________ 司机签名: _________________ 客户签收: _________________</p>
|
||||
<p>签收日期: _________</p>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,178 @@
|
||||
<!-- app/view/pdf/reimbursement_template.php -->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<title>报销单 - <?php echo htmlspecialchars($data['reimbursement_id'] ?? 'N/A'); ?></title>
|
||||
<style>
|
||||
/* 明确指定支持中文的字体族 */
|
||||
body {
|
||||
font-family: "STSongStdLight", "Arial", sans-serif; /* STSongStdLight 对应 TCPDF 的 stsongstdlight */
|
||||
font-size: 10pt;
|
||||
color: #333;
|
||||
margin: 20mm 15mm 20mm 15mm; /* 页边距 */
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
border-bottom: 2px solid #000;
|
||||
padding-bottom: 5mm;
|
||||
margin-bottom: 8mm;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 16pt;
|
||||
color: #000;
|
||||
/* 确保标题也使用正确字体 */
|
||||
font-family: "STSongStdLight", "Arial", sans-serif;
|
||||
}
|
||||
|
||||
.header p {
|
||||
margin: 2mm 0;
|
||||
}
|
||||
|
||||
.company-info {
|
||||
font-size: 9pt;
|
||||
text-align: right;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details {
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.document-details th, .document-details td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
/* 确保表格内容使用正确字体 */
|
||||
font-family: "STSongStdLight", "Arial", sans-serif;
|
||||
}
|
||||
|
||||
.document-details th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.items-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.items-table th, .items-table td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
/* 确保表格内容使用正确字体 */
|
||||
font-family: "STSongStdLight", "Arial", sans-serif;
|
||||
}
|
||||
|
||||
.items-table th {
|
||||
background-color: #eaeaea;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.items-table tfoot td {
|
||||
font-weight: bold;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.footer {
|
||||
border-top: 1px solid #ccc;
|
||||
padding-top: 5mm;
|
||||
font-size: 9pt;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="header">
|
||||
<h1>费用报销申请单</h1>
|
||||
<p>报销编号: <?php echo htmlspecialchars($data['reimbursement_id'] ?? 'N/A'); ?></p>
|
||||
</div>
|
||||
|
||||
<div class="company-info">
|
||||
<!-- 公司信息可以从配置中获取 -->
|
||||
<p>公司名称: Your Company Ltd.</p>
|
||||
<p>地址: 123 Main Street, City</p>
|
||||
<p>电话: (123) 456-7890</p>
|
||||
</div>
|
||||
|
||||
<div class="document-details">
|
||||
<table>
|
||||
<tr>
|
||||
<th width="20%">申请人</th>
|
||||
<td width="30%"><?php echo htmlspecialchars($data['applicant_name'] ?? ''); ?></td>
|
||||
<th width="20%">部门</th>
|
||||
<td width="30%"><?php echo htmlspecialchars($data['department'] ?? ''); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>申请日期</th>
|
||||
<td><?php echo htmlspecialchars($data['application_date'] ?? ''); ?></td>
|
||||
<th>报销总金额</th>
|
||||
<td><?php echo number_format($data['total_amount'] ?? 0, 2); ?> 元</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>事由说明</th>
|
||||
<td colspan="3"><?php echo nl2br(htmlspecialchars($data['reason'] ?? '')); ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>费用明细</h3>
|
||||
<table class="items-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th width="5%">序号</th>
|
||||
<th width="15%">日期</th>
|
||||
<th width="20%">费用类别</th>
|
||||
<th width="30%">说明</th>
|
||||
<th width="15%">金额 (元)</th>
|
||||
<th width="15%">备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (!empty($data['items'])): ?>
|
||||
<?php foreach ($data['items'] as $index => $item): ?>
|
||||
<tr>
|
||||
<td><?php echo $index + 1; ?></td>
|
||||
<td><?php echo htmlspecialchars($item['date'] ?? ''); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['category'] ?? ''); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['description'] ?? ''); ?></td>
|
||||
<td style="text-align: right;"><?php echo number_format($item['amount'] ?? 0, 2); ?></td>
|
||||
<td><?php echo htmlspecialchars($item['remark'] ?? ''); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<tr>
|
||||
<td colspan="6" style="text-align: center;">无费用明细</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colspan="4" style="text-align: right;"><strong>合计:</strong></td>
|
||||
<td style="text-align: right;"><strong><?php echo number_format($data['total_amount'] ?? 0, 2); ?></strong></td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>申请人签名: _________________ 审批人签名: _________________ 日期: _________________</p>
|
||||
<p>本单据由系统生成,仅供参考。</p>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,81 @@
|
||||
/* styles.css */
|
||||
body {
|
||||
font-family: "DejaVu Sans", sans-serif; /* TCPDF 支持的字体 */
|
||||
font-size: 10pt;
|
||||
color: #333;
|
||||
margin: 20mm 15mm 20mm 15mm; /* 页边距 */
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
border-bottom: 2px solid #000;
|
||||
padding-bottom: 5mm;
|
||||
margin-bottom: 8mm;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 16pt;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.header p {
|
||||
margin: 2mm 0;
|
||||
}
|
||||
|
||||
.company-info {
|
||||
font-size: 9pt;
|
||||
text-align: right;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details {
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.document-details table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.document-details th, .document-details td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.document-details th {
|
||||
background-color: #f0f0f0;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.items-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 10mm;
|
||||
}
|
||||
|
||||
.items-table th, .items-table td {
|
||||
border: 1px solid #999;
|
||||
padding: 2mm;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.items-table th {
|
||||
background-color: #eaeaea;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.items-table tfoot td {
|
||||
font-weight: bold;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.footer {
|
||||
border-top: 1px solid #ccc;
|
||||
padding-top: 5mm;
|
||||
font-size: 9pt;
|
||||
text-align: center;
|
||||
}
|
||||
Reference in New Issue
Block a user