| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441 |
- <?php
- /**
- * 分销管理控制器
- */
- namespace app\admin\controller\order;
- use app\common\controller\Backend;
- use think\facade\Db;
- class Distribution extends Backend
- {
- protected array $noNeedLogin = ['*'];
- /**
- * 分销订单列表
- * @return void
- */
- public function index(): void
- {
- $where = [];
- // 分佣产品搜索
- if (!empty($this->request->get('product_name'))) {
- $productName = $this->request->get('product_name');
- $where[] = ['p.name', 'like', '%' . $productName . '%'];
- }
- // 分佣人搜索
- if (!empty($this->request->get('distributor_name'))) {
- $distributorName = $this->request->get('distributor_name');
- $where[] = ['du.name', 'like', '%' . $distributorName . '%'];
- }
- // 购买人搜索
- if (!empty($this->request->get('buyer_name'))) {
- $buyerName = $this->request->get('buyer_name');
- $where[] = ['bu.name', 'like', '%' . $buyerName . '%'];
- }
- // 关联订单号搜索
- if (!empty($this->request->get('order_no'))) {
- $orderNo = $this->request->get('order_no');
- $where[] = ['o.order_no', 'like', '%' . $orderNo . '%'];
- }
- // 状态筛选
- if (!empty($this->request->get('status'))) {
- $status = $this->request->get('status');
- $where['dr.status'] = $status;
- }
- // 创建时间范围筛选
- if (!empty($this->request->get('create_time_range'))) {
- $timeRange = $this->request->get('create_time_range');
- $timeArr = explode(' - ', $timeRange);
- if (count($timeArr) == 2) {
- $startTime = $timeArr[0];
- $endTime = $timeArr[1];
- $where[] = ['dr.create_time', '>=', $startTime . ' 00:00:00'];
- $where[] = ['dr.create_time', '<=', $endTime . ' 23:59:59'];
- }
- }
- // 排序
- $order = [];
- if (!empty($this->request->get('order'))) {
- $order_a = $this->request->get('order');
- $order_a = explode(',', $order_a);
- $order[$order_a[0]] = $order_a[1];
- } else {
- $order['dr.create_time'] = 'desc';
- }
- // 分页
- $page = $this->request->get('page', 1);
- $limit = $this->request->get('limit', 20);
- // 查询分销记录
- $distributionList = Db::name('distribution_record')
- ->alias('dr')
- ->leftJoin('order o', 'dr.order_id = o.id')
- ->leftJoin('product p', 'dr.product_id = p.id')
- ->leftJoin('user_on bu', 'dr.buyer_id = bu.id')
- ->leftJoin('user_on du', 'dr.distributor_id = du.id')
- ->field('
- dr.id,
- o.order_no,
- p.name as commission_product,
- bu.name as g_name,
- du.name as f_name,
- dr.commission_amount,
- dr.create_time,
- dr.status,
- dr.commission_rate
- ')
- ->where($where)
- ->order($order)
- ->paginate([
- 'list_rows' => $limit,
- 'page' => $page
- ]);
- // 状态转换
- $list = $distributionList->items();
- foreach ($list as &$item) {
- $statusMap = [
- 1 => '待结算',
- 2 => '已结算',
- 3 => '已取消'
- ];
- $item['status_text'] = $statusMap[$item['status']] ?? '未知';
- }
- $this->success('查询成功', [
- 'list' => $list,
- 'total' => $distributionList->total()
- ]);
- }
- /**
- * 获取分销设置
- * @return void
- */
- public function getSetting(): void
- {
- $setting = Db::name('distribution_setting')
- ->order('id', 'desc')
- ->find();
- if (!$setting) {
- // 如果不存在,创建默认设置
- $defaultSetting = [
- 'default_rate' => 15.00,
- 'min_withdrawal' => 20.00,
- 'max_withdrawal' => 50000.00,
- 'withdrawal_fee_rate' => 0.00,
- 'update_time' => date('Y-m-d H:i:s')
- ];
- Db::name('distribution_setting')->insert($defaultSetting);
- $setting = $defaultSetting;
- }
- $this->success('获取成功', $setting);
- }
- /**
- * 更新分销设置
- * @return void
- */
- public function updateSetting(): void
- {
- $defaultRate = $this->request->post('default_rate', 15.00);
- $minWithdrawal = $this->request->post('min_withdrawal', 20.00);
- $maxWithdrawal = $this->request->post('max_withdrawal', 50000.00);
- $withdrawalFeeRate = $this->request->post('withdrawal_fee_rate', 0.00);
- if ($defaultRate <= 0 || $defaultRate > 100) {
- $this->error(__('分销佣金比例必须在0-100之间'));
- }
- if ($minWithdrawal <= 0) {
- $this->error(__('最低提现金额必须大于0'));
- }
- if ($maxWithdrawal <= $minWithdrawal) {
- $this->error(__('最高提现金额必须大于最低提现金额'));
- }
- $data = [
- 'default_rate' => $defaultRate,
- 'min_withdrawal' => $minWithdrawal,
- 'max_withdrawal' => $maxWithdrawal,
- 'withdrawal_fee_rate' => $withdrawalFeeRate,
- 'update_time' => date('Y-m-d H:i:s')
- ];
- try {
- // 检查是否已有设置
- $existingSetting = Db::name('distribution_setting')->value('id');
- if ($existingSetting) {
- // 更新
- $result = Db::name('distribution_setting')
- ->where('id', $existingSetting)
- ->update($data);
- } else {
- // 新增
- $result = Db::name('distribution_setting')
- ->insert($data);
- }
- } catch (\Exception $e) {
- $this->error('操作失败: ' . $e->getMessage());
- }
- if ($result) {
- $this->success('更新成功');
- } else {
- $this->error(__('更新失败'));
- }
- }
- /**
- * 手动结算分销佣金
- * @return void
- */
- public function settleCommission(): void
- {
- $id = $this->request->post('id');
- if (empty($id)) {
- $this->error(__('参数错误'));
- }
- try {
- Db::startTrans();
- // 获取分销记录
- $distributionRecord = Db::name('distribution_record')
- ->where('id', $id)
- ->lock(true)
- ->find();
- if (!$distributionRecord) {
- throw new \Exception('分销记录不存在');
- }
- if ($distributionRecord['status'] != 1) {
- throw new \Exception('只有待结算的记录才能结算');
- }
- // 更新分销记录状态
- $updateResult = Db::name('distribution_record')
- ->where('id', $id)
- ->update([
- 'status' => 2,
- 'settle_time' => date('Y-m-d H:i:s')
- ]);
- if (!$updateResult) {
- throw new \Exception('更新分销记录失败');
- }
- // 更新用户佣金
- $userCommission = Db::name('user_commission')
- ->where('user_id', $distributionRecord['distributor_id'])
- ->lock(true)
- ->find();
- if ($userCommission) {
- // 更新现有记录
- $commissionResult = Db::name('user_commission')
- ->where('user_id', $distributionRecord['distributor_id'])
- ->update([
- 'total_commission' => Db::raw('total_commission + ' . $distributionRecord['commission_amount']),
- 'current_commission' => Db::raw('current_commission + ' . $distributionRecord['commission_amount']),
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- } else {
- // 创建新记录
- $commissionResult = Db::name('user_commission')
- ->insert([
- 'user_id' => $distributionRecord['distributor_id'],
- 'total_commission' => $distributionRecord['commission_amount'],
- 'current_commission' => $distributionRecord['commission_amount'],
- 'promotion_link' => 'xxxx.com?from=' . $distributionRecord['distributor_id'],
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- }
- if (!$commissionResult) {
- throw new \Exception('更新用户佣金失败');
- }
- Db::commit();
- $this->success('结算成功');
- } catch (\Exception $e) {
- Db::rollback();
- $this->error('结算失败: ' . $e->getMessage());
- }
- }
- /**
- * 批量结算分销佣金
- * @return void
- */
- public function batchSettle(): void
- {
- $ids = $this->request->post('ids');
- if (empty($ids)) {
- $this->error(__('参数错误'));
- }
- if (!is_array($ids)) {
- $ids = explode(',', $ids);
- }
- $successCount = 0;
- $failCount = 0;
- $messages = [];
- foreach ($ids as $id) {
- try {
- Db::startTrans();
- $distributionRecord = Db::name('distribution_record')
- ->where('id', $id)
- ->lock(true)
- ->find();
- if (!$distributionRecord) {
- throw new \Exception('分销记录不存在');
- }
- if ($distributionRecord['status'] != 1) {
- throw new \Exception('只有待结算的记录才能结算');
- }
- // 更新分销记录状态
- Db::name('distribution_record')
- ->where('id', $id)
- ->update([
- 'status' => 2,
- 'settle_time' => date('Y-m-d H:i:s')
- ]);
- // 更新用户佣金
- $userCommission = Db::name('user_commission')
- ->where('user_id', $distributionRecord['distributor_id'])
- ->lock(true)
- ->find();
- if ($userCommission) {
- Db::name('user_commission')
- ->where('user_id', $distributionRecord['distributor_id'])
- ->update([
- 'total_commission' => Db::raw('total_commission + ' . $distributionRecord['commission_amount']),
- 'current_commission' => Db::raw('current_commission + ' . $distributionRecord['commission_amount']),
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- } else {
- Db::name('user_commission')
- ->insert([
- 'user_id' => $distributionRecord['distributor_id'],
- 'total_commission' => $distributionRecord['commission_amount'],
- 'current_commission' => $distributionRecord['commission_amount'],
- 'promotion_link' => 'xxxx.com?from=' . $distributionRecord['distributor_id'],
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- }
- Db::commit();
- $successCount++;
- } catch (\Exception $e) {
- Db::rollback();
- $failCount++;
- $messages[] = "记录ID {$id}: " . $e->getMessage();
- }
- }
- $message = "结算完成,成功: {$successCount}条,失败: {$failCount}条";
- if (!empty($messages)) {
- $message .= "。失败原因:" . implode('; ', $messages);
- }
- $this->success($message);
- }
- /**
- * 分销统计
- * @return void
- */
- public function statistics(): void
- {
- // 总分销记录数
- $totalCount = Db::name('distribution_record')->count();
- // 待结算记录数
- $pendingCount = Db::name('distribution_record')
- ->where('status', 1)
- ->count();
- // 已结算记录数
- $settledCount = Db::name('distribution_record')
- ->where('status', 2)
- ->count();
- // 总分销金额
- $totalCommission = Db::name('distribution_record')
- ->where('status', 2)
- ->sum('commission_amount');
- // 今日分销统计
- $todayStart = date('Y-m-d 00:00:00');
- $todayEnd = date('Y-m-d 23:59:59');
- $todayCount = Db::name('distribution_record')
- ->whereBetween('create_time', [$todayStart, $todayEnd])
- ->count();
- $todayCommission = Db::name('distribution_record')
- ->whereBetween('create_time', [$todayStart, $todayEnd])
- ->sum('commission_amount');
- // 分销人数统计
- $distributorCount = Db::name('distribution_record')
- ->distinct(true)
- ->field('distributor_id')
- ->count();
- $stats = [
- 'total_count' => $totalCount,
- 'pending_count' => $pendingCount,
- 'settled_count' => $settledCount,
- 'total_commission' => $totalCommission ?? 0,
- 'today_count' => $todayCount,
- 'today_commission' => $todayCommission ?? 0,
- 'distributor_count' => $distributorCount
- ];
- $this->success('获取成功', $stats);
- }
- /**
- * 获取分销状态选项
- * @return void
- */
- public function statusOptions(): void
- {
- $options = [
- ['value' => 1, 'label' => '待结算'],
- ['value' => 2, 'label' => '已结算'],
- ['value' => 3, 'label' => '已取消']
- ];
- $this->success('获取成功', $options);
- }
- }
|