Czgprz.php 12.7 KB
<?php

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

/**
 * 报价申请
 *
 * @icon fa fa-circle-o
 */
class Czgprz extends Common
{
    
    /**
     * Czgprz模型对象
     * @var \app\admin\model\fastflow\bill\Czgprz
     */
    protected $model = null;
    protected $noNeedLogin = ['dateils','setGoods'];

    public function _initialize()
    {



        parent::_initialize();
        $this->model = new \app\admin\model\fastflow\bill\Czgprz;
        $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);

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

        }



        $list = $this->getSignatureInfo($list);

        $result = ['total' => $list->total(), 'rows' => $list->items()];

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


    public function setGoods(){

        $param = $this->request->param();
        $arr = [];
        $arr2 = [];
        $goods_ids = [];

        $goodsModel = new Goods();
        foreach ($param['arra'] as $key=>$item){
            $goods =  $goodsModel->where('goods_name',$item['name'])->find();
            $goods_ids[] = $goods['id'];
            $arr[] = [
                'no'=>$key+1,
                'mb_id'=>$item['mb_id'],
                'productName'=> $item['name'],
                'productID'=>$goods['id'],
                'markingModel'=>$item['type'],
                'dwxh'=>$item['dwxh'],
                'brand'=>$item['brand'],
                'unit'=>$item['unit'],
                'qty'=>intval($item['nums']),
                'unitPrice'=>$item['price']??'',
                'cb_price'=>$goods['purchase'],
                'wholesale_price'=>$goods['wholesale_price'],  //结算价
                'amount'=>$item['total']??'',
                'productParameter'=>$item['comment'],
                'productPicture'=>''
            ];

            $arr2[] = [
                'no'=>$key+1,
                'mb_id'=>$item['mb_id'],
                'productName'=> $item['name'],
                'productID'=>$goods['id'],
                'markingModel'=>$item['type'],
                'dwxh'=>$item['dwxh'],
                'brand'=>$item['brand'],
                'unit'=>$item['unit'],
                'qty'=>intval($item['nums']),
                'unitPrice'=>$item['price']??'',
                'wholesale_price'=>$goods['wholesale_price'],//结算价
                'cb_price'=>$goods['purchase'],
                'amount'=>$item['total']??'',
                'productParameter'=>$item['comment'],
                'productPicture'=>''
            ];


        }

        //halt($arr);


        \think\Cache::set('aaa'.$this->auth->id, ['ids'=>implode(',',$goods_ids),'arr'=>$arr], 1 * 3600);

        \think\Cache::set('aaaa'.$this->auth->id, ['ids'=>implode(',',$goods_ids),'arr'=>$arr2], 1 * 3600);

        $this->success();
    }




    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_czgprz&bill_id='.$id.'&token='.$token);

    }

    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_czgprz&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'));
        }


        $goods_ids = (new Amodel())->where('bill_id',$ids)->where('type','goods')->value('json');
        $row['goods_list'] = json_decode($goods_ids,true);
        if($row['goods_list']){
            $row['ssss']  = 1 ;
        }else{
            $row['ssss']  = 2 ;
        }

        $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);
                $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', ''));
            //--
        }

        $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;
        }

        $row['profit'] = (round($row['profit'],4)*100).'%';

        $this->assignconfig(['billFileds' => $fields, 'canEditFields' => $can_edit_fields]);
        $statusList = (new Goodsmb())->select();
        //$statusList = (new Goodsmb())->column('name');
        $this->assignconfig(['statusList' => $statusList]);
        $this->view->assign('statusList',$statusList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function dateils($ids){

        $row = $this->model->get($ids);
        $goods_ids = (new Amodel())->where('bill_id',$ids)->where('type','goods')->value('json');

        $array = json_decode($goods_ids,true);
        $grouped = [];

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

        $balance = 0;
        $cb_amount = 0;
        foreach ($array as &$item) {
            // halt($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;

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

            //结算价
            // $balance +=  $wholesale_price * $item["qty"];
            $balance +=  $item["unitPrice"] * $item["qty"];
            //成本价
            $cb_amount += $item["qty"]*$item["cb_price"];

        }
        // halt([$balance,$cb_amount]);
        $row['goods_list'] =$grouped;
        $row['balance'] = (round(($balance-$cb_amount)/$cb_amount,4)*100).'%';
        $row['profit'] = (round($row['profit'],4)*100).'%';
        //  halt($row->toArray());

        $group_ids = $this->auth->getGroupIds();

        if(in_array(1,$group_ids) || in_array(2,$group_ids)){
            $admin_id = '1';
        }elseif(in_array(3,$group_ids) || in_array(4,$group_ids) || in_array(8,$group_ids)){
            $admin_id = '2';
        }else{
            $admin_id = '3';
        }

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

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

        $this->view->assign('admin',['admin_id'=>$admin_id]);
        $this->view->assign("row", $row);
        return $this->view->fetch('dateils');



    }
    

}