WIN-2308041133\Administrator 3 weeks ago
parent
commit
8148ede8be

+ 344 - 0
app/admin/controller/user/GroupLevel.php

@@ -0,0 +1,344 @@
+<?php
+
+namespace app\admin\controller\user;
+
+use app\admin\controller\AuthController;
+use think\facade\Route as Url;
+use crmeb\traits\CurdControllerTrait;
+use app\admin\model\user\UserLevel as UserLevelModel;
+use app\admin\model\system\{SystemGroupLevel,SystemUserTask};
+use crmeb\services\{UtilService,JsonService,FormBuilder as Form};
+
+/**
+ * 会员设置
+ * Class UserLevel
+ * @package app\admin\controller\user
+ */
+class GroupLevel extends AuthController
+{
+    use CurdControllerTrait;
+
+    /*
+     * 等级展示
+     * */
+    public function index()
+    {
+        return $this->fetch();
+    }
+
+    /*
+     * 创建form表单
+     * */
+    public function create($id = 0)
+    {
+        if ($id) $vipinfo = SystemGroupLevel::get($id);
+        $field[] = Form::input('name', '等级名称', isset($vipinfo) ? $vipinfo->name : '')->col(Form::col(24));
+//        $field[] = Form::radio('is_forever', '是否为永久', isset($vipinfo) ? $vipinfo->is_forever : 0)->options([['label' => '永久', 'value' => 1], ['label' => '非永久', 'value' => 0]])->col(24);
+        //$field[]= Form::number('money','等级价格',isset($vipinfo) ? $vipinfo->money : 0)->min(0)->col(24);
+        //$field[]= Form::radio('is_pay','是否需要购买',isset($vipinfo) ? $vipinfo->is_pay : 0)->options([['label'=>'需要','value'=>1],['label'=>'免费','value'=>0]])->col(24);
+//        $field[] = Form::number('valid_date', '有效时间(天)', isset($vipinfo) ? $vipinfo->valid_date : 0)->min(0)->col(8);
+        $field[] = Form::number('dividends', '全网分红', isset($vipinfo) ? $vipinfo->dividends : 0)->min(0)->col(8);
+        $field[] = Form::number('grade', '等级', isset($vipinfo) ? $vipinfo->grade : 0)->min(0)->col(8);
+//        $field[] = Form::number('discount', '享受折扣', isset($vipinfo) ? $vipinfo->discount : 0)->min(0)->col(8);
+        $field[] = Form::frameImageOne('icon', '图标', Url::buildUrl('admin/widget.images/index', array('fodder' => 'icon')), isset($vipinfo) ? $vipinfo->icon : '')->icon('image')->width('100%')->height('500px');
+        $field[] = Form::frameImageOne('image', '会员背景', Url::buildUrl('admin/widget.images/index', array('fodder' => 'image')), isset($vipinfo) ? $vipinfo->image : '')->icon('image')->width('100%')->height('500px');
+        $field[] = Form::radio('is_show', '是否显示', isset($vipinfo) ? $vipinfo->is_show : 0)->options([['label' => '显示', 'value' => 1], ['label' => '隐藏', 'value' => 0]])->col(8);
+        $field[] = Form::textarea('explain', '等级说明', isset($vipinfo) ? $vipinfo->explain : '');
+        $form = Form::make_post_form('添加等级设置', $field, Url::buildUrl('save', ['id' => $id]), 2);
+        $this->assign(compact('form'));
+        return $this->fetch('public/form-builder');
+    }
+
+    /*
+     * 会员等级添加或者修改
+     * @param $id 修改的等级id
+     * @return json
+     * */
+    public function save($id = 0)
+    {
+        $data = UtilService::postMore([
+            ['name', ''],
+//            ['is_forever', 0],
+//            ['money', 0],
+//            ['is_pay', 0],
+            ['valid_date', 0],
+            ['dividends', 0],
+            ['grade', 0],
+//            ['discount', 0],
+            ['icon', ''],
+            ['image', ''],
+            ['is_show', ''],
+            ['explain', ''],
+        ]);
+//        if (!$data['dividends']) return JsonService::fail('请输入全网分红比例');
+        if (!$data['name']) return JsonService::fail('请输入等级名称');
+        if (!$data['grade']) return JsonService::fail('请输入等级');
+        if (!$data['explain']) return JsonService::fail('请输入等级说明');
+//        if ($data['is_forever'] == 0 && !$data['valid_date']) return JsonService::fail('请输入有效时间(天)');
+//        if ($data['is_pay']) return JsonService::fail('会员等级购买功能正在开发中,暂时关闭可购买功能!');
+//        if ($data['is_pay'] && !$data['money']) return JsonService::fail('请输入购买金额');
+        if (!$data['icon']) return JsonService::fail('请上传等级图标');
+        if (!$data['image']) return JsonService::fail('请上传等级背景图标');
+        if (!$id && SystemGroupLevel::be(['is_del' => 0, 'grade' => $data['grade']])) return JsonService::fail('已检测到您设置过的会员等级,此等级不可重复');
+        SystemGroupLevel::beginTrans();
+        try {
+            //修改
+            if ($id) {
+                if (SystemGroupLevel::edit($data, $id)) {
+                    SystemGroupLevel::commitTrans();
+                    return JsonService::successful('修改成功');
+                } else {
+                    SystemGroupLevel::rollbackTrans();
+                    return JsonService::fail('修改失败');
+                }
+            } else {
+                //新增
+                $data['add_time'] = time();
+                if (SystemGroupLevel::create($data)) {
+                    SystemGroupLevel::commitTrans();
+                    return JsonService::successful('添加成功');
+                } else {
+                    SystemGroupLevel::rollbackTrans();
+                    return JsonService::fail('添加失败');
+                }
+            }
+        } catch (\Exception $e) {
+            SystemGroupLevel::rollbackTrans();
+            return JsonService::fail($e->getMessage());
+        }
+    }
+
+    /*
+     * 获取系统设置的vip列表
+     * @param int page
+     * @param int limit
+     * */
+    public function get_system_vip_list()
+    {
+        $where = UtilService::getMore([
+            ['page', 0],
+            ['limit', 10],
+            ['title', ''],
+            ['is_show', ''],
+        ]);
+        return JsonService::successlayui(SystemGroupLevel::getSytemList($where));
+    }
+
+    /*
+     * 删除会员等级
+     * @param int $id
+     * */
+    public function delete($id = 0)
+    {
+        if (SystemGroupLevel::edit(['is_del' => 1], $id))
+            return JsonService::successful('删除成功');
+        else
+            return JsonService::fail('删除失败');
+    }
+
+    /**
+     * 设置单个产品上架|下架
+     *
+     * @return json
+     */
+    public function set_show($is_show = '', $id = '')
+    {
+        ($is_show == '' || $id == '') && Json::fail('缺少参数');
+        $res = SystemGroupLevel::where(['id' => $id])->update(['is_show' => (int)$is_show]);
+        if ($res) {
+            return JsonService::successful($is_show == 1 ? '显示成功' : '隐藏成功');
+        } else {
+            return JsonService::fail($is_show == 1 ? '显示失败' : '隐藏失败');
+        }
+    }
+
+    /**
+     * 快速编辑
+     *
+     * @return json
+     */
+    public function set_value($field = '', $id = '', $value = '')
+    {
+        $field == '' || $id == '' || $value == '' && Json::fail('缺少参数');
+        if (SystemGroupLevel::where(['id' => $id])->update([$field => $value]))
+            return JsonService::successful('保存成功');
+        else
+            return JsonService::fail('保存失败');
+    }
+
+
+    /*
+     * 等级任务列表
+     * @param int $vip_id 等级id
+     * @return json
+     * */
+    public function tash($level_id = 0)
+    {
+        $this->assign('level_id', $level_id);
+        return $this->fetch();
+    }
+
+    /**
+     * 快速编辑
+     *
+     * @return json
+     */
+    public function set_tash_value($field = '', $id = '', $value = '')
+    {
+        $field == '' || $id == '' || $value == '' && Json::fail('缺少参数');
+        if (SystemUserTask::where(['id' => $id])->update([$field => $value]))
+            return JsonService::successful('保存成功');
+        else
+            return JsonService::fail('保存失败');
+    }
+
+    /**
+     * 设置单个产品上架|下架
+     *
+     * @return json
+     */
+    public function set_tash_show($is_show = '', $id = '')
+    {
+        ($is_show == '' || $id == '') && Json::fail('缺少参数');
+        $res = SystemUserTask::where(['id' => $id])->update(['is_show' => (int)$is_show]);
+        if ($res) {
+            return JsonService::successful($is_show == 1 ? '显示成功' : '隐藏成功');
+        } else {
+            return JsonService::fail($is_show == 1 ? '显示失败' : '隐藏失败');
+        }
+    }
+
+    /**
+     * 设置单个产品上架|下架
+     *
+     * @return json
+     */
+    public function set_tash_must($is_must = '', $id = '')
+    {
+        ($is_must == '' || $id == '') && Json::fail('缺少参数');
+        $res = SystemUserTask::where(['id' => $id])->update(['is_must' => (int)$is_must]);
+        if ($res) {
+            return JsonService::successful('设置成功');
+        } else {
+            return JsonService::fail('设置失败');
+        }
+    }
+
+    /*
+     * 生成任务表单
+     * @param int $id 任务id
+     * @param int $vip_id 会员id
+     * @return html
+     * */
+    public function create_tash($id = 0, $level_id = 0)
+    {
+        if ($id) $tash = SystemUserTask::get($id);
+        $field[] = Form::select('task_type', '任务类型', isset($tash) ? $tash->task_type : '')->setOptions(function () {
+            $list = SystemUserTask::getTaskTypeAll();
+            $menus = [];
+            foreach ($list as $menu) {
+                $menus[] = ['value' => $menu['type'], 'label' => $menu['name'] . '----单位[' . $menu['unit'] . ']'];
+            }
+            return $menus;
+        })->filterable(1);
+        $field[] = Form::number('number', '限定数量', isset($tash) ? $tash->number : 0)->min(0)->col(24);
+        $field[] = Form::number('sort', '排序', isset($tash) ? $tash->sort : 0)->min(0)->col(24);
+        $field[] = Form::radio('is_show', '是否显示', isset($tash) ? $tash->is_show : 1)->options([['label' => '显示', 'value' => 1], ['label' => '隐藏', 'value' => 0]])->col(24);
+        $field[] = Form::radio('is_must', '是否务必达成', isset($tash) ? $tash->is_must : 1)->options([['label' => '务必达成', 'value' => 1], ['label' => '完成其一', 'value' => 0]])->col(24);
+        $field[] = Form::textarea('illustrate', '任务说明', isset($tash) ? $tash->illustrate : '');
+        $form = Form::make_post_form('添加任务', $field, Url::buildUrl('save_tash', ['id' => $id, 'level_id' => $level_id]), 2);
+        $this->assign(compact('form'));
+        return $this->fetch('public/form-builder');
+    }
+
+
+    /*
+     * 保存或者修改任务
+     * @param int $id 任务id
+     * @param int $vip_id 会员id
+     * */
+    public function save_tash($id = 0, $level_id = 0)
+    {
+        if (!$level_id) return JsonService::fail('缺少参数');
+        $data = UtilService::postMore([
+            ['task_type', ''],
+            ['number', 0],
+            ['is_show', 0],
+            ['sort', 0],
+            ['is_must', 0],
+            ['illustrate', ''],
+        ]);
+        if (!$data['task_type']) return JsonService::fail('请选择任务类型');
+        if ($data['number'] < 1) return JsonService::fail('请输入限定数量,数量不能小于1');
+        $tash = SystemUserTask::getTaskType($data['task_type']);
+        if ($tash['max_number'] != 0 && $data['number'] > $tash['max_number']) return JsonService::fail('您设置的限定数量超出最大限制,最大限制为:' . $tash['max_number']);
+        $data['name'] = SystemUserTask::setTaskName($data['task_type'], $data['number']);
+        try {
+            if ($id) {
+                SystemUserTask::edit($data, $id);
+                return JsonService::successful('修改成功');
+            } else {
+                $data['level_id'] = $level_id;
+                $data['add_time'] = time();
+                $data['real_name'] = $tash['real_name'];
+                if (SystemUserTask::create($data))
+                    return JsonService::successful('添加成功');
+                else
+                    return JsonService::fail('添加失败');
+            }
+        } catch (\Exception $e) {
+            return JsonService::fail($e->getMessage());
+        }
+    }
+
+    /*
+     * 异步获取等级任务列表
+     * @param int $vip_id 会员id
+     * @param int $page 分页
+     * @param int $limit 显示条数
+     * @return json
+     * */
+    public function get_tash_list($level_id = 0)
+    {
+        list($page, $limit) = UtilService::getMore([
+            ['page', 1],
+            ['limit', 10],
+        ], $this->request, true);
+        return JsonService::successlayui(SystemUserTask::getTashList($level_id, (int)$page, (int)$limit));
+    }
+
+    /*
+     * 删除任务
+     * @param int 任务id
+     * */
+    public function delete_tash($id = 0)
+    {
+        if (!$id) return JsonService::fail('缺少差参数');
+        if (SystemUserTask::del($id))
+            return JsonService::successful('删除成功');
+        else
+            return JsonService::fail('删除失败');
+    }
+
+    /*
+     * 会员等级展示
+     *
+     * */
+    public function user_level_list()
+    {
+        $this->assign('level', SystemGroupLevel::where('is_del', 0)->where('is_show', 1)->order('grade asc')->field(['id', 'name'])->select());
+        return $this->fetch();
+    }
+
+    public function get_user_vip_list()
+    {
+        $where = UtilService::getMore([
+            ['page', 1],
+            ['limit', 10],
+            ['nickname', ''],
+            ['level_id', ''],
+        ]);
+        return JsonService::successlayui(UserLevelModel::getUserVipList($where));
+    }
+
+}

+ 74 - 0
app/admin/model/system/SystemGroupLevel.php

@@ -0,0 +1,74 @@
+<?php
+/**
+ * @author: xaboy<365615158@qq.com>
+ * @day: 2017/11/13
+ */
+
+namespace app\admin\model\system;
+
+use crmeb\traits\ModelTrait;
+use crmeb\basic\BaseModel;
+
+/**
+ * 设置会员vip model
+ * Class SystemVip
+ * @package app\admin\model\system
+ */
+class SystemGroupLevel extends BaseModel
+{
+
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'system_group_level';
+
+    use ModelTrait;
+
+    public static function setAddTimeAttr()
+    {
+        return time();
+    }
+    public static function getAddTimeAttr($value)
+    {
+        return date('Y-m-d H:i:s',$value);
+    }
+
+    /**
+     * 获取查询条件
+     * @param $where
+     * @param string $alert
+     * @param null $model
+     * @return SystemUserLevel|null
+     */
+    public static function setWhere($where,$alert='',$model=null)
+    {
+        $model=$model===null ? new self() : $model;
+        if($alert) $model=$model->alias($alert);
+        $alert=$alert ? $alert.'.': '';
+        $model = $model->where("{$alert}is_del",0);
+        if(isset($where['is_show']) && $where['is_show']!=='') $model=$model->where("{$alert}is_show",$where['is_show']);
+        if(isset($where['title']) && $where['title']) $model=$model->where("{$alert}name",'LIKE',"%$where[title]%");
+        return $model;
+    }
+
+    /**
+     * 查找系统设置的会员等级列表
+     * @param $where
+     * @return array
+     */
+    public static function getSytemList($where)
+    {
+        $data=self::setWhere($where)->order('grade asc')->page((int)$where['page'],(int)$where['limit'])->select();
+        $data=count($data) ? $data->toArray() : [];
+        $count=self::setWhere($where)->count();
+        return compact('data','count');
+    }
+
+}

+ 203 - 0
app/admin/view/user/group_level/index.php

@@ -0,0 +1,203 @@
+{extend name="public/container"}
+{block name="content"}
+<div class="layui-fluid">
+    <div class="layui-row layui-col-space15"  id="app">
+        <div class="layui-col-md12">
+            <div class="layui-card">
+                <div class="layui-card-header">搜索条件</div>
+                <div class="layui-card-body">
+                    <form class="layui-form layui-form-pane" action="">
+                        <div class="layui-form-item">
+                            <div class="layui-inline">
+                                <label class="layui-form-label">是否显示</label>
+                                <div class="layui-input-block">
+                                    <select name="is_show">
+                                        <option value="">是否显示</option>
+                                        <option value="1">显示</option>
+                                        <option value="0">不显示</option>
+                                    </select>
+                                </div>
+                            </div>
+                            <div class="layui-inline">
+                                <label class="layui-form-label">等级名称</label>
+                                <div class="layui-input-block">
+                                    <input type="text" name="title" class="layui-input" placeholder="请输入等级名称">
+                                </div>
+                            </div>
+                            <div class="layui-inline">
+                                <div class="layui-input-inline">
+                                    <button class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="search" lay-filter="search">
+                                        <i class="layui-icon layui-icon-search"></i>搜索</button>
+                                </div>
+                            </div>
+                        </div>
+                    </form>
+                </div>
+            </div>
+        </div>
+        <!--产品列表-->
+        <div class="layui-col-md12">
+            <div class="layui-card">
+                <div class="layui-card-header">等级列表</div>
+                <div class="layui-card-body">
+                    <div class="layui-btn-container">
+                        <button class="layui-btn layui-btn-sm" onclick="$eb.createModalFrame(this.innerText,'{:Url('create')}')">添加会员等级</button>
+                    </div>
+                    <table class="layui-hide" id="List" lay-filter="List"></table>
+                    <script type="text/html" id="icon">
+                        <img style="cursor: pointer;max-width: 50px;" lay-event='open_image' src="{{d.icon}}">
+                    </script>
+<!--                    <script type="text/html" id="is_forever">-->
+<!--                        <input type='checkbox' name='id' disabled lay-skin='switch' value="{{d.id}}" lay-filter='is_forever' lay-text='永久|非永久'  {{ d.is_forever == 1 ? 'checked' : '' }}>-->
+<!--                    </script>-->
+                    <script type="text/html" id="is_show">
+                        <input type='checkbox' name='id' lay-skin='switch' value="{{d.id}}" lay-filter='is_show' lay-text='开启|关闭'  {{ d.is_show == 1 ? 'checked' : '' }}>
+                    </script>
+                    <script type="text/html" id="is_pay">
+                        <input type='checkbox' name='id' disabled lay-skin='switch' value="{{d.id}}" lay-filter='is_pay' lay-text='付费|免费'  {{ d.is_pay == 1 ? 'checked' : '' }}>
+                    </script>
+                    <script type="text/html" id="act">
+                        <button type="button" class="layui-btn layui-btn-xs" onclick="dropdown(this)">操作 <span class="caret"></span></button>
+                        <ul class="layui-nav-child layui-anim layui-anim-upbit">
+<!--                            <li>-->
+<!--                                <a href="javascript:void(0)" onclick="$eb.createModalFrame(this.innerText,'{:Url(\'tash\')}?level_id={{d.id}}',{w:1000})">-->
+<!--                                    <i class="fa fa-wrench"></i> 等级任务-->
+<!--                                </a>-->
+<!--                            </li>-->
+                            <li>
+                                <a href="javascript:void(0)" onclick="$eb.createModalFrame(this.innerText,'{:Url(\'create\')}?id={{d.id}}')">
+                                    <i class="fa fa-edit"></i> 编辑等级
+                                </a>
+                            </li>
+                            <li>
+                                <a lay-event='delete' href="javascript:void(0)" >
+                                    <i class="fa fa-times"></i> 删除等级
+                                </a>
+                            </li>
+                        </ul>
+                    </script>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>
+<script src="{__ADMIN_PATH}js/layuiList.js"></script>
+{/block}
+{block name="script"}
+<script>
+    //实例化form
+    layList.form.render();
+    //加载列表
+    layList.tableList('List',"{:Url('get_system_vip_list')}",function (){
+        return [
+            {field: 'id', title: '编号', sort: true,event:'id',width:'6%',align:"center"},
+            {field: 'icon', title: '等级图标',templet:'#icon',align:"center",width:'10%'},
+            {field: 'name', title: '等级名称',edit:'name',width:'6%',align:"center"},
+            {field: 'grade', title: '等级',edit:'grade',width:'6%',align:"center"},
+            // {field: 'discount', title: '享受折扣',edit:'discount',width:'8%',align:"center"},
+            // {field: 'valid_date', title: '有效时间',width:'12%',align:"center"},
+            {field: 'dividends', title: '全网分红',width:'12%',align:"center"},
+            // {field: 'is_forever', title: '是否永久',templet:'#is_forever',width:'8%',align:"center"},
+            {field: 'is_show', title: '是否使用',templet:'#is_show',width:'8%',align:"center"},
+            {field: 'explain', title: '等级说明',align:"center"},
+            {field: 'right', title: '操作',align:'center',toolbar:'#act',width:'8%'},
+        ];
+    });
+    //自定义方法
+    var action= {
+        set_value: function (field, id, value) {
+            layList.baseGet(layList.Url({
+                a: 'set_value',
+                q: {field: field, id: id, value: value}
+            }), function (res) {
+                layList.msg(res.msg);
+            });
+        },
+    }
+    //查询
+    layList.search('search',function(where){
+        layList.reload(where,true);
+    });
+    layList.switch('is_show',function (odj,value) {
+        if(odj.elem.checked==true){
+            layList.baseGet(layList.Url({a:'set_show',p:{is_show:1,id:value}}),function (res) {
+                layList.msg(res.msg);
+            });
+        }else{
+            layList.baseGet(layList.Url({a:'set_show',p:{is_show:0,id:value}}),function (res) {
+                layList.msg(res.msg);
+            });
+        }
+    });
+    //快速编辑
+    layList.edit(function (obj) {
+        var id=obj.data.id,value=obj.value;
+        switch (obj.field) {
+            case 'name':
+                action.set_value('name',id,value);
+                break;
+            case 'grade':
+                action.set_value('grade',id,value);
+                break;
+            // case 'discount':
+            //     action.set_value('discount',id,value);
+                break;
+        }
+    });
+    //监听并执行排序
+    layList.sort(['id','sort'],true);
+    //点击事件绑定
+    layList.tool(function (event,data,obj) {
+        switch (event) {
+            case 'delete':
+                var url=layList.U({a:'delete',q:{id:data.id}});
+                $eb.$swal('delete',function(){
+                    $eb.axios.get(url).then(function(res){
+                        if(res.status == 200 && res.data.code == 200) {
+                            $eb.$swal('success',res.data.msg);
+                            obj.del();
+                        }else
+                            return Promise.reject(res.data.msg || '删除失败')
+                    }).catch(function(err){
+                        $eb.$swal('error',err);
+                    });
+                })
+                break;
+            case 'open_image':
+                $eb.openImage(data.icon);
+                break;
+        }
+    })
+    //下拉框
+    $(document).click(function (e) {
+        $('.layui-nav-child').hide();
+    })
+    function dropdown(that){
+        var oEvent = arguments.callee.caller.arguments[0] || event;
+        oEvent.stopPropagation();
+        var offset = $(that).offset();
+        var top=offset.top-$(window).scrollTop();
+        var index = $(that).parents('tr').data('index');
+        $('.layui-nav-child').each(function (key) {
+            if (key != index) {
+                $(this).hide();
+            }
+        })
+        if($(document).height() < top+$(that).next('ul').height()){
+            $(that).next('ul').css({
+                'padding': 10,
+                'top': - ($(that).parent('td').height() / 2 + $(that).height() + $(that).next('ul').height()/2),
+                'min-width': 'inherit',
+                'position': 'absolute'
+            }).toggle();
+        }else{
+            $(that).next('ul').css({
+                'padding': 10,
+                'top':$(that).parent('td').height() / 2 + $(that).height(),
+                'min-width': 'inherit',
+                'position': 'absolute'
+            }).toggle();
+        }
+    }
+</script>
+{/block}

+ 13 - 1
app/models/store/StoreOrder.php

@@ -802,12 +802,24 @@ class StoreOrder extends BaseModel
             $spread_order = User::where('uid', $order['sale_uid'])->value('spread_order');
             $spread_order = bcadd($spread_order,1,2);  //推荐订单数加1
             User::where('uid', $order['uid'])->update(['spread_uid' => $order['sale_uid'],'spread_time'=>time(),'spread_order'=>$spread_order]);
+            if ($spread_order % 2 == 0) {
+//                echo "双数";
+                $radio = sys_config('secondary_commission_ratio');
+            } else {
+//                echo "单数";
+                $radio = sys_config('primary_commission_ratio');
+            }
+            $money = bcmul($order['pay_price'], bcdiv($radio,100,2), 2);
+            $blance = User::where('uid', $order['sale_uid'])->value('brokerage_price');
+            $blance = bcadd($blance, $money, 2);
+            UserBill::income('推荐佣金', $order['sale_uid'], 'brokerage_price', 'order_money', $money, $order['id'], $blance, '订单推荐佣金');
+            User::where('uid', $order['sale_uid'])->update(['brokerage_price' =>$blance]);
 
         }
 //       如果是报单商品就增加业绩
         if ($order['is_explosive']==1){
             $achievement = User::where('uid', $order['uid'])->value('achievement');
-            $achievement = bcadd($achievement, $order['pay_price'], 2);
+            $achievement = bcadd($achievement, $order['total_price'], 2);
             User::where('uid', $order['uid'])->update(['achievement' => $achievement]);
         }
         $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);

+ 184 - 0
app/models/system/SystemGroupLevel.php

@@ -0,0 +1,184 @@
+<?php
+
+
+namespace app\models\system;
+
+use app\models\user\UserGroupLevel;
+use crmeb\traits\ModelTrait;
+use crmeb\basic\BaseModel;
+use think\db\exception\DataNotFoundException;
+use think\db\exception\DbException;
+use think\db\exception\ModelNotFoundException;
+
+/**
+ * TODO 设置会员等级Model
+ * Class SystemUserLevel
+ * @package app\models\system
+ */
+class SystemGroupLevel extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'system_group_level';
+
+    use ModelTrait;
+
+    public static function getAddTimeAttr($value)
+    {
+        return date('Y-m-d H:i:s', $value);
+    }
+
+    public static function getDiscountAttr($value)
+    {
+        return (int)$value;
+    }
+
+    /*
+     * 获取查询条件
+     * @param string $alert 别名
+     * @param object $model 模型
+     * @return object
+     * */
+    public static function setWhere($alert = '', $model = null)
+    {
+        $model = $model === null ? new self() : $model;
+        if ($alert) $model = $model->alias($alert);
+        $alert = $alert ? $alert . '.' : '';
+        return $model->where("{$alert}is_show", 1)->where("{$alert}is_del", 0);
+    }
+
+    /*
+     * 获取某个等级的折扣
+     * */
+    public static function getLevelDiscount($id = 0)
+    {
+        $model = self::setWhere();
+        if ($id) $model = $model->where('id', $id);
+        else $model = $model->order('grade asc');
+        return $model->value('discount');
+    }
+
+
+    /**
+     * 获取用户等级和当前等级
+     * @param $uid 用户uid
+     * @param bool $isArray 是否查找任务列表
+     * @return array|bool|mixed|string|\think\Model|null
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getLevelInfo($uid, $isArray = false)
+    {
+        $level = ['id' => 0];
+        $task = [];
+        $id = UserGroupLevel::getUserLevel($uid);
+        if ($id !== false) $level = UserGroupLevel::getUserLevelInfo($id);
+        $list = self::getLevelListAndGrade($level['id'], $isArray);
+//        if (isset($list[0]) && $isArray) $task = SystemUserTask::getTashList($list[0]['id'], $uid, $level);
+        if ($isArray) return [$list, $task];
+        else return $level['id'] && $id !== false ? $level : false;
+    }
+
+    /**
+     * 获取会员等级级别
+     * @param $leval_id 等级id
+     * @return mixed
+     */
+    public static function getLevelGrade($leval_id)
+    {
+        return self::setWhere()->where('id', $leval_id)->value('grade');
+    }
+
+    /**
+     * 获取会员等级列表
+     * @param int $leval_id 用户等级
+     * @param bool $isArray 是否查找任务列表
+     * @param string $order
+     * @return array|\think\Collection
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws DbException
+     */
+    public static function getLevelListAndGrade($leval_id, $isArray, $order = 'grade asc')
+    {
+        $grade = 0;
+        if (!$leval_id && !$isArray) $leval_id = self::setWhere()->where('grade', self::setWhere()->min('grade'))->order('add_time DESC')->value('id');
+        $list = self::setWhere()->field('name,discount,image,icon,explain,id,grade')->order($order)->select();
+        $list = count($list) ? $list->toArray() : [];
+        foreach ($list as &$item) {
+            if ($item['id'] == $leval_id)
+                $grade = $item['grade'];
+
+//            if ($isArray)
+//                $item['task_list'] = SystemUserTask::getTashList($item['id']);
+        }
+        foreach ($list as &$item) {
+            if ($grade < $item['grade'])
+                $item['is_clear'] = true;
+            else
+                $item['is_clear'] = false;
+        }
+        return $list;
+    }
+
+    /**
+     *
+     * @param $leval_id
+     * @param null $list
+     * @return bool
+     */
+    public static function getClear($leval_id, $list = null)
+    {
+        $list = $list === null ? self::getLevelListAndGrade($leval_id, false) : $list;
+        foreach ($list as $item) {
+            if ($item['id'] == $leval_id) return $item['is_clear'];
+        }
+        return false;
+    }
+
+
+    /**
+     * 获取当前vipid 的下一个会员id
+     * @param int $leval_id 当前用户的会员id
+     * @param $max
+     * @return int
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws DbException
+     */
+    public static function getNextLevelId($leval_id, $max)
+    {
+        $list = self::getLevelListAndGrade($leval_id, false, 'grade desc');
+        $grade = 0;
+        $leveal = [];
+        foreach ($list as $item) {
+            if ($item['id'] == $leval_id) $grade = $item['grade'];
+        }
+        foreach ($list as $item) {
+            if ($grade < $item['grade'] && $item['grade'] <= $max) array_push($leveal, $item['id']);
+        }
+        return isset($leveal[0]) ? $leveal[0] : 0;
+    }
+
+    /**
+     * 获取会员等级列表
+     * @param $uid
+     * @return array
+     */
+    public static function getLevelList($uid)
+    {
+        list($list, $task) = self::getLevelInfo($uid, true);
+        return ['list' => $list, 'task' => $task];
+    }
+
+
+}

+ 147 - 0
app/models/user/DividendsRecord.php

@@ -0,0 +1,147 @@
+<?php
+/**
+ * Created by CRMEB.
+ * Copyright (c) 2017~2019 http://www.crmeb.com All rights reserved.
+ * Author: liaofei <136327134@qq.com>
+ * Date: 2019/3/27 21:44
+ */
+
+namespace app\models\user;
+
+use app\models\store\StoreOrder;
+use app\models\system\SystemGroupLevel;
+use app\models\system\SystemUserLevel;
+use think\facade\Cache;
+use crmeb\traits\ModelTrait;
+use crmeb\basic\BaseModel;
+
+/**
+ * TODO 用户消费新增金额明细 model
+ * Class UserBill
+ * @package app\models\user
+ */
+class DividendsRecord extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'dividends_record';
+
+    use ModelTrait;
+
+    public static function income($title, $uid, $type, $number , $mark = '', $status = 1)
+    {
+        $pm = 1;
+        $add_time = time();
+        return self::create(compact('title', 'uid', 'type', 'number', 'mark', 'status', 'pm', 'add_time'));
+    }
+
+//    public static function expend($title, $uid, $category, $type, $number, $link_id = 0, $balance = 0, $mark = '', $status = 1)
+//    {
+//        $pm = 0;
+//        $add_time = time();
+//        return self::create(compact('title', 'uid', 'link_id', 'category', 'type', 'number', 'balance', 'mark', 'status', 'pm', 'add_time'));
+//    }
+
+    /**
+     * 积分/佣金 使用记录
+     * @param $uid
+     * @param $page
+     * @param $limit
+     * @param string $category
+     * @return array|\think\Collection
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function userBillList($uid, $page, $limit, $where = [])
+    {
+//        if ($page) {
+            $list = self::where('uid', $uid)
+//                ->where('category', $category)
+                ->field('mark,pm,number,add_time')
+                ->where('status', 1)
+                ->where($where)
+                ->order('add_time DESC')
+                ->page((int)$page, (int)$limit)
+                ->select();
+//        } else {
+//            $list = self::where('uid', $uid)
+//                ->where('category', $category)
+//                ->field('mark,pm,number,add_time')
+//                ->where('status', 1)
+//                ->where($where)
+//                ->order('add_time DESC')
+//                ->select();
+//        }
+        $list = count($list) ? $list->toArray() : [];
+        foreach ($list as &$v) {
+            $v['add_time'] = date('Y/m/d H:i', $v['add_time']);
+            $v['number'] = floatval($v['number']);
+        }
+        return $list;
+    }
+
+    /*
+     * 获取用户账单明细
+     * @param int $uid 用户uid
+     * @param int $page 页码
+     * @param int $limit 展示多少条
+     * @param int $type 展示类型
+     * @return array
+     * */
+    public static function getUserBillList($uid, $page, $limit)
+    {
+        if (!$limit) return [];
+        $model = self::where('uid', $uid)->order('add_time desc')->where('number', '<>', 0)
+            ->field('FROM_UNIXTIME(add_time,"%Y-%m") as time,group_concat(id SEPARATOR ",") ids')->group('time');
+
+        if ($page) $model = $model->page((int)$page, (int)$limit);
+        $list = ($list = $model->select()) ? $list->toArray() : [];
+        $data = [];
+        foreach ($list as $item) {
+            $value['time'] = $item['time'];
+            $value['list'] = self::where('id', 'in', $item['ids'])->field('FROM_UNIXTIME(add_time,"%Y-%m-%d %H:%i") as add_time,title,number,pm,status,mark')->order('add_time DESC')->select();
+            array_push($data, $value);
+        }
+        return $data;
+    }
+//    全网分红
+    public static function wholeNetworkDividend(){
+        $pool = sys_config('dividend_pool');
+        if (!$pool|| $pool <= 0) return false;
+        $user_list = User::where(function($query) {
+            $query->where('level', '>', 0)
+                ->orWhere('group_level', '>', 0);
+        })->select();
+        foreach ($user_list as $user){
+            $dividends=0;
+            if ($user['level'] > 0){
+                $level_grade = SystemUserLevel::where('level', $user['level'])->find();
+                $level_dividends = SystemUserLevel::where('level', '<=', $level_grade)->sum('dividends');
+                $dividends = bcadd($level_dividends, $dividends, 2);
+            }
+            if ($user['group_level'] > 0){
+                $group_level_grade = SystemGroupLevel::where('level', $user['group_level'])->find();
+                $group_level_dividends = SystemGroupLevel::where('level', '<=', $group_level_grade)->sum('dividends');
+                $dividends = bcadd($group_level_dividends, $dividends, 2);
+            }
+            if ($dividends > 0){
+                $brokerage = bcsub($pool, $dividends, 2);
+
+                $id = self::income('全网分红', $user['uid'], 'brokerage_price', $brokerage, '订单推荐佣金');
+                $blance = bcadd($user['brokerage_price'], $brokerage, 2);
+                UserBill::income('全网分红', $user['uid'], 'brokerage_price', 'dividend', $brokerage, $id, $blance, '全网分红奖励');
+            }
+        }
+        return true;
+    }
+
+}

+ 281 - 0
app/models/user/UserGroupLevel.php

@@ -0,0 +1,281 @@
+<?php
+
+namespace app\models\user;
+
+use app\models\system\SystemGroupLevel;
+use app\models\system\SystemUserTask;
+use crmeb\basic\BaseModel;
+use crmeb\traits\ModelTrait;
+use think\db\exception\DataNotFoundException;
+use think\db\exception\DbException;
+use think\db\exception\ModelNotFoundException;
+use think\Model;
+
+/**
+ * TODO 会员等级Model
+ * Class UserLevel
+ * @package app\models\user
+ */
+class UserGroupLevel extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'user_group_level';
+
+    use ModelTrait;
+
+    /**
+     * 获取用户等级人数
+     * @param $uids
+     * @return int
+     */
+    public static function setUserLevelCount($uids)
+    {
+        $model = new self();
+        if (is_array($uids)) $model = $model->where('uid', 'in', $uids);
+        else $model = $model->where('uid', $uids);
+        return $model->count();
+    }
+
+    /**
+     * 设置查询初始化条件
+     * @param string $alias 表别名
+     * @param null $model 模型实例化对象
+     * @return UserLevel
+     */
+    public static function valiWhere($alias = '', $model = null)
+    {
+        $model = is_null($model) ? new self() : $model;
+        if ($alias) {
+            $model = $model->alias($alias);
+            $alias .= '.';
+        }
+        return $model->where("{$alias}status", 1)->where("{$alias}is_del", 0);
+    }
+
+    /**
+     * 设置会员等级
+     * @param int $uid 用户uid
+     * @param int $level_id 等级id
+     * @return UserLevel|bool|Model
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function setUserLevel($uid, $level_id)
+    {
+        $vipinfo = SystemGroupLevel::get($level_id);
+        if (!$vipinfo) return false;
+        $userinfo = User::find($uid);
+        if (!$userinfo) return false;
+        $add_valid_time = (int)$vipinfo->valid_date * 86400;
+        $uservipinfo = self::valiWhere()->where('uid', $uid)->where('level_id', $level_id)->find();
+        //检查是否购买过
+        if ($uservipinfo) {
+            $stay = 0;
+            //剩余时间
+            if (time() < $uservipinfo->valid_time) $stay = $uservipinfo->valid_time - time();
+            //如果购买过当前等级的会员过期了.从当前时间开始计算
+            //过期时效: 剩余时间+当前会员等级时间+当前time
+            $add_valid_time = $stay + $add_valid_time + time();
+            $data['is_forever'] = $vipinfo->is_forever;
+            $data['valid_time'] = $add_valid_time;
+            User::where('uid', $uid)->update(['level' => $level_id]);
+            return self::where('uid', $uid)->where('level_id', $level_id)->update($data);
+        } else {
+            $data = [
+                'is_forever' => $vipinfo->is_forever,
+                'status' => 1,
+                'is_del' => 0,
+                'grade' => $vipinfo->grade,
+                'uid' => $uid,
+                'add_time' => time(),
+                'level_id' => $level_id,
+                'discount' => $vipinfo->discount,
+            ];
+            if ($data['is_forever'])
+                $data['valid_time'] = 0;
+            else
+                $data['valid_time'] = $add_valid_time + time();
+            $data['mark'] = '尊敬的用户' . $userinfo['nickname'] . '在' . date('Y-m-d H:i:s', time()) . '成为了' . $vipinfo['name'];
+            $res = self::create($data);
+            if (!$res) return false;
+            User::where('uid', $uid)->update(['level' => $level_id]);
+            return $res;
+        }
+    }
+
+    /**
+     * 获取当前用户会员等级返回当前用户等级id
+     * @param int $uid 用户uid
+     * @param int $grade 会员id
+     * @return bool|mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getUserLevel($uid, $grade = 0)
+    {
+        $model = self::valiWhere();
+        if ($grade) $model = $model->where('grade', '<', $grade);
+        $level = $model->where('uid', $uid)->order('grade desc')->field('level_id,is_forever,valid_time,id,status,grade')->find();
+        if (!$level) return false;
+        if ($level->is_forever) return $level->id;
+        //会员已经过期
+        if (time() > $level->valid_time) {
+            if ($level->status == 1) {
+                $level->status = 0;
+                $level->save();
+            }
+            return self::getUserLevel($uid, $level->grade);
+        } else
+            //会员没有过期
+            return $level->id;
+    }
+
+    /**
+     * 获取会员详细信息
+     * @param $id 会员记录id
+     * @param string $keyName 字段名
+     * @return array|mixed|string|Model|null
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getUserLevelInfo($id, $keyName = '')
+    {
+        $vipinfo = self::valiWhere('a')->where('a.id', $id)->field('l.id,a.add_time,l.discount,a.level_id,l.name,l.money,l.icon,l.is_pay,l.grade')
+            ->join('system_user_level l', 'l.id=a.level_id')->find();
+        if ($keyName) if (isset($vipinfo[$keyName])) return $vipinfo[$keyName]; else return '';
+        return $vipinfo;
+    }
+
+    /**
+     * 获取当前用户已成为的vip id
+     * @param $uid 用户id
+     * @return array
+     */
+    public static function getUserLevelIds($uid)
+    {
+        return self::valiWhere()->group('level_id')->where('uid', $uid)->order('grade asc')->column('level_id', 'level_id');
+    }
+
+    /**
+     * 检查是否能成为会员
+     * @param int $uid 用户uid
+     * @param bool $leveNowId
+     * @return UserLevel|bool|Model
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws DbException
+     */
+    public static function setLevelComplete($uid, $leveNowId = false)
+    {
+        $user = User::where('uid', $uid)->find();
+        if (!$user) return self::setErrorInfo('没有此用户,无法检测升级会员');
+        $level = self::getUserLevel($uid);
+        if ($level === false)
+            $level_id = 0;
+        else
+            $level_id = self::getUserLevelInfo($level, 'level_id');
+        if (sys_config('level_type', 0) == 0) {
+            $leveNowId = SystemGroupLevel::getNextLevelId($level_id, SystemGroupLevel::setWhere()->where('grade', '>', $level ? self::getUserLevelInfo($level, 'grade') : 0)->min('grade'));
+            if ($leveNowId === 0) return self::setErrorInfo('暂无可升会员');
+            //查找当前需要升级的会员任务
+            $taskAll = SystemUserTask::visibleWhere()->where('level_id', $leveNowId)->column('id', 'id');
+            if (!$taskAll) return true;
+//            self::startTrans();
+            $res2 = true;
+            try {
+                if ($level === false) {
+                    //没有成为会员的从用户添加的时间开始算起,如果被清理过会员从清理的时间开始算起
+                    $add_time = $user['clean_time'] ? $user['clean_time'] : $user['add_time'];
+                } else {
+                    $add_time = self::getUserLevelInfo($level, 'add_time');
+                }
+                //查询并记录任务
+                foreach ($taskAll as $id) {
+                    $res = SystemUserTask::setTaskFinish($id, $uid, $add_time);
+                    if (!$res) return self::setErrorInfo(SystemUserTask::getErrorInfo());
+                }
+                //获取需要成为会员的任务完成度
+                if (SystemUserTask::getTaskComplete($leveNowId, $uid)) {
+                    //设置任务已使用
+                    $res = SystemUserTask::setTarkStatus($leveNowId, $uid);
+                    if (!$res) return self::setErrorInfo('设置任务状态失败');
+                    //记录会员
+                    $res2 = self::setUserLevel($uid, $leveNowId);
+                }
+//                self::commitTrans();
+                return $res2;
+            } catch (\Exception $e) {
+//                self::rollbackTrans();
+                return self::setErrorInfo($e->getMessage());
+            }
+        } else {
+            $leveNowId = SystemGroupLevel::getNextLevelId($level_id, SystemGroupLevel::setWhere()->max('grade'));
+//            self::startTrans();
+            try {
+                while (1) {
+                    if ($leveNowId === 0) return self::setErrorInfo('暂无可升会员');
+                    //查找当前需要升级的会员任务
+                    $taskAll = SystemUserTask::visibleWhere()->where('level_id', $leveNowId)->column('id', 'id');
+                    if (!$taskAll) {
+                        $leveNowGrade = SystemGroupLevel::where('id', $leveNowId)->value('grade');
+                        $leveNowId = SystemGroupLevel::getNextLevelId($level_id, $leveNowGrade - 1);
+                        if ($leveNowId) {
+                            continue;
+                        } else {
+                            return self::setErrorInfo('暂无可升会员');
+                        }
+                    }
+                    $res2 = true;
+                    if ($level === false) {
+                        //没有成为会员的从用户添加的时间开始算起,如果被清理过会员从清理的时间开始算起
+                        $add_time = $user['clean_time'] ? $user['clean_time'] : $user['add_time'];
+                    } else {
+                        $add_time = self::getUserLevelInfo($level, 'add_time');
+                    }
+                    //查询并记录任务
+                    foreach ($taskAll as $id) {
+                        $res = SystemUserTask::setTaskFinish($id, $uid, $add_time);
+                        if (!$res) return self::setErrorInfo(SystemUserTask::getErrorInfo());
+                    }
+                    //获取需要成为会员的任务完成度
+                    if (SystemUserTask::getTaskComplete($leveNowId, $uid)) {
+                        //设置任务已使用
+                        $res = SystemUserTask::setTarkStatus($leveNowId, $uid);
+                        if (!$res) return self::setErrorInfo('设置任务状态失败');
+                        //记录会员
+                        $res2 = self::setUserLevel($uid, $leveNowId);
+                    } else {
+                        $leveNowGrade = SystemGroupLevel::where('id', $leveNowId)->value('grade');
+                        $leveNowId = SystemGroupLevel::getNextLevelId($level_id, $leveNowGrade - 1);
+                        if ($leveNowId) {
+                            continue;
+                        }
+                    }
+                    if ($res2) {
+//                        self::commitTrans();
+                        return $res2;
+                    } else {
+//                        self::rollbackTrans();
+                        return $res2;
+                    }
+                }
+            } catch (\Exception $e) {
+//                self::rollbackTrans();
+                return self::setErrorInfo($e->getMessage());
+            }
+        }
+    }
+
+}