ProjectLogic.php 13.5 KB
<?php

namespace App\Http\Logic\Aside\Project;


use App\Enums\Common\Code;
use App\Helper\Arr;
use App\Helper\Common;
use App\Helper\FormGlobalsoApi;
use App\Http\Logic\Aside\BaseLogic;
use App\Http\Logic\Aside\Manage\ManageLogic;
use App\Models\ASide\APublicModel;
use App\Models\Blog\Blog;
use App\Models\Channel\Channel;
use App\Models\Channel\User;
use App\Models\Channel\Zone;
use App\Models\Devops\ServerConfig;
use App\Models\Inquiry\InquirySet;
use App\Models\Manage\Manage;
use App\Models\News\News;
use App\Models\Project\After;
use App\Models\Project\DeployBuild;
use App\Models\Project\DeployOptimize;
use App\Models\Project\Payment;
use App\Models\Project\Project;
use App\Models\Task\Task;
use App\Utils\EncryptUtils;
use Hashids\Hashids;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Class ProjectLogic
 * @package App\Http\Logic\Aside\Project
 * @author zbj
 * @date 2023/4/26
 */
class ProjectLogic extends BaseLogic
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Project();
    }

    public function getList(array $map = [], array $sort = ['id' => 'desc'], array $columns = ['*'], int $limit = 20)
    {

        parent::setWith(['payment', 'deploy_build', 'deploy_optimize','online_check']);
        $list =  parent::getList($map, $sort, ['id', 'title', 'channel','cooperate_date' ,'type', 'created_at'], $limit);
        $managerLogic = new ManageLogic();
        foreach ($list['list'] as &$item){
            $item = [
                'id' => $item['id'],
                'title' => $item['title'],
                'channel' => Channel::getChannelText($item['channel']['user_id'] ?? 0),
                'key' => $item['deploy_build']['keyword_num'] ?? 0,
                'day' => $item['deploy_build']['service_duration'] ?? 0,
                'amount' => $item['payment']['amount'] ?? 0,
                'build_leader' => $managerLogic->getCacheName($item['deploy_build']['leader_mid'] ?? 0), //组长
                'build_manager' => $managerLogic->getCacheName($item['deploy_build']['manager_mid'] ?? 0), //项目经理
                'build_designer' => $managerLogic->getCacheName($item['deploy_build']['designer_mid'] ?? 0), //设计师
                'build_tech' => $managerLogic->getCacheName($item['deploy_build']['tech_mid'] ?? 0), //技术助理
                'optimize_manager' => $managerLogic->getCacheName($item['deploy_optimize']['manager_mid'] ?? 0), //优化服务经理
                'optimize_optimist' => $managerLogic->getCacheName($item['deploy_optimize']['optimist_mid'] ?? 0), //优化师
                'optimize_assist' => $managerLogic->getCacheName($item['deploy_optimize']['assist_mid'] ?? 0), //优化助理
                'optimize_tech' => $managerLogic->getCacheName($item['deploy_optimize']['tech_mid'] ?? 0), //售后技术
                'type' => $item['type'],
                'test_domain' => $item['deploy_build']['test_domain'] ?? 0,
                'plan' =>Project::planMap()[$item['deploy_build']['plan']],
                'domain' => $item['deploy_optimize']['domain'] ?? 0,
                'created_at' => date('Y年m月d日', strtotime($item['created_at'])),
                'autologin_code' => $this->getAutoLoginCode($item['id']),
                'product_num' => APublicModel::getProductNumByProjectId($item['id']),
                'keyword_num' => $item['deploy_build']['keyword_num'] ?? 0,
                'article_num' => APublicModel::getBlogNumByProjectId($item['id']) + APublicModel::getNewsNumByProjectId($item['id']),
                'task_finish_num' => Task::getNumByProjectId($item['id'], Task::STATUS_DOWN),
                'task_pending_num' => Task::getNumByProjectId($item['id'], [Task::STATUS_DONGING, Task::STATUS_WAIT]),
                'optimist_status'=>$item['online_check']['optimist_status'] ?? 0,
                'qa_status'=>$item['online_check']['qa_status'] ?? 0,
                'service_day'=>$item['deploy_build']['service_duration'],
            ];
        }
        return $list;
    }

    /**
     * @remark :自动登录加密
     * @name   :getAutoLoginCode
     * @author :lyh
     * @method :post
     * @time   :2023/8/7 9:47
     */
    public function getAutoLoginCode($project_id){
        $encrypt = new EncryptUtils();
        return $encrypt->authcode(json_encode(['project_id' => $project_id]), 'ENCODE', 'autologin', 3600);
    }

    /**
     * @remark :获取当前数据详情
     * @name   :getProjectInfo
     * @author :lyh
     * @method :post
     * @time   :2023/7/28 17:11
     */
    public function getProjectInfo($id){
        $info = Common::get_user_cache($this->model->getTable(),$id);
        if(empty($info)){
            $info = $this->model->with('payment')->with('deploy_build')
                ->with('deploy_optimize')->with('online_check')
                ->with('project_after')->where(['id'=>$id])->first()->toArray();
            if(!empty($info['online_check']['created_manage_id'])){
                $info['online_check']['name'] = (new Manage())->read(['id'=>$info['online_check']['created_manage_id']])['name'] ?? '';
            }
            $info['deploy_optimize']['minor_keywords'] = json_decode($info['deploy_optimize']['minor_keywords']) ?? '';
            if($info['extend_type'] != 0){
                $info['type'] = $info['extend_type'];
            }
            Common::set_user_cache($info,$this->model->getTable(),$id);
        }
        return $this->success($info);
    }

    /**
     * @remark :保存项目配置数据
     * @name   :save
     * @author :lyh
     * @method :post
     * @time   :2023/8/17 14:19
     */
    public function save($param){
        DB::beginTransaction();
        try {
            if($param['type'] == 5){
                $param['extend_type'] == 5;
                unset($param['type']);
            }
            $res = parent::save($param);
            $param['id'] = $res['id'];
            Common::del_user_cache($this->model->getTable(),$param['id']);
            $this->savePayment($param);
            $this->saveDeployBuild($param);
            $this->saveDeployOptimize($param);
            $this->saveAfter($param);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            errorLog('项目保存失败', $param, $e);
            $this->fail('保存失败');
        }
        return $this->success();
    }

    /**
     * @remark :验证域名
     * @name   :verifyDomain
     * @author :lyh
     * @method :post
     * @time   :2023/8/17 16:22
     */
    public function verifyDomain($domain){
        if(!empty($domain)){
            $domain = checkDomain($domain);
            if(!$domain){
                $this->fail('正式域名格式不正确');
            }
            return $this->success();
        }
    }
    /**
     * 保存付款续费
     * @author zbj
     * @date 2023/4/26
     */
    protected function savePayment($param){
        if(empty($param['payment'])){
            return true;
        }
        $data = $param['payment'];
        $data['project_id'] = $param['id'];
        $data['id'] = Payment::where('project_id', $param['id'])->value('id');
//        Arr::forget($data, ['amount']);
        return (new PaymentLogic)->save($data);
    }

    /**
     * 保存建站部署
     * @author zbj
     * @date 2023/4/26
     */
    protected function saveDeployBuild($param){
        if(empty($param['deploy_build'])){
            return true;
        }
        $data = $param['deploy_build'];
        $data['project_id'] = $param['id'];
        $hashids = new Hashids('test_domain', 5, 'abcdefghjkmnpqrstuvwxyz1234567890');
        $code = $hashids->encode($data['project_id']);
        $data['test_domain'] = 'v6-' . $code . '.globalso.site';;
        $data['id'] = DeployBuild::where('project_id', $param['id'])->value('id');
        return (new DeployBuildLogic)->save($data);
    }

    /**
     * 保存优化部署
     * @author zbj
     * @date 2023/4/26
     */
    protected function saveDeployOptimize($param){
        if(empty($param['deploy_optimize'])){
            return true;
        }
        $data = $param['deploy_optimize'];
        $data['minor_keywords'] = json_encode($data['minor_keywords']) ?? '';
        $data['project_id'] = $param['id'];
        $data['id'] = DeployOptimize::where('project_id', $param['id'])->value('id');
        return (new DeployOptimizeLogic)->save($data);
    }
    /**
     * 保存优化部署
     * @author zbj
     * @date 2023/4/26
     */
    protected function saveAfter($param){
        if(empty($param['project_after'])){
            return true;
        }
        $data = $param['project_after'];
        $data['project_id'] = $param['id'];
        //查询数据是否存在
        $afterModel = new After();
        $info = $afterModel->read(['project_id'=>$data['project_id']]);
        if($info === false){
            $rs = $afterModel->add($data);
        }else{
            $rs = $afterModel->edit($data,['id'=>$info['id']]);
        }
        return $rs;
    }
    public function clearCache($id)
    {
        parent::clearCache($id);
        parent::setWith(['payment', 'deploy_build', 'deploy_optimize', 'online_check']);
        parent::clearCache($id);
    }

    /**
     * 保存询盘通知设置
     * @author zbj
     * @date 2023/5/17
     */
    public function saveInquirySet($param)
    {
        $project = $this->getCacheInfo($param['project_id']);
        //同步到接口
        $domain = parse_url($project['deploy_optimize']['domain'])['host'];
        $emails = Arr::arrToSet($param['emails']??'', 'trim');
        $phones = Arr::arrToSet($param['phones']??'', 'trim');
        $form_global_api  = new FormGlobalsoApi();
        $res = $form_global_api->setInquiry($domain, $emails, $phones);
        if (!$res) {
            $this->fail('保存失败');
        }
        if ($res['status'] != 200) {
            $this->fail($res['message'] ?? '保存失败');
        }
        //保存
        $set = InquirySet::where('project_id', $param['project_id'])->first();
        if (!$set) {
            $set = new InquirySet();
        }
        $set->project_id = $param['project_id'];
        $set->emails = $emails;
        $set->phones = $phones;
        $set->save();
        return $this->success();
    }

    public function dataSource(){
        $data = [];
        $data['level'] = $this->model::levelMap();
        $data['type'] = $this->model::typeMap();
        $data['special'] = $this->model::specialMap();
        $data['plan'] = $this->model::planMap();
        return $data;
    }


    public function channelSource($param){
        switch ($param['type']){
            case 1:
                return Zone::pluck('title', 'id')->toArray();
            case 2:
                return Channel::where('zone_id', $param['zone_id']??0)->pluck('alias', 'id')->toArray();
            case 3:
                return User::where('channel_id', $param['channel_id']??0)->pluck('name', 'id')->toArray();
        }
        return [];
    }


    /**
     * @remark :导入数据
     * @name   :sync
     * @author :lyh
     * @method :post
     * @time   :2023/8/9 15:04
     */
    public function sync($param){
        $title = date('Ymd') . '-' . $param['company_name'];
        $data = [
            'title' => $title,
            'api_no'=> $param['id'],
            'company' => $param['company_name'],
            'lead_name' => $param['principal_name'],
            'mobile' => $param['principal_mobile'],
            'qq' => $param['customer_qq'],
            'channel' => Channel::getProjectChannel($param['company_id'], $param['username_sales']),
            'requirement' => $param['remark'],
            'cooperate_date' => date('Y-m-d', $param['create_time']),
            'deploy_build' => [
                'service_duration' => $param['years'],
                'plan' => $this->versionData($param['plan_marketing']),
            ],
            'deploy_optimize' => [
                'api_no' => $param['id']
            ],
            'payment' => [
                'amount' => $param['plan_price'],
                'contract' => $param['files'],
                'bill' => $param['images'],
            ],
        ];
        DB::beginTransaction();
        try {
            $res = parent::save($data);
            $data['id'] = $res['id'];
            $this->setPostId($data['deploy_build']['plan'],$res['id']);
            $this->savePayment($data);
            $this->saveDeployBuild($data);
            $this->saveDeployOptimize($data);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            errorLog('项目同步失败', $data, $e);
            $this->fail('同步失败');
        }
    }

    /**
     * @remark :获取版本
     * @name   :versionData
     * @author :lyh
     * @method :post
     * @time   :2023/8/9 14:46
     */
    public function versionData($param){
        $data = Project::planMap();
        $data = array_flip($data);
        if(isset($data[$param])){
            return $data[$param];
        }else{
            return 1;
        }
    }

    /**
     * @remark :设置post_id
     * @name   :setPostId
     * @author :lyh
     * @method :post
     * @time   :2023/8/9 14:47
     */
    public function setPostId($plan,$id){
        $length = strlen((string)$id); // 获取变量的位数
        $paddingLength = 5 - $length; // 计算填充前面的 0 的位数
        $zeros = str_repeat("0", $paddingLength);
        $number = '6'.$plan.$zeros.$id;
        $projectModel = new Project();
        $projectModel->edit(['post_id'=>$number],['id'=>$id]);
        return true;
    }
}