Payment.php 21.8 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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
<?php

/**
 * v2 缴费模块
 */
namespace app\em\controller;
use app\admin\controller\Base;
use app\admin\model\DepartmentModel;
use app\admin\model\ElectricMeter;
use app\em\model\EmAccount;
use app\em\model\EmCert;
use app\em\model\EmCheckBill;
use app\em\model\EmInvoice;
use app\em\model\EmPayment;
use app\em\model\EmPaymentFk;
use app\em\model\EmPaymentInvoice;
use app\em\model\EmPaymentInvoiceBalance;
use app\em\model\EmPaymentReceipt;
use app\em\model\Staff;
use app\em\model\Station;
use app\em\validate\AddFkInfoDetailsValidate;
use app\em\validate\AddFkInfoValidate;
use app\em\validate\AddPaymentValidate;
use think\Db;
use think\Exception;
use think\facade\Request;

class Payment extends Base
{
    const PAYMENT_STATUS = [
        0 => '待审核',
        1 => '未提交',
        2 => '审核中',
        3 => '已付款',
        4 => '已付款 缺发票',
        5 => '已付款 发票已上传',
        7 => '被驳回',
        8 => '已确收',
        9 => '审核失败',
    ];

    const PAYMENT_STAUS_STYLE = [
        0 => 'layui-color-black',
        1 => 'layui-color-black',
        2 => 'layui-color-black',
        3 => 'layui-color-green',
        4 => 'layui-color-green',
        5 => 'layui-color-green',
        7 => 'layui-color-gray',
        8 => 'layui-color-blue',
        9 => 'layui-color-cyan',
    ];
    const PAYMENT_TYPE = [
        0 => '未知',
        1 => "读表",
        2 => "充值",
        3 => "读表",
        4 => "充值"
    ];

    const PAYMENT_STATUS_CHECK_NODE = 5;

    //缴费单列表
    public function index(){
        $search_text = Request::get('search_text');
        $search_type = Request::get('search_type');
        $payment_status = Request::get('payment_status');

        $map=[];

        //权限检测
        if(!$this->user['is_admin']) $map[]= check_data();

        if($search_text){
            switch ($search_type) {
                case '1':
                    if(strstr($search_text,',')){
                        $searchArr = explode(',',$search_text);
                        $map[]=['pay.payment_id','in',$searchArr];
                    } else {
                        $map[]=['pay.payment_id','=',"$search_text"];
                    }
                    break;
                case '2':
                    $map[]=['epi.invoice_id','like',"%$search_text%"];
                    break;
                case '3':
                    $map[]=['em.em_numb','like',"%$search_text%"];
                    break;
                case '4':
                    $map[]=['station.station_name','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
            }
        }
        $this->assign('search_type',$search_type ?: '');
        $this->assign('search_text',$search_text ?: '');

        //缴费状态
        if($payment_status !== '') $map[]=['pay.status','=',"$payment_status"];
        $this->assign('payment_status',$payment_status ?: '');

        //区域
        $area_id = Request::get('area_id');
        if($area_id) $map[] = ['station.area_id','=',$area_id];
        $this->assign('area_id',$area_id ?: '');

        //创建时间查询条件
        $dateStart = strtotime(Request::get('date_start'));
        $dateEnd = strtotime(Request::get('date_end'));
        //区间查询
        if( !empty($dateStart) && !empty($dateEnd) ){
            $map[] = ['pay.create_time','between',[$dateStart,$dateEnd]];
            $this->assign('date_start',Request::get('date_start'));
            $this->assign('date_end',Request::get('date_end'));
        } elseif (!empty($dateStart) && empty($dateEnd)){
            $map[] = ['pay.create_time','>',$dateStart];
            $this->assign('date_start',Request::get('date_start'));
            $this->assign('date_end','');
        } elseif (empty($dateStart) && !empty($dateEnd)){
            $map[] = ['pay.create_time','<',$dateEnd];
            $this->assign('date_end',Request::get('date_end'));
            $this->assign('date_start','');
        }else{
            $this->assign('date_start','');
            $this->assign('date_end','');
        }
        $page =Request::param('page')?Request::param('page'):1;
        $limit = Request::param('limit')?Request::param('limit'):10;
        $region=new ElectricMeter();
        $emPaymentModel = new EmPayment();
        $data = $emPaymentModel->getPaymentList($map,$page,$limit);

        $PaymentCount = (new EmPayment())->getPaymentCount($map);
        if(Request::param('page')){
            return ['code'=>0,'msg'=>'','count'=>$PaymentCount,'data'=>$data];
        }

        $this->assign('regions',getTree($region->regions()));
        return $this->fetch();
    }

    //批量生成缴费单
    public function createAll(){
        $ids = Request::param('ids');

        //首先查询这些账单是否具备生成条件
        $eiModel = new EmInvoice();
        $invs = $eiModel->where('payment_balance','neq',0)
                        ->where(['invoice_id'=>$ids])->order('invoice_id asc')->select();

        if($invs->isEmpty()) {
            $invIds = implode(',',$ids);
            return json(['status'=>0,'message'=>'账单号: '.$invIds.' 不能重复生成缴费单!']);
        }
        //过滤不可以生成缴费单的账单ID
        $idsArr = [];
        $amount = 0;
        foreach ($invs as $inv){
            //未生成缴费或已挂起
            $amount += $inv->payment_balance;
            //是否已挂起
            $epiModel = EmPaymentInvoice::field('payment_id')
                                            ->where('invoice_id','=',$inv->invoice_id)
                                            ->order('create_time desc')->find();
            if($epiModel){
                //找到关联的缴费单
                $payment = EmPayment::where('payment_id','=',$epiModel->payment_id)->find();

                if(!$payment) return json(['status'=>0,'单据:'.$epiModel->payment_id.'出现异常,单据与账单关系存在,但缴费单不存在!']);
                 //如果缴费单并未缴费
                if($payment->amount == 0){
                    $message = '账单号: '.$inv->invoice_id.' 已经挂起,无法生成缴费单';
                    return json(['status'=>0,'message'=>$message]);
                } else {
                    $idsArr[] = $inv->invoice_id;
                }
            } else {
                $idsArr[] = $inv->invoice_id;
            }

        }
        $ids = $idsArr;

        //如果没有生成过缴费单,则生成缴费单
        //1.创建缴费号
        $paymentId = $this->getPaymentId();
        //2.将缴费号与账单号写入关联表
        $paymentInvoiceArr = [];
        foreach ($ids as $inv_id){
            $paymentInvoiceArr [] = [
                'payment_id' => $paymentId,
                'invoice_id' => $inv_id
            ];
        }
        $model = new EmPaymentInvoice();
        if(!$model->saveAll($paymentInvoiceArr)){
            throw new Exception('保存账单与缴费关联数据失败');
        };


        //3.将账单数据汇总写入缴费表
        $pData  = [];
        $pData['payment_id'] = $paymentId;
        $pData['status'] = 1;
        $pData['account_id'] = '\\';  //占位符,表示空的无效的
        $pData['em_id'] = '\\';    //占位符,表示空的无效的
        $pData['payment_type'] = 1;
        $pData['balance'] = $pData['amount'] = round($amount,2);

        if((new EmPayment())->save($pData)){
            return json(['status'=>1,'message'=>'已创建缴费单']);
        } else {
            throw new Exception('创建缴费信息失败');
        }
    }

    //预付费表先缴费
    public function create(){
        $em_id = Request::param('em_id');
        if(!(new Em())->checkEmcomplete($em_id)){
            $this->error('电表信息不完整,需要补充基础信息','/em');
        }
        $payment  =  new EmPayment();
        $payment->payment_id = $this->getPaymentId();

        $account = (new EmAccount())->get(['em_id'=>$em_id]);
        $this->assign('account',$account);

        $this->assign('uid',$this->uid);
        $this->assign('staffs',(new Staff())->getStaffs($this->user['is_admin']));

        $this->assign('em_id',$em_id);
        $this->assign('payment',$payment);
        return $this->fetch();
    }

    //缴费单详情
    public function detail(){
        $payment_id = Request::param('payment_id');
        $epModel = new EmPayment();
        //查询缴费单基本信息
        $payment = $epModel->where('payment_id','=',$payment_id)->find();

        if($payment->status > 1 && $payment->status != 7){
            $fkModel = EmPaymentFk::get(['payment_id'=>$payment->payment_id]);
            $fkModel->link = config('oafk.base_url').config('oafk.link') . $fkModel->oafk_id;
        } else if ($payment->status == 7) {
            $fkModel = EmCheckBill::get(['mode_id'=>$payment->payment_id]);
            $fkModel->oafk_numb = '';
            $fkModel->link = '';
        } else {
            $fkModel = new EmPaymentFk();
            $fkModel->oafk_numb = '';
            $fkModel->link = '';
        }

        $payment->statusStyle =  self::PAYMENT_STAUS_STYLE[$payment->status];
        $this->assign('fk',$fkModel);

        $payment->statusTitle = self::PAYMENT_STATUS[$payment->status];

        $payment->checkNode = self::PAYMENT_STATUS_CHECK_NODE;
        $this->assign('payment',$payment);
        //查询账单信息
        $invs = $epModel->getinvsInfo($payment->payment_id);

        $amount = 0;
        foreach ($invs as $inv){
            if($inv->payment_balance == 0){
                $inv->paid_amount = $inv->payment_amount;
            } else {
                $inv->paid_amount = $inv->payment_amount - $inv->payment_balance;
            }
            $amount += $inv->payment_balance;
        }

        $payment->amount = $payment->amount ?: round($amount,2);
        $this->assign('invs',$invs);

        //实缴金额
        $amount = EmCert::where('payment_id','=',$payment_id)->sum('amount');
        if($payment->mark){
            if($payment->balance == 0){
                $amount = $payment->amount;
            } else {
                $amount = $payment->amount - $payment->balance;
            }
        }
        $this->assign('payment_sum_amount',$amount);
        //查询凭证信息
        $receipts = (new EmPaymentReceipt)->getPaymentReceiptByPaymentId($payment_id);
        if(!$receipts)  $receipts = [];
        foreach ($receipts as &$receipt){
            $receipt->file_src = trim($receipt->file_src,'.');
        }
        $this->assign('receipts',$receipts);

        $account = (new EmAccount())->get(['account_id'=>$payment->account_id]);
        $em = (new \app\em\model\Em())->field('em_type_id')->get(['id'=>$account->em_id]);

        if($em->em_type_id == 2 || $em->em_type_id == 4){
            $this->assign('em',$em);
            $this->assign('account',$account);
        }

        return $this->fetch();
    }

    //生成缴费单号
    private function getPaymentId(){
        $payment = EmPayment::field('id')->order('id desc,create_time desc')->find();
        if(!$payment) $id = 1;
        else $id = $payment->id + 1;
        return "JF".date('Ymd').zero($id);
    }

    //更新状态
    public function updateStatus($payment_id){
        //变更为已缴费
        $paymentModel = EmPayment::get(['payment_id'=>$payment_id]);
        $paymentModel->status = 1;
        $paymentModel->save();
    }

    /**
     * 保存缴费单
     * 1.保存缴费人信息
     * 2.保存缴费状态
     */
    public function store(){
        $data = Request::post();

        //如果是预付费缴费 充值卡
        $em =  (new \app\em\model\Em())->get($data['em_id']);
        $validate = new AddPaymentValidate();
        if(!$validate->scene('s2')->check($data))
            return json(['status'=>0,'message'=>$validate->getError()]);
        $paymentModel = new EmPayment;
        $paymentModel->payment_type = $em->em_type_id;
        $paymentModel->em_id = $data['em_id'];

        //更新账户
        $account = new Account();
        $accountId = $account->getAccountId($data['em_id']);

        $paymentModel->payment_id = $this->getPaymentId();
        $paymentModel->account_id = $accountId;
        $paymentModel->balance = $data['amount'];
        $paymentModel->staff_id = $data['staff_id'];
        $paymentModel->cid = $this->uid;
        $paymentModel->payment_type =  $em->em_type_id;
        $paymentModel->is_check = $em->em_type_id == 2 || $em->em_type_id == 4 ? 0 : 1;
        $paymentModel->status = 0;

        if($paymentModel->save($data))
            return json(['status'=>1,'message'=>'保存缴费信成功']);
        else
            return json(['status'=>0,'message'=>'保存缴费信息失败']);
    }

    /**
     * 预交费审核
     */
    public function checkPayment(){
        $payment_id = Request::param('payment_id');
        $payment =  EmPayment::get(['payment_id'=>$payment_id]);
        if($payment->is_check !== 0) return json(['status'=>0,'message'=>'单据已经审核过,不能再次审核']);

        //如果是驳回则记录驳回状态
        $checkType = Request::param('checkType');
        (new EmCheckBill)->check(Request::param('refuseInfo'),$this->uid,Request::controller(),$payment_id,$checkType);
        if($checkType == 2) {
            $payment->status = 7;   //7代表被驳回
            $payment->save();
            return json(['status'=>0,'message'=>'单据已经驳回']);
        }
        $payment->status = 1;
        $payment->is_check = 1;
        $payment->save();
        return json(['status'=>1,'message'=>'已审核']);

    }

    //审核通过开始销账
    public function confirm(){
        $payment_id = Request::param('payment_id');

        //判断是否具备审核条件
        $amount = EmCert::where('payment_id','=',$payment_id)->sum('amount');
        $paymentModel = EmPayment::get(['payment_id' => $payment_id]);

        //账单实缴金额保存到账单里面
        if($amount > 0 && $paymentModel->status == 3) {

            $paymentModel->pay_date = date('Y:m:d H:i:s',time());
            $paymentModel->amount = $paymentModel->balance = $amount;
            $paymentModel->save();
            //销账
            (new Account())->upAmount($paymentModel->account_id,$paymentModel->amount);

            $result =  (new Invoice())->writeOffFromPayment($paymentModel->account_id,$payment_id);
            return json(['status'=>1,'message'=>$result]);
        }
        return json(['status'=>0,'message'=>'不满足审核条件']);
    }

    /**
     * 显示缴费详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payDetail(){
        $invoice_id = Request::param('invoice_id');
        $eibs = EmPaymentInvoiceBalance::where('invoice_id','=',$invoice_id)
                                        ->order('payment_id asc')->select();
        $this->assign('data',$eibs);
        return $this->fetch();
    }

    public function payoa(){
        $payment_id  = Request::param('payment_id');
        $payment = EmPayment::get(['payment_id'=>$payment_id]);
        //获取当前登录人信息
        $staff =  new Staff();
        if($this->user['is_admin'] == 1){
            $staff = $staff->get(['name' => $this->user['name']]);
        } else {
            $staff = $staff->get($this->uid);
        }
        $invs  = null ;
        if($payment->payment_type == 2 || $payment->payment_type == 4){
            $invs[0]['invoice_id'] = '/';
            $invs[0]['charge_type'] = "维护电费";
            $invs[0]['payment_amount'] = $payment->amount;
            $invs[0]['proj_number'] = $this->getCbzxIdByEmId($payment->em_id);
        } else {
            $invs = (new EmPayment())->getinvsInfo($payment_id);
            foreach ($invs as $inv){
                if($inv->payment_balance == 0){
                    $inv->paid_amount = $inv->payment_amount;
                } else {
                    $inv->paid_amount = $inv->payment_amount - $inv->payment_balance;
                }
            }
        }

        $this->assign('invs',$invs);

        $this->assign('payment_id',$payment_id);
        $this->assign('payee',$this->getGys($staff->email));
        $this->assign('org',$this->getFkInfo(2));
        $this->assign('payway',$this->getFkInfo(1));
        return $this->fetch('pay_oa');
    }

    //下推付款单
    public function docnumb(){
        $staff = Staff::get($this->uid);
        $dept = DepartmentModel::get($staff->d_id);

        $post = Request::post();
        $payment = EmPayment::get(['payment_id'=>$post['payment_id']]);

        if($this->checkFkStatus($post['payment_id'])) return json(['status'=>0,'message'=>'该缴费单已经创建付款单无法再次创建.']);
        if($this->user['is_admin']) $staffName = 'admin';
        else $staffName = substr($staff->email,0,strpos($staff->email,'@'));

        $details = [];

        if($payment->payment_type == 2 || $payment->payment_type == 4){
            $details[0]['charge_type'] = "维护电费";
            $details[0]['amount'] = $payment->amount;
            $details[0]['cbzxid'] = $this->getCbzxIdByEmId($payment->em_id);
        } else {
            $invs = (new EmPayment())->getinvsInfo($payment->payment_id);
            foreach ($invs as $k => $inv){
                $details[$k]['charge_type'] = "维护电费";
                if($inv->payment_balance == 0){
                    $details[$k]['amount'] = 0;
                } else if($inv->payment_amount == $inv->payment_balance){
                    $details[$k]['amount'] = $inv->payment_amount;
                } else {
                    $details[$k]['amount'] = $inv->payment_amount - $inv->payment_balance;
                }
                $details[$k]['cbzxid'] = $this->getDetailsFields($inv->account_id);
            }
        }

        $data = [
            'title'=>$post['title'] . ' 缴费单据:'.$post['payment_id'],
            'uname'=>$staffName,
            'payway'=>$post['payway'],
            'dept'=>$dept->name,
            'payee'=>$post['payee'],
            'org'=>$post['org'],
            'info'=>$post['info'],
            'cause'=>$post['cause'],
            'date'=>$post['date'],
            'details'=> $details
        ];

        //验证单据头
        $fkValidate = new AddFkInfoValidate();
        if(!$fkValidate->check($data)){
            return json(['status'=>0,'message'=>$fkValidate->getError()]);
        }

        //验证单据体
        $fkDetailsValidate = new AddFkInfoDetailsValidate();
        foreach ($data['details'] as $a=>$b){
            if(!$fkDetailsValidate->check($b)){
               return json(['status'=>0,'message'=>$fkDetailsValidate->getError()]);
            }
        }

        //创建付款单据
        $receipt =  $this->createFkNumb($data);

        //创建结果
        $result = false;
        if(!empty($receipt['data'])){
            $payment->status = 2;
            $fkModel = new EmPaymentFk();
            $fkModel->payment_id = $payment->payment_id;
            $fkModel->oafk_id = $receipt['data']['id'];
            $fkModel->oafk_numb = $receipt['data']['numb'];

            Db::startTrans();
            try{
                $payment->save();
                $fkModel->save();
                Db::commit();
                $result = true;
            } catch (\Exception $e){
                $result = false;
                Db::rollback();
            }
        }

        if($result) return json(['status'=>1,'message'=>'创建单据成功']);
        else return json(['status'=>0,'message'=>'创建单据失败']);
    }

    public function apiKey(){
        return md5(config('oafk.oa_key'));
    }

    public function getGys($email)
    {
        $url = config('oafk.base_url').config('oafk.gys') . $this->apiKey();
        $url .= '&email='.$email;
        $res = curlGet($url);
        $res = json_decode($res,true);
        foreach ($res['data'] as $k => $v){
            if(!empty($v['bank_info'])){
                foreach ($v['bank_info'] as $a => $b){
                    $temp[$a] = '银行名称: '.$b['open_bank_name']. '账号: '.$b['bank_code'];
                }
                $res['data'][$k]['bankInfo'] =  json_encode($temp);
            }
        }
        return $res['data'];
    }

    //获取付款所需信息
    public function getFkInfo($type){
        $url = config('oafk.base_url').config('oafk.type') . $this->apiKey();
        $data = ['type'=>$type];
        $res = httpPOST($url, $data);
        $res = json_decode($res,true);
        return $res['data'];
    }

    //创建付款编号
    public function createFkNumb($data){
        $url = config('oafk.base_url').config('oafk.fk') . $this->apiKey();
        $res = httpPOST($url, ['data'=>json_encode($data)]);
//        $start = strpos($res,'{');
//        $end = strpos($res,'}');
//        $str = substr($res,$start,$end);
        $res = json_decode($res,true);
        return $res;
    }

    public function checkFkStatus($payment_id){
        $res = (new EmPaymentFk())->get(['payment_id'=>$payment_id]);
        return $res ? true : false;
    }

    public function getDetailsFields($account_id,$contract=false){
        $account = EmAccount::get(['account_id'=>$account_id]);
        $em =  \app\em\model\Em::get($account->em_id);
        if($contract === true){
            if(!$em) return json(['status'=>0,'message'=>'没有找到所属电表']);
            return $em->contract_numb ?: '';
        }

        $station = Station::get(['station_id'=>$em->station_id]);
        if(!$station) return json(['status'=>0,'message'=>'没有找到所属基站']);
        return $station->proj_number ?: '';
    }

    public function getCbzxIdByEmId($em_id){
        $em = \app\em\model\Em::get($em_id);
        $station = \app\station\model\Station::get(['station_id'=>$em->station_id]);
        return $station->proj_number;
    }
}