server/app/Job/FileExportJob.php

65 lines
2.2 KiB
PHP

<?php
namespace App\Job;
use App\Utils\Excel;
use App\Utils\QueueClient;
use Hyperf\AsyncQueue\Job;
use App\Model\Attachment as aModel;
use App\Model\Post as pModel;
use App\Model\Message as mModel;
class FileExportJob extends Job
{
protected int $maxAttempts = 1;
protected int $attachmentId;
public function __construct(array $params)
{
$this->attachmentId = $params['attachmentId'];
}
public function handle()
{
try {
sleep(10);
$attach = aModel::find($this->attachmentId);
if (empty($attach)) return false;
// 参数解析
$params = $attach->params ? json_decode($attach->params, true) : [];
// 导出类型 默认excel
$type = "excel";
switch ($attach->module) {
case "post_export":
list($header, $data) = pModel::list($attach->belong_id, $attach->account_type, $params['post_name'] ?? "", true);
$res = Excel::exportData($attach->name, $header, $data);
break;
default:
throw new \Exception("导出模块不存在");
}
if (!$res) {
return aModel::edit(['attachment_id' => $this->attachmentId, 'status' => 2, 'fail_reason' => "导出失败"]);
}
aModel::edit(['attachment_id' => $this->attachmentId, 'status' => 1, 'type' => $type, 'path' => $res]);
// 导出成功,消息通知
$data['type'] = 'system';
$id = mModel::add([
'type' => 'attach',
'title' => $attach->name . " [执行成功]",
'content' => '执行成功',
'create_id' => $attach->account_id,
]);
if ($id) {
QueueClient::push("App\Job\NotifyJob", ['messageId' => $id, 'channels' => ['websocket', 'email'], 'userIds' => [$attach->account_id]]);
}
return true;
} catch (\Exception $e) {
aModel::edit([
'attachment_id' => $this->attachmentId,
'status' => 2,
'fail_reason' => $e->getMessage()
]);
}
return true;
}
}