Dealer.php 17.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
<?php

namespace app\admin\controller\dealer;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;

/**
 * 经销商管理
 *
 * @icon fa fa-circle-o
 */
class Dealer extends Backend
{
    
    /**
     * Dealer模型对象
     * @var \app\admin\model\dealer\Dealer
     */
    protected $model = null;
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dealer\Dealer;

    }

    public function import()
    {
        parent::import();
    }

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

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 经销商
            $group_id_arr = array_column($this->auth->getGroups(), 'group_id');
            $where1 = [];
            if(!in_array(1,$group_id_arr) && in_array(2,$group_id_arr)){
                $where1['dealer.id'] = \app\admin\model\dealer\Dealer::where('admin_id',$this->auth->id)->value('id');
            }
            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','dealer_name','createtime']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if(empty($params['username'])) {
                    $this->error('请填写账号');
                }
                if(empty($params['password'])) {
                    $this->error('请填写密码');
                }
                if (!Validate::is($params['username'], '\w{3,12}')) {
                    $this->error('用户名只能由3-12位数字、字母、下划线组合');
                }
                $admin_model = new Admin;
                $has = $admin_model->where('username',$params['username'])->field('id')->find();
                if($has){
                    $this->error('账号已存在');
                }
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error('密码长度必须在6-16位之间,不能包含空格');
                }

                $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 . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // 生成管理员账号
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $admin_model->allowField(true)->save($params);
                    (new AuthGroupAccess)->save(['uid'=>$admin_model->id,'group_id'=>2]);
                    // 增加经销商
                    $params['admin_id'] = $admin_model->id;
                    $result = $this->model->allowField(true)->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 inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $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);
                if (!Validate::is($params['username'], '\w{3,12}')) {
                    $this->error('用户名只能由3-12位数字、字母、下划线组合');
                }
                $admin_model = new Admin;
                $has = $admin_model
                    ->where('username',$params['username'])
                    ->where('id','neq',$row['admin_id'])
                    ->field('id')
                    ->find();
                if($has){
                    $this->error('账号已存在');
                }
                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error('密码长度必须在6-16位之间,不能包含空格');
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                $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);
                    }
                    $row->admin->allowField(true)->save($params);
                    $result = $row->allowField(true)->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'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 删除管理员账号
                    Admin::where('id',$v['admin_id'])->delete();
                    // 删除权限分组
                    AuthGroupAccess::where('uid',$v['admin_id'])->delete();
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 商品规格
     */
    public function sku($id)
    {
        $skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $id]);
        if ($skuList) {
            foreach ($skuList as &$s) {
                $s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $id]);
            }
        }
        $skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $id]);


        $this->assignconfig('skuList', $skuList);

        $this->assignconfig('skuPrice', $skuPrice);

        return $this->view->fetch();

    }

    /**
     * 供应商品
     */
    public function goods()
    {
        $dealer_id = $this->request->param('dealer_id');
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $goods_model = new \app\admin\model\shopro\goods\Goods;

            $where = [];
            // 经销商
            $goods_ids = [];
            if(isset($dealer_id) && $dealer_id != 0) {
                $goods_ids = \app\admin\model\dealer\DealerStock::alias('a')
                    ->join('shopro_goods_sku_price b','a.sku_price_id = b.id')
                    ->where('dealer_id',$dealer_id)
                    ->column('a.goods_id');
            }

            if ($goods_ids) {
                $where['id'] = ['in',$goods_ids];
                // 删除无用的供货商库存
                \app\admin\model\dealer\DealerStock::where('goods_id','not in',$goods_ids)
                    ->where('dealer_id',$dealer_id)
                    ->delete();
            }

            $total = $goods_model->where($where)->count();

            $subsql = \app\admin\model\shopro\goods\SkuPrice::where('status', 'up')->field('sum(stock) as stock, goods_id')->group('goods_id')->buildSql();
            $goodsTableName = $goods_model->getQuery()->getTable();
            // 关联规格表,获取总库存
            $list = $goods_model->join([$subsql => 'w'], $goodsTableName . '.id = w.goods_id', 'left');

            // 关联查询当前商品的活动,一个商品可能存在多条活动记录,关联条件 只有 find_in_set 会存在一个商品出现多次,所以使用 group
            $actSubSql = \app\admin\model\shopro\activity\Activity::field('type as activity_type, id as activity_id, goods_ids')->buildSql();
            $list = $list->join([$actSubSql => 'act'], "find_in_set(" . $goodsTableName . ".id, goods_ids)", 'left')->group('id');

            $list = $list->orderRaw($sort . ' ' . $order)
                ->where($where)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'type', 'activity_id', 'activity_type', 'app_type', 'title', 'status', 'weigh', 'category_ids', 'image', 'price', 'likes', 'views', 'sales', 'stock', 'show_sales', 'dispatch_type', 'updatetime']);
            }
            $list = collection($list)->toArray();
            return json(["total" => $total, "rows" => $list]);
        }
        $this->assignconfig('dealer_id', $dealer_id);
        return $this->view->fetch();
    }

    /**
     * 经销商规格
     */
    public function dealerSku($id, $dealer_id)
    {
        $skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $id]);
        if ($skuList) {
            foreach ($skuList as &$s) {
                $s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $id]);
            }
        }
        $skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $id]);


        //编辑
        foreach ($skuPrice as $k => &$p) {
            $actSkuPrice[$k] = \app\admin\model\dealer\DealerStock::get(['sku_price_id' => $p['id'], 'dealer_id' => $dealer_id]);

            if (!$actSkuPrice[$k]) {

                $actSkuPrice[$k]['id'] = 0;
                $actSkuPrice[$k]['dealer_id'] = $dealer_id;
                $actSkuPrice[$k]['goods_id'] = $id;
                $actSkuPrice[$k]['status'] = 'down';
                $actSkuPrice[$k]['stock'] = '';
                $actSkuPrice[$k]['sales'] = '0';
                $actSkuPrice[$k]['sku_price_id'] = $p['id'];

            }else{
                $actSkuPrice[$k]['status'] = 'up';
            }
        }

        $this->assignconfig('skuList', $skuList);

        $this->assignconfig('skuPrice', $skuPrice);
        $this->assignconfig('actSkuPrice', $actSkuPrice);

        return $this->view->fetch();

    }

    /**
     * 更新经销商规格库存
     */
    public function createOrUpdateSku($actSkuPrice)
    {
        $actSkuPrice = json_decode($actSkuPrice, true);

        $list = [];
        $act = new \app\admin\model\dealer\DealerStock;

        Db::startTrans();
        try {
            foreach ($actSkuPrice as $a => $c) {
                if($c['status'] == 'down'){
                    $act->where('id',$c['id'])->delete();
                }else{
                    if ($c['id'] == 0) {
                        unset($c['id']);
                    }
                    $list[] = $c;
                }
            }
            $act->allowField(true)->saveAll($list);

            // 更新规格库存
            foreach ($list as $v) {
                $sum_stock = $act->where('sku_price_id',$v['sku_price_id'])->where('deletetime',null)->sum('stock');
                \app\admin\model\shopro\goods\SkuPrice::where('id',$v['sku_price_id'])->update(['stock'=>$sum_stock]);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 申请提现
     */
    public function apply () {
        // 经销商
        $dealer = [];
        $group_id_arr = array_column($this->auth->getGroups(), 'group_id');
        if(!in_array(1,$group_id_arr) && in_array(2,$group_id_arr)){
            $dealer = \app\admin\model\dealer\Dealer::where('admin_id',$this->auth->id)->find();
        }
        empty($dealer) && $this->error('没有权限');
        if ($this->request->isPost()) {
            $money = $this->request->post('money');
            $money <= 0 && $this->error('请输入提现金额');
            $result = false;
            Db::startTrans();
            try {
                $applyModel = new \app\admin\model\dealer\DealerMoneyApply;
                $result = $applyModel->save([
                    'dealer_id' => $dealer['id'],
                    'money' => $money,
                    'status' => 0
                ]);
                // 扣除余额
                \app\admin\model\dealer\Dealer::moneyReduce($dealer->id, $money, 'cash', $applyModel->id);
                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('申请失败');
            }
        }
        $this->view->assign("dealer", $dealer);
        return $this->view->fetch();
    }

    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }

}