Browse Source

fix:分销商

super-yimizi 1 day ago
parent
commit
bfe42ed880

+ 96 - 25
application/admin/controller/commission/Agent.php

@@ -85,7 +85,13 @@ class Agent extends Backend
         ->find();
         if (!$row) {
             $this->error(__('No Results were found'));
-        }       
+        }
+        
+        // 如果expire_time为空,设置默认值为become_time + 1年
+        // if (!$row->expire_time && $row->become_time) {
+        //     $row->expire_time = strtotime('+1 year', $row->become_time);
+        // }
+    
         $this->view->assign('row', $row);
         return $this->view->fetch();
     }
@@ -166,34 +172,33 @@ class Agent extends Backend
      *
      * @param  $id
      */
-    public function edit($id = null)
+    public function edit($ids = null)
     {
         $params = $this->request->only(['status', 'upgrade_lock', 'level_status', 'level']);
-
-        $result = Db::transaction(function () use ($id, $params) {
-            $row = $this->model->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])->where('user_id', $id)->find();
-            if (!$row) {
-                $this->error('未找到该分销商');
-            }
-
-            foreach ($params as $field => $value) {
-                switch ($field) {
-                    case 'status':  // 修改状态
-                        return $this->changeStatus($row, $value);
-                        break;
-                    case 'level_status':    // 审核等级
-                        return $this->changeLevelStatus($row, $value);
-                        break;
-                    case 'level':           // 修改等级
-                        return $this->changeLevel($row, $value);
-                        break;
-                    default:
-                        return $row->save([$field => $value]);
-                }
+        $row = $this->model->with(['user', 'level_info', 'level_status_info', 'upgrade_level'])->where('user_id', $ids)->find();
+        if (!$row) {
+            $this->error('未找到该分销商');
+        }
+        
+        $result = false;
+        foreach ($params as $field => $value) {
+            switch ($field) {
+                case 'status':  // 修改状态
+                    $result = $this->changeStatus($row, $value);
+                    break;
+                case 'level_status':    // 审核等级
+                    $result = $this->changeLevelStatus($row, $value);
+                    break;
+                case 'level':           // 修改等级
+                    $result = $this->changeLevel($row, $value);
+                    break;
+                default:
+                    $result = $row->save([$field => $value]);
             }
-        });
+        }
+        
         if ($result) {
-            $this->success('更新成功', null, $result);
+            $this->success('更新成功');
         } else {
             $this->error('更新失败');
         }
@@ -204,6 +209,7 @@ class Agent extends Backend
     private function changeStatus($row, $value)
     {
         $result = $row->save(['status' => $value]);
+       
         if ($result) {
             LogModel::add($row->user_id, 'agent', ['type' => 'status', 'value' => $value]);
             (new AgentService($row->user_id))->createAsyncAgentUpgrade();
@@ -317,4 +323,69 @@ class Agent extends Backend
 
         return false;
     }
+
+    /**
+     * 更新分销商到期时间
+     */
+    public function updateExpireTime()
+    {
+        $userId = $this->request->param('user_id');
+        $expireTime = $this->request->param('expire_time');
+        
+        if (!$userId) {
+            $this->error(__('参数错误'));
+        }
+
+        // 验证分销商是否存在
+        $agent = AgentModel::get($userId);
+        if (!$agent) {
+            $this->error(__('分销商不存在'));
+        }
+
+        // 验证时间格式
+        if ($expireTime && !strtotime($expireTime)) {
+            $this->error(__('时间格式不正确'));
+        }
+
+        // try {
+            // 更新到期时间
+            $updateData = [];
+            if ($expireTime) {
+                $updateData['expire_time'] = strtotime($expireTime);
+            } else {
+                $updateData['expire_time'] = null; // 设置为null表示永久有效
+            }
+
+            $result = AgentModel::where('user_id', $userId)->update($updateData);
+            
+            if ($result !== false) {
+                $this->success(__('修改成功'));
+            } else {
+                $this->error(__('修改失败'));
+            }
+        // } catch (\Exception $e) {
+        //     $this->error(__('修改失败: %s', $e->getMessage()));
+        // }
+    }
+
+    /**
+     * 设置默认到期时间
+     * 在用户成为分销商时调用,设置默认到期时间为成为分销商时间+1年
+     */
+    public function setDefaultExpireTime($userId, $becomeTime = null)
+    {
+        if (!$becomeTime) {
+            $becomeTime = time(); // 如果没有传入成为分销商时间,使用当前时间
+        }
+
+        // 计算默认到期时间(1年后)
+        $expireTime = strtotime('+1 year', $becomeTime);
+
+        // 更新到期时间
+        AgentModel::where('user_id', $userId)->update([
+            'expire_time' => $expireTime
+        ]);
+
+        return $expireTime;
+    }
 }

+ 81 - 4
application/admin/view/commission/agent/detail.html

@@ -54,9 +54,11 @@
                                     {case value="reject"}<span class="label label-danger">拒绝</span>{/case}
                                     {default /}<span class="label label-default">{$row.status}</span>
                                     {/switch}
-                                    <!-- {if $auth->check('commission/agent/edit')}
-                                    <button class="btn btn-xs btn-warning" onclick="changeStatus({$row.user_id}, '{$row.status}')">修改状态</button>
-                                    {/if} -->
+                                    {if $auth->check('commission/agent/edit')}
+                                    <button class="btn btn-xs btn-warning btn-edit-status" 
+                                            data-user-id="{$row.user_id}" 
+                                            data-current-status="{$row.status}">修改状态</button>
+                                    {/if}
                                 </td>
                             </tr>
                             <tr>
@@ -97,7 +99,18 @@
                             </tr> -->
                             <tr>
                                 <td>成为分销商时间</td>
-                                <td>{$row.become_time|datetime}</td>
+                                <td>{$row.become_time|date='Y-m-d H:i:s',###}</td>
+                            </tr>
+                            <tr>
+                                <td>分销商到期时间</td>
+                                <td>
+                                    <span id="expire-time-display">{$row.expire_time|date='Y-m-d H:i:s',###}</span>
+                                    {if $auth->check('commission/agent/edit')}
+                                    <button class="btn btn-xs btn-warning btn-edit-expire-time" 
+                                            data-user-id="{$row.user_id}" 
+                                            data-expire-time="{$row.expire_time|default=''}">修改到期时间</button>
+                                    {/if}
+                                </td>
                             </tr>
                         </table>
                     </div>
@@ -216,3 +229,67 @@
         </div>
     </div>
 </div>
+
+<script type="text/html" id="expiretimetpl">
+    <div style="padding:15px 15px 0 15px;">
+        <form role="expiretimeform">
+            <ul class="list-group">
+                <li class="list-group-item" style="border: none; padding: 10px 15px;">
+                    <div class="form-group" style="margin-bottom: 0;">
+                        <label class="control-label" style="width: 85px; float: left; line-height: 34px;">到期时间:</label>
+                        <input type="hidden" id="user_id" value="<%=userId%>" />
+                        <div style="margin-left: 95px;">
+                            <div class='input-group date datetimepicker'>
+                                <input type='text' name="expire_time" id="expire_time" 
+                                       data-date-format="YYYY-MM-DD HH:mm:ss" 
+                                       value="<%=currentTime%>" 
+                                       placeholder="请选择到期时间,留空为永久有效" 
+                                       class="form-control datetimepicker"/>
+                                <span class="input-group-addon">
+                                    <span class="fa fa-calendar"></span>
+                                </span>
+                            </div>
+                        </div>
+                    </div>
+                </li>
+                <li class="list-group-item">
+                    <small class="text-muted">
+                        <i class="fa fa-info-circle"></i> 
+                        时间格式:2024-01-01 00:00:00,留空表示永久有效
+                    </small>
+                </li>
+            </ul>
+        </form>
+    </div>
+</script>
+
+<script type="text/html" id="statusedittml">
+    <div style="padding:15px 15px 0 15px;">
+        <form role="statuseditform">
+            <ul class="list-group">
+                <li class="list-group-item" style="border: none; padding: 10px 15px;">
+                    <div class="form-group" style="margin-bottom: 0;">
+                        <label class="control-label" style="width: 85px; float: left; line-height: 34px;">状态选择:</label>
+                        <input type="hidden" id="status_user_id" value="<%=userId%>" />
+                        <div style="margin-left: 95px;">
+                            <div class="radio-group">
+                                <label class="radio-inline">
+                                    <input type="radio" name="status" value="normal" <%=currentStatus=='normal'?'checked':''%>> 正常
+                                </label>
+                                <label class="radio-inline" style="margin-left: 20px;">
+                                    <input type="radio" name="status" value="freeze" <%=currentStatus=='freeze'?'checked':''%>> 冻结
+                                </label>
+                            </div>
+                        </div>
+                    </div>
+                </li>
+                <li class="list-group-item">
+                    <small class="text-muted">
+                        <i class="fa fa-info-circle"></i> 
+                        选择分销商状态:正常表示可以正常分销,冻结表示暂停分销
+                    </small>
+                </li>
+            </ul>
+        </form>
+    </div>
+</script>

+ 1 - 0
application/common/Service/Commission/AgentApply.php

@@ -331,6 +331,7 @@ class AgentApply
 
         // 生成唯一邀请码
         $agent->invite_code = $this->generateInviteCode();
+        $agent->expire_time = time() + 365 * 24 * 60 * 60;
 
         $agent->save();
 

+ 149 - 138
application/common/model/commission/Agent.php

@@ -1,138 +1,149 @@
-<?php
-
-namespace app\common\model\commission;
-
-use app\common\model\User;
-use app\common\Enum\AgentType;
-use app\common\library\BcMath;
-use app\common\model\commission\Level;
-use app\common\model\commission\Reward;
-use think\Model;
-class Agent  extends Model
-{
-    protected $pk = 'user_id';
-
-    protected $name = 'shop_commission_agent';
-
-    protected $type = [
-        'become_time' => 'timestamp',
-        'child_agent_level_1' => 'json',
-        'child_agent_level_all' => 'json',
-    ];
-    protected $append = [
-        'status_text',
-        'agent_type_text',
-        'pending_reward',
-        'commission_balance'
-    ];
-
-    // 分销商状态 AGENT_STATUS
-    const AGENT_STATUS_NORMAL = 'normal';       // 正常 
-    const AGENT_STATUS_PENDING = 'pending';     // 审核中 不分佣、不打款、没有团队信息
-    const AGENT_STATUS_FREEZE = 'freeze';       // 冻结 正常记录分佣、不打款,记录业绩和团队信息 冻结解除后立即打款
-    const AGENT_STATUS_FORBIDDEN = 'forbidden'; // 禁用 不分佣、不记录业绩和团队信息
-    const AGENT_STATUS_NEEDINFO = 'needinfo';   // 需要完善表单资料 临时状态
-    const AGENT_STATUS_REJECT = 'reject';       // 审核驳回, 重新修改   临时状态
-    const AGENT_STATUS_NULL = NULL;             // 未满足成为分销商条件
-
-
-    // 分销商升级锁 UPGRADE_LOCK
-    const UPGRADE_LOCK_OPEN = 1;  // 禁止分销商升级
-    const UPGRADE_LOCK_CLOSE = 0;  // 允许分销商升级
-
-    public function statusList()
-    {
-        return [
-            self::AGENT_STATUS_NORMAL => '正常',
-            self::AGENT_STATUS_PENDING => '审核中',
-            self::AGENT_STATUS_FREEZE => '冻结',
-            self::AGENT_STATUS_FORBIDDEN => '禁用',
-            self::AGENT_STATUS_REJECT => '拒绝'
-        ];
-    }
-
-    /**
-     * 获取状态文本
-     */
-    public function getStatusTextAttr($value, $data)
-    {
-        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
-        $statusList = $this->statusList();
-        return isset($statusList[$value]) ? $statusList[$value] : '正常';
-    }
-
-    /**
-     * 获取代理商类型文本
-     */
-    public function getAgentTypeTextAttr($value, $data)
-    {
-        $value = $value ? $value : (isset($data['agent_type']) ? $data['agent_type'] : 'normal');
-        return AgentType::getTypeText($value);
-    }
-
-    /**
-     * 可用分销商
-     */
-    public function scopeAvaliable($query)
-    {
-        return $query->where('status', 'in', [self::AGENT_STATUS_NORMAL, self::AGENT_STATUS_FREEZE]);
-    }
-
-    public function user()
-    {
-        return $this->belongsTo(User::class, 'user_id', 'id')->field('id, nickname, avatar, mobile, total_consume, parent_user_id');
-    }
-
-    public function levelInfo()
-    {
-        return $this->belongsTo(Level::class, 'level', 'level')->field(['level', 'name', 'image', 'commission_rules']);
-    }
-    
-    // 添加蛇形命名的关联方法别名
-    public function level_info()
-    {
-        return $this->levelInfo();
-    }
-
-    public function getPendingRewardAttr($value, $data)
-    {
-        $amount = Reward::pending()->where('agent_id', $data['user_id'])->sum('commission');
-        // 使用BcMath工具类格式化金额,确保精度
-        return BcMath::format($amount);
-    }
-
-    /**
-     * 获取佣金余额(累计收益 - 已提现金额)
-     */
-    public function getCommissionBalanceAttr($value, $data)
-    {
-        $totalIncome = $data['total_income'] ?? '0.00';
-        $withdrawnAmount = $data['withdrawn_amount'] ?? '0.00';
-        
-        // 使用BcMath工具类计算余额,并确保不为负数
-        $balance = BcMath::sub($totalIncome, $withdrawnAmount);
-        return BcMath::max($balance);
-    }
-
-    public function levelStatusInfo()
-    {
-        return $this->belongsTo(Level::class, 'level_status', 'level');
-    }
-    
-    // 添加蛇形命名的关联方法别名
-    public function level_status_info()
-    {
-        return $this->levelStatusInfo();
-    }
-
-    public function upgradeLevel()
-    {
-        return $this->belongsTo(Level::class, 'level_status', 'level');
-    }
-    
-    // 添加蛇形命名的关联方法别名
-    public function upgrade_level()
-    {
-        return $this->upgradeLevel();
-    }
-}
+<?php
+
+namespace app\common\model\commission;
+
+use app\common\model\User;
+use app\common\Enum\AgentType;
+use app\common\library\BcMath;
+use app\common\model\commission\Level;
+use app\common\model\commission\Reward;
+use think\Model;
+class Agent  extends Model
+{
+    protected $pk = 'user_id';
+
+    protected $name = 'shop_commission_agent';
+
+    protected $type = [
+        'become_time' => 'timestamp',
+        'expire_time' => 'timestamp',
+        'child_agent_level_1' => 'json',
+        'child_agent_level_all' => 'json',
+    ];
+    protected $append = [
+        'status_text',
+        'agent_type_text',
+        'pending_reward',
+        'commission_balance'
+    ];
+
+    // 分销商状态 AGENT_STATUS
+    const AGENT_STATUS_NORMAL = 'normal';       // 正常 
+    const AGENT_STATUS_PENDING = 'pending';     // 审核中 不分佣、不打款、没有团队信息
+    const AGENT_STATUS_FREEZE = 'freeze';       // 冻结 正常记录分佣、不打款,记录业绩和团队信息 冻结解除后立即打款
+    const AGENT_STATUS_FORBIDDEN = 'forbidden'; // 禁用 不分佣、不记录业绩和团队信息
+    const AGENT_STATUS_NEEDINFO = 'needinfo';   // 需要完善表单资料 临时状态
+    const AGENT_STATUS_REJECT = 'reject';       // 审核驳回, 重新修改   临时状态
+    const AGENT_STATUS_NULL = NULL;             // 未满足成为分销商条件
+
+
+    // 分销商升级锁 UPGRADE_LOCK
+    const UPGRADE_LOCK_OPEN = 1;  // 禁止分销商升级
+    const UPGRADE_LOCK_CLOSE = 0;  // 允许分销商升级
+
+    public function statusList()
+    {
+        return [
+            self::AGENT_STATUS_NORMAL => '正常',
+            self::AGENT_STATUS_PENDING => '审核中',
+            self::AGENT_STATUS_FREEZE => '冻结',
+            self::AGENT_STATUS_FORBIDDEN => '禁用',
+            self::AGENT_STATUS_REJECT => '拒绝'
+        ];
+    }
+
+    // public function getExpireTimeAttr($value, $data)
+    // {
+    //     // 时间格式
+    //     if ($value) {
+    //         return date('Y-m-d H:i:s', $value);
+    //     }
+    //     return '';
+
+    // }
+
+    /**
+     * 获取状态文本
+     */
+    public function getStatusTextAttr($value, $data)
+    {
+        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
+        $statusList = $this->statusList();
+        return isset($statusList[$value]) ? $statusList[$value] : '正常';
+    }
+
+    /**
+     * 获取代理商类型文本
+     */
+    public function getAgentTypeTextAttr($value, $data)
+    {
+        $value = $value ? $value : (isset($data['agent_type']) ? $data['agent_type'] : 'normal');
+        return AgentType::getTypeText($value);
+    }
+
+    /**
+     * 可用分销商
+     */
+    public function scopeAvaliable($query)
+    {
+        return $query->where('status', 'in', [self::AGENT_STATUS_NORMAL, self::AGENT_STATUS_FREEZE]);
+    }
+
+    public function user()
+    {
+        return $this->belongsTo(User::class, 'user_id', 'id')->field('id, nickname, avatar, mobile, total_consume, parent_user_id');
+    }
+
+    public function levelInfo()
+    {
+        return $this->belongsTo(Level::class, 'level', 'level')->field(['level', 'name', 'image', 'commission_rules']);
+    }
+    
+    // 添加蛇形命名的关联方法别名
+    public function level_info()
+    {
+        return $this->levelInfo();
+    }
+
+    public function getPendingRewardAttr($value, $data)
+    {
+        $amount = Reward::pending()->where('agent_id', $data['user_id'])->sum('commission');
+        // 使用BcMath工具类格式化金额,确保精度
+        return BcMath::format($amount);
+    }
+
+    /**
+     * 获取佣金余额(累计收益 - 已提现金额)
+     */
+    public function getCommissionBalanceAttr($value, $data)
+    {
+        $totalIncome = $data['total_income'] ?? '0.00';
+        $withdrawnAmount = $data['withdrawn_amount'] ?? '0.00';
+        
+        // 使用BcMath工具类计算余额,并确保不为负数
+        $balance = BcMath::sub($totalIncome, $withdrawnAmount);
+        return BcMath::max($balance);
+    }
+
+    public function levelStatusInfo()
+    {
+        return $this->belongsTo(Level::class, 'level_status', 'level');
+    }
+    
+    // 添加蛇形命名的关联方法别名
+    public function level_status_info()
+    {
+        return $this->levelStatusInfo();
+    }
+
+    public function upgradeLevel()
+    {
+        return $this->belongsTo(Level::class, 'level_status', 'level');
+    }
+    
+    // 添加蛇形命名的关联方法别名
+    public function upgrade_level()
+    {
+        return $this->upgradeLevel();
+    }
+}

+ 113 - 16
public/assets/js/backend/commission/agent.js

@@ -20,6 +20,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                 url: $.fn.bootstrapTable.defaults.extend.index_url,
                 pk: 'user_id',
                 sortName: 'user_id',
+                fixedColumns: true, // 启用固定列功能
+                fixedRightNumber: 1, // 固定右侧最后1列(操作列)
                 columns: [
                     [
                         {checkbox: true},
@@ -194,23 +196,118 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
             }
 
             // 详情页面特有的全局函数
-            window.changeStatus = function(userId, currentStatus) {
-                Layer.prompt({
-                    title: '修改状态',
-                    formType: 2,
-                    value: currentStatus,
-                    select: ['normal', 'pending', 'freeze', 'forbidden', 'reject'],
-                    selectTips: ['正常', '审核中', '冻结', '禁用', '拒绝']
-                }, function(value, index) {
-                    Fast.api.ajax({
-                        url: 'commission/agent/edit',
-                        data: {ids: userId, status: value}
-                    }, function() {
-                        Layer.close(index);
-                        location.reload();
-                    });
+            // 修改状态事件委托
+            $(document).on('click', '.btn-edit-status', function () {
+                var userId = $(this).data('user-id');
+                var currentStatus = $(this).data('current-status') || 'normal';
+                
+                var html = Template('statusedittml', {
+                    currentStatus: currentStatus,
+                    userId: userId
                 });
-            };
+                
+                layer.open({
+                    type: 1,
+                    skin: 'layui-layer-demo',
+                    title: '修改分销商状态',
+                    anim: 2,
+                    area: ['400px', '280px'],
+                    shadeClose: 1,
+                    content: html,
+                    btn: ['确定', '取消'],
+                    zIndex: 999999,
+                    yes: function (index) {
+                        var newStatus = $('input[name="status"]:checked').val();
+                        
+                        if (!newStatus) {
+                            Toastr.error('请选择状态');
+                            return false;
+                        }
+                        
+                        // 发送AJAX请求
+                        Fast.api.ajax({
+                            url: 'commission/agent/edit',
+                            data: {
+                                ids: $('#status_user_id').val(),
+                                status: newStatus
+                            }
+                        }, function(data, ret) {
+                            window.location.reload();
+                            Toastr.success('修改成功');
+                            layer.close(index);
+                        });
+                    },
+                    success: function (layero, index) {
+                        // 使用FastAdmin标准方式绑定表单事件
+                        Form.api.bindevent(layero.find("form"));
+                    }
+                });
+            });
+
+            // 修改到期时间 - 使用事件委托
+            $(document).on('click', '.btn-edit-expire-time', function () {
+                var userId = $(this).data('user-id');
+                var expireTime = $(this).data('expire-time');
+                
+                // 将时间戳转换为日期字符串
+                var currentTime = '';
+                if (expireTime && expireTime != '') {
+                    var date = new Date(expireTime * 1000);
+                    currentTime = date.getFullYear() + '-' + 
+                                 String(date.getMonth() + 1).padStart(2, '0') + '-' + 
+                                 String(date.getDate()).padStart(2, '0') + ' ' +
+                                 String(date.getHours()).padStart(2, '0') + ':' +
+                                 String(date.getMinutes()).padStart(2, '0') + ':' +
+                                 String(date.getSeconds()).padStart(2, '0');
+                }
+                
+                // 使用Template渲染HTML
+                var html = Template('expiretimetpl', {
+                    currentTime: currentTime,
+                    userId: userId
+                });
+                
+                layer.open({
+                    type: 1,
+                    skin: 'layui-layer-demo',
+                    title: '修改分销商到期时间',
+                    anim: 2,
+                    area: ['500px', '500px'],
+                    shadeClose: 1,
+                    content: html,
+                    btn: ['确定', '取消'],
+                    zIndex: 999999,
+                    yes: function (index) {
+                        var newTime = ($('#expire_time').val()).trim();
+                        
+                        // 验证时间格式
+                        if (newTime && !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(newTime)) {
+                            Toastr.error('时间格式不正确,请使用格式: 2024-01-01 00:00:00');
+                            return;
+                        }
+                        
+                        var userId = $('#user_id').val();
+                        
+                        Fast.api.ajax({
+                            url: 'commission/agent/updateExpireTime',
+                            data: {
+                                user_id: userId,
+                                expire_time: newTime
+                            }
+                        }, function(data, ret) {
+                            window.location.reload();
+                            Toastr.success('修改成功');
+                            layer.close(index);
+                        });
+                    },
+                    success: function (layero, index) {
+                        // 使用FastAdmin标准方式绑定表单事件
+                        Form.api.bindevent(layero.find("form"));
+                        
+
+                    }
+                });
+            });
 
             window.changeLevel = function(userId) {
                 Toastr.info('等级修改功能待完善');