From f04153a5b3a53445b53b7bc8b9fd9751454cb689 Mon Sep 17 00:00:00 2001 From: "WIN-C27C5MSVTPO\\16961" <1696136552@qq.com> Date: Mon, 12 Jan 2026 15:32:16 +0800 Subject: [PATCH] 1 --- app/command/CrmRotateUserCommand.php | 105 ---- app/command/CustomerCodeCommand.php | 62 -- app/command/CustomerCreatedAtCommand.php | 69 --- app/command/DomainCommand.php | 79 --- app/command/EmailDetailCommand.php | 206 ------- app/command/EmailParseCommand.php | 144 ----- app/command/EmailUidCommand.php | 185 ------ app/command/FinanceRecoCommand.php | 32 - app/command/FixInquiryLogOrderNo.php | 103 ---- app/command/ImportCustomerCommand.php | 178 ------ app/command/InitUserPasswordCommand.php | 34 -- app/command/TbCommand.php | 36 -- ...UpdateInquiryLogFromCrmCustomerCommand.php | 144 ----- app/command/VehMoneyCommand.php | 29 - app/common/controller/UsedCarController.php | 2 +- app/common/utils/pdf/template/usedCar.stub | 10 +- app/crmAdmin/controller/BaseController.php | 51 -- .../controller/CustomerController.php | 270 --------- .../controller/StatisticsController.php | 187 ------ app/crmAdmin/logic/CustomerLogic.php | 34 -- app/crmAdmin/service/CustomerService.php | 557 ------------------ app/mobile/controller/InvItemController.php | 55 -- .../controller/InvRequisitionController.php | 55 -- .../InvRequisitionItemReturnController.php | 56 -- .../controller/AttachmentController.php | 11 - app/ticket/controller/BaseController.php | 51 -- app/ticket/controller/CategorieController.php | 64 -- .../controller/ConversationController.php | 64 -- app/ticket/controller/TicketController.php | 88 --- app/ticket/logic/AttachmentLogic.php | 82 --- app/ticket/logic/CategorieLogic.php | 74 --- app/ticket/logic/ConversationLogic.php | 60 -- app/ticket/logic/TicketLogic.php | 77 --- app/ticket/model/Attachment.php | 66 --- app/ticket/model/Categorie.php | 54 -- app/ticket/model/CategorieTranslation.php | 35 -- app/ticket/model/Conversation.php | 30 - app/ticket/model/Ticket.php | 95 --- app/ticket/service/CategorieService.php | 105 ---- app/ticket/service/ConversationService.php | 160 ----- app/ticket/service/TicketService.php | 167 ------ 41 files changed, 6 insertions(+), 3960 deletions(-) delete mode 100644 app/command/CrmRotateUserCommand.php delete mode 100644 app/command/CustomerCodeCommand.php delete mode 100644 app/command/CustomerCreatedAtCommand.php delete mode 100644 app/command/DomainCommand.php delete mode 100644 app/command/EmailDetailCommand.php delete mode 100644 app/command/EmailParseCommand.php delete mode 100644 app/command/EmailUidCommand.php delete mode 100644 app/command/FinanceRecoCommand.php delete mode 100644 app/command/FixInquiryLogOrderNo.php delete mode 100644 app/command/ImportCustomerCommand.php delete mode 100644 app/command/InitUserPasswordCommand.php delete mode 100644 app/command/TbCommand.php delete mode 100644 app/command/UpdateInquiryLogFromCrmCustomerCommand.php delete mode 100644 app/command/VehMoneyCommand.php delete mode 100644 app/crmAdmin/controller/BaseController.php delete mode 100644 app/crmAdmin/controller/CustomerController.php delete mode 100644 app/crmAdmin/controller/StatisticsController.php delete mode 100644 app/crmAdmin/logic/CustomerLogic.php delete mode 100644 app/crmAdmin/service/CustomerService.php delete mode 100644 app/mobile/controller/InvItemController.php delete mode 100644 app/mobile/controller/InvRequisitionController.php delete mode 100644 app/mobile/controller/InvRequisitionItemReturnController.php delete mode 100644 app/ticket/controller/AttachmentController.php delete mode 100644 app/ticket/controller/BaseController.php delete mode 100644 app/ticket/controller/CategorieController.php delete mode 100644 app/ticket/controller/ConversationController.php delete mode 100644 app/ticket/controller/TicketController.php delete mode 100644 app/ticket/logic/AttachmentLogic.php delete mode 100644 app/ticket/logic/CategorieLogic.php delete mode 100644 app/ticket/logic/ConversationLogic.php delete mode 100644 app/ticket/logic/TicketLogic.php delete mode 100644 app/ticket/model/Attachment.php delete mode 100644 app/ticket/model/Categorie.php delete mode 100644 app/ticket/model/CategorieTranslation.php delete mode 100644 app/ticket/model/Conversation.php delete mode 100644 app/ticket/model/Ticket.php delete mode 100644 app/ticket/service/CategorieService.php delete mode 100644 app/ticket/service/ConversationService.php delete mode 100644 app/ticket/service/TicketService.php diff --git a/app/command/CrmRotateUserCommand.php b/app/command/CrmRotateUserCommand.php deleted file mode 100644 index 5defb24..0000000 --- a/app/command/CrmRotateUserCommand.php +++ /dev/null @@ -1,105 +0,0 @@ -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('开始执行 crm:rotate-user'); - - 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('未找到满足条件的用户(status=2 且 corp_id=3)。无需处理。'); - return self::SUCCESS; - } - - $output->writeln('匹配到用户数:' . count($userIds) .' '. implode(',',$userNames) . ''); - - // 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('未找到相关的 crm_customer 记录。'); - return self::SUCCESS; - } - - $output->writeln('需要处理的 crm_customer 数量:' . count($customers) . ''); - - // 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('已处理:' . $assignCount . ''); - } - } - - $output->writeln('处理完成,共更新 crm_customer:' . $assignCount . ' 条'); - }); - - return self::SUCCESS; - } catch (\Throwable $e) { - $output->writeln('执行失败:' . $e->getMessage() . ''); - return self::FAILURE; - } - } -} - diff --git a/app/command/CustomerCodeCommand.php b/app/command/CustomerCodeCommand.php deleted file mode 100644 index a82ec0f..0000000 --- a/app/command/CustomerCodeCommand.php +++ /dev/null @@ -1,62 +0,0 @@ -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('全部处理完成!'); - return self::SUCCESS; - } -} \ No newline at end of file diff --git a/app/command/CustomerCreatedAtCommand.php b/app/command/CustomerCreatedAtCommand.php deleted file mode 100644 index 57a4020..0000000 --- a/app/command/CustomerCreatedAtCommand.php +++ /dev/null @@ -1,69 +0,0 @@ -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('开始更新 crm_customer 的 created_at 字段...'); - - try { - // 使用事务确保数据一致性 - DB::transaction(function () use ($output) { - // 查询所有 sn 字段不为空的客户记录 - $customers = Db::table('crm_customer') - ->where('sn', '<>', '') - ->whereNotNull('sn') - ->get(['id', 'sn']); - $output->writeln(''.count($customers).''); - - $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("已更新客户 ID {$customer->id} 的 created_at 为: {$created_at}"); - } - } - - $output->writeln("更新完成,总共更新了 {$updatedCount} 条记录。"); - }); - - return self::SUCCESS; - } catch (\Exception $e) { - $output->writeln('执行过程中发生错误: ' . $e->getMessage() . ''); - return self::FAILURE; - } - } -} \ No newline at end of file diff --git a/app/command/DomainCommand.php b/app/command/DomainCommand.php deleted file mode 100644 index 7d09da5..0000000 --- a/app/command/DomainCommand.php +++ /dev/null @@ -1,79 +0,0 @@ -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; -} \ No newline at end of file diff --git a/app/command/EmailDetailCommand.php b/app/command/EmailDetailCommand.php deleted file mode 100644 index 78e5720..0000000 --- a/app/command/EmailDetailCommand.php +++ /dev/null @@ -1,206 +0,0 @@ -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("IMAP 连接失败:". imap_last_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("所有 UID 均已处理完毕。"); - 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("UID={$uid} overview 失败:{$err}"); - $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("UID={$uid} 写入 emails 成功"); - } catch (\Throwable $e) { - $output->writeln("UID={$uid} 写入失败:{$e->getMessage()}"); - $this->logError("UID={$uid} 写入失败:{$e->getMessage()}"); - continue; - } - - // 4. 标记已处理 - try { - Db::table('email_uids') - ->where('uid', $uid) - ->update([ - 'status' => 1, - 'processed_at' => $now, - ]); - $output->writeln("UID={$uid} 标记为已处理"); - } catch (\Throwable $e) { - $output->writeln("UID={$uid} 标记状态失败:{$e->getMessage()}"); - $this->logError("UID={$uid} 标记状态失败:{$e->getMessage()}"); - // 即使更新 status 失败,也继续下一条 - } - } catch (\Throwable $e) { - // 捕获任何非预期错误 - $output->writeln("UID={$uid} 处理异常:{$e->getMessage()}"); - $this->logError("UID={$uid} 处理异常:{$e->getMessage()}"); - continue; - } - } - - // 批次结束后稍作休眠,防止服务器过载 - sleep(1); - } - - imap_close($inbox); - $output->writeln("\n✅ 全部邮件处理完成。"); - 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; - } - } -} \ No newline at end of file diff --git a/app/command/EmailParseCommand.php b/app/command/EmailParseCommand.php deleted file mode 100644 index 3bf21f7..0000000 --- a/app/command/EmailParseCommand.php +++ /dev/null @@ -1,144 +0,0 @@ -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,找不到

Preview

则返回 null, - * 否则提取所有 Key: Value 为小写蛇形 key=>value 数组 - */ - protected function parseHtml(string $html): ?array - { - $doc = new \DOMDocument(); - libxml_use_internal_errors(true); - $doc->loadHTML('' . $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; - } -} \ No newline at end of file diff --git a/app/command/EmailUidCommand.php b/app/command/EmailUidCommand.php deleted file mode 100644 index bf0e744..0000000 --- a/app/command/EmailUidCommand.php +++ /dev/null @@ -1,185 +0,0 @@ -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("第 {$attempt} 次失败:{$error}"); - - // 若出现 too many login failures 立即暂停一段时间 - if (stripos($error, 'Too many login failures') !== false) { - $output->writeln("检测到登录失败次数过多,暂停 60 秒避免封禁"); - sleep(60); - } else { - sleep($retryDelay); - } - } - - if (!$inbox) { - $output->writeln("最终仍然连接失败:" . imap_last_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("{$e->getMessage()}"); - } - } - - 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) - -*/ \ No newline at end of file diff --git a/app/command/FinanceRecoCommand.php b/app/command/FinanceRecoCommand.php deleted file mode 100644 index 1406ab9..0000000 --- a/app/command/FinanceRecoCommand.php +++ /dev/null @@ -1,32 +0,0 @@ -generatePrivateUrl('fdesk_test/20251104/20251104_财务.xlsx');; - - $service = new \app\common\service\FinanceReconDubaiFilesService(); - $result = $service->dImport('fdesk_test/20251104/20251104_迪拜.xlsx'); - - return self::SUCCESS; - } -} \ No newline at end of file diff --git a/app/command/FixInquiryLogOrderNo.php b/app/command/FixInquiryLogOrderNo.php deleted file mode 100644 index 91d3c04..0000000 --- a/app/command/FixInquiryLogOrderNo.php +++ /dev/null @@ -1,103 +0,0 @@ -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; - } - } -} \ No newline at end of file diff --git a/app/command/ImportCustomerCommand.php b/app/command/ImportCustomerCommand.php deleted file mode 100644 index 61551ac..0000000 --- a/app/command/ImportCustomerCommand.php +++ /dev/null @@ -1,178 +0,0 @@ -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("文件不存在: {$filePath}"); - 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("读取第{$row}行单元格时出错: " . $cellError->getMessage() . ""); - 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("{$errorMsg}"); - } - } - - $output->writeln("\n导入完成!"); - $output->writeln("成功导入: {$successCount} 条记录"); - $output->writeln("失败: {$errorCount} 条记录"); - - if (!empty($errors)) { - $output->writeln("\n错误详情:"); - foreach ($errors as $error) { - $output->writeln("{$error}"); - } - } - - return self::SUCCESS; - - } catch (\Exception $e) { - $output->writeln("导入过程中发生错误: " . $e->getMessage() . ""); - $output->writeln("文件: " . $e->getFile() . " 行: " . $e->getLine() . ""); - $output->writeln("堆栈: " . $e->getTraceAsString() . ""); - return self::FAILURE; - } - } -} \ No newline at end of file diff --git a/app/command/InitUserPasswordCommand.php b/app/command/InitUserPasswordCommand.php deleted file mode 100644 index bdf76b5..0000000 --- a/app/command/InitUserPasswordCommand.php +++ /dev/null @@ -1,34 +0,0 @@ -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("用户ID {$user->id} 的sn字段为空,无法初始化密码"); - } - } - - $output->writeln("共初始化 {$count} 个用户密码"); - return self::SUCCESS; - } -} \ No newline at end of file diff --git a/app/command/TbCommand.php b/app/command/TbCommand.php deleted file mode 100644 index 265d24c..0000000 --- a/app/command/TbCommand.php +++ /dev/null @@ -1,36 +0,0 @@ -all(); - - // foreach ($list as $item) { - // // UserSn::where('user_sn', $item->sn)->update(['user_id' => $item->id]); - // } - - $m = new Emails(); - $m->fenpai(); - - return self::SUCCESS; - } -} \ No newline at end of file diff --git a/app/command/UpdateInquiryLogFromCrmCustomerCommand.php b/app/command/UpdateInquiryLogFromCrmCustomerCommand.php deleted file mode 100644 index 06afbc0..0000000 --- a/app/command/UpdateInquiryLogFromCrmCustomerCommand.php +++ /dev/null @@ -1,144 +0,0 @@ -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('DRY RUN 模式 - 不会实际执行更新操作'); - } - - $output->writeln('开始更新 inquiry_log 表...'); - $output->writeln("处理限制: {$limit} 条记录"); - - 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("找到 " . count($customers) . " 条客户记录需要处理"); - - $updatedCount = 0; - $skippedCount = 0; - $defaultTimestamp = strtotime('2025-08-26 00:00:00'); - - $output->writeln("找到 " . count($customers) . " 条客户记录需要处理"); - $step = []; - $updateId = []; - foreach ($customers as $customer) { - $output->writeln("处理客户 ID: {$customer->id}, SN: {$customer->sn}, User ID: {$customer->user_id}, obtain: {$customer->obtain}, created_at: {$customer->created_at}"); - // 查找匹配的 inquiry_log 记录 - $inquiryLog = Db::table('inquiry_log') - ->where('order_no', $customer->sn) - ->first(['id', 'recipient', 't_time']); - - if (!$inquiryLog) { - $step[] = $customer->id; - $output->writeln("跳过客户 ID {$customer->id} (sn: {$customer->sn}) - 未找到对应的 inquiry_log 记录"); - $skippedCount++; - continue; - } - $output->writeln("$inquiryLog->id"); - - // 准备更新数据 - $updateData = []; - - // 更新 recipient 字段 (user_id) - if ($customer->user_id != $inquiryLog->recipient) { - $updateData['recipient'] = $customer->user_id; - $output->writeln("客户 ID {$customer->id}: recipient 将从 {$inquiryLog->recipient} 更新为 {$customer->user_id}"); - } - - 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("更新obtain $obtain"); - } - - // 更新 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("客户 ID {$customer->id}: t_time 将从 " . ($inquiryLog->t_time ? date('Y-m-d H:i:s', $inquiryLog->t_time) : 'NULL') . " 更新为 {$timeStr}"); - } - 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("已更新 inquiry_log ID {$inquiryLog->id}"); - } else { - $output->writeln("客户 ID {$customer->id} - 无需更新"); - } - } - - $output->writeln("处理完成!"); - $output->writeln("总记录数: " . count($customers) . ""); - $updateIdstr = implode(",", $updateId); - $output->writeln("更新记录数: {$updatedCount},更新id:$updateIdstr"); - $stepstr = implode(",", $step); - $output->writeln("跳过记录数: {$skippedCount},跳过id: {$stepstr}"); - - if ($isDryRun) { - $output->writeln("DRY RUN 模式 - 未实际执行任何更新操作"); - } - }); - - return self::SUCCESS; - } catch (\Exception $e) { - $output->writeln('执行过程中发生错误: ' . $e->getMessage() . ''); - $output->writeln('错误位置: ' . $e->getFile() . ':' . $e->getLine() . ''); - return self::FAILURE; - } - } -} \ No newline at end of file diff --git a/app/command/VehMoneyCommand.php b/app/command/VehMoneyCommand.php deleted file mode 100644 index 0485e09..0000000 --- a/app/command/VehMoneyCommand.php +++ /dev/null @@ -1,29 +0,0 @@ -header('host'); + $baseUrl = 'http://' . request()->header('host'); $url = $baseUrl . '/pdf/' . $raw['pdf_src']; return $this->success([ diff --git a/app/common/utils/pdf/template/usedCar.stub b/app/common/utils/pdf/template/usedCar.stub index c77f415..398986c 100644 --- a/app/common/utils/pdf/template/usedCar.stub +++ b/app/common/utils/pdf/template/usedCar.stub @@ -103,6 +103,11 @@ +

车况介绍

+
+ +
+

产品图

@@ -112,10 +117,5 @@
-

车况介绍

-
- -
- diff --git a/app/crmAdmin/controller/BaseController.php b/app/crmAdmin/controller/BaseController.php deleted file mode 100644 index 1c066b5..0000000 --- a/app/crmAdmin/controller/BaseController.php +++ /dev/null @@ -1,51 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/app/crmAdmin/controller/CustomerController.php b/app/crmAdmin/controller/CustomerController.php deleted file mode 100644 index 161c4f7..0000000 --- a/app/crmAdmin/controller/CustomerController.php +++ /dev/null @@ -1,270 +0,0 @@ -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()); - } - } - -} \ No newline at end of file diff --git a/app/crmAdmin/controller/StatisticsController.php b/app/crmAdmin/controller/StatisticsController.php deleted file mode 100644 index 2d1e47f..0000000 --- a/app/crmAdmin/controller/StatisticsController.php +++ /dev/null @@ -1,187 +0,0 @@ -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] ?? []; - } -} \ No newline at end of file diff --git a/app/crmAdmin/logic/CustomerLogic.php b/app/crmAdmin/logic/CustomerLogic.php deleted file mode 100644 index 5c4192a..0000000 --- a/app/crmAdmin/logic/CustomerLogic.php +++ /dev/null @@ -1,34 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/app/crmAdmin/service/CustomerService.php b/app/crmAdmin/service/CustomerService.php deleted file mode 100644 index ecd2a17..0000000 --- a/app/crmAdmin/service/CustomerService.php +++ /dev/null @@ -1,557 +0,0 @@ -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, - ]; - } -} \ No newline at end of file diff --git a/app/mobile/controller/InvItemController.php b/app/mobile/controller/InvItemController.php deleted file mode 100644 index 3606afa..0000000 --- a/app/mobile/controller/InvItemController.php +++ /dev/null @@ -1,55 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/app/mobile/controller/InvRequisitionController.php b/app/mobile/controller/InvRequisitionController.php deleted file mode 100644 index 21d369e..0000000 --- a/app/mobile/controller/InvRequisitionController.php +++ /dev/null @@ -1,55 +0,0 @@ -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; - // } -} \ No newline at end of file diff --git a/app/mobile/controller/InvRequisitionItemReturnController.php b/app/mobile/controller/InvRequisitionItemReturnController.php deleted file mode 100644 index 58df807..0000000 --- a/app/mobile/controller/InvRequisitionItemReturnController.php +++ /dev/null @@ -1,56 +0,0 @@ -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()); - } - } -} \ No newline at end of file diff --git a/app/ticket/controller/AttachmentController.php b/app/ticket/controller/AttachmentController.php deleted file mode 100644 index 94e1724..0000000 --- a/app/ticket/controller/AttachmentController.php +++ /dev/null @@ -1,11 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/app/ticket/controller/CategorieController.php b/app/ticket/controller/CategorieController.php deleted file mode 100644 index 84e8bd7..0000000 --- a/app/ticket/controller/CategorieController.php +++ /dev/null @@ -1,64 +0,0 @@ -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()); - } - } -} \ No newline at end of file diff --git a/app/ticket/controller/ConversationController.php b/app/ticket/controller/ConversationController.php deleted file mode 100644 index 6b90750..0000000 --- a/app/ticket/controller/ConversationController.php +++ /dev/null @@ -1,64 +0,0 @@ -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()); - } - } -} \ No newline at end of file diff --git a/app/ticket/controller/TicketController.php b/app/ticket/controller/TicketController.php deleted file mode 100644 index cb2290e..0000000 --- a/app/ticket/controller/TicketController.php +++ /dev/null @@ -1,88 +0,0 @@ -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()); - } - } - -} diff --git a/app/ticket/logic/AttachmentLogic.php b/app/ticket/logic/AttachmentLogic.php deleted file mode 100644 index b498f7e..0000000 --- a/app/ticket/logic/AttachmentLogic.php +++ /dev/null @@ -1,82 +0,0 @@ -$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 - } -} \ No newline at end of file diff --git a/app/ticket/logic/CategorieLogic.php b/app/ticket/logic/CategorieLogic.php deleted file mode 100644 index 7eefaed..0000000 --- a/app/ticket/logic/CategorieLogic.php +++ /dev/null @@ -1,74 +0,0 @@ -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); - } - } -} \ No newline at end of file diff --git a/app/ticket/logic/ConversationLogic.php b/app/ticket/logic/ConversationLogic.php deleted file mode 100644 index 53a5a18..0000000 --- a/app/ticket/logic/ConversationLogic.php +++ /dev/null @@ -1,60 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/app/ticket/logic/TicketLogic.php b/app/ticket/logic/TicketLogic.php deleted file mode 100644 index 540e7c5..0000000 --- a/app/ticket/logic/TicketLogic.php +++ /dev/null @@ -1,77 +0,0 @@ -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 - } -} \ No newline at end of file diff --git a/app/ticket/model/Attachment.php b/app/ticket/model/Attachment.php deleted file mode 100644 index f5fc843..0000000 --- a/app/ticket/model/Attachment.php +++ /dev/null @@ -1,66 +0,0 @@ -belongsTo(Ticket::class, 'ticket_id', 'id'); - } -} diff --git a/app/ticket/model/Categorie.php b/app/ticket/model/Categorie.php deleted file mode 100644 index 610c693..0000000 --- a/app/ticket/model/Categorie.php +++ /dev/null @@ -1,54 +0,0 @@ - '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'); - } -} \ No newline at end of file diff --git a/app/ticket/model/CategorieTranslation.php b/app/ticket/model/CategorieTranslation.php deleted file mode 100644 index 6660dea..0000000 --- a/app/ticket/model/CategorieTranslation.php +++ /dev/null @@ -1,35 +0,0 @@ - 'datetime:Y-m-d H:i:s', - 'created_at' => 'datetime:Y-m-d H:i:s', - ]; - protected $fillable = [ - 'categorie_id', - 'locale', - 'name', - 'description', - ]; -} \ No newline at end of file diff --git a/app/ticket/model/Conversation.php b/app/ticket/model/Conversation.php deleted file mode 100644 index 641ff35..0000000 --- a/app/ticket/model/Conversation.php +++ /dev/null @@ -1,30 +0,0 @@ -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'); - } -} diff --git a/app/ticket/service/CategorieService.php b/app/ticket/service/CategorieService.php deleted file mode 100644 index dedccd4..0000000 --- a/app/ticket/service/CategorieService.php +++ /dev/null @@ -1,105 +0,0 @@ -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; - } - } -} \ No newline at end of file diff --git a/app/ticket/service/ConversationService.php b/app/ticket/service/ConversationService.php deleted file mode 100644 index 972938e..0000000 --- a/app/ticket/service/ConversationService.php +++ /dev/null @@ -1,160 +0,0 @@ -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'] = '
  • 最新回复:' . $conversation['content'] . '
  • '; - $notice['reply'] = '
  • 最新回复:' . '卡罗拉、极石01、比亚迪唐,宋Plus、丰田荣放、捷途T2、极氪7x、(阿联酋, 亚美尼亚, 阿塞拜疆, 白俄罗斯, 哥斯达黎加, 埃塞俄比亚, 格鲁吉亚, 加纳, 吉尔吉斯斯坦, 蒙古, 巴拉圭, 沙特阿拉伯, 塔吉克斯坦, 土库曼斯坦, 乌兹别克斯坦,委内瑞拉)起亚亦跑(阿尔及利亚),基本上每个车都推中亚中东南美非洲' . '
  • '; - } - - \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; - } - } -} \ No newline at end of file diff --git a/app/ticket/service/TicketService.php b/app/ticket/service/TicketService.php deleted file mode 100644 index ce772df..0000000 --- a/app/ticket/service/TicketService.php +++ /dev/null @@ -1,167 +0,0 @@ -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; - } -}