Distribution.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. /**
  3. * 分销管理控制器
  4. */
  5. namespace app\admin\controller\distribution;
  6. use app\common\controller\Backend;
  7. use think\facade\Db;
  8. class Distribution extends Backend
  9. {
  10. protected array $noNeedLogin = ['*'];
  11. /**
  12. * 分销订单列表
  13. * @return void
  14. */
  15. public function index(): void
  16. {
  17. $where = [];
  18. // 分佣产品搜索
  19. if (!empty($this->request->get('product_name'))) {
  20. $productName = $this->request->get('product_name');
  21. $where[] = ['p.name', 'like', '%' . $productName . '%'];
  22. }
  23. // 分佣人搜索
  24. if (!empty($this->request->get('distributor_name'))) {
  25. $distributorName = $this->request->get('distributor_name');
  26. $where[] = ['du.name', 'like', '%' . $distributorName . '%'];
  27. }
  28. // 购买人搜索
  29. if (!empty($this->request->get('buyer_name'))) {
  30. $buyerName = $this->request->get('buyer_name');
  31. $where[] = ['bu.name', 'like', '%' . $buyerName . '%'];
  32. }
  33. // 关联订单号搜索
  34. if (!empty($this->request->get('order_no'))) {
  35. $orderNo = $this->request->get('order_no');
  36. $where[] = ['o.order_no', 'like', '%' . $orderNo . '%'];
  37. }
  38. // 状态筛选
  39. if (!empty($this->request->get('status'))) {
  40. $status = $this->request->get('status');
  41. $where['dr.status'] = $status;
  42. }
  43. // 创建时间范围筛选
  44. if (!empty($this->request->get('create_time_range'))) {
  45. $timeRange = $this->request->get('create_time_range');
  46. $timeArr = explode(' - ', $timeRange);
  47. if (count($timeArr) == 2) {
  48. $startTime = $timeArr[0];
  49. $endTime = $timeArr[1];
  50. $where[] = ['dr.create_time', '>=', $startTime . ' 00:00:00'];
  51. $where[] = ['dr.create_time', '<=', $endTime . ' 23:59:59'];
  52. }
  53. }
  54. // 排序
  55. $order = [];
  56. if (!empty($this->request->get('order'))) {
  57. $order_a = $this->request->get('order');
  58. $order_a = explode(',', $order_a);
  59. $order[$order_a[0]] = $order_a[1];
  60. } else {
  61. $order['dr.create_time'] = 'desc';
  62. }
  63. // 分页
  64. $page = $this->request->get('page', 1);
  65. $limit = $this->request->get('limit', 20);
  66. // 查询分销记录
  67. $distributionList = Db::name('distribution_record')
  68. ->alias('dr')
  69. ->leftJoin('order o', 'dr.order_id = o.id')
  70. ->leftJoin('product p', 'dr.product_id = p.id')
  71. ->leftJoin('user bu', 'dr.buyer_id = bu.id')
  72. ->leftJoin('user du', 'dr.distributor_id = du.id')
  73. ->field('
  74. dr.id as 编号,
  75. o.order_no as 关联订单号,
  76. p.name as 分佣产品,
  77. bu.name as 购买人,
  78. du.name as 分佣人,
  79. dr.commission_amount as 分佣金额,
  80. dr.create_time as 创建时间,
  81. dr.status,
  82. dr.commission_rate
  83. ')
  84. ->where($where)
  85. ->order($order)
  86. ->paginate([
  87. 'list_rows' => $limit,
  88. 'page' => $page
  89. ]);
  90. // 状态转换
  91. $list = $distributionList->items();
  92. foreach ($list as &$item) {
  93. $statusMap = [
  94. 1 => '待结算',
  95. 2 => '已结算',
  96. 3 => '已取消'
  97. ];
  98. $item['status_text'] = $statusMap[$item['status']] ?? '未知';
  99. }
  100. $this->success('查询成功', [
  101. 'list' => $list,
  102. 'total' => $distributionList->total()
  103. ]);
  104. }
  105. /**
  106. * 获取分销设置
  107. * @return void
  108. */
  109. public function getSetting(): void
  110. {
  111. $setting = Db::name('distribution_setting')
  112. ->order('id', 'desc')
  113. ->find();
  114. if (!$setting) {
  115. // 如果不存在,创建默认设置
  116. $defaultSetting = [
  117. 'default_rate' => 15.00,
  118. 'min_withdrawal' => 20.00,
  119. 'max_withdrawal' => 50000.00,
  120. 'withdrawal_fee_rate' => 0.00,
  121. 'update_time' => date('Y-m-d H:i:s')
  122. ];
  123. Db::name('distribution_setting')->insert($defaultSetting);
  124. $setting = $defaultSetting;
  125. }
  126. $this->success('获取成功', $setting);
  127. }
  128. /**
  129. * 更新分销设置
  130. * @return void
  131. */
  132. public function updateSetting(): void
  133. {
  134. $defaultRate = $this->request->post('default_rate', 15.00);
  135. $minWithdrawal = $this->request->post('min_withdrawal', 20.00);
  136. $maxWithdrawal = $this->request->post('max_withdrawal', 50000.00);
  137. $withdrawalFeeRate = $this->request->post('withdrawal_fee_rate', 0.00);
  138. if ($defaultRate <= 0 || $defaultRate > 100) {
  139. $this->error(__('分销佣金比例必须在0-100之间'));
  140. }
  141. if ($minWithdrawal <= 0) {
  142. $this->error(__('最低提现金额必须大于0'));
  143. }
  144. if ($maxWithdrawal <= $minWithdrawal) {
  145. $this->error(__('最高提现金额必须大于最低提现金额'));
  146. }
  147. $data = [
  148. 'default_rate' => $defaultRate,
  149. 'min_withdrawal' => $minWithdrawal,
  150. 'max_withdrawal' => $maxWithdrawal,
  151. 'withdrawal_fee_rate' => $withdrawalFeeRate,
  152. 'update_time' => date('Y-m-d H:i:s')
  153. ];
  154. try {
  155. // 检查是否已有设置
  156. $existingSetting = Db::name('distribution_setting')->find();
  157. if ($existingSetting) {
  158. // 更新
  159. $result = Db::name('distribution_setting')
  160. ->where('id', $existingSetting['id'])
  161. ->update($data);
  162. } else {
  163. // 新增
  164. $result = Db::name('distribution_setting')
  165. ->insert($data);
  166. }
  167. if ($result) {
  168. $this->success('更新成功');
  169. } else {
  170. $this->error(__('更新失败'));
  171. }
  172. } catch (\Exception $e) {
  173. $this->error('操作失败: ' . $e->getMessage());
  174. }
  175. }
  176. /**
  177. * 手动结算分销佣金
  178. * @return void
  179. */
  180. public function settleCommission(): void
  181. {
  182. $id = $this->request->post('id');
  183. if (empty($id)) {
  184. $this->error(__('参数错误'));
  185. }
  186. try {
  187. Db::startTrans();
  188. // 获取分销记录
  189. $distributionRecord = Db::name('distribution_record')
  190. ->where('id', $id)
  191. ->lock(true)
  192. ->find();
  193. if (!$distributionRecord) {
  194. throw new \Exception('分销记录不存在');
  195. }
  196. if ($distributionRecord['status'] != 1) {
  197. throw new \Exception('只有待结算的记录才能结算');
  198. }
  199. // 更新分销记录状态
  200. $updateResult = Db::name('distribution_record')
  201. ->where('id', $id)
  202. ->update([
  203. 'status' => 2,
  204. 'settle_time' => date('Y-m-d H:i:s')
  205. ]);
  206. if (!$updateResult) {
  207. throw new \Exception('更新分销记录失败');
  208. }
  209. // 更新用户佣金
  210. $userCommission = Db::name('user_commission')
  211. ->where('user_id', $distributionRecord['distributor_id'])
  212. ->lock(true)
  213. ->find();
  214. if ($userCommission) {
  215. // 更新现有记录
  216. $commissionResult = Db::name('user_commission')
  217. ->where('user_id', $distributionRecord['distributor_id'])
  218. ->update([
  219. 'total_commission' => Db::raw('total_commission + ' . $distributionRecord['commission_amount']),
  220. 'current_commission' => Db::raw('current_commission + ' . $distributionRecord['commission_amount']),
  221. 'update_time' => date('Y-m-d H:i:s')
  222. ]);
  223. } else {
  224. // 创建新记录
  225. $commissionResult = Db::name('user_commission')
  226. ->insert([
  227. 'user_id' => $distributionRecord['distributor_id'],
  228. 'total_commission' => $distributionRecord['commission_amount'],
  229. 'current_commission' => $distributionRecord['commission_amount'],
  230. 'promotion_link' => 'xxxx.com?from=' . $distributionRecord['distributor_id'],
  231. 'update_time' => date('Y-m-d H:i:s')
  232. ]);
  233. }
  234. if (!$commissionResult) {
  235. throw new \Exception('更新用户佣金失败');
  236. }
  237. Db::commit();
  238. $this->success('结算成功');
  239. } catch (\Exception $e) {
  240. Db::rollback();
  241. $this->error('结算失败: ' . $e->getMessage());
  242. }
  243. }
  244. /**
  245. * 批量结算分销佣金
  246. * @return void
  247. */
  248. public function batchSettle(): void
  249. {
  250. $ids = $this->request->post('ids');
  251. if (empty($ids)) {
  252. $this->error(__('参数错误'));
  253. }
  254. if (!is_array($ids)) {
  255. $ids = explode(',', $ids);
  256. }
  257. $successCount = 0;
  258. $failCount = 0;
  259. $messages = [];
  260. foreach ($ids as $id) {
  261. try {
  262. Db::startTrans();
  263. $distributionRecord = Db::name('distribution_record')
  264. ->where('id', $id)
  265. ->lock(true)
  266. ->find();
  267. if (!$distributionRecord) {
  268. throw new \Exception('分销记录不存在');
  269. }
  270. if ($distributionRecord['status'] != 1) {
  271. throw new \Exception('只有待结算的记录才能结算');
  272. }
  273. // 更新分销记录状态
  274. Db::name('distribution_record')
  275. ->where('id', $id)
  276. ->update([
  277. 'status' => 2,
  278. 'settle_time' => date('Y-m-d H:i:s')
  279. ]);
  280. // 更新用户佣金
  281. $userCommission = Db::name('user_commission')
  282. ->where('user_id', $distributionRecord['distributor_id'])
  283. ->lock(true)
  284. ->find();
  285. if ($userCommission) {
  286. Db::name('user_commission')
  287. ->where('user_id', $distributionRecord['distributor_id'])
  288. ->update([
  289. 'total_commission' => Db::raw('total_commission + ' . $distributionRecord['commission_amount']),
  290. 'current_commission' => Db::raw('current_commission + ' . $distributionRecord['commission_amount']),
  291. 'update_time' => date('Y-m-d H:i:s')
  292. ]);
  293. } else {
  294. Db::name('user_commission')
  295. ->insert([
  296. 'user_id' => $distributionRecord['distributor_id'],
  297. 'total_commission' => $distributionRecord['commission_amount'],
  298. 'current_commission' => $distributionRecord['commission_amount'],
  299. 'promotion_link' => 'xxxx.com?from=' . $distributionRecord['distributor_id'],
  300. 'update_time' => date('Y-m-d H:i:s')
  301. ]);
  302. }
  303. Db::commit();
  304. $successCount++;
  305. } catch (\Exception $e) {
  306. Db::rollback();
  307. $failCount++;
  308. $messages[] = "记录ID {$id}: " . $e->getMessage();
  309. }
  310. }
  311. $message = "结算完成,成功: {$successCount}条,失败: {$failCount}条";
  312. if (!empty($messages)) {
  313. $message .= "。失败原因:" . implode('; ', $messages);
  314. }
  315. $this->success($message);
  316. }
  317. /**
  318. * 分销统计
  319. * @return void
  320. */
  321. public function statistics(): void
  322. {
  323. // 总分销记录数
  324. $totalCount = Db::name('distribution_record')->count();
  325. // 待结算记录数
  326. $pendingCount = Db::name('distribution_record')
  327. ->where('status', 1)
  328. ->count();
  329. // 已结算记录数
  330. $settledCount = Db::name('distribution_record')
  331. ->where('status', 2)
  332. ->count();
  333. // 总分销金额
  334. $totalCommission = Db::name('distribution_record')
  335. ->where('status', 2)
  336. ->sum('commission_amount');
  337. // 今日分销统计
  338. $todayStart = date('Y-m-d 00:00:00');
  339. $todayEnd = date('Y-m-d 23:59:59');
  340. $todayCount = Db::name('distribution_record')
  341. ->whereBetween('create_time', [$todayStart, $todayEnd])
  342. ->count();
  343. $todayCommission = Db::name('distribution_record')
  344. ->whereBetween('create_time', [$todayStart, $todayEnd])
  345. ->sum('commission_amount');
  346. // 分销人数统计
  347. $distributorCount = Db::name('distribution_record')
  348. ->distinct(true)
  349. ->field('distributor_id')
  350. ->count();
  351. $stats = [
  352. 'total_count' => $totalCount,
  353. 'pending_count' => $pendingCount,
  354. 'settled_count' => $settledCount,
  355. 'total_commission' => $totalCommission ?? 0,
  356. 'today_count' => $todayCount,
  357. 'today_commission' => $todayCommission ?? 0,
  358. 'distributor_count' => $distributorCount
  359. ];
  360. $this->success('获取成功', $stats);
  361. }
  362. /**
  363. * 获取分销状态选项
  364. * @return void
  365. */
  366. public function statusOptions(): void
  367. {
  368. $options = [
  369. ['value' => 1, 'label' => '待结算'],
  370. ['value' => 2, 'label' => '已结算'],
  371. ['value' => 3, 'label' => '已取消']
  372. ];
  373. $this->success('获取成功', $options);
  374. }
  375. }