Contract.php 14.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
<?php

namespace addons\antis\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *合同表
 */
class Contract Extends Model {

	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_contract';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//创建合同
	public static function createContract($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
        $product = [];
        if (isset($params['product']) && $params['product']) {
            $product = $params['product'];
            unset($params['product']);
            foreach ($product as $tkey => $t) {
                $parts=$t['parts']??[];
                $new=[];
                if($parts){
                    foreach ($parts as $v){
                        if(!isset($v['part_id'])){
                            continue;
                        }
                        $new[]=['part_id'=>$v['part_id'],'number'=>$v['number']];
                    }
                }
                $product[$tkey]['parts'] = json_encode($new);
            }
        }
        if (isset($params['ratio_id']) && $params['ratio_id'] == 0) {
            $params['ratios'] = '';
        }
        if (isset($params['ratios']) && $params['ratios']) {
            foreach ($params['ratios'] as $v) {
                if (empty($v['staff_id'])) {
                    throw new Exception('业绩归属人必须全部选择');
                }
            }
            $params['ratios'] = json_encode($params['ratios']);
        }


        //halt($params);
        $customer=Customer::where(['id'=>$params['customer_id']])->find();
        if(empty($customer)){
            throw new Exception('客户不存在');
        }
        $params['owner_staff_id'] = $customer->owner_staff_id;

        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }



        //以下可以删除
        $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];
        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
        //以上可以删除

        //走新地审批流程

        $xtuqllModel = new \app\admin\model\fastflow\bill\xtuqll;
        $xtuqllModel->save([
            'initiator_id'=>$params['create_staff_id'],//发起人
            'sxepcntz'=>$params['name'],//合同名称
            'jcupfjta'=>$params['num'],

        ]);

        $params['bill_id'] = $xtuqllModel->id;
		$Model = new self;

        $result = $Model->allowField(true)->save($params);

		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}

		$lastId     = $Model->id;
		$otherModel = new ContractOther();
		if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        $addRatios = [];

        if (isset($params['ratios']) && $params['ratios']) {
            $ratios=json_decode($params['ratios'],true);
            foreach ($ratios as $v) {
                $addRatios[] = [
                    'contract_id' => $lastId,
                    'ratio' => $v['ratio'],
                    'staff_id' => $v['staff_id'],
                    'ratio_money' => $params['money'] * ($v['ratio'] / 100)
                ];
            }
        }


        //业绩分成 默认自己全部
        if (empty($addRatios)) {
            $addRatios[] = [
                'contract_id' => $lastId,
                'ratio' => 100,
                'staff_id' => isset($params['owner_staff_id']) ? $params['owner_staff_id'] : $staff->id ,
                'ratio_money' => $params['money']
            ];
        }
        if ($addRatios) {
            $ratioModel = new ContractRatio();
            $ratioModel->insertAll($addRatios);
        }
        $addProduct = [];
        foreach ($product as $v) {
            if (isset($v['id'])){
                unset($v['id']);
            }
            $v['contract_id'] = $lastId;
            $addProduct[]     = $v;
        }
        if ($addProduct) {
            $productModel = new ContractProduct();
            $productModel->allowField(true)->saveAll($addProduct);
        }
        

		OperationLog::createLog(OperationLog::CONTRACT_TYPE, $lastId, '创建合同');
		


		return true;
	}


	//修改合同
	public static function updateContract($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
        $product = [];
        if (isset($params['product'])) {
            $product = $params['product'];
            unset($params['product']);
            foreach ($product as $tkey => $t) {
                $parts=$t['parts']??[];
                $new=[];
                if($parts){
                    foreach ($parts as $v){
                        if(!isset($v['part_id'])){
                            continue;
                        }
                        $new[]=['part_id'=>$v['part_id'],'number'=>$v['number']];
                    }
                }
                $product[$tkey]['parts'] = json_encode($new);
            }
        }


        if (isset($params['ratio_id']) && $params['ratio_id'] == 0) {
            $params['ratios'] = '';
        }
        if (isset($params['ratios']) && $params['ratios']) {
            foreach ($params['ratios'] as $v) {
                if (empty($v['staff_id'])) {
                    throw new Exception('业绩归属人必须全部选择');
                }
            }
            $params['ratios'] = json_encode($params['ratios']);
        }
        $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

		$Model                  = new self;
		$params['check_status'] = 1;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $Model->allowField(true)->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}

		$otherModel = new ContractOther();
		if ($otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)], ['id' => $params['id']]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        $addRatios = [];
        if (isset($params['ratios']) && $params['ratios']) {
            $ratios=json_decode($params['ratios'],true);
            foreach ($ratios as $v) {
                $addRatios[] = [
                    'contract_id' => $params['id'],
                    'ratio' => $v['ratio'],
                    'staff_id' => $v['staff_id'],
                    'ratio_money' => $params['money'] * ($v['ratio'] / 100)
                ];
            }
        }
        //业绩分成 默认自己全部
        $staff = Staff::info();
        if (empty($addRatios)) {
            $addRatios[] = [
                'contract_id' => $params['id'],
                'ratio' => 100,
                'staff_id' => isset($params['owner_staff_id']) ? $params['owner_staff_id'] : $staff->id,
                'ratio_money' => $params['money']
            ];
        }
        if ($addRatios) {
            $ratioModel = new ContractRatio();
            $ratioModel->where(['contract_id' => $params['id']])->delete();
            $ratioModel->insertAll($addRatios);
        }

        $addProduct = [];
		if($product){
            foreach ($product as $v) {
                if (isset($v['id'])){
                    unset($v['id']);
                }
                $v['contract_id'] = $params['id'];
                $addProduct[]     = $v;
            }
        }
        if ($addProduct) {
            $productModel = new ContractProduct();
            $productModel->where(['contract_id' => $params['id']])->delete();
            $productModel = new ContractProduct();
            $productModel->allowField(true)->saveAll($addProduct);
        }

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::CONTRACT_STATUS, $params['id']);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::CONTRACT_TYPE, $params['id'], $staff_id);
            }
        }

		return true;
	}


	//获取更新时间
	public function getUpdatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name');
	}

    //获取合同相关信息
    public function contractOther() {
        return $this->belongsTo(ContractOther::class,'id','id');
    }


	//客户
	public function customer() {
		return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,follow');
	}
    //项目
    public function business() {
        return $this->hasOne(Business::class, 'id', 'business_id')->field('id,name');
    }

	//联系人
	public function contacts() {
		return $this->hasOne(Contacts::class, 'id', 'contacts_id')->field('id,name');
	}


	//员工
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img,department_id,post');
	}


	//签约人
	public function orderStaff() {
		return $this->hasOne(Staff::class, 'id', 'order_staff_id')->field('id,name');
	}

    //产品
    public function product(){
        return $this->hasMany(ContractProduct::class,'contract_id','id')->with('product');
    }

	//回款统计
	public function receivables() {
		return $this->hasOne(Receivables::class, 'contract_id', 'id')->where(['check_status' => 2])->group('contract_id')->field('contract_id,sum(money) as repayment_money');
	}


    //导入
    public static function importContract($data) {
        $addContacts = [];
        $addOther     = [];
        $addratio = [];
        foreach ($data as $params) {
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }else{
                    if($params[$name] === ''){
                        $params[$name]=NULL;
                    }
                }
            }
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $params['check_status']   = 2;
            $other['id']           = $params['id'];
            $addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addContacts[]        = $params;
            $addratio[] = array(
                'contract_id'=>$params['id'],
                'ratio'=>100,
                'staff_id'=>isset($params['owner_staff_id'])?$params['owner_staff_id']:0,
                'ratio_money'=>isset($params['money'])?$params['money']:0,

            );
        }

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->insertAll($addContacts);

        $otherModel = new ContractOther();
        $otherModel->allowField(true)->insertAll($addOther);

        $modelRatio = new ContractRatio();
        $modelRatio->allowField(true)->insertAll($addratio);

        return true;
    }

    public static function getNum()
    {
        return 'C' . date('Ymd') . rand(10000,99999);
    }

    /**
     * 获取编号
     * @param int $type   编号类型
     * @return mixed
     */
    public static function getCodes($code,$type)
    {
        $set = \think\Db::name('kuerp_prefix')->where(((new \app\admin\controller\kuerp\Goods()))->setWhere(['type'=>$type]))->find();
        if(empty($set)){
            return '';
        }else{
            preg_match_all("/\d+/",$code,$num);
            $order_num = implode('',$num[0]);
            if($order_num<$set['start']){
                $order_num = $set['start'];
            }else{
                $order_num = (float)$order_num+1;
            }
            $prefix = $set['prefix'];
            if($set['year']==1){
                $prefix = $prefix.date('Y');
            }
            if($set['month']==1){
                $prefix = $prefix.date('m');
            }
            if($set['day']==1){
                $prefix = $prefix.date('d');
            }
            if($set['hour']==1){
                $prefix = $prefix.date('H');
            }
            if($set['minute']==1){
                $prefix = $prefix.date('i');
            }
            if($set['second']==1){
                $prefix = $prefix.date('s');
            }
            $s = '';
            if(strlen($order_num)<$set['strlen']){
                for ($a=1;$a<=$set['strlen']-(strlen($order_num));$a++){
                    $s .= '0';
                }
            }
            $code = $order_num;
            $order_num = $prefix.$s.$order_num;
        }
        if(!empty($set['dbname']) && !empty($set['field'])){
            $res = \think\Db::name($set['dbname'])->where([$set['field']=>$order_num])->value('id');
            if($res){
                return self::getCodes($code,$type);
            }
        }
        return $order_num;
    }
}