初始版本

This commit is contained in:
root
2026-06-14 21:12:22 +08:00
commit 6a81742dc7
806 changed files with 179174 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace app\admin\model;
use think\Model;
use think\Session;
class Admin extends Model
{
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $hidden = [
'password',
'salt'
];
public static function init()
{
self::beforeWrite(function ($row) {
$changed = $row->getChangedData();
//如果修改了用户或或密码则需要重新登录
if (isset($changed['username']) || isset($changed['password']) || isset($changed['salt'])) {
$row->token = '';
}
});
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace app\admin\model;
use app\admin\library\Auth;
use think\Model;
use think\Loader;
class AdminLog extends Model
{
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
//自定义日志标题
protected static $title = '';
//自定义日志内容
protected static $content = '';
//忽略的链接正则列表
protected static $ignoreRegex = [
'/^(.*)\/(selectpage|index)$/i',
];
public static function setTitle($title)
{
self::$title = $title;
}
public static function setContent($content)
{
self::$content = $content;
}
public static function setIgnoreRegex($regex = [])
{
$regex = is_array($regex) ? $regex : [$regex];
self::$ignoreRegex = array_merge(self::$ignoreRegex, $regex);
}
/**
* 记录日志
* @param string $title 日志标题
* @param string $content 日志内容
*/
public static function record($title = '', $content = '')
{
$auth = Auth::instance();
$admin_id = $auth->isLogin() ? $auth->id : 0;
$username = $auth->isLogin() ? $auth->username : __('Unknown');
// 设置过滤函数
request()->filter('trim,strip_tags,htmlspecialchars');
$controllername = Loader::parseName(request()->controller());
$actionname = strtolower(request()->action());
$path = str_replace('.', '/', $controllername) . '/' . $actionname;
if (self::$ignoreRegex) {
foreach (self::$ignoreRegex as $index => $item) {
if (preg_match($item, $path)) {
return;
}
}
}
$content = $content ?: self::$content;
if (!$content) {
$content = request()->param('') ?: file_get_contents("php://input");
$content = self::getPureContent($content);
}
$title = $title ?: self::$title;
if (!$title) {
$title = [];
$breadcrumb = Auth::instance()->getBreadcrumb($path);
foreach ($breadcrumb as $k => $v) {
$title[] = $v['title'];
}
$title = implode(' / ', $title);
}
self::create([
'title' => $title,
'content' => !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content,
'url' => substr(xss_clean(strip_tags(request()->url())), 0, 1500),
'admin_id' => $admin_id,
'username' => $username,
'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
'ip' => xss_clean(strip_tags(request()->ip()))
]);
}
/**
* 获取已屏蔽关键信息的数据
* @param $content
* @return array
*/
protected static function getPureContent($content)
{
if (!is_array($content)) {
return $content;
}
foreach ($content as $index => &$item) {
if (preg_match("/(password|salt|token)/i", $index)) {
$item = "***";
} else {
if (is_array($item)) {
$item = self::getPureContent($item);
}
}
}
return $content;
}
public function admin()
{
return $this->belongsTo('Admin', 'admin_id')->setEagerlyType(0);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace app\admin\model;
use think\Model;
class AuthGroup extends Model
{
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
public function getNameAttr($value, $data)
{
return __($value);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace app\admin\model;
use think\Model;
class AuthGroupAccess extends Model
{
//
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace app\admin\model;
use think\Cache;
use think\Model;
class AuthRule extends Model
{
// 开启自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 数据自动完成字段
protected $insert = ['py', 'pinyin'];
protected $update = ['py', 'pinyin'];
// 拼音对象
protected static $pinyin = null;
protected static function init()
{
self::$pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
self::beforeWrite(function ($row) {
if (isset($_POST['row']) && is_array($_POST['row']) && isset($_POST['row']['condition'])) {
$originRow = $_POST['row'];
$row['condition'] = $originRow['condition'] ?? '';
}
});
self::afterWrite(function ($row) {
Cache::rm('__menu__');
});
}
public function getTitleAttr($value, $data)
{
return __($value);
}
public function getMenutypeList()
{
return ['addtabs' => __('Addtabs'), 'dialog' => __('Dialog'), 'ajax' => __('Ajax'), 'blank' => __('Blank')];
}
public function setPyAttr($value, $data)
{
if (isset($data['title']) && $data['title']) {
return self::$pinyin->abbr(__($data['title']));
}
return '';
}
public function setPinyinAttr($value, $data)
{
if (isset($data['title']) && $data['title']) {
return self::$pinyin->permalink(__($data['title']), '');
}
return '';
}
}
+189
View File
@@ -0,0 +1,189 @@
<?php
declare(strict_types=1);
namespace app\admin\model;
use think\Model;
/**
* 域名管理模型
*/
class Domain extends Model
{
/** @var string 中国域名后缀黑名单 */
public const CHINA_SUFFIX_BLACKLIST = [
'cn', 'com.cn', 'net.cn', 'org.cn', 'gov.cn', 'edu.cn', 'ac.cn', 'mil.cn',
];
protected $name = 'domain';
protected $autoWriteTimestamp = 'integer';
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
protected $append = [
'zone_status_text',
'ns_status_text',
'dns_status_text',
];
public function getZoneStatusList(): array
{
return [
'pending' => __('Zone pending'),
'active' => __('Zone active'),
'failed' => __('Zone failed'),
];
}
public function getNsStatusList(): array
{
return [
'pending' => __('NS pending'),
'verified' => __('NS verified'),
'failed' => __('NS failed'),
];
}
public function getDnsStatusList(): array
{
return [
'pending' => __('DNS pending'),
'created' => __('DNS created'),
'failed' => __('DNS failed'),
];
}
public function getZoneStatusTextAttr($value, $data): string
{
$value = $value ?: ($data['zone_status'] ?? '');
$list = $this->getZoneStatusList();
return $list[$value] ?? '';
}
public function getNsStatusTextAttr($value, $data): string
{
$value = $value ?: ($data['ns_status'] ?? '');
$list = $this->getNsStatusList();
return $list[$value] ?? '';
}
public function getDnsStatusTextAttr($value, $data): string
{
$value = $value ?: ($data['dns_status'] ?? '');
$list = $this->getDnsStatusList();
return $list[$value] ?? '';
}
public function setNameserversAttr($value): string
{
if (is_array($value)) {
return json_encode(array_values($value), JSON_UNESCAPED_UNICODE);
}
return (string)$value;
}
/**
* @return array<int, string>
*/
public function getNameserversArray(): array
{
$value = $this->getAttr('nameservers');
if (is_array($value)) {
return $value;
}
if (is_string($value) && $value !== '') {
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : [];
}
return [];
}
public static function normalizeDomain(string $domain): string
{
return strtolower(trim($domain));
}
public static function isValidRootDomain(string $domain): bool
{
$domain = self::normalizeDomain($domain);
if ($domain === '' || strlen($domain) > 253) {
return false;
}
if (strpos($domain, 'www.') === 0) {
return false;
}
if (!preg_match('/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i', $domain)) {
return false;
}
if (self::isChinaSuffix($domain)) {
return false;
}
$label = self::getDomainLabelWithoutSuffix($domain);
if ($label === '' || strpos($label, '.') !== false) {
return false;
}
return true;
}
public static function isChinaSuffix(string $domain): bool
{
$domain = self::normalizeDomain($domain);
foreach (self::CHINA_SUFFIX_BLACKLIST as $suffix) {
if ($domain === $suffix || self::endsWith($domain, '.' . $suffix)) {
return true;
}
}
return false;
}
public static function getMatchedSuffix(string $domain): string
{
$domain = self::normalizeDomain($domain);
$suffixes = array_merge(self::CHINA_SUFFIX_BLACKLIST, ['co.uk', 'com', 'net', 'org', 'io', 'co', 'me', 'info', 'biz']);
usort($suffixes, function ($a, $b) {
return strlen($b) - strlen($a);
});
foreach ($suffixes as $suffix) {
if ($domain === $suffix || self::endsWith($domain, '.' . $suffix)) {
return $suffix;
}
}
return '';
}
public static function getDomainLabelWithoutSuffix(string $domain): string
{
$domain = self::normalizeDomain($domain);
$suffix = self::getMatchedSuffix($domain);
if ($suffix === '') {
$pos = strrpos($domain, '.');
return $pos === false ? $domain : substr($domain, 0, $pos);
}
$suffixWithDot = '.' . $suffix;
if (self::endsWith($domain, $suffixWithDot)) {
return substr($domain, 0, -strlen($suffixWithDot));
}
return $domain;
}
public static function mapCloudflareZoneStatus(string $status): string
{
if ($status === 'active') {
return 'active';
}
if (in_array($status, ['pending', 'initializing'], true)) {
return 'pending';
}
return 'failed';
}
private static function endsWith(string $haystack, string $needle): bool
{
if ($needle === '') {
return true;
}
return substr($haystack, -strlen($needle)) === $needle;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace app\admin\model;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Model;
class User extends Model
{
// 表名
protected $name = 'user';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
'prevtime_text',
'logintime_text',
'jointime_text'
];
public function getOriginData()
{
return $this->origin;
}
protected static function init()
{
self::beforeUpdate(function ($row) {
$changed = $row->getChangedData();
//如果有修改密码
if (isset($changed['password'])) {
if ($changed['password']) {
$salt = \fast\Random::alnum();
$row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
$row->salt = $salt;
} else {
unset($row->password);
}
}
});
self::beforeUpdate(function ($row) {
$changedata = $row->getChangedData();
$origin = $row->getOriginData();
if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
}
if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
}
});
}
public function getGenderList()
{
return ['1' => __('Male'), '0' => __('Female')];
}
public function getStatusList()
{
return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
}
public function getPrevtimeTextAttr($value, $data)
{
$value = $value ? $value : ($data['prevtime'] ?? "");
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getLogintimeTextAttr($value, $data)
{
$value = $value ? $value : ($data['logintime'] ?? "");
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
public function getJointimeTextAttr($value, $data)
{
$value = $value ? $value : ($data['jointime'] ?? "");
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
protected function setPrevtimeAttr($value)
{
return $value && !is_numeric($value) ? strtotime($value) : $value;
}
protected function setLogintimeAttr($value)
{
return $value && !is_numeric($value) ? strtotime($value) : $value;
}
protected function setJointimeAttr($value)
{
return $value && !is_numeric($value) ? strtotime($value) : $value;
}
protected function setBirthdayAttr($value)
{
return $value ? $value : null;
}
public function group()
{
return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace app\admin\model;
use think\Model;
class UserGroup extends Model
{
// 表名
protected $name = 'user_group';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
'status_text'
];
public function getStatusList()
{
return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
}
public function getStatusTextAttr($value, $data)
{
$value = $value ? $value : $data['status'];
$list = $this->getStatusList();
return $list[$value] ?? '';
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace app\admin\model;
use fast\Tree;
use think\Model;
class UserRule extends Model
{
// 表名
protected $name = 'user_rule';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
'status_text'
];
protected static function init()
{
self::afterInsert(function ($row) {
if (!$row['weigh']) {
$pk = $row->getPk();
$row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
}
});
}
public function getTitleAttr($value, $data)
{
return __($value);
}
public function getStatusList()
{
return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
}
public function getStatusTextAttr($value, $data)
{
$value = $value ? $value : $data['status'];
$list = $this->getStatusList();
return $list[$value] ?? '';
}
public static function getTreeList($selected = [])
{
$ruleList = collection(self::where('status', 'normal')->order('weigh desc,id desc')->select())->toArray();
$nodeList = [];
Tree::instance()->init($ruleList);
$ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
$hasChildrens = [];
foreach ($ruleList as $k => $v)
{
if ($v['haschild'])
$hasChildrens[] = $v['id'];
}
foreach ($ruleList as $k => $v) {
$state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens));
$nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
}
return $nodeList;
}
}
+138
View File
@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace app\admin\model\split;
use app\common\library\CountryIso;
use think\Model;
/**
* 分流链接模型
*/
class Link extends Model
{
protected $name = 'split_link';
protected $autoWriteTimestamp = 'integer';
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
protected $append = [
'countries_text',
'auto_reply_text',
'ip_protect_text',
'random_shuffle_text',
'status_text',
];
public function getIpProtectList(): array
{
return [
'0' => __('Ip protect off'),
'1' => __('Ip protect on'),
];
}
public function getRandomShuffleList(): array
{
return [
'0' => __('Random shuffle off'),
'1' => __('Random shuffle on'),
];
}
public function getStatusList(): array
{
return [
'normal' => __('Status normal'),
'hidden' => __('Status hidden'),
];
}
public function setCountriesAttr($value): string
{
if (is_array($value)) {
return CountryIso::codesToStorage($value);
}
return CountryIso::codesToStorage(explode(',', (string)$value));
}
/**
* 分流链接码统一为小写
*/
public function setLinkCodeAttr($value): string
{
return strtolower(trim((string) $value));
}
/**
* 自动回复:存储为一行一条(换行分隔)
*
* @param mixed $value
*/
public function setAutoReplyAttr($value): string
{
return \app\common\service\SplitAutoReplyService::formatStorage($value);
}
/**
* 自动回复语句数组
*
* @return array<int, string>
*/
public function getAutoReplyLines(): array
{
return \app\common\service\SplitAutoReplyService::parseLines((string) $this->getAttr('auto_reply'));
}
public function getCountriesTextAttr($value, $data): string
{
return CountryIso::codesToText((string)($data['countries'] ?? ''));
}
/**
* 列表「回复语」列预览(最多 50 字 + ...,悬停用原始 auto_reply 换行展示)
*/
public function getAutoReplyTextAttr($value, $data): string
{
return \app\common\service\SplitAutoReplyService::previewForList((string) ($data['auto_reply'] ?? ''));
}
public function getIpProtectTextAttr($value, $data): string
{
$value = $value !== '' && $value !== null ? $value : ($data['ip_protect'] ?? '');
$list = $this->getIpProtectList();
return $list[(string)$value] ?? '';
}
public function getRandomShuffleTextAttr($value, $data): string
{
$value = $value !== '' && $value !== null ? $value : ($data['random_shuffle'] ?? '');
$list = $this->getRandomShuffleList();
return $list[(string)$value] ?? '';
}
public function getStatusTextAttr($value, $data): string
{
$value = $value ?: ($data['status'] ?? '');
$list = $this->getStatusList();
return $list[$value] ?? '';
}
/**
* 已选国家 ISO 代码数组(供编辑表单多选回显)
*
* @return array<int, string>
*/
public function getSelectedCountries(): array
{
$countries = (string)$this->getAttr('countries');
if ($countries === '') {
return [];
}
return CountryIso::normalizeCodes(explode(',', $countries));
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
namespace app\admin\model\split;
use app\common\service\SplitPlatformDomainService;
use think\Db;
use think\Model;
/**
* 分流号码模型
*/
class Number extends Model
{
protected $name = 'split_number';
protected static function init(): void
{
self::beforeInsert(function (self $row): void {
if ((int) ($row['weigh'] ?? 0) > 0) {
return;
}
$linkId = (int) ($row['split_link_id'] ?? 0);
if ($linkId <= 0) {
return;
}
$maxWeigh = (int) self::where('split_link_id', $linkId)->max('weigh');
$row->setAttr('weigh', $maxWeigh + 1);
});
}
protected $autoWriteTimestamp = 'integer';
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
protected $append = [
'number_type_text',
'link_url_text',
'status_text',
'manual_manage_text',
'platform_status_text',
];
/**
* 号码类型(与工单模块一致)
*
* @return array<string, string>
*/
public function getNumberTypeList(): array
{
return [
'whatsapp' => 'WhatsApp',
'telegram' => 'Telegram',
'line' => 'Line',
'custom' => __('Number type custom'),
];
}
/**
* @return array<string, string>
*/
public function getStatusList(): array
{
return [
'normal' => __('Status normal'),
'hidden' => __('Status hidden'),
];
}
/**
* @return array<string, string>
*/
public function getManualManageList(): array
{
return [
'0' => __('Manual manage no'),
'1' => __('Manual manage yes'),
];
}
/**
* @return array<string, string>
*/
public function getPlatformStatusList(): array
{
return [
'online' => __('Platform status online'),
'offline' => __('Platform status offline'),
'unknown' => __('Platform status unknown'),
];
}
/**
* 关联分流链接
*/
public function splitLink()
{
return $this->belongsTo(Link::class, 'split_link_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
public function setNumberTypeCustomAttr($value): string
{
return trim((string) $value);
}
public function setManualManageAttr($value): int
{
return (int) $value === 1 ? 1 : 0;
}
public function getNumberTypeTextAttr($value, $data): string
{
$type = (string) ($data['number_type'] ?? '');
if ($type === 'custom') {
$custom = trim((string) ($data['number_type_custom'] ?? ''));
return $custom !== '' ? $custom : (string) __('Number type custom');
}
$list = $this->getNumberTypeList();
return $list[$type] ?? $type;
}
/**
* 列表展示用:仅显示分流链接码(非完整 URL)
*/
public function getLinkUrlTextAttr($value, $data): string
{
if (isset($data['split_link']) && is_array($data['split_link'])) {
return (string) ($data['split_link']['link_code'] ?? '');
}
$linkId = (int) ($data['split_link_id'] ?? 0);
if ($linkId <= 0) {
return '';
}
return (string) Link::where('id', $linkId)->value('link_code');
}
public function getStatusTextAttr($value, $data): string
{
$key = (string) ($data['status'] ?? '');
$list = $this->getStatusList();
return $list[$key] ?? $key;
}
public function getManualManageTextAttr($value, $data): string
{
$key = (string) ((int) ($data['manual_manage'] ?? 0));
$list = $this->getManualManageList();
return $list[$key] ?? $key;
}
public function getPlatformStatusTextAttr($value, $data): string
{
$key = (string) ($data['platform_status'] ?? 'unknown');
$list = $this->getPlatformStatusList();
return $list[$key] ?? $key;
}
/**
* 根据链接码生成完整分流 URL
*/
public static function buildLinkUrl(string $linkCode): string
{
$linkCode = trim($linkCode);
if ($linkCode === '') {
return '';
}
$raw = trim((string) \think\Config::get('site.split_platform_domain'));
if ($raw === '') {
$raw = trim((string) Db::name('config')->where('name', 'split_platform_domain')->value('value'));
}
$domains = SplitPlatformDomainService::parseList($raw);
$domain = $domains[0] ?? '';
if ($domain === '') {
return '';
}
return 'https://' . $domain . '/s/' . $linkCode;
}
/**
* 解析 textarea 号码列表
*
* @return array<int, string>
*/
public static function parseNumbersText(string $text): array
{
$lines = preg_split('/\r\n|\r|\n/', $text) ?: [];
$numbers = [];
foreach ($lines as $line) {
$num = trim((string) $line);
if ($num === '') {
continue;
}
$numbers[$num] = $num;
}
return array_values($numbers);
}
}
+299
View File
@@ -0,0 +1,299 @@
<?php
declare(strict_types=1);
namespace app\admin\model\split;
use think\Db;
use think\Model;
/**
* 分流工单模型
*/
class Ticket extends Model
{
protected $name = 'split_ticket';
protected $autoWriteTimestamp = 'integer';
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
protected $append = [
'ticket_type_text',
'number_type_text',
'link_code_text',
'start_time_text',
'end_time_text',
'status_text',
'click_count',
'ticket_progress_text',
'inbound_ratio_text',
'sync_display_text',
];
/**
* 工单类型
*
* @return array<string, string>
*/
public function getTicketTypeList(): array
{
return [
'xinghe' => __('Ticket type xinghe'),
'haiwang' => __('Ticket type haiwang'),
'taiji' => __('Ticket type taiji'),
'huojian' => __('Ticket type huojian'),
'ss_channel' => __('Ticket type ss_channel'),
'ss_customer' => __('Ticket type ss_customer'),
'yifafa' => __('Ticket type yifafa'),
'a2c' => __('Ticket type a2c'),
'ceo_scrm' => __('Ticket type ceo_scrm'),
'whatshub' => __('Ticket type whatshub'),
'sihai' => __('Ticket type sihai'),
];
}
/**
* @return array<string, string>
*/
public function getStatusList(): array
{
return [
'normal' => __('Status normal'),
'hidden' => __('Status hidden'),
];
}
/**
* @return array<string, string>
*/
public function getSyncStatusList(): array
{
return [
'success' => __('Sync status success'),
'error' => __('Sync status error'),
'pending' => __('Sync status pending'),
];
}
/**
* 号码类型
*
* @return array<string, string>
*/
public function getNumberTypeList(): array
{
return [
'whatsapp' => 'Whatsapp',
'telegram' => 'Telegram',
'line' => 'Line',
'custom' => __('Number type custom'),
];
}
/**
* 关联分流链接
*/
public function splitLink()
{
// IN 预载入:避免 eagerlyType=0(JOIN) 与列表 field 子查询冲突导致 SQL 1064
return $this->belongsTo(Link::class, 'split_link_id', 'id', [], 'LEFT')->setEagerlyType(1);
}
/**
* 列表子查询注入的点击数,无则按关联号码汇总
*
* @param mixed $value
* @param array<string, mixed> $data
*/
public function getClickCountAttr($value, $data): int
{
if (isset($data['click_count']) && $data['click_count'] !== '' && $data['click_count'] !== null) {
return (int) $data['click_count'];
}
return self::sumVisitCountForTicket($data);
}
/**
* 工单进度:完成数量 / 工单总量
*
* @param mixed $value
* @param array<string, mixed> $data
*/
public function getTicketProgressTextAttr($value, $data): string
{
$total = (int) ($data['ticket_total'] ?? 0);
$complete = (int) ($data['complete_count'] ?? 0);
if ($total <= 0) {
return '0%';
}
$percent = round($complete / $total * 100, 2);
return $percent . '%';
}
/**
* 进线比例:进线人数 / 点击数(点击数=关联号码 visit_count 之和)
*
* @param mixed $value
* @param array<string, mixed> $data
*/
public function getInboundRatioTextAttr($value, $data): string
{
$clicks = $this->getClickCountAttr(null, $data);
$inbound = (int) ($data['inbound_count'] ?? 0);
if ($clicks <= 0) {
return '—';
}
$percent = round($inbound / $clicks * 100, 2);
return $percent . '%';
}
/**
* 同步状态展示文案
*
* @param mixed $value
* @param array<string, mixed> $data
*/
public function getSyncDisplayTextAttr($value, $data): string
{
$status = (string) ($data['sync_status'] ?? 'pending');
$online = (int) ($data['online_count'] ?? 0);
if ($status === 'success') {
return sprintf((string) __('Sync display success'), $online);
}
if ($status === 'pending') {
return (string) __('Sync display pending');
}
return (string) __('Sync display error');
}
public function setStartTimeAttr($value): ?int
{
return self::parseTimeValue($value);
}
public function setEndTimeAttr($value): ?int
{
return self::parseTimeValue($value);
}
public function setNumberTypeCustomAttr($value): string
{
return trim((string) $value);
}
public function setTicketTotalAttr($value): int
{
return max(0, (int) $value);
}
public function getTicketTypeTextAttr($value, $data): string
{
$key = (string) ($data['ticket_type'] ?? '');
$list = $this->getTicketTypeList();
return $list[$key] ?? $key;
}
public function getNumberTypeTextAttr($value, $data): string
{
$type = (string) ($data['number_type'] ?? '');
if ($type === 'custom') {
$custom = trim((string) ($data['number_type_custom'] ?? ''));
return $custom !== '' ? $custom : (string) __('Number type custom');
}
$list = $this->getNumberTypeList();
return $list[$type] ?? $type;
}
public function getLinkCodeTextAttr($value, $data): string
{
if ($value !== '' && $value !== null) {
return (string) $value;
}
$linkId = (int) ($data['split_link_id'] ?? 0);
if ($linkId <= 0) {
return '';
}
$code = Link::where('id', $linkId)->value('link_code');
return (string) $code;
}
public function getStartTimeTextAttr($value, $data): string
{
return self::formatTimeText($data['start_time'] ?? null);
}
public function getEndTimeTextAttr($value, $data): string
{
return self::formatTimeText($data['end_time'] ?? null);
}
public function getStatusTextAttr($value, $data): string
{
$key = (string) ($data['status'] ?? '');
$list = $this->getStatusList();
return $list[$key] ?? $key;
}
/**
* 构建列表用 click_count 子查询 SQL 片段
*/
public static function buildClickCountSubQuery(string $ticketTableAlias = ''): string
{
$ticketTable = (new self())->getTable();
$numberTable = (new Number())->getTable();
$t = $ticketTableAlias !== '' ? $ticketTableAlias : $ticketTable;
return "(SELECT COALESCE(SUM(n.visit_count), 0) FROM `{$numberTable}` n "
. "WHERE n.ticket_name = `{$t}`.ticket_name "
. "AND n.split_link_id = `{$t}`.split_link_id "
. "AND n.admin_id = `{$t}`.admin_id) AS click_count";
}
/**
* @param array<string, mixed> $data
*/
private static function sumVisitCountForTicket(array $data): int
{
$ticketName = (string) ($data['ticket_name'] ?? '');
$linkId = (int) ($data['split_link_id'] ?? 0);
$adminId = (int) ($data['admin_id'] ?? 0);
if ($ticketName === '' || $linkId <= 0) {
return 0;
}
$sum = Db::name('split_number')
->where('ticket_name', $ticketName)
->where('split_link_id', $linkId)
->where('admin_id', $adminId)
->sum('visit_count');
return (int) $sum;
}
/**
* @param mixed $value
*/
private static function parseTimeValue($value): ?int
{
if ($value === '' || $value === null) {
return null;
}
if (is_numeric($value)) {
return (int) $value;
}
$ts = strtotime((string) $value);
return $ts === false ? null : $ts;
}
/**
* @param mixed $value
*/
private static function formatTimeText($value): string
{
if ($value === '' || $value === null || !is_numeric($value)) {
return '';
}
$ts = (int) $value;
return $ts > 0 ? date('Y-m-d H:i:s', $ts) : '';
}
}