Bywnpk.php 12.7 KB
<?php

namespace app\admin\controller\fastflow\bill;
use addons\qingdong\model\Amodel;
use addons\qingdong\model\Amodela;
use addons\qingdong\model\Customer;
use addons\antis\model\Business;
use app\admin\controller\fastflow\bill\Common;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\qingdong\Contacts;
use app\admin\model\qingdong\Contract;
use fastflow\api;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use app\admin\model\kuerp\Goods;
use app\admin\model\qingdong\customer\Goodsmb;


/**
 * 合同审批
 *
 * @icon fa fa-circle-o
 */
class Bywnpk extends Common
{
    
    /**
     * Bywnpk模型对象
     * @var \app\admin\model\fastflow\bill\Bywnpk
     */
    protected $model = null;
    protected $noNeedLogin = ['dateils'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fastflow\bill\Bywnpk;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage,则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $bill_ids = $this->filtrateBillIds();

        //halt($bill_ids);
        if (is_array($bill_ids) && empty($bill_ids)) {
            return ['total' => 0, 'rows' => []];
        }
        if (is_array($bill_ids) && !empty($bill_ids)) {
            $this->model->where($this->model->getTable().'.id in (' . implode(',', $bill_ids) . ')')->where($this->model->getTable().'.status','<>','-1');
        }

        $list = $this->model
//            ->with(['business','customer'])
            ->where($where)->where($this->model->getTable().'.status','<>','-1')
            ->order($sort, $order)
            ->paginate($limit);


		$businessModel = new Business();
		$ustomerModel = new Customer();

	   foreach($list as $item){

	   	$item['business'] = $businessModel->where('id',$item['business_id'])->find();
	   	$item['customer'] = $ustomerModel->where('id',$item['customer_id'])->find();
//			halt($item);
	   			
	   }

        $amodel = new Amodel();
        foreach ($list as &$item){
            $item['afile'] = $amodel->where('bill_id',$item['id'])->where('type','contract')->value('file');

        }


        $list = $this->getSignatureInfo($list);
        //halt($list->items());
        //halt(111);
        $result = ['total' => $list->total(), 'rows' => $list->items()];

        //halt($result);
        return json($result);
    }

    public function add()
    {
        $aa = $this->request->param();
        $token='';
        if(isset($aa['token'])){
            $token = $aa['token'];
        }

        $param = [
            'initiator_id'=>$this->auth->id,
            'status'=>'-1',
        ];

        $this->model->save($param);
        $id = $this->model->id;
        $this->redirect('admin\fastflow/flow/run/start3?bill=ats_bywnpk&bill_id='.$id.'&token='.$token);
        //$this->redirect('admin\fastflow/flow/run/start?bill=ats_hvuxhg&bill_id=33');
    }

    public function add2()
    {
        $aa = $this->request->param();
        $token='';
        if(isset($aa['token'])){
            $token = $aa['token'];
        }

        $param = [
            'initiator_id'=>$this->auth->id,
            'status'=>'-1',
        ];

        $this->model->save($param);
        $id = $this->model->id;
        $this->redirect('admin\fastflow/flow/run/start?bill=ats_bywnpk&bill_id='.$id.'&token='.$token);
        //$this->redirect('admin\fastflow/flow/run/start?bill=ats_hvuxhg&bill_id=33');
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $can_edit_fields = [];
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $api = new api();
        $isSuperManager = false;
        $admin_id = Session::get()['admin']['id'];
        $groupAccess = AuthGroupAccess::where('uid', $admin_id)->select();
        foreach ($groupAccess as $access) {
            $groupId = $access['group_id'];
            $group = AuthGroup::find($groupId);
            if ($group['pid'] == 0) {
                $isSuperManager = true;
            }
        }
        $bill = Config::get('database')['prefix'] . $this->model->getName();
        if (input('threadid') == null) {
            if (!$isSuperManager) {
                $bill_process = $api->getProcessByBill($bill, $row['id']);
                if ($bill_process) {
                    if (input('way') == 'detail') {
                        $can_edit_fields = [];
                    } else {
                        $this->error('流程审批中,您不能直接编辑该单据', '');
                    }
                } else {
                    $agency_info = $api->checkAgency($bill, $row['id'], 1, [$row['initiator_id']]);
                    if ($agency_info) {
                        if (!in_array($admin_id, $agency_info['agency_workers']) && !$isSuperManager) {
                            $this->error('您不是超级管理员或代理人,无权限编辑该单据', '');
                        } else {
                            $can_edit_fields = true;
                        }
                    } else {
                        if ($row['initiator_id'] != Session::get()['admin']['id'] && !$isSuperManager) {
                            $this->error('您不是超级管理员或流程发起人,暂无权限编辑该单据', '');
                        } else {
                            $can_edit_fields = true;
                        }
                    }
                }
            } else {
                $can_edit_fields = true;
            }
        } else {
            $can_edit_fields = (new api())->getCanEditFields($bill, $row['id'], input('threadid'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                //halt($params);
                //$data = [
                //    'customer_id'=>$params['customer_id'],
                //    'business_id'=>$params['business_id'],
                //    'bill_id'=>$row['id'],
                //    'offer_id'=>$params['bill_id'],
                //    'name'=>$params['cawhvqvv']??'BSNCD11111',
                //    'num'=>$params['cawhvqvv']??'BSNCD11111',
                //    'money'=>$params['wcvzhwhu']??1000,
                //    'total_price'=>$params['wcvzhwhu']??1000,
                //    'discount_rate'=>0,
                //    'contract_status'=>0,
                //    'check_status'=>0,
                //    //'order_date'=>$params['ecsnlsxg']?strtotime($params['ecsnlsxg']):time(),
                //    'order_date'=>time(),
                //    'create_staff_id'=>$this->auth->id,
                //    'owner_staff_id'=>$this->auth->id,
                //];
                //
                //(new Contract())->save($data);
                //
                //$customer_name = Customer::where('id',$params['customer_id'])->value('name');
                //$json = [
                //    '甲方'=>'博西尼信息科技有限公司',
                //    '乙方'=>$customer_name,
                //];
                //$a_data = [
                //    'bill_id'=>$row['id'],
                //    'type'=>'contract',
                //    'json'=>json_encode($json),
                //];
                //$amodel = new Amodel();
                //$amodel->save($a_data);


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField($can_edit_fields === true ? true : implode(',', $can_edit_fields))->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            //4.4.1--
            $this->success();
            //$this->error(__('Parameter %s can not be empty', ''));
            //--
        }


        $offer_id = (new Contract())->where('bill_id',$row['id'])->value('offer_id');
        $goods_ids = (new Amodela())->where('id',$offer_id)->value('json');
        $row['goods_list'] = json_decode($goods_ids,true);

        //halt($row['goods_list']);
        if($row['goods_list']){

            $totalprice = 0;
            foreach ($row['goods_list'] as $v){
                $totalprice += intval($v['amount']);
            }
            $row['totalprice'] = $totalprice;


            $row['ssss']  = 1 ;
        }else{
            $row['ssss']  = 2 ;
        }



        $bill_fileds = $api->getFieldsWithComment($bill);
        $fields = [];
        foreach ($bill_fileds as $bill_filed) {
            $fields[] = $bill_filed['field'];
        }
        if ($can_edit_fields === true) {
            $can_edit_fields = $fields;
        }

        $this->assignconfig(['billFileds' => $fields, 'canEditFields' => $can_edit_fields]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function dateils($ids){

        $row = $this->model->get($ids);
        //halt($ids);
        $offer_id = (new Contract())->where('bill_id',$row['id'])->value('offer_id');
        $amodela = (new Amodela())->where('id',$offer_id)->find();
		
		

        $array = json_decode($amodela['json'],true);


        $grouped = [];

        $mbModel = new Goodsmb();
        $goodsModel = new Goods();

        $balance = 0;
        $cb_amount = 0;
        $totalprice = 0;
        foreach ($array as &$item) {

            $mb_id = $item["mb_id"];
            $mb_name = $mbModel->where('id',$mb_id)->value('name');
            $item['mb_name'] = $mb_name;

            $wholesale_price = $goodsModel->where('id',$item["productID"])->value('wholesale_price');
            $item['wholesale_price'] = $wholesale_price;

            $item['profitrate'] = $goodsModel->where('id',$item["productID"])->value('profitrate');

            if (!isset($grouped[$mb_name])) {
                $grouped[$mb_name] = [];
            }
            $grouped[$mb_name][] = $item;

            //结算价
            $balance +=  intval($wholesale_price * $item["qty"]);
            //成本价
            $cb_amount += intval($item["qty"]*$item["cb_price"]);
            $totalprice += intval($item['amount']);

        }
        $row['bill_name'] = $amodela['name'];
        $row['totalprice'] = $totalprice;
        $row['goods_list'] =$grouped;
        $row['balance'] = (round(($balance-$cb_amount)/$cb_amount,4)*100).'%';
        $row['profit'] = (round($amodela['lr'],4)*100).'%';

        $role = $this->auth->getRole($this->auth->id);

        $this->view->assign('role',$role);


 	   $this->view->assign("contract", (new Contract())->where('bill_id',$row['id'])->find());
        $this->view->assign("row", $row);
        return $this->view->fetch('dateils');



    }






    

}