You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Controllers/Admin/TicketController.php

255 lines
9.9 KiB
PHTML

<?php
namespace App\Controllers\Admin;
use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\User;
use App\Services\Auth;
use App\Services\AdminDataMasker;
use App\Services\AdminPermission;
use App\Services\TicketTelegramConfig;
use App\Services\TicketTelegramNotifier;
use App\Services\AdminCsrf;
use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
use App\Services\Ticket\TicketViewer;
use App\Services\Mail;
use App\Services\Config;
use App\Utils\SafeDatatables as Datatables;
use App\Utils\DatatablesHelper;
use App\Controllers\AdminController;
class TicketController extends AdminController
{
public function index($request, $response, $args)
{
$table_config['total_column'] = array("op" => "操作", "id" => "ID",
"datetime" => "时间", "title" => "标题", "userid" => "用户ID",
"user_name" => "用户名", "status" => "状态");
$table_config['default_show_column'] = array("op", "id",
"datetime", "title", "userid", "user_name", "status");
$table_config['ajax_url'] = 'ticket/ajax';
$view = $this->view()->assign('table_config', $table_config);
if (AdminPermission::isSuperAdmin()) {
$telegram = $this->telegramViewState();
$view
->assign('telegram_config', $telegram['config'])
->assign('telegram_enabled', $telegram['config']['enabled'])
->assign('telegram_configured', $telegram['config']['configured'])
->assign('telegram_bound', $telegram['binding']['bound'])
->assign('telegram_admin_id', $telegram['binding']['admin_id']);
}
return $view->display('admin/ticket/index.tpl');
}
private function telegramViewState(): array
{
$binding = ['bound' => false, 'admin_id' => null];
$bindingError = '';
try {
$binding = TicketTelegramNotifier::bindingStatus();
} catch (\Throwable $exception) {
$bindingError = 'Telegram 绑定状态读取失败,请检查数据库日志';
}
try {
$config = TicketTelegramConfig::publicValues();
} catch (\Throwable $exception) {
$config = [
'enabled' => false,
'webhook_base_url' => '',
'webhook_url' => '',
'bot_token_configured' => false,
'webhook_secret_configured' => false,
'configured' => false,
'configuration_error' => 'Telegram 配置读取失败,请检查数据库与 cloud_data_key',
];
}
if ($bindingError !== '' && ($config['configuration_error'] ?? '') === '') {
$config['configuration_error'] = $bindingError;
}
return ['config' => $config, 'binding' => $binding];
}
public function update($request, $response, $args)
{
$id = $args['id'];
$content = $request->getParam('content');
$status = $request->getParam('status');
if (AdminPermission::isSuperAdmin()) {
if (!AdminCsrf::verify($request)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']);
}
if (!is_string($content) || trim($content) === '' || !in_array((string) $status, ['0', '1'], true)) {
$res['ret'] = 0;
$res['msg'] = "请填全";
return $this->echoJson($response, $res);
}
try {
$result = (new TicketThreadService())->reply(new ReplyTicketCommand(
(int) $id,
(int) Auth::getUser()->id,
$content,
(int) $status,
$request,
null,
true
));
} catch (\Throwable $exception) {
error_log('Admin ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
'ret' => 0,
'msg' => $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单回复保存失败',
]);
}
if ($result === null) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']);
}
$ticketMain = $result->root;
try {
$user = User::where('id', (int) $ticketMain->userid)->first();
if ($user !== null && trim((string) $user->email) !== '') {
Mail::send($user->email, Config::get('appName') . ' - 工单收到回复', 'ticket/replied.tpl', [
'user' => $user,
'ticket' => $ticketMain,
'ticket_url' => rtrim((string) Config::get('baseUrl'), '/') . '/user/ticket/' . (int) $ticketMain->id . '/view',
], [], 'ticket_replied');
}
} catch (\Throwable $exception) {
error_log('Ticket user notification failed: ' . $exception->getMessage());
}
$res['ret'] = 1;
$res['msg'] = "提交成功";
return $this->echoJson($response, $res);
} else {
$res['ret'] = 0;
$res['msg'] = "你没有提交工单权限";
return $this->echoJson($response, $res);
}
}
public function show($request, $response, $args)
{
$id = (int) ($args['id'] ?? 0);
$pageNum = 1;
if (isset($request->getQueryParams()["page"])) {
$pageNum = max(1, (int) $request->getQueryParams()["page"]);
}
$isSuperAdmin = AdminPermission::isSuperAdmin();
$thread = (new TicketReadModel())->thread(
new TicketThreadQuery($id, $pageNum, 5),
TicketViewer::administrator((int) Auth::getUser()->id, $isSuperAdmin)
);
if ($thread === null) {
return $response->withStatus(404);
}
$ticketMain = $thread['root'];
$ticketset = $thread['messages'];
$ticketset->setPath('/admin/ticket/'.$id."/view");
return $this->view()->assign('ticketset', $ticketset)
->assign('ticket_main', $ticketMain)
->assign('ticket_display_title', $thread['title'])
->assign('id', $id)
->assign('ticket_can_view_attachments', $isSuperAdmin)
->display('admin/ticket/view.tpl');
}
public function attachment($request, $response, $args)
{
try {
$ticket = Ticket::where('id', (int) ($args['id'] ?? 0))->where('rootid', 0)->first();
$attachment = TicketAttachment::where('id', (int) ($args['attachment_id'] ?? 0))
->where('ticket_id', $ticket ? (int) $ticket->id : -1)->first();
} catch (\Throwable $exception) {
return $response->withStatus(404);
}
return $this->streamTicketAttachment($response, $attachment);
}
public function ajax($request, $response, $args)
{
$datatables = new Datatables(new DatatablesHelper());
$connection = (new Ticket())->getConnection();
$schema = $connection->getSchemaBuilder();
$ticketType = $this->ticketColumnExpression($schema, 'ticket_type', "'technical'");
$priority = $this->ticketColumnExpression($schema, 'priority', "'medium'");
$instanceId = $this->ticketColumnExpression($schema, 'instance_id', 'NULL');
$datatables->query('SELECT ticket.id AS op,ticket.id,'
. 'CASE WHEN ticket_activity.last_reply_at IS NULL '
. 'OR ticket_activity.last_reply_at < ticket.datetime '
. 'THEN ticket.datetime ELSE ticket_activity.last_reply_at END AS datetime,'
. 'ticket.title,ticket.userid,user.user_name,'
. $ticketType . ' AS ticket_type,' . $priority . ' AS priority,' . $instanceId
. ' AS instance_id,ticket.status FROM ticket '
. 'INNER JOIN user ON ticket.userid = user.id '
. 'LEFT JOIN (SELECT rootid, MAX(datetime) AS last_reply_at FROM ticket '
. 'WHERE rootid <> 0 GROUP BY rootid) AS ticket_activity ON ticket_activity.rootid = ticket.id '
. 'WHERE ticket.rootid = 0');
$datatables->edit('op', function ($data) {
return '<a class="btn btn-brand" href="/admin/ticket/'.$data['id'].'/view">查看</a>';
});
$datatables->edit('datetime', function ($data) {
return date('Y-m-d H:i:s', $data['datetime']);
});
$datatables->edit('user_name', function ($data) {
return AdminDataMasker::account($data['user_name']);
});
$datatables->edit('title', function ($data) {
return AdminDataMasker::sensitiveText($data['title']);
});
$datatables->edit('status', function ($data) {
return $data['status'] == 1 ? '开启' : '关闭';
});
$statusTotals = Ticket::where('rootid', 0)
->selectRaw('COUNT(*) AS total')
->selectRaw('SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS open_count')
->selectRaw('SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS closed_count')
->first();
$payload = $datatables->generate(false);
$payload['statusTotals'] = [
'total' => (int) ($statusTotals->total ?? 0),
'open' => (int) ($statusTotals->open_count ?? 0),
'closed' => (int) ($statusTotals->closed_count ?? 0),
];
$body = $response->getBody();
$body->write((string) json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
}
private function ticketColumnExpression($schema, string $column, string $fallback): string
{
try {
return $schema->hasColumn('ticket', $column) ? 'ticket.' . $column : $fallback;
} catch (\Throwable $exception) {
return $fallback;
}
}
}