1
This commit is contained in:
@@ -1,105 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\crm\model\CustomerHis;
|
||||
use support\Db;
|
||||
use Symfony\Component\Console\Command\Command as SymfonyCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class CrmRotateUserCommand extends SymfonyCommand
|
||||
{
|
||||
protected static $defaultName = 'crm:rotate-user';
|
||||
protected static $defaultDescription = '将满足条件的 crm_customer 的 user_id 轮流改为 1、2、3';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this->setHelp('查询 user 表中 status=2 且 corp_id=3 的用户,
|
||||
然后查找其关联的 crm_customer 记录,
|
||||
按顺序将这些 crm_customer.user_id 轮流设置为 1、2、3。');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$corpId = 3;
|
||||
$status = 2;
|
||||
$roundRobinUserIds = [64,63,83,93,118,131,132,143,145,150,156,157,158,160];
|
||||
|
||||
$output->writeln('<info>开始执行 crm:rotate-user</info>');
|
||||
|
||||
try {
|
||||
// 1) 找到 user 表中满足条件的用户ID,派卡离职用户
|
||||
$userRows = Db::table('user')
|
||||
->where('corp_id', $corpId)
|
||||
->where('status', $status)
|
||||
->get(['id','name']);
|
||||
|
||||
$userIds = [];
|
||||
$userNames = [];
|
||||
foreach ($userRows as $row) {
|
||||
$userIds[] = (int)$row->id;
|
||||
$userNames[] = $row->name;
|
||||
}
|
||||
|
||||
if (empty($userIds)) {
|
||||
$output->writeln('<comment>未找到满足条件的用户(status=2 且 corp_id=3)。无需处理。</comment>');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$output->writeln('<info>匹配到用户数:' . count($userIds) .' '. implode(',',$userNames) . '</info>');
|
||||
|
||||
// 2) 查找 crm_customer 中属于这些用户的记录
|
||||
$customers = Db::table('crm_customer')
|
||||
->whereIn('user_id', $userIds)
|
||||
->orderBy('id', 'asc')
|
||||
->get(['id','user_id']);
|
||||
|
||||
if (!$customers || count($customers) === 0) {
|
||||
$output->writeln('<comment>未找到相关的 crm_customer 记录。</comment>');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$output->writeln('<info>需要处理的 crm_customer 数量:' . count($customers) . '</info>');
|
||||
|
||||
// 3) 事务中按顺序轮流设置
|
||||
// 初始化 UID 轮询器
|
||||
$uidRotator = new \app\common\utils\RedisUidRotator('email_parsed_result_20250804');
|
||||
$uidRotator->setUids([64, 63, 83, 93, 118, 131, 132, 143, 145, 150, 156, 157, 158, 160], false);
|
||||
|
||||
Db::connection()->transaction(function () use ($customers, $roundRobinUserIds, $output, $uidRotator) {
|
||||
$assignCount = 0;
|
||||
$targetCount = count($roundRobinUserIds);
|
||||
|
||||
foreach ($customers as $index => $customer) {
|
||||
// 获取下一个分配的UID
|
||||
$newUserId = $uidRotator->next();
|
||||
Db::table('crm_customer')
|
||||
->where('id', $customer->id)
|
||||
->update(['user_id' => $newUserId]);
|
||||
|
||||
$his = CustomerHis::create([
|
||||
'customer_id' => $customer->id,
|
||||
'user_his' => $customer->user_id,
|
||||
'user_id' => $newUserId,
|
||||
]);
|
||||
|
||||
|
||||
$assignCount++;
|
||||
|
||||
if ($assignCount % 500 === 0) {
|
||||
$output->writeln('<comment>已处理:' . $assignCount . '</comment>');
|
||||
}
|
||||
}
|
||||
|
||||
$output->writeln('<info>处理完成,共更新 crm_customer:' . $assignCount . ' 条</info>');
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln('<error>执行失败:' . $e->getMessage() . '</error>');
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\crm\model\Customer;
|
||||
use support\Log;
|
||||
use Symfony\Component\Console\Command\Command as SymfonyCommand;
|
||||
use Webman\Console\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class CustomerCodeCommand extends SymfonyCommand
|
||||
{
|
||||
protected static $defaultName = 'customer:generate-code';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this->setDescription('为crm_customer表所有记录生成唯一code码,分批处理');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$batchSize = 1000;
|
||||
$total = Customer::withTrashed()->where('code','')->count();
|
||||
$output->writeln("总计需处理:$total 条记录");
|
||||
|
||||
$processed = 0;
|
||||
do {
|
||||
// 查询一批未生成code的记录
|
||||
$customers = Customer::withTrashed()->where('code','')->limit($batchSize)->get();
|
||||
if ($customers->isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Eloquent 批量处理
|
||||
foreach ($customers as $customer) {
|
||||
// 生成唯一16位code,CM+14位
|
||||
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
|
||||
$code = 'CM' . $unique;
|
||||
|
||||
// 防止极小概率重复
|
||||
while (Customer::where('code', $code)->exists()) {
|
||||
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
|
||||
$code = 'CM' . $unique;
|
||||
}
|
||||
|
||||
$created_at = $customer->created_at->getTimestamp();
|
||||
$obtain = $created_at > strtotime('2025-07-29')?$created_at:strtotime('2025-07-29');
|
||||
|
||||
$customer->code = $code;
|
||||
$customer->obtain = $obtain;
|
||||
$customer->save();
|
||||
$processed++;
|
||||
}
|
||||
|
||||
$output->writeln("已处理:$processed / $total");
|
||||
} while (true);
|
||||
|
||||
$output->writeln('<info>全部处理完成!</info>');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\crm\model\Customer;
|
||||
use support\Command;
|
||||
use support\Db;
|
||||
use Symfony\Component\Console\Command\Command as SymfonyCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
// 假设你有对应的模型类
|
||||
// use app\model\CrmCustomer;
|
||||
// use app\model\InquiryLog;
|
||||
|
||||
class CustomerCreatedAtCommand extends SymfonyCommand
|
||||
{
|
||||
protected static $defaultName = 'customer:update-created-at';
|
||||
protected static $defaultDescription = '根据 inquiry_log 记录更新 crm_customer 的 created_at 字段';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this->setHelp('该命令将查询 crm_customer 表中 sn 不为空的记录,并根据 sn 在 inquiry_log 表中查找对应的 order_no 记录,将 inquiry_log 的 created_at 更新到 crm_customer 的 created_at 字段');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$output->writeln('<info>开始更新 crm_customer 的 created_at 字段...</info>');
|
||||
|
||||
try {
|
||||
// 使用事务确保数据一致性
|
||||
DB::transaction(function () use ($output) {
|
||||
// 查询所有 sn 字段不为空的客户记录
|
||||
$customers = Db::table('crm_customer')
|
||||
->where('sn', '<>', '')
|
||||
->whereNotNull('sn')
|
||||
->get(['id', 'sn']);
|
||||
$output->writeln('<info>'.count($customers).'</info>');
|
||||
|
||||
$updatedCount = 0;
|
||||
|
||||
foreach ($customers as $customer) {
|
||||
// 查找匹配的 inquiry_log 记录
|
||||
$inquiryLog = Db::table('inquiry_log')
|
||||
->where('order_no', $customer->sn)
|
||||
->first(['r_time','created_at']);
|
||||
|
||||
// 如果找到匹配记录,则更新客户的 created_at 字段
|
||||
if ($inquiryLog && isset($inquiryLog->r_time)) {
|
||||
$created_at = $inquiryLog->r_time?:$inquiryLog->created_at;
|
||||
DB::table('crm_customer')
|
||||
->where('id', $customer->id)
|
||||
->update(['created_at' => $created_at]);
|
||||
|
||||
$updatedCount++;
|
||||
$output->writeln("<comment>已更新客户 ID {$customer->id} 的 created_at 为: {$created_at}</comment>");
|
||||
}
|
||||
}
|
||||
|
||||
$output->writeln("<info>更新完成,总共更新了 {$updatedCount} 条记录。</info>");
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln('<error>执行过程中发生错误: ' . $e->getMessage() . '</error>');
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\model\InquiryLog;
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* 主要处理询单详情中的图片地址
|
||||
*/
|
||||
class DomainCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'domain';
|
||||
protected static $defaultDescription = '';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$log = new InquiryLog();
|
||||
$list = $log->orderBy('id', 'desc')->get();
|
||||
|
||||
foreach ($list as $item) {
|
||||
if (!$item->content) {
|
||||
continue;
|
||||
}
|
||||
$item->content = processRichTextImagesEnhanced($item->content);
|
||||
$item->save();
|
||||
$output->writeln("处理了{$item->id} \n");
|
||||
}
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增强版 - 处理富文本内容中的图片URL
|
||||
*
|
||||
* @param string $content 富文本HTML内容
|
||||
* @param string $newDomain 新域名(如: https://fdesk.hnxinyouhe.com)
|
||||
* @param string $oldDomain 旧域名(如: http://219.157.255.213:25326)
|
||||
* @return string 处理后的富文本内容
|
||||
*/
|
||||
function processRichTextImagesEnhanced($content, $newDomain = 'https://x-server.hnxinyouhe.com', $oldDomain = 'http://219.157.255.213:25326') {
|
||||
// 标准化域名格式(去除末尾斜杠)
|
||||
$newDomain = rtrim($newDomain, '/');
|
||||
$oldDomain = rtrim($oldDomain, '/');
|
||||
|
||||
// 要处理的属性列表
|
||||
$attributes = ['src', 'data-href', 'href', 'data-src', 'data-original'];
|
||||
|
||||
foreach ($attributes as $attr) {
|
||||
// 情况1:替换旧域名为新域名
|
||||
$content = preg_replace(
|
||||
'/('.$attr.'=["\'])'.preg_quote($oldDomain, '/').'(\/uploads\/)/i',
|
||||
'$1' . $newDomain . '$2',
|
||||
$content
|
||||
);
|
||||
|
||||
// 情况2:给无域名的路径添加新域名
|
||||
$content = preg_replace(
|
||||
'/('.$attr.'=["\'])(\/uploads\/)/i',
|
||||
'$1' . $newDomain . '$2',
|
||||
$content
|
||||
);
|
||||
|
||||
// 情况3:处理可能存在的其他域名(可选)
|
||||
$content = preg_replace(
|
||||
'/('.$attr.'=["\'])(https?:\/\/[^\/]+)(\/uploads\/)/i',
|
||||
'$1' . $newDomain . '$3',
|
||||
$content
|
||||
);
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* 拉取邮箱的详情入库(根据emai_uid)
|
||||
*/
|
||||
class EmailDetailCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'email-detail';
|
||||
protected static $defaultDescription = '拉取 detail 入库';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this->addOption(
|
||||
'per-page', 'p',
|
||||
InputOption::VALUE_OPTIONAL,
|
||||
'每批处理多少条详情',
|
||||
config('imap.per_page', 50)
|
||||
);
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
try {
|
||||
$cfg = config('imap');
|
||||
$mailbox = $cfg['mailbox'];
|
||||
$username = $cfg['username'];
|
||||
$password = $cfg['password'];
|
||||
$batch = (int)$input->getOption('per-page');
|
||||
|
||||
// 打开 IMAP
|
||||
$inbox = @imap_open($mailbox, $username, $password);
|
||||
if (!$inbox) {
|
||||
$output->writeln("<error>IMAP 连接失败:". imap_last_error() ."</error>");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 阶段二:逐批拉取详情并写入 emails 表
|
||||
$output->writeln("依次拉取详情并写入 emails 表 …");
|
||||
while (true) {
|
||||
$pending = Db::table('email_uids')
|
||||
->where('status', 0)
|
||||
// ->where('uid', '>', 13399)
|
||||
->orderBy('uid', 'desc')
|
||||
->limit(2)
|
||||
->get();
|
||||
|
||||
if (count($pending) === 0) {
|
||||
$output->writeln("<info>所有 UID 均已处理完毕。</info>");
|
||||
break;
|
||||
}
|
||||
|
||||
$output->writeln("处理下一批 " . count($pending) . " 条 …");
|
||||
|
||||
foreach ($pending as $row) {
|
||||
$uid = $row->uid;
|
||||
|
||||
// 包裹整行处理在 try/catch 中,任何异常都不会中断循环
|
||||
try {
|
||||
$output->writeln("---- 开始处理 UID={$uid} ----");
|
||||
|
||||
// 1. fetch overview
|
||||
$ov = @imap_fetch_overview($inbox, $uid, FT_UID)[0] ?? null;
|
||||
if (!$ov) {
|
||||
$err = imap_last_error() ?: '未知错误';
|
||||
$output->writeln("<error>UID={$uid} overview 失败:{$err}</error>");
|
||||
$this->logError("UID={$uid} overview 失败:{$err}");
|
||||
continue;
|
||||
}
|
||||
$subject = mb_convert_encoding($ov->subject ?? '', 'UTF-8', 'GBK,UTF-8');
|
||||
$from = $ov->from ?? '';
|
||||
$date = $ov->date ?? '';
|
||||
|
||||
$output->writeln("UID={$uid} overview 成功,subject={$subject}");
|
||||
|
||||
// 2. fetch body
|
||||
$body = $this->getMailBody($inbox, $uid, true);
|
||||
$output->writeln("UID={$uid} body 长度:" . strlen($body));
|
||||
|
||||
// 3. sanitize & insert
|
||||
$body = $this->sanitizeUtf8($body);
|
||||
$now = time();
|
||||
|
||||
try {
|
||||
Db::table('emails')->insert([
|
||||
'uid' => $uid,
|
||||
'subject' => $subject,
|
||||
'from' => $from,
|
||||
'date' => $date,
|
||||
'body' => $body,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$output->writeln("<info>UID={$uid} 写入 emails 成功</info>");
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln("<error>UID={$uid} 写入失败:{$e->getMessage()}</error>");
|
||||
$this->logError("UID={$uid} 写入失败:{$e->getMessage()}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 4. 标记已处理
|
||||
try {
|
||||
Db::table('email_uids')
|
||||
->where('uid', $uid)
|
||||
->update([
|
||||
'status' => 1,
|
||||
'processed_at' => $now,
|
||||
]);
|
||||
$output->writeln("<info>UID={$uid} 标记为已处理</info>");
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln("<error>UID={$uid} 标记状态失败:{$e->getMessage()}</error>");
|
||||
$this->logError("UID={$uid} 标记状态失败:{$e->getMessage()}");
|
||||
// 即使更新 status 失败,也继续下一条
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 捕获任何非预期错误
|
||||
$output->writeln("<error>UID={$uid} 处理异常:{$e->getMessage()}</error>");
|
||||
$this->logError("UID={$uid} 处理异常:{$e->getMessage()}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 批次结束后稍作休眠,防止服务器过载
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
imap_close($inbox);
|
||||
$output->writeln("\n<info>✅ 全部邮件处理完成。</info>");
|
||||
return Command::SUCCESS;
|
||||
} catch (\Throwable $th) {
|
||||
dpr($th);
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任意字符串清洗为有效 UTF-8,移除或替换无效字节
|
||||
*/
|
||||
protected function sanitizeUtf8(string $text): string
|
||||
{
|
||||
return iconv('UTF-8', 'UTF-8//IGNORE', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录错误到日志
|
||||
*/
|
||||
protected function logError(string $msg): void
|
||||
{
|
||||
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n";
|
||||
file_put_contents(
|
||||
runtime_path('logs/email_errors.log'),
|
||||
$line,
|
||||
FILE_APPEND | LOCK_EX
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按编码解码并保留 "\r\n"
|
||||
*/
|
||||
protected function getMailBody($inbox, int $id, bool $isUid = false): string
|
||||
{
|
||||
$flags = $isUid ? FT_UID : 0;
|
||||
$structure = imap_fetchstructure($inbox, $id, $flags);
|
||||
|
||||
if (!empty($structure->parts)) {
|
||||
// HTML 部分
|
||||
foreach ($structure->parts as $i => $part) {
|
||||
if (isset($part->subtype) && strtolower($part->subtype) === 'html') {
|
||||
$data = imap_fetchbody($inbox, $id, (string)($i+1), $flags);
|
||||
return $this->decodeBody($data, $part->encoding);
|
||||
}
|
||||
}
|
||||
// 文本部分
|
||||
foreach ($structure->parts as $i => $part) {
|
||||
if (isset($part->subtype) && strtolower($part->subtype) === 'plain') {
|
||||
$data = imap_fetchbody($inbox, $id, (string)($i+1), $flags);
|
||||
return $this->decodeBody($data, $part->encoding);
|
||||
}
|
||||
}
|
||||
// 原始 body
|
||||
return imap_body($inbox, $id, $flags);
|
||||
}
|
||||
|
||||
return imap_body($inbox, $id, $flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按编码解码
|
||||
*/
|
||||
protected function decodeBody(string $body, int $encoding): string
|
||||
{
|
||||
switch ($encoding) {
|
||||
case 3: return imap_base64($body);
|
||||
case 4: return imap_qprint($body);
|
||||
default: return $body;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
<?php
|
||||
namespace app\command;
|
||||
|
||||
use support\Db;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* 将拉取邮箱的详情进行清洗,找出询盘的邮件入库(根据emai_detail)
|
||||
*/
|
||||
class EmailParseCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'email-parse';
|
||||
protected static $defaultDescription = '邮件清洗';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
// 不再接收参数,固定每次 100 条
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$batchSize = 100; // 每次处理 100 条
|
||||
$page = 0;
|
||||
|
||||
// 明确定义 parsed_contacts 表里要插入的所有列(顺序无所谓,但要全部包含)
|
||||
$fields = [
|
||||
'email_id',
|
||||
'date',
|
||||
'email',
|
||||
'name',
|
||||
'tel',
|
||||
'company',
|
||||
'country',
|
||||
'form_url',
|
||||
'message',
|
||||
'ip',
|
||||
'iplocation',
|
||||
'ilang',
|
||||
'mailto',
|
||||
'navigator_language',
|
||||
'navigator_platform',
|
||||
'screen_width',
|
||||
'screen_height',
|
||||
'ucountry',
|
||||
];
|
||||
|
||||
while (true) {
|
||||
$rows = Db::table('emails')
|
||||
->orderBy('id', 'asc')
|
||||
->limit($batchSize)
|
||||
->offset($page * $batchSize)
|
||||
->get();
|
||||
|
||||
if ($rows->isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
$toInsert = [];
|
||||
foreach ($rows as $row) {
|
||||
$parsed = $this->parseHtml($row->body);
|
||||
if ($parsed === null) {
|
||||
$output->writeln(" ↳ [{$row->id}] skip: not a contact-form HTML");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 严格按 $fields 顺序填充每条记录,缺失的字段补 null
|
||||
$record = [];
|
||||
foreach ($fields as $col) {
|
||||
if ($col === 'email_id') {
|
||||
$record[$col] = $row->id;
|
||||
} else {
|
||||
$record[$col] = $parsed[$col] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
$toInsert[] = $record;
|
||||
}
|
||||
|
||||
if (!empty($toInsert)) {
|
||||
Db::table('email_parsed_result')->insert($toInsert);
|
||||
$output->writeln("Inserted batch #" . ($page + 1) . ", count: " . count($toInsert));
|
||||
}
|
||||
|
||||
$page++;
|
||||
}
|
||||
|
||||
$output->writeln("✔ All done.");
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 HTML,找不到 <h2>Preview</h2> 则返回 null,
|
||||
* 否则提取所有 <span>Key:</span> Value 为小写蛇形 key=>value 数组
|
||||
*/
|
||||
protected function parseHtml(string $html): ?array
|
||||
{
|
||||
$doc = new \DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$doc->loadHTML('<?xml encoding="utf-8"?>' . $html);
|
||||
libxml_clear_errors();
|
||||
|
||||
$xpath = new \DOMXPath($doc);
|
||||
|
||||
// 类型检查
|
||||
if ($xpath->query("//h2[text()='Preview']")->length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nodes = $xpath->query("//div[span]");
|
||||
$data = [];
|
||||
|
||||
/** @var \DOMElement $node */
|
||||
foreach ($nodes as $node) {
|
||||
$span = $xpath->query("span", $node)->item(0);
|
||||
if (! $span) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 原始键名
|
||||
$key = trim(str_replace(':', '', $span->textContent));
|
||||
// 转成小写蛇形
|
||||
$col = strtolower(str_replace(' ', '_', $key));
|
||||
|
||||
// 获取值
|
||||
$a = $xpath->query(".//a", $node)->item(0);
|
||||
if ($a && $a->hasAttribute('href')) {
|
||||
$value = trim($a->getAttribute('href'));
|
||||
} else {
|
||||
$clone = $node->cloneNode(true);
|
||||
$spanClone = $xpath->query(".//span", $clone)->item(0);
|
||||
if ($spanClone) {
|
||||
$spanClone->parentNode->removeChild($spanClone);
|
||||
}
|
||||
$value = trim($clone->textContent);
|
||||
}
|
||||
|
||||
$data[$col] = $value;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
|
||||
/**
|
||||
* 拉取邮箱的UID入库
|
||||
*/
|
||||
class EmailUidCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'email-uid';
|
||||
protected static $defaultDescription = '拉取 UID 入库';
|
||||
|
||||
// protected function configure()
|
||||
// {
|
||||
// $this->addOption(
|
||||
// 'per-page', 'p',
|
||||
// InputOption::VALUE_OPTIONAL,
|
||||
// '每批处理多少条详情',
|
||||
// config('imap.per_page', 50)
|
||||
// );
|
||||
// }
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
try {
|
||||
$cfg = config('imap');
|
||||
$mailbox = $cfg['mailbox'];
|
||||
$username = $cfg['username'];
|
||||
$password = $cfg['password'];
|
||||
// $batch = (int)$input->getOption('per-page');
|
||||
|
||||
$retryTimes = 3;
|
||||
$retryDelay = 10; // 秒
|
||||
|
||||
$inbox = false;
|
||||
$attempt = 0;
|
||||
|
||||
$maxUid = Db::table('email_uids')->max('uid');
|
||||
|
||||
while ($attempt < $retryTimes) {
|
||||
$attempt++;
|
||||
$output->writeln("尝试第 {$attempt} 次连接 IMAP...");
|
||||
$inbox = @imap_open($mailbox, $username, $password);
|
||||
|
||||
if ($inbox) {
|
||||
break;
|
||||
}
|
||||
|
||||
$error = imap_last_error();
|
||||
$output->writeln("<comment>第 {$attempt} 次失败:{$error}</comment>");
|
||||
|
||||
// 若出现 too many login failures 立即暂停一段时间
|
||||
if (stripos($error, 'Too many login failures') !== false) {
|
||||
$output->writeln("<error>检测到登录失败次数过多,暂停 60 秒避免封禁</error>");
|
||||
sleep(60);
|
||||
} else {
|
||||
sleep($retryDelay);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$inbox) {
|
||||
$output->writeln("<error>最终仍然连接失败:" . imap_last_error() . "</error>");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 拉取 UID 并入库
|
||||
$output->writeln("开始拉取 UID 并入库 …");
|
||||
$uids = imap_search($inbox, 'ALL', SE_UID) ?: [];
|
||||
|
||||
$uids = array_filter($uids, function($uid) use ($maxUid) {
|
||||
return $uid > $maxUid;
|
||||
});
|
||||
|
||||
sort($uids);
|
||||
$now = time();
|
||||
$count = 0;
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
try {
|
||||
Db::table('email_uids')->insert([
|
||||
'uid' => $uid,
|
||||
'fetched_at' => $now,
|
||||
'email' => $cfg['username']
|
||||
]);
|
||||
$count++;
|
||||
|
||||
$output->writeln("UID:".$uid." 已写入数据库");
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln("<comment>{$e->getMessage()}</comment>");
|
||||
}
|
||||
}
|
||||
|
||||
imap_close($inbox);
|
||||
$output->writeln(date('Y-m-d H:i:s').":共拉到 {$count} 个 UID 并写入 email_uids 表。");
|
||||
return Command::SUCCESS;
|
||||
} catch (\Throwable $th) {
|
||||
dpr($th);
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定格式的日期字符串
|
||||
*
|
||||
* @param string|null $input_date 可选,指定的日期(可以是任何PHP可解析的日期格式)
|
||||
* @return string 返回格式为 'd-M-Y' 的日期字符串(如 '28-Jul-2025')
|
||||
*/
|
||||
function getImapFormattedDate($input_date = null) {
|
||||
// 如果有传入日期参数,尝试解析
|
||||
if ($input_date !== null) {
|
||||
$timestamp = strtotime($input_date);
|
||||
if ($timestamp === false) {
|
||||
// 如果日期解析失败,使用当前日期并记录警告
|
||||
trigger_error("无法解析提供的日期: '$input_date',将使用当前日期", E_USER_WARNING);
|
||||
$timestamp = time();
|
||||
}
|
||||
} else {
|
||||
// 如果没有提供日期,使用当前日期
|
||||
$timestamp = time();
|
||||
}
|
||||
|
||||
// 格式化为 IMAP 需要的日期格式 (如 '28-Jul-2025')
|
||||
return date('d-M-Y', $timestamp);
|
||||
}
|
||||
|
||||
// // 使用示例
|
||||
// echo getImapFormattedDate(); // 输出当天的日期,如 '31-Jul-2025'
|
||||
// echo getImapFormattedDate('2025-07-28'); // 输出 '28-Jul-2025'
|
||||
// echo getImapFormattedDate('28/07/2025'); // 输出 '28-Jul-2025'
|
||||
// echo getImapFormattedDate('next Monday'); // 输出下个周一的日期
|
||||
|
||||
/*
|
||||
|
||||
// imap_search() 条件
|
||||
|
||||
// 1. 基本日期搜索(按接收日期)
|
||||
// 搜索今天收到的邮件
|
||||
$today = date("d-M-Y");
|
||||
$uids = imap_search($inbox, 'SINCE "' . $today . '"', SE_UID);
|
||||
|
||||
// 搜索特定日期之后的邮件
|
||||
$since_date = '15-Jul-2023';
|
||||
$uids = imap_search($inbox, 'SINCE "' . $since_date . '"', SE_UID);
|
||||
|
||||
// 搜索特定日期之前的邮件
|
||||
$before_date = '20-Jul-2023';
|
||||
$uids = imap_search($inbox, 'BEFORE "' . $before_date . '"', SE_UID);
|
||||
|
||||
// 搜索特定日期的邮件
|
||||
$on_date = '18-Jul-2023';
|
||||
$uids = imap_search($inbox, 'ON "' . $on_date . '"', SE_UID);
|
||||
|
||||
// 2. 日期范围搜索
|
||||
// 搜索2023年7月15日到2023年7月20日之间的邮件
|
||||
$start_date = '15-Jul-2023';
|
||||
$end_date = '20-Jul-2023';
|
||||
$uids = imap_search($inbox, 'SINCE "' . $start_date . '" BEFORE "' . $end_date . '"', SE_UID);
|
||||
|
||||
// 3. 结合日期和其他条件
|
||||
// 搜索2023年7月以后未读的邮件
|
||||
$date = '1-Jul-2023';
|
||||
$uids = imap_search($inbox, 'SINCE "' . $date . '" UNSEEN', SE_UID);
|
||||
|
||||
// 搜索2023年7月来自某人的邮件
|
||||
$date = '1-Jul-2023';
|
||||
$from = 'example@domain.com';
|
||||
$uids = imap_search($inbox, 'SINCE "' . $date . '" FROM "' . $from . '"', SE_UID);
|
||||
|
||||
// 4. 日期格式注意事项
|
||||
// - IMAP日期格式通常为 d-M-Y,例如 15-Jul-2023
|
||||
// - 月份使用英文缩写(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
|
||||
// - 日期格式必须用双引号括起来
|
||||
|
||||
所有ID
|
||||
imap_search($inbox, 'ALL', SE_UID)
|
||||
|
||||
*/
|
||||
@@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
use app\common\utils\email\Emails;
|
||||
|
||||
/**
|
||||
* 批量处理用户编号(也用于调试)
|
||||
*/
|
||||
class FinanceRecoCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'finance-reco';
|
||||
protected static $defaultDescription = '';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
|
||||
// $tmp = (new \app\common\service\OssService)->generatePrivateUrl('fdesk_test/20251104/20251104_财务.xlsx');;
|
||||
|
||||
$service = new \app\common\service\FinanceReconDubaiFilesService();
|
||||
$result = $service->dImport('fdesk_test/20251104/20251104_迪拜.xlsx');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
<?php
|
||||
namespace app\command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
use support\Log;
|
||||
|
||||
/**
|
||||
* 处理询单中的编号重复
|
||||
*/
|
||||
class FixInquiryLogOrderNo extends Command
|
||||
{
|
||||
protected static $defaultName = 'sn';
|
||||
protected static $defaultDescription = 'Fix duplicate order_no values in inquiry_log table';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
// Start transaction for safety
|
||||
Db::beginTransaction();
|
||||
|
||||
try {
|
||||
$output->writeln('Starting duplicate order_no fix process...');
|
||||
|
||||
// Find all duplicate order_no values using Laravel-style query
|
||||
$duplicates = Db::table('inquiry_log')
|
||||
->select('order_no', Db::raw('COUNT(*) as count'))
|
||||
->groupBy('order_no')
|
||||
->having('count', '>', 1)
|
||||
->get();
|
||||
|
||||
if ($duplicates->isEmpty()) {
|
||||
$output->writeln('No duplicate order_no values found.');
|
||||
Db::commit();
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$output->writeln(sprintf('Found %d order_no values with duplicates.', $duplicates->count()));
|
||||
|
||||
$totalFixed = 0;
|
||||
|
||||
foreach ($duplicates as $dup) {
|
||||
$orderNo = $dup->order_no;
|
||||
|
||||
$output->writeln("Processing duplicates for order_no: {$orderNo}");
|
||||
|
||||
// Get all records with this order_no, ordered by created_at (oldest first)
|
||||
$records = Db::table('inquiry_log')
|
||||
->where('order_no', $orderNo)
|
||||
->orderBy('created_at', 'asc')
|
||||
->get();
|
||||
|
||||
// Keep the first record as is, modify the rest
|
||||
$keepOriginal = true;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if ($keepOriginal) {
|
||||
$output->writeln("Keeping original record ID {$record->id} with order_no {$record->order_no}");
|
||||
$keepOriginal = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Generate new order_no by appending suffix
|
||||
$newOrderNo = orderNum();
|
||||
$output->writeln("Updating record ID {$record->id} from {$record->order_no} to {$newOrderNo}");
|
||||
|
||||
// Update the record
|
||||
Db::table('inquiry_log')
|
||||
->where('id', $record->id)
|
||||
->update(['order_no' => $newOrderNo]);
|
||||
|
||||
$totalFixed++;
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
Db::commit();
|
||||
$output->writeln("Successfully fixed {$totalFixed} duplicate records.");
|
||||
|
||||
// Verify no duplicates remain
|
||||
$remainingDuplicates = Db::table('inquiry_log')
|
||||
->select('order_no', Db::raw('COUNT(*) as count'))
|
||||
->groupBy('order_no')
|
||||
->having('count', '>', 1)
|
||||
->get();
|
||||
|
||||
if ($remainingDuplicates->isEmpty()) {
|
||||
$output->writeln('Verification: No duplicate order_no values remain.');
|
||||
} else {
|
||||
$output->writeln('Warning: Some duplicates still remain. Please run the command again.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
$output->writeln("Error: " . $e->getMessage());
|
||||
Log::error("FixInquiryLogOrderNo command failed: " . $e->getMessage());
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\crm\model\Country;
|
||||
use app\crm\model\Customer;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
class ImportCustomerCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'import:customer';
|
||||
protected static $defaultDescription = '导入Excel文件到crm_customer表';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
// $this->addArgument('file', InputArgument::REQUIRED, 'Excel文件路径')
|
||||
// ->addOption('user-id', 'u', InputOption::VALUE_REQUIRED, '用户ID', 0)
|
||||
// ->addOption('channel-id', 'c', InputOption::VALUE_REQUIRED, '渠道ID', 5)
|
||||
// ->addOption('corp-abbr', 'a', InputOption::VALUE_REQUIRED, '公司缩写', 2);
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
// $filePath = $input->getArgument('file');
|
||||
// $userId = $input->getOption('user-id');
|
||||
// $channelId = $input->getOption('channel-id');
|
||||
// $corpAbbr = $input->getOption('corp-abbr');
|
||||
$filePath = 'C:\Users\16961\Downloads\中国制造 2023-2025-询盘导出.xls';
|
||||
$userId = 0;
|
||||
$channelId = 5;
|
||||
$corpAbbr = 2;
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!file_exists($filePath)) {
|
||||
$output->writeln("<error>文件不存在: {$filePath}</error>");
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$output->writeln("开始导入文件: {$filePath}");
|
||||
|
||||
// 加载Excel文件
|
||||
$output->writeln("正在加载Excel文件...");
|
||||
$spreadsheet = IOFactory::load($filePath);
|
||||
$worksheet = $spreadsheet->getActiveSheet();
|
||||
$output->writeln("Excel文件加载成功");
|
||||
|
||||
// 获取数据范围
|
||||
$highestRow = $worksheet->getHighestRow();
|
||||
$highestColumn = $worksheet->getHighestColumn();
|
||||
|
||||
$output->writeln("文件包含 {$highestRow} 行数据");
|
||||
|
||||
// 获取所有国家数据,用于匹配
|
||||
$output->writeln("正在获取国家数据...");
|
||||
// $countries = Country::select('id', 'cn_addr', 'en_addr')->get()->keyBy(function($item) {
|
||||
// return strtolower(trim($item->cn_addr));
|
||||
// });
|
||||
// $output->writeln("获取到 " . $countries->count() . " 个国家数据");
|
||||
|
||||
$successCount = 0;
|
||||
$errorCount = 0;
|
||||
$errors = [];
|
||||
|
||||
// 从第二行开始读取数据(第一行是标题)
|
||||
$output->writeln("开始读取Excel数据...");
|
||||
for ($row = 2; $row <= $highestRow; $row++) {
|
||||
try {
|
||||
$output->writeln("正在处理第 {$row} 行...");
|
||||
|
||||
// 读取各列数据 - 使用坐标方法
|
||||
try {
|
||||
$countryName = trim($worksheet->getCell('B' . $row)->getValue() ?? '');
|
||||
$contacts = trim($worksheet->getCell('A' . $row)->getValue() ?? '');
|
||||
$email = trim($worksheet->getCell('C' . $row)->getValue() ?? '');
|
||||
$phone = trim($worksheet->getCell('D' . $row)->getValue() ?? '');
|
||||
$inquiryProduct = trim($worksheet->getCell('E' . $row)->getValue() ?? '');
|
||||
} catch (\Exception $cellError) {
|
||||
$output->writeln("<error>读取第{$row}行单元格时出错: " . $cellError->getMessage() . "</error>");
|
||||
continue;
|
||||
}
|
||||
|
||||
$output->writeln("读取数据: 国家={$countryName}, 客户={$contacts}, 产品={$inquiryProduct}");
|
||||
|
||||
// 跳过空行
|
||||
// if (empty($contacts)) {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// 查找国家ID
|
||||
$countryId = 0;
|
||||
// if (!empty($countryName)) {
|
||||
// $countryKey = strtolower($countryName);
|
||||
// if ($countries->has($countryKey)) {
|
||||
// $countryId = $countries->get($countryKey)->id;
|
||||
// } else {
|
||||
// // 尝试英文名称匹配
|
||||
// $countryByEn = $countries->first(function($item) use ($countryName) {
|
||||
// return strtolower(trim($item->en_addr)) === strtolower($countryName);
|
||||
// });
|
||||
// if ($countryByEn) {
|
||||
// $countryId = $countryByEn->id;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// 检查是否已存在相同客户名
|
||||
// $existingCustomer = Customer::where('contacts', $customerName)->first();
|
||||
// if ($existingCustomer) {
|
||||
// $output->writeln("跳过已存在的客户: {$customerName}");
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// 创建客户记录
|
||||
// $customerData = [
|
||||
// 'user_id' => $userId,
|
||||
// 'corp_abbr' => $corpAbbr,
|
||||
// 'channel_id' => $channelId,
|
||||
// 'country_id' => $countryId,
|
||||
// 'contacts' => $customerName,
|
||||
// 'email' => $email,
|
||||
// 'phone' => $phone,
|
||||
// 'desc_collect' => $inquiryProduct,
|
||||
// 'grade' => 0, // 默认等级
|
||||
// 'magnitude' => 1, // 默认商机
|
||||
// 'type' => 1, // 默认类型
|
||||
// 'sex' => 0, // 默认性别
|
||||
// 'enter_user_id' => $userId,
|
||||
// ];
|
||||
$where = [
|
||||
['id', '<', 28110],
|
||||
['id', '>', 25714],
|
||||
];
|
||||
$customer = Customer::where('contacts',$email)->where($where)->first();
|
||||
$customer->email = $email;
|
||||
$customer->phone = $phone;
|
||||
$customer->contacts = $contacts;
|
||||
$customer->save();
|
||||
$successCount++;
|
||||
|
||||
$output->writeln("成功导入客户: {$contacts} (ID: {$customer->id})");
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$errorCount++;
|
||||
$errorMsg = "第{$row}行导入失败: " . $e->getMessage();
|
||||
$errorMsg .= "\n文件: " . $e->getFile() . " 行: " . $e->getLine();
|
||||
$errorMsg .= "\n堆栈: " . $e->getTraceAsString();
|
||||
$errors[] = $errorMsg;
|
||||
$output->writeln("<error>{$errorMsg}</error>");
|
||||
}
|
||||
}
|
||||
|
||||
$output->writeln("\n导入完成!");
|
||||
$output->writeln("成功导入: {$successCount} 条记录");
|
||||
$output->writeln("失败: {$errorCount} 条记录");
|
||||
|
||||
if (!empty($errors)) {
|
||||
$output->writeln("\n错误详情:");
|
||||
foreach ($errors as $error) {
|
||||
$output->writeln("<error>{$error}</error>");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln("<error>导入过程中发生错误: " . $e->getMessage() . "</error>");
|
||||
$output->writeln("<error>文件: " . $e->getFile() . " 行: " . $e->getLine() . "</error>");
|
||||
$output->writeln("<error>堆栈: " . $e->getTraceAsString() . "</error>");
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\model\User;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class InitUserPasswordCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'init:user-password';
|
||||
protected static $defaultDescription = '初始化user表密码,如果密码为空则用sn加密后写入password字段';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$users = User::whereNull('password')->orWhere('password', '')->get();
|
||||
$count = 0;
|
||||
|
||||
foreach ($users as $user) {
|
||||
if (!empty($user->sn)) {
|
||||
$user->password = password_hash($user->sn, PASSWORD_DEFAULT);
|
||||
$user->save();
|
||||
$output->writeln("用户ID {$user->id} 密码已初始化");
|
||||
$count++;
|
||||
} else {
|
||||
$output->writeln("<error>用户ID {$user->id} 的sn字段为空,无法初始化密码</error>");
|
||||
}
|
||||
}
|
||||
|
||||
$output->writeln("共初始化 {$count} 个用户密码");
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
use app\common\utils\email\Emails;
|
||||
|
||||
/**
|
||||
* 批量处理用户编号(也用于调试)
|
||||
*/
|
||||
class TbCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'tb-db';
|
||||
protected static $defaultDescription = '';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
// $user = new User();
|
||||
// $list = $user->all();
|
||||
|
||||
// foreach ($list as $item) {
|
||||
// // UserSn::where('user_sn', $item->sn)->update(['user_id' => $item->id]);
|
||||
// }
|
||||
|
||||
$m = new Emails();
|
||||
$m->fenpai();
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use support\Command;
|
||||
use support\Db;
|
||||
use Symfony\Component\Console\Command\Command as SymfonyCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
class UpdateInquiryLogFromCrmCustomerCommand extends SymfonyCommand
|
||||
{
|
||||
protected static $defaultName = 'inquiry:update-from-crm-customer';
|
||||
protected static $defaultDescription = '将crm_customer表的部分字段更新到inquiry_log表';
|
||||
|
||||
protected function configure()
|
||||
{
|
||||
$this->setHelp('该命令将crm_customer表的user_id更新到inquiry_log表的recipient字段,将obtain字段更新到t_time字段。')
|
||||
->addOption('dry-run', null, InputOption::VALUE_NONE, '仅显示将要执行的更新操作,不实际执行')
|
||||
->addOption('limit', 'l', InputOption::VALUE_OPTIONAL, '限制处理的记录数量', 5000);
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$isDryRun = $input->getOption('dry-run');
|
||||
$limit = (int) $input->getOption('limit');
|
||||
|
||||
if ($isDryRun) {
|
||||
$output->writeln('<info>DRY RUN 模式 - 不会实际执行更新操作</info>');
|
||||
}
|
||||
|
||||
$output->writeln('<info>开始更新 inquiry_log 表...</info>');
|
||||
$output->writeln("<info>处理限制: {$limit} 条记录</info>");
|
||||
|
||||
try {
|
||||
// 使用事务确保数据一致性
|
||||
DB::transaction(function () use ($output, $isDryRun, $limit) {
|
||||
// 查询需要更新的记录
|
||||
$customers = Db::table('crm_customer')
|
||||
->select('id', 'sn', 'user_id', 'obtain','created_at')
|
||||
->whereNotNull('sn')
|
||||
->where('sn', '<>', '')
|
||||
->offset($limit)
|
||||
->limit(4000)
|
||||
->orderBy('id', 'asc')
|
||||
->get();
|
||||
|
||||
$output->writeln("<info>找到 " . count($customers) . " 条客户记录需要处理</info>");
|
||||
|
||||
$updatedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$defaultTimestamp = strtotime('2025-08-26 00:00:00');
|
||||
|
||||
$output->writeln("<info>找到 " . count($customers) . " 条客户记录需要处理</info>");
|
||||
$step = [];
|
||||
$updateId = [];
|
||||
foreach ($customers as $customer) {
|
||||
$output->writeln("<info>处理客户 ID: {$customer->id}, SN: {$customer->sn}, User ID: {$customer->user_id}, obtain: {$customer->obtain}, created_at: {$customer->created_at}</info>");
|
||||
// 查找匹配的 inquiry_log 记录
|
||||
$inquiryLog = Db::table('inquiry_log')
|
||||
->where('order_no', $customer->sn)
|
||||
->first(['id', 'recipient', 't_time']);
|
||||
|
||||
if (!$inquiryLog) {
|
||||
$step[] = $customer->id;
|
||||
$output->writeln("<comment>跳过客户 ID {$customer->id} (sn: {$customer->sn}) - 未找到对应的 inquiry_log 记录</comment>");
|
||||
$skippedCount++;
|
||||
continue;
|
||||
}
|
||||
$output->writeln("<info>$inquiryLog->id</info>");
|
||||
|
||||
// 准备更新数据
|
||||
$updateData = [];
|
||||
|
||||
// 更新 recipient 字段 (user_id)
|
||||
if ($customer->user_id != $inquiryLog->recipient) {
|
||||
$updateData['recipient'] = $customer->user_id;
|
||||
$output->writeln("<comment>客户 ID {$customer->id}: recipient 将从 {$inquiryLog->recipient} 更新为 {$customer->user_id}</comment>");
|
||||
}
|
||||
|
||||
if(empty($customer->obtain)&& !empty($customer->user_id)){
|
||||
if($customer->user_id == $inquiryLog->recipient){
|
||||
$obtain = $inquiryLog->t_time;
|
||||
}else{
|
||||
$obtain = strtotime('2025-08-01 10:00:00');
|
||||
$obtain = $customer->created_at > $obtain?$customer->created_at:$obtain;
|
||||
}
|
||||
Db::table('crm_customer')
|
||||
->where('id', $customer->id)
|
||||
->update(['obtain' => $obtain]);
|
||||
$output->writeln("<info>更新obtain $obtain</info>");
|
||||
}
|
||||
|
||||
// 更新 t_time 字段 (obtain)
|
||||
$newTTime = $customer->obtain > 0 ? $customer->obtain : $defaultTimestamp;
|
||||
if ($newTTime != $inquiryLog->t_time && !empty($updateData['recipient'])) {
|
||||
$updateData['t_time'] = $newTTime;
|
||||
$timeStr = date('Y-m-d H:i:s', $newTTime);
|
||||
$output->writeln("<comment>客户 ID {$customer->id}: t_time 将从 " . ($inquiryLog->t_time ? date('Y-m-d H:i:s', $inquiryLog->t_time) : 'NULL') . " 更新为 {$timeStr}</comment>");
|
||||
}
|
||||
if($customer->user_id == 0 && $inquiryLog->recipient != 0){
|
||||
$updateData['recipient'] = 0;
|
||||
$updateData['t_time'] = time();
|
||||
$updateData['status'] = 1;
|
||||
$updateData['r_time'] = time();
|
||||
|
||||
}
|
||||
|
||||
// 如果有需要更新的字段,执行更新
|
||||
if (!empty($updateData)) {
|
||||
$updateId[] = $customer->id;
|
||||
if (!$isDryRun) {
|
||||
Db::table('inquiry_log')
|
||||
->where('id', $inquiryLog->id)
|
||||
->update($updateData);
|
||||
}
|
||||
$updatedCount++;
|
||||
$output->writeln("<info>已更新 inquiry_log ID {$inquiryLog->id}</info>");
|
||||
} else {
|
||||
$output->writeln("<comment>客户 ID {$customer->id} - 无需更新</comment>");
|
||||
}
|
||||
}
|
||||
|
||||
$output->writeln("<info>处理完成!</info>");
|
||||
$output->writeln("<info>总记录数: " . count($customers) . "</info>");
|
||||
$updateIdstr = implode(",", $updateId);
|
||||
$output->writeln("<info>更新记录数: {$updatedCount},更新id:$updateIdstr</info>");
|
||||
$stepstr = implode(",", $step);
|
||||
$output->writeln("<info>跳过记录数: {$skippedCount},跳过id: {$stepstr}</info>");
|
||||
|
||||
if ($isDryRun) {
|
||||
$output->writeln("<info>DRY RUN 模式 - 未实际执行任何更新操作</info>");
|
||||
}
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln('<error>执行过程中发生错误: ' . $e->getMessage() . '</error>');
|
||||
$output->writeln('<error>错误位置: ' . $e->getFile() . ':' . $e->getLine() . '</error>');
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use support\Db;
|
||||
use app\common\utils\email\Emails;
|
||||
|
||||
/**
|
||||
* 批量处理用户编号(也用于调试)
|
||||
*/
|
||||
class VehMoneyCommand extends Command
|
||||
{
|
||||
protected static $defaultName = 'veh-money';
|
||||
protected static $defaultDescription = '';
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
|
||||
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,7 @@ class UsedCarController extends BaseController
|
||||
}
|
||||
|
||||
// 返回访问地址
|
||||
$baseUrl = 'https://' . request()->header('host');
|
||||
$baseUrl = 'http://' . request()->header('host');
|
||||
$url = $baseUrl . '/pdf/' . $raw['pdf_src'];
|
||||
|
||||
return $this->success([
|
||||
|
||||
@@ -103,6 +103,11 @@
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2>车况介绍</h2>
|
||||
<div class="desc">
|
||||
<?= nl2br(htmlspecialchars($car['condition_desc'])) ?>
|
||||
</div>
|
||||
|
||||
<h2>产品图</h2>
|
||||
<div class="image-list">
|
||||
<?php foreach ($car['images'] as $img): ?>
|
||||
@@ -112,10 +117,5 @@
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
|
||||
<h2>车况介绍</h2>
|
||||
<div class="desc">
|
||||
<?= nl2br(htmlspecialchars($car['condition_desc'])) ?>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\crmAdmin\controller;
|
||||
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
use support\exception\BusinessException;
|
||||
use app\common\traits\ResponseTrait;
|
||||
use think\Validate;
|
||||
|
||||
abstract class BaseController
|
||||
{
|
||||
use ResponseTrait;
|
||||
|
||||
protected mixed $validator = null;
|
||||
|
||||
/**
|
||||
* 验证数据
|
||||
*
|
||||
* @param Validate $validator 验证器实例
|
||||
* @param array $data 待验证的数据
|
||||
* @param string $scene 验证场景
|
||||
* @return array 验证后的数据
|
||||
* @throws BusinessException 验证失败时抛出业务异常
|
||||
*/
|
||||
public function validate(Validate $validator, array $data, string $scene = ''): array
|
||||
{
|
||||
// 如果指定了验证场景,并且验证器支持场景方法,则设置验证场景
|
||||
if ($scene && method_exists($validator, 'scene')) {
|
||||
$validator->scene($scene);
|
||||
}
|
||||
// 执行数据验证
|
||||
if (!$validator->check($data)) {
|
||||
// 验证失败,抛出业务异常,异常信息为验证器返回的错误信息
|
||||
throw new BusinessException($validator->getError());
|
||||
}
|
||||
// 验证成功,返回原始数据
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function page($result){
|
||||
$current = $result->currentPage();
|
||||
$total = $result->total();
|
||||
$size = $result->perPage();
|
||||
$result = $result->toArray();
|
||||
$result['current'] = $current;
|
||||
$result['total'] = $total;
|
||||
$result['size'] = $size;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\crmAdmin\controller;
|
||||
|
||||
use app\common\model\Corp;
|
||||
use app\crm\model\Customer;
|
||||
use app\crm\utils\Util;
|
||||
use app\crmAdmin\service\CustomerService;
|
||||
use support\Request;
|
||||
|
||||
class CustomerController extends BaseController
|
||||
{
|
||||
|
||||
/**
|
||||
* 不需要头信息的方法
|
||||
*/
|
||||
protected $noNeedHeader = [];
|
||||
protected $noNeedHeaderData = ['export'];
|
||||
|
||||
protected $noNeedLogin = ['export'];
|
||||
|
||||
/**
|
||||
* 客户列表
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function list(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
$corp = Corp::where(['abbr' => $request->basic_data['corp_abbr']])->first();
|
||||
$param['corp_id'] = $corp->id;
|
||||
// $param['corp_abbr'] = $request->basic_data['corp_abbr'];
|
||||
$result = (new CustomerService())->list($param);
|
||||
|
||||
return $this->success($this->page($result));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage().$e->getFile().$e->getLine().$e->getTraceAsString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户导出
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function export(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
// $corp = Corp::where(['abbr' => $request->basic_data['corp_abbr']])->first();
|
||||
// $param['corp_id'] = $corp->id;
|
||||
|
||||
$result = (new CustomerService())->export($param);
|
||||
$excelContent = file_get_contents($result['filepath']);
|
||||
// 生成文件名
|
||||
$filename = '客户数据_' . date('Y-m-d_H-i-s') . '.xlsx';
|
||||
return response()
|
||||
->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
->withHeader('Content-Disposition', 'attachment; filename="'.$filename.'"')
|
||||
->withBody($excelContent);
|
||||
|
||||
/*$result = (new CustomerService())->export($param);
|
||||
// 检查文件是否存在
|
||||
if (!file_exists($result['filepath'])) {
|
||||
return $this->error('导出文件生成失败');
|
||||
}
|
||||
|
||||
// 获取文件信息
|
||||
$fileSize = filesize($result['filepath']);
|
||||
$filename = $result['filename'];
|
||||
|
||||
// 设置响应头
|
||||
$response = response()->file($result['filepath']);
|
||||
$response->header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
$response->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
|
||||
$response->header('Content-Length', $fileSize);
|
||||
$response->header('Cache-Control', 'no-cache, must-revalidate');
|
||||
$response->header('Pragma', 'no-cache');
|
||||
|
||||
return $response;*/
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核客户
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function audit(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
if (empty($param['id'])) {
|
||||
return $this->error('ID'.trans('not_null'));
|
||||
}
|
||||
|
||||
if (!in_array($param['scene'],['delete','report'])) {
|
||||
return $this->error('scene 不合法');
|
||||
}
|
||||
$result = (new CustomerService())->audit($param);
|
||||
|
||||
return $this->success($result);
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage().$e->getFile().$e->getLine().$e->getTraceAsString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 批量转让
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function transfer(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
if (empty($param['customer_id'])) {
|
||||
return $this->error('customer_id'.trans('not_null'));
|
||||
}
|
||||
if (empty($param['user_id'])) {
|
||||
return $this->error('user_id'.trans('not_null'));
|
||||
}
|
||||
|
||||
$result = (new CustomerService())->transfer($param);
|
||||
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function delete(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
$scene = $param['scene'] ?? '';
|
||||
$status_desc = $param['status_desc'] ?? '';
|
||||
|
||||
if($scene != 'force' && empty($param['status_desc'])){
|
||||
return $this->error( '移除原因不能为空');
|
||||
}
|
||||
if (empty($param['customer_id'])) {
|
||||
return $this->error('customer_id'.trans('not_null'));
|
||||
}
|
||||
|
||||
$customer_id = explode(',', $param['customer_id']);
|
||||
$query = Customer::whereIn('id',$customer_id)->withTrashed();
|
||||
if(!$query->exists()){
|
||||
return $this->error( trans('fail'));
|
||||
}
|
||||
if ($scene === 'list') { //管理端客户列表移除
|
||||
$res = $query->update(['status' => 4, 'status_desc' => $status_desc, 'deleted_at' => time()]);
|
||||
} elseif ($scene === 'force') { //强删除
|
||||
$res = $query->forceDelete();
|
||||
} else { //公海软删除
|
||||
$res = $query->update(['status' => 3, 'status_desc' => $status_desc, 'deleted_at' => time()]);
|
||||
}
|
||||
|
||||
return $this->success($res);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 客户恢复
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function restore(Request $request)
|
||||
{
|
||||
try {
|
||||
$id = $request->input('id', '');
|
||||
if (Util::isEmpty($id)) {
|
||||
return $this->error(trans('id_empty'));
|
||||
}
|
||||
$ids = explode(',', $id);
|
||||
$query = Customer::withTrashed()->whereIn('id', $ids);
|
||||
if (!$query->exists()) {
|
||||
return $this->error(trans('fail'));
|
||||
}
|
||||
// 恢复软删除(清空 deleted_at)
|
||||
$query->restore();
|
||||
// 恢复为在库状态,放入公海
|
||||
$res = Customer::whereIn('id', $ids)->update(['status' => 1, 'user_id' => 0]);
|
||||
return $this->success($res, trans('success'));
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户详情
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function detail(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
if (empty($param['id'])) {
|
||||
return $this->error('id'.trans('not_null'));
|
||||
}
|
||||
|
||||
$result = (new CustomerService())->detail($param);
|
||||
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户详情
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function follow(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
if (empty($param['id'])) {
|
||||
return $this->error('id'.trans('not_null'));
|
||||
}
|
||||
|
||||
$result = (new CustomerService())->follow($param);
|
||||
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 离职员工客户分配
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function allocation(Request $request)
|
||||
{
|
||||
try {
|
||||
$param = $request->all();
|
||||
if (empty($param['corp_id'])) {
|
||||
return $this->error('corp_id'.trans('not_null'));
|
||||
}
|
||||
if (empty($param['user_id'])) {
|
||||
return $this->error('user_id'.trans('not_null'));
|
||||
}
|
||||
|
||||
$result = (new CustomerService())->allocation($param);
|
||||
|
||||
return $this->success($result,'成功分配'.$result['userCount'].'位离职用户的'.$result['customerCount'].'位客户');
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
<?php
|
||||
namespace app\crmAdmin\controller;
|
||||
|
||||
use app\common\controller\BaseController;
|
||||
use app\common\model\Country;
|
||||
use app\common\model\InquiryChannel;
|
||||
use app\common\model\InquiryLog;
|
||||
use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\crm\model\Customer;
|
||||
use app\inquiry\service\CountryService;
|
||||
use support\Request;
|
||||
use support\Db;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class StatisticsController extends BaseController
|
||||
{
|
||||
use CrudControllerTrait;
|
||||
|
||||
protected $service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->service = new CountryService();
|
||||
}
|
||||
|
||||
public function whole()
|
||||
{
|
||||
$totals = Customer::count('id');
|
||||
$channelCount = InquiryChannel::count('id');
|
||||
$todayCount = Customer::where('created_at', '>=', strtotime(date('Y-m-d')))->count('id');
|
||||
$releaseCount = Customer::distinct('enter_user_id')->count('id');
|
||||
$countryCount = Country::count('id');
|
||||
$trackCount = Customer::distinct('user_id')->count();
|
||||
|
||||
$data = [
|
||||
'totals' => $totals,
|
||||
'channelCount' => $channelCount,
|
||||
'todayCount' => $todayCount,
|
||||
'releaseCount' => $releaseCount,
|
||||
'countryCount' => $countryCount,
|
||||
'trackCount' => $trackCount
|
||||
];
|
||||
return $this->success($data);
|
||||
}
|
||||
|
||||
// 各渠道计数
|
||||
public function channelCount()
|
||||
{
|
||||
$inquiryChannelList = InquiryChannel::all(['id', 'name']);
|
||||
$channels = [];
|
||||
foreach ($inquiryChannelList as $key => $val) {
|
||||
$channels[$val->id] = $val->name;
|
||||
}
|
||||
|
||||
$list = Customer::select('channel_id', Db::raw('COUNT(*) as totals'))
|
||||
->groupBy('channel_id')
|
||||
->get()->toArray();
|
||||
|
||||
$channelCounts = [];
|
||||
foreach ($list as $vo) {
|
||||
$channelCounts[] = [
|
||||
"name" => $channels[$vo["channel_id"]],
|
||||
"value" => $vo["totals"]
|
||||
];
|
||||
}
|
||||
return $this->success($channelCounts);
|
||||
}
|
||||
|
||||
// 各国家计数
|
||||
public function countryCount()
|
||||
{
|
||||
$list = Customer::with("countryInfo")
|
||||
->select('country_id', Db::raw('COUNT(*) as totals'))
|
||||
->where('country_id','<>',0)
|
||||
->groupBy('country_id')
|
||||
->get();
|
||||
$arr = [];
|
||||
foreach ($list as $val) {
|
||||
$arr[] = [
|
||||
"value" => $val->totals,
|
||||
"name" => $val->countryInfo->cn_addr
|
||||
];
|
||||
}
|
||||
return $this->success($arr);
|
||||
}
|
||||
|
||||
// 跟单人计数
|
||||
public function trackCount()
|
||||
{
|
||||
$list = Customer::with(["user"])
|
||||
->where("user_id", ">", 0)
|
||||
->whereNotIn('user_id', [1,5,10,11,13,155,16,17,19,74,75,78,141,147])
|
||||
->select('user_id', Db::raw('COUNT(*) as totals'))
|
||||
->groupBy('user_id')
|
||||
->get();
|
||||
$optionType = [];
|
||||
$counts = [];
|
||||
foreach ($list as $val) {
|
||||
if (isset($val->user) && $val->user) {
|
||||
$optionType[] = $val->user->name;
|
||||
$counts[] = $val->totals;
|
||||
}
|
||||
}
|
||||
$arr = [
|
||||
"optionType" => $optionType,
|
||||
"counts" => $counts
|
||||
];
|
||||
return $this->success($arr);
|
||||
}
|
||||
|
||||
// 每日录单数
|
||||
public function dayCount()
|
||||
{
|
||||
$list = Db::table('crm_customer')
|
||||
->where('created_at', '>=', Carbon::now()->subDay(7)->timestamp)
|
||||
->select(
|
||||
Db::raw('DATE(FROM_UNIXTIME(created_at)) as date'),
|
||||
Db::raw('COUNT(*) as order_count')
|
||||
)
|
||||
->groupBy('date')
|
||||
->pluck('order_count', 'date')->toArray();
|
||||
$optionType = [];
|
||||
$counts = [];
|
||||
foreach ($list as $key=>$val) {
|
||||
$optionType[] = $key;
|
||||
$counts[] = $val;
|
||||
}
|
||||
$arr = [
|
||||
"optionType" => $optionType,
|
||||
"counts" => $counts
|
||||
];
|
||||
return $this->success($arr);
|
||||
}
|
||||
|
||||
public function customerCount(Request $request)
|
||||
{
|
||||
$companyId = $request->get('company_id') ?? 0;
|
||||
|
||||
// 1. 计算时间范围
|
||||
$now = Carbon::now();
|
||||
$sixMonthsAgo = $now->copy()->subMonths(5)->startOfMonth(); // 包含6个月
|
||||
|
||||
// 2. 获取关联渠道ID
|
||||
$channelIds = $this->getChannelIdsByCompany($companyId);
|
||||
|
||||
if (empty($channelIds)) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
// 3. 执行查询
|
||||
$list = Customer::select([
|
||||
DB::raw("DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m') AS month"),
|
||||
DB::raw('COUNT(*) AS total_count')
|
||||
])
|
||||
->whereIn('channel_id', $channelIds)
|
||||
->where('created_at', '>', 0)
|
||||
->where('created_at', '>=', $sixMonthsAgo->timestamp) // 添加时间限制
|
||||
->groupBy('month')
|
||||
->orderBy('month')
|
||||
->get();
|
||||
|
||||
$optionType = [];
|
||||
$counts = [];
|
||||
foreach ($list as $item) {
|
||||
$optionType[] = $item->month;
|
||||
$counts[] = $item->total_count;
|
||||
}
|
||||
$arr = [
|
||||
"optionType" => $optionType,
|
||||
"counts" => $counts
|
||||
];
|
||||
return $this->success($arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公司与渠道的映射
|
||||
*/
|
||||
private function getChannelIdsByCompany($companyId)
|
||||
{
|
||||
$data = [
|
||||
0 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
|
||||
1 => [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
3 => [9, 10, 11]
|
||||
];
|
||||
return $data[$companyId] ?? [];
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\crmAdmin\logic;
|
||||
|
||||
use app\crm\model\Customer;
|
||||
|
||||
class CustomerLogic
|
||||
{
|
||||
|
||||
public function status(int $id,int $status)
|
||||
{
|
||||
$customer = Customer::withTrashed()->find($id);
|
||||
$customer->status = $status;
|
||||
$res = $customer->save();
|
||||
|
||||
if($status == 1){
|
||||
$customer->restore();
|
||||
}
|
||||
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
public function forceDelete(int $id ,string $status_desc = '')
|
||||
{
|
||||
$customer = Customer::withTrashed()->find($id);
|
||||
//强制删除
|
||||
// $res = $customer->forceDelete();
|
||||
$customer->status = 3;
|
||||
$customer->status_desc = $status_desc;
|
||||
$res = $customer->save();
|
||||
return $res;
|
||||
}
|
||||
}
|
||||
@@ -1,557 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\crmAdmin\service;
|
||||
|
||||
use app\common\model\CustomerAudit;
|
||||
use app\common\model\InquiryLog;
|
||||
use app\common\model\User;
|
||||
use app\common\service\OssService;
|
||||
use app\crm\model\CustomerHis;
|
||||
use app\crmAdmin\logic\CustomerLogic;
|
||||
use app\crm\model\CarType;
|
||||
use app\crm\model\Channel;
|
||||
use app\crm\model\Country;
|
||||
use app\crm\model\Customer;
|
||||
use app\crm\model\Follow;
|
||||
use app\crm\utils\Util;
|
||||
use config\constants\Constants;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Border;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
use support\Log;
|
||||
|
||||
class CustomerService
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$customer = $this->search($params);
|
||||
return $customer;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询列表数据
|
||||
* @param $params
|
||||
* @param $export
|
||||
* @return Customer[]|\Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Collection[]|\Illuminate\Pagination\LengthAwarePaginator
|
||||
*/
|
||||
public function search($params, $export = false)
|
||||
{
|
||||
|
||||
// $page = $request->input('page', 1);
|
||||
// $perPage = $request->input('per_page', 10);
|
||||
$perPage = $params['size'] ?? 10;
|
||||
$page = $params['current'] ?? 1;
|
||||
$keyword = $params['keyword'] ?? '';
|
||||
$recycle = $params['recycle'] ?? '';
|
||||
$follow = $params['follow'] ?? '';
|
||||
$follow_last = $params['follow_last'] ?? '';
|
||||
$tagId = $params['tag_id'] ?? [];
|
||||
$user_id = $params['user_id'] ?? '';
|
||||
$seas = $params['seas'] ?? ''; //recyclea:管理端回收站,audit:待审核列表,seas:公海
|
||||
$scene = $params['scene'] ?? '';
|
||||
$channelId = $params['channel_id'] ?? '';
|
||||
$where = [];
|
||||
|
||||
if ($scene == 'audit') {
|
||||
$where[] = ['status', '=', 2];
|
||||
} elseif ($scene == 'recyclea') {
|
||||
$where[] = ['status', '>', 2];
|
||||
} else {
|
||||
$where[] = ['status', '=', 1];
|
||||
}
|
||||
if ($seas == 'seas' || $scene == 'seas') {
|
||||
$where[] = ['user_id', 0];
|
||||
}
|
||||
// if($recycle == 'recycle'){
|
||||
// $where[] = ['user_id', $user_id];
|
||||
// }
|
||||
|
||||
if (!empty($channelId)){
|
||||
$where[] = ['channel_id', $channelId];
|
||||
}
|
||||
|
||||
$grade = [];
|
||||
if (!Util::isEmpty($follow) && $follow == 0) {
|
||||
$where[] = ['grade', '<=', 2];
|
||||
} elseif (!Util::isEmpty($follow) && $follow == 1) {
|
||||
$grade = [3, 4];
|
||||
} elseif (!Util::isEmpty($follow) && $follow == 2) {
|
||||
$where[] = ['grade', '=', 5];
|
||||
}
|
||||
|
||||
if (!Util::isEmpty($follow_last) && $follow_last == 0) {
|
||||
$where[] = ['follow_last', '>', strtotime('-1 day')];
|
||||
} elseif (!Util::isEmpty($follow_last) && $follow_last == 1) {
|
||||
$where[] = ['follow_last', '>', strtotime('-3 day')];
|
||||
} elseif (!Util::isEmpty($follow_last) && $follow_last == 2) {
|
||||
$where[] = ['follow_last', '>', strtotime('-7 day')];
|
||||
}
|
||||
|
||||
$query = Customer::where($where);
|
||||
|
||||
if (!empty($user_id)) {
|
||||
$query->whereIn('user_id', explode(',', $user_id));
|
||||
} elseif ($user_id === 0 && $export) {
|
||||
$query->where('user_id', 0);
|
||||
}
|
||||
|
||||
if (!empty($tagId)) {
|
||||
//查询有$tagId 里任意一个标签的客户
|
||||
//$query->whereHas('crm_tag', function($query) use ($tagId){
|
||||
// $query->whereIn ('tag.id', $tagId);
|
||||
//});
|
||||
//查询有$tagId 里所有标签的客户
|
||||
foreach ($tagId as $id) {
|
||||
$query->whereHas('tags', function($query) use ($id){
|
||||
$query->where('tag_id', $id);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!Util::isEmpty($keyword)) {
|
||||
$query->where(function ($query) use ($keyword) {
|
||||
$query->where('contacts', 'like', "%{$keyword}%")
|
||||
->orWhere('phone', 'like', "%{$keyword}%")
|
||||
->orWhere('email', 'like', "%{$keyword}%")
|
||||
->orWhere('WhatsApp', 'like', "%{$keyword}%")
|
||||
->orWhere('code', 'like', "%{$keyword}%");
|
||||
});
|
||||
}
|
||||
if (!Util::isEmpty($grade)) {
|
||||
$query->whereIn('grade', $grade);
|
||||
}
|
||||
|
||||
if ($recycle == 'recycle' || $scene == 'recycle' || $scene == 'audit') {
|
||||
$query->onlyTrashed();
|
||||
}
|
||||
if ($seas == 'seas' || $scene == 'recyclea') {
|
||||
$query = $query->withTrashed();
|
||||
}
|
||||
|
||||
if (!$export) {
|
||||
$customer = $query->orderBy('id', 'desc')->paginate($perPage, ['*'], 'page', $page);
|
||||
} else {
|
||||
$customer = $query->orderBy('id', 'desc')->get();
|
||||
|
||||
return $customer;
|
||||
}
|
||||
if (!$export) {
|
||||
foreach ($customer as &$item) {
|
||||
$item = $this->getCustomer($item);
|
||||
$item['desc_collect'] = $item['desc_collect'] ?? '';
|
||||
if ($seas == 'seas' || $scene == 'seas') {
|
||||
$item['seas_time'] = time() - (empty($item['deleted_at'])?strtotime($item['updated_at']):strtotime($item['deleted_at']));
|
||||
}
|
||||
if ($scene == 'audit') { //审核时查询举报人姓名
|
||||
$customerHis = CustomerHis::where('customer_id', $item->id)->orderBy('id', 'desc')->first(['user_his']);
|
||||
$item['user_name'] = empty($customerHis['user_his']) ? '' : User::where('id',$customerHis['user_his'])->value('name');
|
||||
$audit = CustomerAudit::where('customer_id', $item->id)->orderBy('id', 'desc')->first();
|
||||
if (!empty($audit)&&!empty($audit['img'])) {
|
||||
$audit = $audit?$audit->toArray():'';
|
||||
$audit['img'] = explode(',', $audit['img']);
|
||||
|
||||
$ossservice = new OssService();
|
||||
foreach ($audit['img'] as $k => $img) {
|
||||
$audit['img'][$k] = $ossservice->generatePrivateUrl($img);
|
||||
}
|
||||
}
|
||||
$item['audit'] = $audit;
|
||||
}
|
||||
if ($scene == 'recyclea' && $item['status'] == 3) { //回收站删除来源
|
||||
$item['del_source'] = '公海';
|
||||
}elseif ($scene == 'recyclea' && $item['status'] == 4) {
|
||||
$item['del_source'] = '管理端';
|
||||
}elseif ($scene == 'recyclea' && $item['status'] == 5) {
|
||||
$source = (!empty($item['user_id'])) ? (':' . User::where('id',$item['user_id'])->value('name')) : '';
|
||||
$item['del_source'] = '业务员' . $source;
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($item);
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
public function export($params)
|
||||
{
|
||||
if(empty($params['user_id']) && empty($params['tag_id']) && empty($params['channel_id'])){
|
||||
$params['user_id'] = 0;
|
||||
}
|
||||
$customers = $this->search($params, true);
|
||||
|
||||
// 创建新的Spreadsheet对象
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// 设置表头
|
||||
$headers = [
|
||||
'A1' => '客户ID',
|
||||
'B1' => '联系人',
|
||||
'C1' => '电话',
|
||||
'D1' => '邮箱',
|
||||
'E1' => 'WhatsApp',
|
||||
'F1' => '性别',
|
||||
'G1' => '国家/地区',
|
||||
'H1' => '渠道来源',
|
||||
'I1' => '描述',
|
||||
'J1' => '所属人',
|
||||
'K1' => '录入人',
|
||||
'L1' => '详情',
|
||||
'M1' => '录入时间',
|
||||
];
|
||||
|
||||
// 设置表头样式
|
||||
foreach ($headers as $cell => $value) {
|
||||
$sheet->setCellValue($cell, $value);
|
||||
}
|
||||
|
||||
// 设置表头样式
|
||||
$headerStyle = [
|
||||
'font' => [
|
||||
'bold' => true,
|
||||
'color' => ['rgb' => 'FFFFFF'],
|
||||
],
|
||||
'fill' => [
|
||||
'fillType' => Fill::FILL_SOLID,
|
||||
'startColor' => ['rgb' => '4472C4'],
|
||||
],
|
||||
'alignment' => [
|
||||
'horizontal' => Alignment::HORIZONTAL_CENTER,
|
||||
'vertical' => Alignment::VERTICAL_CENTER,
|
||||
],
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => Border::BORDER_THIN,
|
||||
'color' => ['rgb' => '000000'],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$sheet->getStyle('A1:M1')->applyFromArray($headerStyle);
|
||||
|
||||
// 填充数据
|
||||
$row = 2;
|
||||
foreach ($customers as $customer) {
|
||||
// 获取完整的客户信息
|
||||
$customerData = $this->getCustomer($customer);
|
||||
|
||||
// 填充数据行
|
||||
$sheet->setCellValue('A' . $row, $customerData['id']);
|
||||
$sheet->setCellValue('B' . $row, $customerData['contacts']);
|
||||
$sheet->setCellValue('C' . $row, $customerData['phone']);
|
||||
$sheet->setCellValue('D' . $row, $customerData['email']);
|
||||
$sheet->setCellValue('E' . $row, $customerData['WhatsApp']);
|
||||
$sheet->setCellValue('F' . $row, $customerData['sex_txt']);
|
||||
$sheet->setCellValue('G' . $row, $customerData['country_name']);
|
||||
$sheet->setCellValue('H' . $row, $customerData['channel_name']);
|
||||
$sheet->setCellValue('I' . $row, $customerData['describe']);
|
||||
$sheet->setCellValue('J' . $row, $customerData['user_name']); // 所属人姓名
|
||||
$sheet->setCellValue('K' . $row, $customerData['enter_user_name']);
|
||||
$sheet->setCellValue('L' . $row, empty($customerData['desc_collect'])? '' :strip_tags($customerData['desc_collect']));
|
||||
$sheet->setCellValue('M' . $row, $customerData['created_at']->toDateTimeString());
|
||||
|
||||
$row++;
|
||||
}
|
||||
|
||||
// 设置数据行样式
|
||||
$dataStyle = [
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => Border::BORDER_THIN,
|
||||
'color' => ['rgb' => '000000'],
|
||||
],
|
||||
],
|
||||
'alignment' => [
|
||||
'vertical' => Alignment::VERTICAL_CENTER,
|
||||
],
|
||||
];
|
||||
|
||||
$lastRow = $row - 1;
|
||||
if ($lastRow >= 2) {
|
||||
$sheet->getStyle('A2:K' . $lastRow)->applyFromArray($dataStyle);
|
||||
}
|
||||
|
||||
// 自动调整列宽
|
||||
foreach (range('A', 'K') as $column) {
|
||||
$sheet->getColumnDimension($column)->setAutoSize(true);
|
||||
}
|
||||
|
||||
// 设置行高
|
||||
$sheet->getRowDimension(1)->setRowHeight(25);
|
||||
|
||||
// 生成文件名
|
||||
$filename = '客户数据_' . date('Y-m-d_H-i-s') . '.xlsx';
|
||||
|
||||
// 创建输出目录
|
||||
$exportDir = runtime_path() . '/export/';
|
||||
if (!is_dir($exportDir)) {
|
||||
mkdir($exportDir, 0755, true);
|
||||
}
|
||||
|
||||
$filepath = $exportDir . $filename;
|
||||
|
||||
// 创建Excel写入器
|
||||
$writer = new Xlsx($spreadsheet);
|
||||
$writer->save($filepath);
|
||||
// $writer->save('php://output');
|
||||
// $excelContent = ob_get_clean();
|
||||
// return $excelContent;
|
||||
|
||||
// 返回文件信息
|
||||
return [
|
||||
'filename' => $filename,
|
||||
'filepath' => $filepath,
|
||||
'size' => filesize($filepath),
|
||||
'count' => count($customers)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
* @return bool
|
||||
*/
|
||||
public function audit($params)
|
||||
{
|
||||
|
||||
$id = $params['id'];
|
||||
|
||||
$logic = new CustomerLogic();
|
||||
$audit = CustomerAudit::where('customer_id', $id)->orderBy('id', 'desc')->first();
|
||||
if ($params['scene'] == 'delete') {
|
||||
if(!empty($audit)){
|
||||
$audit->status = 3;
|
||||
$audit->save();
|
||||
}
|
||||
return $logic->forceDelete($params['id'],$audit->remark);
|
||||
} else {
|
||||
if(!empty($audit)){
|
||||
$audit->status = 2;
|
||||
$audit->save();
|
||||
}
|
||||
return $logic->status($params['id'], 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
* @return bool
|
||||
*/
|
||||
public function transfer($params)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$customerId = $params['customer_id'];
|
||||
$userId = $params['user_id'];
|
||||
|
||||
$query= Customer::whereIn('id',explode(',',$customerId));
|
||||
$customer = $query->get();
|
||||
$user = User::where(['id' => $userId])->first();
|
||||
|
||||
foreach ($customer as $item) {
|
||||
//记录客户关系变化
|
||||
$his = CustomerHis::create([
|
||||
'customer_id' => $item->id,
|
||||
'user_his' => $item->user_id,
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
|
||||
\app\crm\service\CustomerService::inquiryUpdate($item,$userId);
|
||||
}
|
||||
$data = [
|
||||
'user_id' => $userId,
|
||||
'corp_id' => $user->corp_id,
|
||||
'obtain' => time(),
|
||||
];
|
||||
$res = $query->update($data);
|
||||
|
||||
Db::commit();
|
||||
return $res;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
* @return bool
|
||||
*/
|
||||
public function delete($params)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$customerId = $params['customer_id'];
|
||||
|
||||
$query= Customer::whereIn('id',explode(',',$customerId));
|
||||
$customer = $query->get();
|
||||
|
||||
foreach ($customer as $item) {
|
||||
//记录客户关系变化
|
||||
$his = CustomerHis::create([
|
||||
'customer_id' => $item->id,
|
||||
'user_his' => $item->user_id,
|
||||
'user_id' => 0,
|
||||
]);
|
||||
|
||||
\app\crm\service\CustomerService::inquiryUpdate($item,0);
|
||||
}
|
||||
$res = $query->update(['user_id' => 0]);
|
||||
|
||||
Db::commit();
|
||||
return $res;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $customer
|
||||
* @param $request
|
||||
* @param $tag 是否返回客户标签
|
||||
* @return mixed
|
||||
*/
|
||||
public static function getCustomer($customer, $language = 'zh_CN', $tag = false)
|
||||
{
|
||||
$customer['grade_txt'] = Util::language($language, Constants::GRADE_EN[$customer['grade']], Constants::GRADE_ZH[$customer['grade']], Constants::GRADE_RU[$customer['grade']]);
|
||||
$customer['magnitude'] = ($customer['magnitude']==0)?1:$customer['magnitude'];
|
||||
$customer['magnitude_txt'] = Util::language($language, Constants::MAGNITUDE_EN[$customer['magnitude']], Constants::MAGNITUDE[$customer['magnitude']], Constants::MAGNITUDE_RU[$customer['magnitude']]);
|
||||
$customer['sex_txt'] = Util::language($language, Constants::SEX_EN[$customer['sex']], Constants::SEX[$customer['sex']], Constants::SEX_RU[$customer['sex']]);
|
||||
|
||||
if ($customer['grade'] <= 2) {
|
||||
$customer['follow'] = 0;
|
||||
$customer['follow_txt'] = Util::language($language, 'Following', '跟进中', 'Продолжение');
|
||||
} elseif ($customer['grade'] < 5) {
|
||||
$customer['follow'] = 1;
|
||||
$customer['follow_txt'] = Util::language($language, 'transacted', '已成交', 'Транзакция завершена');
|
||||
} else {
|
||||
$customer['follow'] = 2;
|
||||
$customer['follow_txt'] = Util::language($language, 'lost', '已流失', 'Потерянный');
|
||||
}
|
||||
|
||||
$where = [
|
||||
'customer_id' => $customer['id']
|
||||
];
|
||||
$begin_follow = Follow::select('id', 'created_at', 'updated_at')
|
||||
->where($where)
|
||||
->min('created_at');
|
||||
|
||||
|
||||
$customer['begin_follow'] = Util::timeTotDate($begin_follow);
|
||||
// $customer['created_at'] = Util::timeTotDate($customer['created_at']);
|
||||
// $customer['updated_at'] = Util::timeTotDate($customer['updated_at']);
|
||||
|
||||
$customer = Util::formatDate($customer, ['follow_next','follow_last']);
|
||||
$nameLang = $language == 'en' ? 'name_en' : ($language == 'ru' ? 'name_ru' : 'name');
|
||||
$countryLang = $language == 'en' ? 'en_addr' : 'cn_addr';
|
||||
// $customer['car_type_name'] = empty($customer['car_type_id'])?'':CarType::where(['id'=>$customer['car_type_id']])->value($nameLang);
|
||||
$customer['country_name'] = empty($customer['country_id']) ? '' : Country::where(['id' => $customer['country_id']])->value($countryLang);
|
||||
$customer['channel_name'] = empty($customer['channel_id']) ? '' : Channel::where(['id' => $customer['channel_id']])->value($nameLang);
|
||||
// $customer['last_follow'] = $last_follow;
|
||||
|
||||
if ($tag) {
|
||||
foreach ($customer['tags'] as &$tag) {
|
||||
$tag['names'] = unserialize($tag['names']);
|
||||
$tag['name'] = $tag['names'][$language];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$customer['enter_user_name'] = empty($customer['enter_user_id']) ? '' : User::where('id',$customer['enter_user_id'])->value('name');
|
||||
$customer['user_name'] = empty($customer['user_id']) ? '公海' : User::where('id',$customer['user_id'])->value('name');
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
|
||||
public function detail($params)
|
||||
{
|
||||
$id = $params['id'];
|
||||
$customer = Customer::with('tags')
|
||||
->where('id', $id)
|
||||
->first();
|
||||
$customer = $this->getCustomer($customer);
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
public function follow($params)
|
||||
{
|
||||
$id = $params['id'];
|
||||
$follow = Follow::
|
||||
where('customer_id', $id)
|
||||
->get();
|
||||
|
||||
$ossservice = new OssService();
|
||||
foreach ($follow as $item) {
|
||||
$item = Util::formatDate($item,['created_at','updated_at','follow_time']);
|
||||
$item['follow_time'] = empty($item['follow_time'])?'':$item['follow_time'];
|
||||
$item['picture_full'] = empty($item->picture)?'':$ossservice->generatePrivateUrl($item->picture);
|
||||
}
|
||||
|
||||
return $follow;
|
||||
}
|
||||
|
||||
/**
|
||||
* 离职员工客户分配
|
||||
* @param $params
|
||||
* @return string[]
|
||||
*/
|
||||
public function allocation($params)
|
||||
{
|
||||
$corpId = $params['corp_id'];
|
||||
$userId = explode(',', $params['user_id']);
|
||||
|
||||
log::info('开始分配离职员工客户,corp_id:'.$corpId.' 被分配员工'. implode(',', $userId));
|
||||
|
||||
//查询离职客户
|
||||
$userResign = User::where('status', 2)
|
||||
->where('corp_id', $corpId)
|
||||
->get(['id','name']);
|
||||
|
||||
$resignUerIds = [];
|
||||
$userNames = [];
|
||||
foreach ($userResign as $row) {
|
||||
$resignUerIds[] = (int)$row->id;
|
||||
$userNames[] = $row->name;
|
||||
}
|
||||
if (empty($userResign)) {
|
||||
log::info('未匹配到离职用户');
|
||||
throw new BusinessException('未匹配到离职用户', 500);
|
||||
}
|
||||
log::info('匹配到离职用户数:' . count($resignUerIds) .' '. implode(',',$userNames));
|
||||
|
||||
$customerCount = Customer::whereIn('user_id', $resignUerIds)
|
||||
->orderBy('id', 'asc')
|
||||
->count();
|
||||
|
||||
if ($customerCount === 0) {
|
||||
log::info('未找到离职员工相关的客户记录。');
|
||||
throw new BusinessException('未找到离职员工相关的客户记录', 500);
|
||||
}
|
||||
|
||||
// 初始化 UID 轮询器
|
||||
$uidRotator = new \app\common\utils\RedisUidRotator('allocation_customer_user');
|
||||
$uidRotator->setUids($userId, false);
|
||||
|
||||
Customer::whereIn('user_id', $resignUerIds)
|
||||
->orderBy('id', 'asc')
|
||||
->chunkById(500, function ($customers) use ($uidRotator) {
|
||||
foreach ($customers as $customer) {
|
||||
// 获取下一个分配的UID
|
||||
$newUserId = $uidRotator->next();
|
||||
$customer->user_id = $newUserId;
|
||||
$customer->save();
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
|
||||
return [
|
||||
'userCount' => count($resignUerIds),
|
||||
'customerCount' => $customerCount,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
namespace app\mobile\controller;
|
||||
|
||||
use app\common\controller\BaseController;
|
||||
use app\common\model\Corp;
|
||||
use app\common\model\User;
|
||||
use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\common\service\InvItemService;
|
||||
use support\Request;
|
||||
|
||||
class InvItemController extends BaseController
|
||||
{
|
||||
use CrudControllerTrait;
|
||||
|
||||
protected $service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->service = new InvItemService();
|
||||
}
|
||||
|
||||
public function preset(Request $request){
|
||||
try {
|
||||
$res = $this->service->getList();
|
||||
$result = [];
|
||||
foreach ($res as $value) {
|
||||
$value['company_name'] = Corp::where('id', $value['company_id'])->value('name');
|
||||
$value['manage_user_name'] = User::where('id', $value['manage_user_id'])->value('name');
|
||||
$result[] = $value;
|
||||
}
|
||||
return $this->success($result, '获取物品列表');
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表页数据格式化
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
protected function indexFormat($data)
|
||||
{
|
||||
if (isset($data['created_at']))
|
||||
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
|
||||
if (isset($data['updated_at']))
|
||||
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
|
||||
if (isset($data['company_id']))
|
||||
$data['company_name'] = Corp::where('id', $data['company_id'])->value('name');
|
||||
if (isset($data['manage_user_id']))
|
||||
$data['manage_user_name'] = User::where('id', $data['manage_user_id'])->value('name');
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
namespace app\mobile\controller;
|
||||
|
||||
use app\common\controller\BaseController;
|
||||
use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\common\service\InvRequisitionService;
|
||||
use support\Request;
|
||||
|
||||
class InvRequisitionController extends BaseController
|
||||
{
|
||||
use CrudControllerTrait;
|
||||
|
||||
protected $service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->service = new InvRequisitionService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交物品申请
|
||||
*
|
||||
* @param Request $request
|
||||
* @return mixed
|
||||
*/
|
||||
public function apply(Request $request)
|
||||
{
|
||||
try {
|
||||
// 验证申请数据
|
||||
$data = $this->validate($this->service->getValidator(), $request->post(), 'apply');
|
||||
|
||||
// 处理申请逻辑
|
||||
$result = $this->service->serviceStore($request, $data, 'apply');
|
||||
|
||||
return $this->success($result, '申请提交成功');
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表页数据格式化
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
// protected function indexFormat($data)
|
||||
// {
|
||||
// if (isset($data['created_at']))
|
||||
// $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
|
||||
// if (isset($data['updated_at']))
|
||||
// $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
|
||||
// return $data;
|
||||
// }
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
<?php
|
||||
namespace app\mobile\controller;
|
||||
|
||||
use app\common\controller\BaseController;
|
||||
use app\common\traits\crud\CrudControllerTrait;
|
||||
use app\common\service\InvRequisitionItemReturnService;
|
||||
use support\Request;
|
||||
|
||||
class InvRequisitionItemReturnController extends BaseController
|
||||
{
|
||||
use CrudControllerTrait;
|
||||
|
||||
protected $service;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->service = new InvRequisitionItemReturnService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表页数据格式化
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
// protected function indexFormat($data)
|
||||
// {
|
||||
// if (isset($data['created_at']))
|
||||
// $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
|
||||
// if (isset($data['updated_at']))
|
||||
// $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
|
||||
// return $data;
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
* 物品兑换确认
|
||||
*
|
||||
* @param Request $request
|
||||
* @return mixed
|
||||
*/
|
||||
public function returnConfirm(Request $request)
|
||||
{
|
||||
try {
|
||||
// 验证申请数据
|
||||
$data = $this->validate($this->service->getValidator(), $request->post(), 'returnConfirm');
|
||||
|
||||
// 处理申请逻辑
|
||||
$result = $this->service->serviceReturnConfirm($request, $data, 'returnConfirm');
|
||||
|
||||
return $this->success($result, '申请提交成功');
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\controller;
|
||||
|
||||
use app\ticket\service\TicketService;
|
||||
use support\Request;
|
||||
|
||||
class AttachmentController extends BaseController
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\controller;
|
||||
|
||||
use support\Request;
|
||||
use support\Response;
|
||||
use support\exception\BusinessException;
|
||||
use app\common\traits\ResponseTrait;
|
||||
use think\Validate;
|
||||
|
||||
abstract class BaseController
|
||||
{
|
||||
use ResponseTrait;
|
||||
|
||||
protected mixed $validator = null;
|
||||
|
||||
/**
|
||||
* 验证数据
|
||||
*
|
||||
* @param Validate $validator 验证器实例
|
||||
* @param array $data 待验证的数据
|
||||
* @param string $scene 验证场景
|
||||
* @return array 验证后的数据
|
||||
* @throws BusinessException 验证失败时抛出业务异常
|
||||
*/
|
||||
public function validate(Validate $validator, array $data, string $scene = ''): array
|
||||
{
|
||||
// 如果指定了验证场景,并且验证器支持场景方法,则设置验证场景
|
||||
if ($scene && method_exists($validator, 'scene')) {
|
||||
$validator->scene($scene);
|
||||
}
|
||||
// 执行数据验证
|
||||
if (!$validator->check($data)) {
|
||||
// 验证失败,抛出业务异常,异常信息为验证器返回的错误信息
|
||||
throw new BusinessException($validator->getError());
|
||||
}
|
||||
// 验证成功,返回原始数据
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function page($result){
|
||||
$current = $result->currentPage();
|
||||
$total = $result->total();
|
||||
$size = $result->perPage();
|
||||
$result = $result->toArray();
|
||||
$result['current'] = $current;
|
||||
$result['total'] = $total;
|
||||
$result['size'] = $size;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\controller;
|
||||
|
||||
use app\ticket\service\CategorieService;
|
||||
use support\Request;
|
||||
|
||||
class CategorieController extends BaseController
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
try {
|
||||
$result = (new CategorieService())->list($request->all());
|
||||
return $this->success($this->page($result));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function getAll(Request $request)
|
||||
{
|
||||
try {
|
||||
$result = (new CategorieService())->getAll($request->all());
|
||||
return $this->success($result);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function add(Request $request)
|
||||
{
|
||||
try {
|
||||
return (new CategorieService())->add($request->all())
|
||||
? $this->success()
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage().' '.$th->getLine().' '.$th->getFile());
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(Request $request)
|
||||
{
|
||||
try {
|
||||
$result = (new CategorieService())->edit($request->all());
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage().' '.$th->getLine().' '.$th->getFile());
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(Request $request)
|
||||
{
|
||||
try {
|
||||
$result = (new CategorieService())->delete($request->input('id'));
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage().' '.$th->getLine().' '.$th->getFile());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\controller;
|
||||
|
||||
use app\ticket\service\ConversationService;
|
||||
use support\Request;
|
||||
|
||||
class ConversationController extends BaseController
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
try {
|
||||
$ticket_id = $request->input('ticket_id');
|
||||
if(empty($ticket_id)){
|
||||
return $this->error('ticket_id不能为空');
|
||||
}
|
||||
$result = (new ConversationService())->list($request->all());
|
||||
return $this->success($this->page($result));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage().$e->getLine().$e->getFile());
|
||||
}
|
||||
}
|
||||
public function add(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setPost('user_id', $request->user->uid);
|
||||
return (new ConversationService())->add($request->all())
|
||||
? $this->success()
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工单邮件补发
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function sendEmail(Request $request)
|
||||
{
|
||||
try {
|
||||
$res = (new ConversationService())->sendEmail($request->all());
|
||||
return $res
|
||||
? $this->success($res)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setPost('user_id', $request->user->uid);
|
||||
$result = (new ConversationService())->edit($request->all());
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage().' '.$th->getLine().' '.$th->getFile());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\controller;
|
||||
|
||||
use app\ticket\service\TicketService;
|
||||
use support\Request;
|
||||
|
||||
class TicketController extends BaseController
|
||||
{
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
try {
|
||||
$result = (new TicketService())->list($request->all());
|
||||
return $this->success($this->page($result));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 我的工单
|
||||
* @param Request $request
|
||||
* @return \support\Response
|
||||
*/
|
||||
public function self(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setGet('user_id',$request->user->uid);
|
||||
$result = (new TicketService())->list($request->all());
|
||||
return $this->success($result);
|
||||
// return $this->success($this->page($result));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function add(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setPost('user_id', $request->user->uid);
|
||||
|
||||
return (new TicketService())->add($request->all())
|
||||
? $this->success()
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setPost('user_id', $request->user->uid);
|
||||
$result = (new TicketService())->edit($request->all());
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
public function status(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setPost('user_id', $request->user->uid);
|
||||
$result = (new TicketService())->status($request->all());
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
public function getStatus(Request $request)
|
||||
{
|
||||
try {
|
||||
$request->setGet('user_id', $request->user->uid);
|
||||
$result = (new TicketService())->getStatus($request->all());
|
||||
return $result
|
||||
? $this->success($result)
|
||||
: $this->error();
|
||||
} catch (\Throwable $th) {
|
||||
return $this->error($th->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\logic;
|
||||
|
||||
use app\common\model\UserTokenLog;
|
||||
use app\common\model\Systems;
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use app\common\utils\Jwt;
|
||||
use app\ticket\model\Attachment;
|
||||
use app\ticket\model\Ticket;
|
||||
use support\Redis;
|
||||
use support\exception\BusinessException;
|
||||
use support\Log;
|
||||
|
||||
class AttachmentLogic
|
||||
{
|
||||
public function adds(array $data,int $ticket_id,int $user_id)
|
||||
{
|
||||
try {
|
||||
foreach ($data as $k=>$v){
|
||||
$v['ticket_id'] = $ticket_id;
|
||||
$v['user_id'] = $user_id;
|
||||
$res = Attachment::create($v);
|
||||
}
|
||||
return $res;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('工单创建失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('工单创建失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(array $data,int $ticket_id,int $user_id)
|
||||
{
|
||||
try {
|
||||
$attachmentsId = [];
|
||||
foreach ($data as $k=>$v){
|
||||
$v['ticket_id'] = $ticket_id;
|
||||
$v['user_id'] = $user_id;
|
||||
if(!empty($v['id'])){ //修改附件
|
||||
$attachmentId = $v['id'];
|
||||
$attachmentsId[] = $attachmentId;
|
||||
// $v_res = Attachment::update($attachmentId, $v);
|
||||
$v_res = Attachment::updateOrCreate(['id' => $v['id']],$v);
|
||||
if (!$v_res) {
|
||||
throw new BusinessException('附件保存失败');
|
||||
}
|
||||
} else { //新增附件
|
||||
unset($v['id']);
|
||||
$v_res = Attachment::create($v);
|
||||
if (!$v_res) {
|
||||
throw new BusinessException('附件创建失败');
|
||||
}
|
||||
$vId = $v_res->id;
|
||||
$attachmentsId[] = $vId;
|
||||
}
|
||||
}
|
||||
|
||||
//删除本次没有出现的附件
|
||||
$res = Attachment::whereNotIn('id', $attachmentsId)->where('ticket_id',$ticket_id)->delete();
|
||||
return $res;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('工单编辑(附件)失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('工单编辑失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public static function generateSimpleTicketNo(): string
|
||||
{
|
||||
$date = date('Ymd'); // 日期
|
||||
$prefix = 'GD'; // 前缀
|
||||
$random = strtoupper(substr(md5(uniqid()), 0, 5)); // 5位随机字母数字
|
||||
|
||||
return $prefix . $date . '-' . $random; // 如 GD20240702-AB3X9Z
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\logic;
|
||||
|
||||
use app\ticket\model\Categorie;
|
||||
use support\Log;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class CategorieLogic
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$where = [];
|
||||
$size = $params['size'] ?? 10;
|
||||
$current = $params['current'] ?? 1;
|
||||
return Categorie::with('translation')->where($where)->paginate($size, ['*'], 'page', $current);
|
||||
}
|
||||
|
||||
public function getAll($params)
|
||||
{
|
||||
$where = [];
|
||||
$where[] = ['status', '=', 1];
|
||||
return Categorie::with('translation')->where($where)->get();
|
||||
}
|
||||
|
||||
public function find($id)
|
||||
{
|
||||
return Categorie::with(['translation' => function ($query) {
|
||||
$query->where('locale', locale());
|
||||
}])->where('status', 1)
|
||||
->find($id);
|
||||
}
|
||||
|
||||
public function add(array $data)
|
||||
{
|
||||
try {
|
||||
return Categorie::create($data);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('分类创建失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('分类创建失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
$categorie = Categorie::updateOrCreate(['id' => $data['id']], $data);
|
||||
return $categorie;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('分类编辑失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('分类编辑失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(int $id)
|
||||
{
|
||||
try {
|
||||
$categorie = Categorie::where(['id'=>$id])->delete();
|
||||
return $categorie;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('分类删除失败', [
|
||||
'id' => $id,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('分类删除失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\logic;
|
||||
|
||||
use app\ticket\model\Conversation;
|
||||
use support\Log;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class ConversationLogic
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$where = [];
|
||||
if (!empty($params['ticket_id'])) {
|
||||
$where['ticket_id'] = $params['ticket_id'];
|
||||
}
|
||||
$size = $params['size'] ?? 10;
|
||||
$current = $params['current'] ?? 1;
|
||||
return Conversation::where($where)->paginate($size, ['*'], 'page', $current);
|
||||
}
|
||||
|
||||
public function add(array $data)
|
||||
{
|
||||
try {
|
||||
return Conversation::create($data);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('会话创建失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('会话创建失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
$conversation = Conversation::updateOrCreate(['id' => $data['id']], $data);
|
||||
return $conversation;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('会话编辑失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('会话编辑失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取工单最新一条记录
|
||||
* @param array $data
|
||||
* @return Conversation|\Illuminate\Database\Eloquent\Model|object|null
|
||||
*/
|
||||
public function firstByTicket(int $ticketId)
|
||||
{
|
||||
$conversation = Conversation::where('ticket_id',$ticketId)
|
||||
->orderBy('id','desc')
|
||||
->first();
|
||||
return $conversation;
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\logic;
|
||||
|
||||
use app\common\model\UserTokenLog;
|
||||
use app\common\model\Systems;
|
||||
use app\common\model\User;
|
||||
use app\common\model\UserSn;
|
||||
use app\common\utils\Jwt;
|
||||
use app\ticket\model\Ticket;
|
||||
use support\Redis;
|
||||
use support\exception\BusinessException;
|
||||
use support\Log;
|
||||
|
||||
class TicketLogic
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$where = [];
|
||||
if(!empty($params['categorie_id'])){
|
||||
$where[] = ['categorie_id', '=', $params['categorie_id']];
|
||||
}
|
||||
if(!empty($params['user_id'])){
|
||||
$where[] = ['user_id', '=', $params['user_id']];
|
||||
}
|
||||
if(!empty($params['status'])){
|
||||
$where[] = ['status', '=', $params['status']];
|
||||
}
|
||||
$size = $params['size']??10;
|
||||
$current = $params['current']??1;
|
||||
|
||||
return Ticket::with('attachments')->with('categorie')->with('categorie.translation')->where($where)->orderBy('id','desc')->paginate($size, ['*'], 'page', $current);
|
||||
}
|
||||
public function add(array $data)
|
||||
{
|
||||
$data['status'] = 1;
|
||||
$data['code'] = self::generateSimpleTicketNo();
|
||||
try {
|
||||
return Ticket::create($data);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('工单创建失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('工单创建失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
unset($data['code']);
|
||||
$ticket = Ticket::updateOrCreate(['id' => $data['id']],$data);
|
||||
return $ticket;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('工单编辑失败', [
|
||||
'data' => $data,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
throw new BusinessException('工单编辑失败,请稍后重试', 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function find(int $id)
|
||||
{
|
||||
$ticket = Ticket::find($id);
|
||||
return $ticket;
|
||||
}
|
||||
|
||||
public static function generateSimpleTicketNo(): string
|
||||
{
|
||||
$date = date('Ymd'); // 日期
|
||||
$prefix = 'GD'; // 前缀
|
||||
$random = strtoupper(substr(md5(uniqid()), 0, 5)); // 5位随机字母数字
|
||||
|
||||
return $prefix . $date . '-' . $random; // 如 GD20240702-AB3X9Z
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\model;
|
||||
|
||||
use app\common\model\Resource;
|
||||
use app\common\model\Role;
|
||||
use app\common\model\Systems;
|
||||
use support\Model;
|
||||
|
||||
/**
|
||||
* users 用户表
|
||||
* @property integer $id 用户ID(主键)
|
||||
* @property string $ticket_id 工单编号
|
||||
* @property string $user_id 分类id
|
||||
* @property string $original_name 内容
|
||||
* @property string $storage_path 排序
|
||||
* @property string $mime_type 状态
|
||||
* @property integer $file_size 创建人id
|
||||
* @property string $created_at
|
||||
* @property string $updated_at
|
||||
*/
|
||||
class Attachment extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'tkt_ticket_attachment';
|
||||
|
||||
/**
|
||||
* 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 = [
|
||||
'ticket_id',
|
||||
'user_id',
|
||||
'original_name',
|
||||
'storage_path',
|
||||
'mime_type',
|
||||
'file_size'
|
||||
];
|
||||
|
||||
public function ticket(){
|
||||
return $this->belongsTo(Ticket::class, 'ticket_id', 'id');
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\model;
|
||||
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use support\Model;
|
||||
|
||||
/**
|
||||
* ticket_categorie 工单分类表
|
||||
* @property integer $id 主键
|
||||
* @property string $name 分类名称
|
||||
* @property string $description 分类描述
|
||||
* @property string $created_at 创建时间
|
||||
* @property string $updated_at 更新时间
|
||||
* @property string $deleted_at 删除时间
|
||||
*/
|
||||
class Categorie extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
protected $connection = 'mysql';
|
||||
protected $table = 'tkt_ticket_categorie';
|
||||
protected $primaryKey = 'id';
|
||||
public $timestamps = true;
|
||||
protected $dateFormat = 'U';
|
||||
protected $dates = ['created_at', 'updated_at'];
|
||||
protected $casts = [
|
||||
'updated_at' => 'datetime:Y-m-d H:i:s',
|
||||
'created_at' => 'datetime:Y-m-d H:i:s',
|
||||
];
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'description',
|
||||
];
|
||||
|
||||
/**
|
||||
* 单条翻译
|
||||
*/
|
||||
public function translation()
|
||||
{
|
||||
return $this->hasOne(CategorieTranslation::class, 'categorie_id')->where('locale', locale());
|
||||
}
|
||||
|
||||
/**
|
||||
* 多条翻译
|
||||
*/
|
||||
public function translations()
|
||||
{
|
||||
return $this->hasMany(CategorieTranslation::class, 'categorie_id');
|
||||
}
|
||||
|
||||
public function ticket(){
|
||||
return $this->hasOne(Ticket::class, 'categorie_id', 'id');
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
/**
|
||||
* ticket_categorie_translation 工单分类多语言表
|
||||
* @property integer $id 主键
|
||||
* @property integer $categorie_id 分类ID
|
||||
* @property string $locale 语言
|
||||
* @property string $name 分类名称
|
||||
* @property string $description 分类描述
|
||||
* @property string $created_at 创建时间
|
||||
* @property string $updated_at 更新时间
|
||||
*/
|
||||
class CategorieTranslation extends Model
|
||||
{
|
||||
protected $connection = 'mysql';
|
||||
protected $table = 'tkt_ticket_categorie_translation';
|
||||
protected $primaryKey = 'id';
|
||||
public $timestamps = true;
|
||||
protected $dateFormat = 'U';
|
||||
protected $dates = ['created_at', 'updated_at'];
|
||||
protected $casts = [
|
||||
'updated_at' => 'datetime:Y-m-d H:i:s',
|
||||
'created_at' => 'datetime:Y-m-d H:i:s',
|
||||
];
|
||||
protected $fillable = [
|
||||
'categorie_id',
|
||||
'locale',
|
||||
'name',
|
||||
'description',
|
||||
];
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
/**
|
||||
* ticket_conversation 工单会话表
|
||||
* @property integer $id 主键
|
||||
* @property integer $ticket_id 工单ID
|
||||
* @property integer $user_id 用户ID
|
||||
* @property string $content 会话内容
|
||||
* @property string $created_at 创建时间
|
||||
* @property string $updated_at 更新时间
|
||||
*/
|
||||
class Conversation extends Model
|
||||
{
|
||||
protected $connection = 'mysql';
|
||||
protected $table = 'tkt_ticket_conversation';
|
||||
protected $primaryKey = 'id';
|
||||
public $timestamps = true;
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
protected $fillable = [
|
||||
'ticket_id',
|
||||
'user_id',
|
||||
'content',
|
||||
'attachment',
|
||||
];
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\model;
|
||||
|
||||
use app\common\model\Resource;
|
||||
use app\common\model\Role;
|
||||
use app\common\model\Systems;
|
||||
use support\Model;
|
||||
|
||||
/**
|
||||
* users 用户表
|
||||
* @property integer $id 用户ID(主键)
|
||||
* @property string $code 工单编号
|
||||
* @property string $categorie_id 分类id
|
||||
* @property string $content 内容
|
||||
* @property string $sort 排序
|
||||
* @property integer $status 状态
|
||||
* @property string $user_id 创建人id
|
||||
* @property string $created_at
|
||||
* @property string $updated_at
|
||||
*/
|
||||
class Ticket extends Model
|
||||
{
|
||||
/**
|
||||
* The connection name for the model.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connection = 'mysql';
|
||||
|
||||
/**
|
||||
* The table associated with the model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'tkt_ticket';
|
||||
|
||||
/**
|
||||
* The primary key associated with the table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
/**
|
||||
* Indicates if the model should be timestamped.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $timestamps = false;
|
||||
|
||||
protected $dateFormat = 'U';
|
||||
|
||||
/**
|
||||
* 在保存时手动设置时间戳
|
||||
*/
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
$model->created_at = time();
|
||||
$model->updated_at = time();
|
||||
});
|
||||
|
||||
static::updating(function ($model) {
|
||||
$model->updated_at = time();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定哪些字段自动转换为 Carbon 实例
|
||||
*/
|
||||
public function getDates()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'categorie_id',
|
||||
'content',
|
||||
'sort',
|
||||
'status',
|
||||
'user_id'
|
||||
];
|
||||
|
||||
public function attachments(){
|
||||
return $this->hasMany(Attachment::class, 'ticket_id', 'id');
|
||||
}
|
||||
|
||||
public function categorie(){
|
||||
return $this->belongsTo(Categorie::class, 'categorie_id', 'id');
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\service;
|
||||
|
||||
use app\common\utils\translation\service\TranslationService;
|
||||
use app\queue\utils\Translat;
|
||||
use app\ticket\logic\CategorieLogic;
|
||||
use app\ticket\model\CategorieTranslation;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class CategorieService
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$result = (new CategorieLogic())->list($params);
|
||||
// $value=$result[0]->toArray();
|
||||
foreach ($result as $key => &$value) {
|
||||
$value['name'] = isset($value['translation']) ? $value['translation']['name'] : '';
|
||||
unset($value['translation']);
|
||||
}
|
||||
unset($value);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getAll($params)
|
||||
{
|
||||
$result = (new CategorieLogic())->getAll($params);
|
||||
foreach ($result as $key => &$value) {
|
||||
$value['name'] = isset($value['translation']) ? $value['translation']['name'] : '';
|
||||
unset($value['translation']);
|
||||
}
|
||||
unset($value);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public $translatFields = ['name'];
|
||||
|
||||
public function add(array $data)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$sourceLocale = locale();
|
||||
$traitsourceFields = Translat::extractSourceFields($data, $this->translatFields);
|
||||
|
||||
$result = (new CategorieLogic())->add($data);
|
||||
|
||||
(new TranslationService())->queueTranslations(
|
||||
'ticket_categorie',
|
||||
$result->id,
|
||||
$sourceLocale,
|
||||
$traitsourceFields
|
||||
);
|
||||
|
||||
Db::commit();
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$sourceLocale = locale();
|
||||
$traitsourceFields = Translat::extractSourceFields($data, $this->translatFields);
|
||||
|
||||
$result = (new CategorieLogic())->edit($data);
|
||||
|
||||
// (new TranslationService())->queueTranslations(
|
||||
// 'ticket_categorie',
|
||||
// $data['id'],
|
||||
// $sourceLocale,
|
||||
// $traitsourceFields
|
||||
// );
|
||||
CategorieTranslation::updateOrCreate(
|
||||
[
|
||||
'categorie_id' => $data['id'],
|
||||
'locale' => $sourceLocale,
|
||||
],
|
||||
$traitsourceFields
|
||||
);
|
||||
Db::commit();
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
public function delete(int $id)
|
||||
{
|
||||
if(empty($id)){
|
||||
throw new BusinessException('id不能为空');
|
||||
}
|
||||
try {
|
||||
$result = (new CategorieLogic())->delete($id);
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\service;
|
||||
|
||||
use app\common\model\User;
|
||||
use app\common\service\MessageNotificationsService;
|
||||
use app\common\service\OssService;
|
||||
use app\ticket\logic\CategorieLogic;
|
||||
use app\ticket\logic\ConversationLogic;
|
||||
use app\ticket\logic\TicketLogic;
|
||||
use app\ticket\model\Conversation;
|
||||
use config\constants\Constants;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class ConversationService
|
||||
{
|
||||
public function list($params)
|
||||
{
|
||||
$locale = locale();
|
||||
// $locale = 'zh';
|
||||
$ticket_status = $locale == 'zh'? Constants::TICKET_STATUS_ZH:Constants::TICKET_STATUS_EN;
|
||||
// $ticket_status = Constants::TICKET_STATUS_ZH;
|
||||
// $params['locale'] = locale();
|
||||
$result = (new ConversationLogic())->list($params);
|
||||
|
||||
$status_fanyi = array_map(fn($v) => "{{{$v}}}", array_flip(Constants::TICKET_STATUS));
|
||||
$ossservice = new OssService();
|
||||
foreach ($result as $key => $value) {
|
||||
$value=$value->toArray();
|
||||
$value['content'] = str_replace($status_fanyi,$ticket_status,$value['content']);
|
||||
$value['attachment'] = empty($value['attachment'])?[]:unserialize($value['attachment']);
|
||||
foreach ($value['attachment'] as $k => $attachment) {
|
||||
$value['attachment'][$k]['storage_path_full'] = (!empty($attachment))?$ossservice->generatePrivateUrl($attachment['storage_path']):'';
|
||||
}
|
||||
$user = User::where('id', $value['user_id'])->first();
|
||||
$value['user_name'] = $user?->name;
|
||||
$value['user_avatar'] = $user?->avatar;
|
||||
$value['created_at'] = date('Y-m-d H:i:s', strtotime($value['created_at']));
|
||||
$value['updated_at'] = date('Y-m-d H:i:s', strtotime($value['updated_at']));
|
||||
$result[$key] = $value;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function add(array $data)
|
||||
{
|
||||
try {
|
||||
$data['attachment'] = serialize($data['attachment']);
|
||||
if (empty($data['content'])) {
|
||||
throw new BusinessException('消息内容不能为空');
|
||||
}
|
||||
|
||||
$conversation = (new ConversationLogic())->firstByTicket($data['ticket_id']);
|
||||
$ticket = (new TicketLogic())->find($data['ticket_id']);
|
||||
$categorie= (new CategorieLogic())->find($ticket['categorie_id']);
|
||||
$categorieName = isset($categorie['translation']) ? $categorie['translation']['name'] : '';
|
||||
|
||||
$userDefault = [1, 75, 78];
|
||||
$tiket_content = $ticket['content'];
|
||||
if (empty($conversation)) { //没有沟通记录
|
||||
$title = '新工单提醒-'.$categorieName;
|
||||
$notice_user_id = $userDefault;
|
||||
}else{
|
||||
$title = '工单回复';
|
||||
$tiket = (new TicketLogic())->find($conversation['ticket_id']);
|
||||
if($data['user_id'] != $tiket['user_id']){
|
||||
$notice_user_id = [$tiket['user_id']];
|
||||
}else{
|
||||
$conversationLast = Conversation::where('ticket_id', '=', $conversation['ticket_id'])
|
||||
->where('user_id', '!=', $data['user_id'])
|
||||
->orderBy('id', 'desc')
|
||||
->first();
|
||||
|
||||
$notice_user_id = (!empty($conversationLast['user_id']))? [$conversationLast['user_id']]:$userDefault;
|
||||
}
|
||||
$tiket_content = $tiket['content'];
|
||||
|
||||
$status_fanyi = array_map(fn($v) => "{{{$v}}}", array_flip(Constants::TICKET_STATUS));
|
||||
$locale = locale();
|
||||
$ticket_status = $locale == 'zh'? Constants::TICKET_STATUS_ZH:Constants::TICKET_STATUS_EN;
|
||||
$content = str_replace($status_fanyi,$ticket_status,$data['content']);
|
||||
|
||||
$reply = $content?($content."\n".'工单内容:'):'' ;
|
||||
}
|
||||
|
||||
$notice = ['sender_id' => 0, //发送人ID 0默认系统
|
||||
'sender_type' => 'system', //发送者类型 user admin system
|
||||
'title' => $title, //标题
|
||||
'content' => ($reply??'') . $tiket_content, //内容
|
||||
'scene' => 1, //场景 0系统公共 1系统通知
|
||||
'recipient' => $notice_user_id, //接收人 空为全部
|
||||
'push_method' => 0 //推送方式0系统推送1手动推送
|
||||
];
|
||||
|
||||
// 异步推送
|
||||
\Webman\RedisQueue\Redis::send('notice', $notice);
|
||||
|
||||
unset($data['categorie_id']);
|
||||
unset($data['code']);
|
||||
|
||||
return (new ConversationLogic())->add($data);
|
||||
} catch (\Throwable $e) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function sendEmail(array $data)
|
||||
{
|
||||
$conversation = (new ConversationLogic())->firstByTicket($data['ticket_id']);
|
||||
$ticket = (new TicketLogic())->find($data['ticket_id']);
|
||||
$categorie= (new CategorieLogic())->find($ticket['categorie_id']);
|
||||
$categorieName = isset($categorie['translation']) ? $categorie['translation']['name'] : '';
|
||||
$notice = [
|
||||
'code' => $ticket['code'],
|
||||
'category' => $categorieName,
|
||||
'content' => $ticket['content'],
|
||||
'reply' => '',
|
||||
];
|
||||
//$emailDefault = 'app@hnxinyouhe.com'; //公共邮箱
|
||||
//$emailDefault = 'support@hnxinyouhe.com'; //公共邮箱
|
||||
$emailDefault = env('ticket_email_default');
|
||||
if (empty($conversation)) {
|
||||
$email = $emailDefault;
|
||||
}else{
|
||||
$tiket = (new TicketLogic())->find($conversation['ticket_id']);
|
||||
|
||||
if($conversation['user_id'] != $tiket['user_id']){
|
||||
$email = User::where('id',$tiket['user_id'])->value('email');
|
||||
}else{
|
||||
$conversationLast = Conversation::where('ticket_id', '=', $conversation['ticket_id'])
|
||||
->where('user_id', '!=', $conversation['user_id'])
|
||||
->orderBy('id', 'desc')
|
||||
->first();
|
||||
$email = (!empty($conversationLast['user_id']))?User::where('id',$conversationLast['user_id'])->value('email',$emailDefault):$emailDefault;
|
||||
}
|
||||
|
||||
$notice['content'] = $tiket['content'];
|
||||
// $notice['reply'] = '<li>最新回复:' . $conversation['content'] . '</li>';
|
||||
$notice['reply'] = '<li>最新回复:' . '卡罗拉、极石01、比亚迪唐,宋Plus、丰田荣放、捷途T2、极氪7x、(阿联酋, 亚美尼亚, 阿塞拜疆, 白俄罗斯, 哥斯达黎加, 埃塞俄比亚, 格鲁吉亚, 加纳, 吉尔吉斯斯坦, 蒙古, 巴拉圭, 沙特阿拉伯, 塔吉克斯坦, 土库曼斯坦, 乌兹别克斯坦,委内瑞拉)起亚亦跑(阿尔及利亚),基本上每个车都推中亚中东南美非洲' . '</li>';
|
||||
}
|
||||
|
||||
\app\common\utils\email\MailSend::send($email, '【XYH】新的工单提醒', replaceTpl($notice, 'work_order'));
|
||||
return $email;
|
||||
}
|
||||
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$data['attachment'] = serialize($data['attachment']);
|
||||
$result = (new ConversationLogic())->edit($data);
|
||||
Db::commit();
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\ticket\service;
|
||||
|
||||
use app\common\model\User;
|
||||
use app\ticket\logic\AttachmentLogic;
|
||||
use app\ticket\logic\ConversationLogic;
|
||||
use app\ticket\logic\TicketLogic;
|
||||
use app\ticket\model\Ticket;
|
||||
use config\constants\Constants;
|
||||
use support\Db;
|
||||
use support\exception\BusinessException;
|
||||
use support\Log;
|
||||
|
||||
class TicketService
|
||||
{
|
||||
|
||||
public function list($params)
|
||||
{
|
||||
$res = (new TicketLogic())->list($params);
|
||||
foreach ($res as $k => &$v) {
|
||||
$name = isset($v['categorie']['translation']) ? $v['categorie']['translation']['name'] : '';
|
||||
if(isset($res[$k]['categorie'])){
|
||||
$res[$k]['categorie']['name'] = $name;
|
||||
}
|
||||
if (isset($v['categorie']['translation'])){
|
||||
unset($res[$k]['categorie']['translation']);
|
||||
}
|
||||
foreach ($v['attachments'] as &$attachments) {
|
||||
$attachments['storage_path_full'] = (new \app\common\service\OssService())->generatePrivateUrl($attachments['storage_path']);
|
||||
}
|
||||
|
||||
$user = User::where('id', $v['user_id'])->first();
|
||||
$res[$k]['user_name'] = $user?->name;
|
||||
$res[$k]['user_avatar'] = $user?->avatar;
|
||||
$res[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
|
||||
$res[$k]['updated_at'] = date('Y-m-d H:i:s', $v['updated_at']);
|
||||
}
|
||||
unset($v);
|
||||
unset($attachments);
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
public function add(array $data)
|
||||
{
|
||||
try {
|
||||
$attachment = $data['attachment']??[];
|
||||
$logic = new TicketLogic();
|
||||
$data['code'] = $logic::generateSimpleTicketNo();
|
||||
$result = $logic->add($data);
|
||||
if(!empty($attachment)){
|
||||
(new AttachmentLogic())->adds($attachment, $result->id, $data['user_id']);
|
||||
}
|
||||
|
||||
$cleanContent = trim(preg_replace('/\s+/', ' ', strip_tags($data['content'] ?? '')));
|
||||
$conversation = [
|
||||
'ticket_id' => $result->id,
|
||||
'categorie_id' => $data['categorie_id'],
|
||||
'code' => $data['code'],
|
||||
'content' => $cleanContent,
|
||||
'user_id' => $data['user_id'],
|
||||
'attachment' => $data['attachment'],
|
||||
];
|
||||
(new ConversationService())->add($conversation);
|
||||
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(array $data)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$logic = new TicketLogic();
|
||||
$result = $logic->find($data['id']);
|
||||
|
||||
if(empty($result)){
|
||||
throw new BusinessException('工单不存在');
|
||||
}
|
||||
if($result['user_id'] != $data['user_id']){
|
||||
throw new BusinessException('只能编辑自己的工单');
|
||||
}
|
||||
if($result['status'] != 1){
|
||||
throw new BusinessException('只能修改待受理工单');
|
||||
}
|
||||
|
||||
$attachment = $data['attachment']??[];
|
||||
$result = $logic->edit($data);
|
||||
|
||||
if(!empty($attachment)){
|
||||
(new AttachmentLogic())->edit($attachment, $result->id, $data['user_id']);
|
||||
}
|
||||
Db::commit();
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function status(array $data)
|
||||
{
|
||||
try {
|
||||
Db::beginTransaction();
|
||||
$msg = $data['msg']??[];
|
||||
$ticket = (new TicketLogic())->find($data['id']);
|
||||
if(empty($ticket)){
|
||||
throw new BusinessException('工单不存在');
|
||||
}
|
||||
if($data['status'] <= $ticket->status){
|
||||
throw new BusinessException(trans('status_not_modified'));
|
||||
}
|
||||
|
||||
// if(!in_array($ticket->status, [Constants::TICKET_STATUS['PENDING'], Constants::TICKET_STATUS['CONFIRM']])
|
||||
// && empty($msg)){
|
||||
// throw new BusinessException('提交失败');
|
||||
// }
|
||||
|
||||
$ticket->status = $data['status'];
|
||||
$result = $ticket->save();
|
||||
|
||||
if(!empty($msg)){
|
||||
$conversation = [
|
||||
'ticket_id' => $ticket->id,
|
||||
'user_id' => $data['user_id'],
|
||||
'content' => '状态更新为{{'.array_search($data['status'],Constants::TICKET_STATUS).'}}:'.$msg
|
||||
];
|
||||
$res = (new ConversationLogic())->add($conversation);
|
||||
}
|
||||
|
||||
Db::commit();
|
||||
return $result;
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function getStatus(array $data)
|
||||
{
|
||||
$locale = locale();
|
||||
$ticket_status = $locale == 'zh'? Constants::TICKET_STATUS_ZH:Constants::TICKET_STATUS_EN;
|
||||
|
||||
$status = [];
|
||||
foreach ($ticket_status as $key => $value) {
|
||||
$status[] = ['value' => $key, 'text' => $value];
|
||||
}
|
||||
|
||||
if (empty($data['id'])) {
|
||||
return $status;
|
||||
}
|
||||
|
||||
$res = (new TicketLogic())->find($data['id']);
|
||||
if(!empty($res) && $res->user_id == $data['user_id']){
|
||||
$status = [
|
||||
['value' => Constants::TICKET_STATUS['PENDING'], 'text' => $ticket_status[Constants::TICKET_STATUS['PENDING']]],
|
||||
['value' => Constants::TICKET_STATUS['REJECTED'], 'text' => $ticket_status[Constants::TICKET_STATUS['REJECTED']]],
|
||||
];
|
||||
}
|
||||
|
||||
return $status;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user