Taskorderguquan.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. <?php
  2. /**
  3. * @package merchant
  4. * @Author: Qinii
  5. * @Date: 2020/5/28
  6. */
  7. namespace app\controller\api\store\merchant;
  8. use app\common\model\user\User;
  9. use think\facade\Db;
  10. use think\Request;
  11. class Taskorderguquan
  12. {
  13. public function assignment()
  14. {
  15. /**
  16. * 业绩25000分配
  17. * 补贴下面人员
  18. * 13331043787张吉良55
  19. *
  20. * 其余部分做分红
  21. */
  22. $data = [
  23. '13331043787' => 55
  24. ];
  25. $result = Db::name("user")
  26. ->whereIn("account", array_keys($data))
  27. ->where('is_del', 0)
  28. ->field('uid, brokerage_price, account, nickname')
  29. ->select();
  30. $res = [];
  31. foreach ($result as $v) {
  32. $yj_90 = $data[$v['account']] * 0.9;
  33. $fg_10 = $data[$v['account']] * 0.1;
  34. Db::name("user")->where("uid", $v['uid'])->inc("brokerage_price", $yj_90)->save();
  35. Db::name("user")->where("uid", $v['uid'])->inc("total_amount_old", $yj_90)->save();
  36. Db::name("user")->where("uid", $v['uid'])->inc("amount_old", $yj_90)->save();
  37. Db::name("user")->where("uid", $v['uid'])->inc("fugou", $fg_10)->save();
  38. $this->bill_user_log111111($v['uid'], "佣金补贴", $yj_90, "佣金补贴", 8);//股权分佣明细2.0系统
  39. $this->fugou_user_log($v['uid'], $fg_10, 16, 1, 1);//复购金明细入账
  40. $res[] = [
  41. 'uid' => $v['uid'],
  42. 'account' => $v['account'],
  43. 'brokerage_price_pre' => $v['brokerage_price'],
  44. 'brokerage_price' => $data[$v['account']],
  45. 'nickname' => $v['nickname']
  46. ];
  47. }
  48. return json($res);
  49. try {
  50. // 1. 获取所有用户数据(按level_id正序排序保证父级在前)
  51. $users = Db::name('user')
  52. ->where('is_del', '=', 0)
  53. ->where('status', '=', 1)
  54. ->where('user_group', '>=', 2)
  55. ->order('level_id', 'asc')
  56. ->field('uid,account,nickname,level_id,is_del,status,user_group')
  57. ->select()
  58. ->toArray();
  59. // 2. 构建以UID为键的映射表
  60. $userMap = [];
  61. foreach ($users as $user) {
  62. $user['children'] = []; // 初始化子节点
  63. $userMap[$user['uid']] = [
  64. '用户ID' => $user['uid'],
  65. '用户账号' => $user['account'],
  66. '用户昵称' => $user['nickname'],
  67. '用户身份' => $user['user_group'],
  68. '上级用户ID' => $user['level_id'],
  69. '直属下级用户人数' => 0,
  70. '直属下级用户列表' => $user['children'],
  71. ];
  72. }
  73. // 3. 递归构建树形结构
  74. $tree = [];
  75. foreach ($userMap as $uid => &$user) {
  76. $parentId = $user['上级用户ID'];
  77. if ($parentId == 0) {
  78. // 顶级节点直接加入树
  79. $tree[] = &$user;
  80. } elseif (isset($userMap[$parentId])) {
  81. // 非顶级节点加入父节点的children
  82. $userMap[$parentId]['直属下级用户列表'][] = &$user;
  83. $userMap[$parentId]['直属下级用户人数']++;
  84. }
  85. }
  86. unset($user); // 销毁引用
  87. return json($tree);
  88. } catch (\Exception $e) {
  89. // 记录错误日志
  90. return json(['code' => 0, 'msg' => '树结构生成失败']);
  91. }
  92. $result = [
  93. 'oldOrderExistGongXian' => [],
  94. 'orderExistGongXian' => [],
  95. 'oldOrderExistPv' => [],
  96. 'orderExistPv' => [],
  97. 'gongXianDataOldList' => [],
  98. 'gongXianDataList' => [],
  99. 'pvDataOldList' => [],
  100. 'pvDataList' => [],
  101. 'contributeNot' => [],
  102. 'pvNot' => [],
  103. 'userUpdateSummary' => ['success' => 0, 'failed' => 0, 'skipped' => 0], // 优化: 汇总用户更新结果
  104. 'insertGongXianSummary' => ['success' => 0, 'failed' => 0], // 优化: 汇总贡献插入结果
  105. 'insertPvSummary' => ['success' => 0, 'failed' => 0], // 优化: 汇总PV插入结果
  106. 'errors' => [], // 优化: 统一记录错误信息
  107. ];
  108. // --- 数据库查询部分 (保持不变,已优化) ---
  109. // 1. 查询用户
  110. $userList = Db::name("user")
  111. ->where('is_del', 0)
  112. // ->whereIn('uid', [277, 1593])
  113. ->column('uid, spread_uid, contribute, per_contribute, pv', 'uid');
  114. // $userIds = array_keys($userList);
  115. $oldUserList = Db::name("old_user_jbp")
  116. ->column('id, amount');
  117. // 2. 查询老订单
  118. $userOfGoodsListRaw = Db::name("old_user_of_goods")
  119. ->where('status', 1)
  120. // 优化: 如果用户量大,可以考虑只查相关用户的订单
  121. // ->whereIn('user_id', $userIds)
  122. ->field('user_id, money, order_id, create_time')
  123. ->select()
  124. ->toArray();
  125. // 3. 查询新订单
  126. $storeOrderListRaw = Db::name("store_order")
  127. ->whereIn('status', [0, 1, 2, 3])
  128. // 优化: 如果用户量大,可以考虑只查相关用户的订单
  129. // ->whereIn('uid', $userIds)
  130. ->field('uid, pay_price, mer_id, status, order_id, create_time')
  131. ->select()
  132. ->toArray();
  133. // 4. 查询已存在的贡献值记录
  134. $gongXianListRaw = Db::name("user_sign_gongxian")
  135. ->where('status', '<>', -1)
  136. // 优化: 如果记录非常多,可以分批查询或只查相关用户的
  137. // ->whereIn('uid', array_merge($userIds, array_column($userList, 'spread_uid'))) // 查询购买者和潜在推广者
  138. ->field('uid, order_id, number, status, type')
  139. ->select()
  140. ->toArray();
  141. // 5. 查询已存在的PV记录
  142. $pvListRaw = Db::name("user_pv_log")
  143. ->where('status', '<>', -1)
  144. // 优化: 同上
  145. // ->whereIn('uid', $userIds)
  146. ->field('uid, order_id, pv, status')
  147. ->select()
  148. ->toArray();
  149. // --- 数据预处理部分
  150. $existingGongXian = [];
  151. $existingGongXianByUid = [];
  152. foreach ($gongXianListRaw as $gx) {
  153. $existingGongXian[$gx['uid'] . '_' . $gx['order_id']] = ['number' => $gx['number'], 'status' => $gx['status'], 'type' => $gx['type']];
  154. // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
  155. if ((1 <= $gx['order_id'] && $gx['order_id'] <= 900) || (4868 <= $gx['order_id'] && $gx['order_id'] <= 6869)) {
  156. $existingGongXianByUid[$gx['uid']][] = $gx['order_id'];
  157. }
  158. }
  159. unset($gongXianListRaw);
  160. $existingPv = [];
  161. $existingPvByUid = [];
  162. foreach ($pvListRaw as $pv) {
  163. $existingPv[$pv['uid'] . '_' . $pv['order_id']] = ['pv' => $pv['pv'], 'status' => $pv['status']];
  164. // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
  165. if ((1 <= $pv['order_id'] && $pv['order_id'] <= 900) || (4868 <= $pv['order_id'] && $pv['order_id'] <= 6869)) {
  166. $existingPvByUid[$pv['uid']][] = $pv['order_id'];
  167. }
  168. }
  169. unset($pvListRaw);
  170. $userOfGoodsByUid = [];
  171. foreach ($userOfGoodsListRaw as $oldOrder) $userOfGoodsByUid[$oldOrder['user_id']][] = $oldOrder;
  172. unset($userOfGoodsListRaw);
  173. $storeOrdersByUid = [];
  174. foreach ($storeOrderListRaw as $order) $storeOrdersByUid[$order['uid']][] = $order;
  175. unset($storeOrderListRaw);
  176. // *** 主逻辑处理与数据收集 ***
  177. $gongXianDataToInsert = []; // 优化: 合并新旧贡献插入列表
  178. $pvDataToInsert = []; // 优化: 合并新旧PV插入列表
  179. $userUpdateData = []; // 优化: 收集所有需要更新的用户数据 [uid => ['contribute'=>float, 'pv'=>float, 'per_contribute'=>float]]
  180. // 初始化所有用户的待更新数据
  181. foreach ($userList as $uid => $user) {
  182. // 预先设置初始值,确保即使没有订单的用户也能被包含在后续可能的更新逻辑中(如果需要)
  183. // 如果用户没有任何订单,他们的 contribute 和 pv 应该保持数据库原始值或根据业务逻辑设为0
  184. // 这里我们先假设如果没有订单,他们的计算值就是0
  185. $userUpdateData[$uid] = [
  186. 'uid' => $uid,
  187. 'contribute' => 0.0,
  188. 'pv' => 0.0,
  189. 'per_contribute' => 0.0,
  190. ];
  191. // 初始化推广者的 per_contribute 累加器
  192. if (!empty($user['spread_uid'])) {
  193. $spreadUid = $user['spread_uid'];
  194. if (!isset($userUpdateData[$spreadUid])) {
  195. if (isset($userList[$spreadUid])) {
  196. if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
  197. $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
  198. }
  199. } else {
  200. // 记录或处理推广者不在当前用户列表的情况
  201. $result['errors'][] = "执行{$uid}时,没找到 推荐人 {$spreadUid}";
  202. // 可以选择跳过给这个推广者增加 per_contribute
  203. }
  204. } else if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
  205. $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
  206. }
  207. }
  208. }
  209. // 遍历用户列表进行计算和数据收集
  210. foreach ($userList as $uid => $user) {
  211. $spreadUid = $user['spread_uid'];
  212. $existingGongXianByUid[$uid] = $existingGongXianByUid[$uid] ?? [];
  213. $existingPvByUid[$uid] = $existingPvByUid[$uid] ?? [];
  214. if (isset($userOfGoodsByUid[$uid])) {
  215. foreach ($userOfGoodsByUid[$uid] as $oldOrder) {
  216. switch ($oldOrder['money']) {
  217. case 1180:
  218. $totalPv = 700.0;
  219. break;
  220. case 11800:
  221. $totalPv = 7000.0;
  222. break;
  223. case 10620:
  224. $totalPv = 6300.0;
  225. break;
  226. case 2360:
  227. $totalPv = 1400.0;
  228. break;
  229. case 9440:
  230. $totalPv = 5600.0;
  231. break;
  232. default:
  233. $totalPv = round($oldOrder['money'] * 0.7, 2);
  234. break;
  235. }
  236. $settlementTimeOld = $oldOrder['create_time'] ? date('Y-m-d H:i:s', $oldOrder['create_time']) : strtotime($user['create_time']);
  237. // --- 收集贡献值插入数据 ---
  238. $orderKey = $uid . '_' . $oldOrder['order_id'];
  239. // 一个人 同一个订单 可能有多条记录 有问题
  240. if (isset($existingGongXian[$orderKey])) {
  241. $result['oldOrderExistGongXian'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
  242. $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
  243. if ($existingGongXian[$orderKey]['status'] == 1) {
  244. if ($existingGongXian[$orderKey]['type'] == 1) {
  245. $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
  246. } else if ($existingGongXian[$orderKey]['type'] == 2) {
  247. $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
  248. }
  249. }
  250. if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
  251. $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
  252. if (isset($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']])) {
  253. if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['status'] == 1) {
  254. if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 1) {
  255. $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
  256. } else if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 2) {
  257. $userUpdateData[$spreadUid]['per_contribute'] -= $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
  258. }
  259. }
  260. }
  261. }
  262. } else {
  263. if ($totalPv > 0) {
  264. $userUpdateData[$uid]['contribute'] += $totalPv;
  265. // --- 收集贡献值插入数据 ---
  266. $gongXianBase = [
  267. "number" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
  268. "order_type" => 21, "order_id" => $oldOrder['order_id'],
  269. "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeOld
  270. ];
  271. // 本人
  272. $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买会员专区商品赠送贡献值(1.0)"], $gongXianBase);
  273. $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
  274. // 推广人
  275. if (!empty($user['spread_uid'])) {
  276. if (isset($userUpdateData[$spreadUid])) {
  277. $userUpdateData[$spreadUid]['per_contribute'] += $totalPv;
  278. $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广会员专区商品赠送贡献值(1.0)"], $gongXianBase);
  279. $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
  280. }
  281. }
  282. }
  283. }
  284. // --- 收集 PV 插入数据 ---
  285. if (isset($existingPv[$orderKey])) {
  286. $result['oldOrderExistPv'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
  287. if ($existingPv[$orderKey]['status'] == 1) {
  288. $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
  289. }
  290. } else {
  291. $userUpdateData[$uid]['pv'] += $totalPv;
  292. $pvDataToInsert[] = [
  293. "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
  294. "order_type" => 21, "order_id" => $oldOrder['order_id'],
  295. "mark" => "购买会员专区商品赠送PV(1.0)", 'settlement_time' => $settlementTimeOld
  296. ];
  297. }
  298. if (!empty($existingPvByUid[$uid])) {
  299. $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$oldOrder['order_id']]);
  300. }
  301. }
  302. } // end if isset($userOfGoodsByUid[$uid])
  303. // --- 处理新订单 ---
  304. if (isset($storeOrdersByUid[$uid])) {
  305. foreach ($storeOrdersByUid[$uid] as $order) {
  306. $totalPv = 0.0;
  307. // ... (if/else logic and switch case for $totalPv calculation - same as before)
  308. if ($order['mer_id'] == 496) {
  309. switch ($order['pay_price']) {
  310. case 1180:
  311. $totalPv = 700.0;
  312. break;
  313. case 11800:
  314. $totalPv = 7000.0;
  315. break;
  316. case 10620:
  317. $totalPv = 6300.0;
  318. break;
  319. case 2360:
  320. $totalPv = 1400.0;
  321. break;
  322. case 9440:
  323. $totalPv = 5600.0;
  324. break;
  325. default:
  326. $totalPv = round($order['pay_price'] * 0.7, 2);
  327. break;
  328. }
  329. } else if ($order['status'] == 3) {
  330. $totalPv = round($order['pay_price'] * 0.7, 2);
  331. }
  332. // --- 收集贡献值插入数据 ---
  333. $orderKey = $uid . '_' . $order['order_id'];
  334. $settlementTimeNew = $order['create_time'] ?: date('Y-m-d H:i:s', $user['create_time']);
  335. // --- 收集贡献值插入数据 ---
  336. if (isset($existingGongXian[$orderKey])) {
  337. $result['orderExistGongXian'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
  338. $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
  339. // 累加计算值
  340. if ($existingGongXian[$orderKey]['status'] == 1) {
  341. if ($existingGongXian[$orderKey]['type'] == 1) {
  342. $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
  343. } else if ($existingGongXian[$orderKey]['type'] == 2) {
  344. $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
  345. }
  346. }
  347. if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
  348. $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
  349. if (isset($existingGongXian[$spreadUid . '_' . $order['order_id']])) {
  350. if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['status'] == 1) {
  351. if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 1) {
  352. $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
  353. } else if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 2) {
  354. $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
  355. }
  356. }
  357. }
  358. }
  359. } else {
  360. if ($totalPv > 0) {
  361. $userUpdateData[$uid]['contribute'] += $totalPv;
  362. $gongXianBase = [ // 优化: 提取公共字段
  363. "number" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
  364. "order_type" => 22, "order_id" => $order['order_id'],
  365. "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeNew
  366. ];
  367. // 本人
  368. $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买商品赠送贡献值(2.0)"], $gongXianBase);
  369. $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
  370. // 推广人
  371. if (!empty($user['spread_uid'])) {
  372. $spreadUid = $user['spread_uid'];
  373. if (isset($userUpdateData[$spreadUid])) { // 确保推广者存在
  374. $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广商品赠送贡献值(2.0)"], $gongXianBase);
  375. $userUpdateData[$spreadUid]['per_contribute'] += $totalPv; // 累加推广者业绩
  376. $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
  377. }
  378. }
  379. }
  380. }
  381. // --- 收集 PV 插入数据 ---
  382. if (isset($existingPv[$orderKey])) {
  383. $result['orderExistPv'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
  384. if ($existingPv[$orderKey]['status'] == 1) {
  385. $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
  386. }
  387. } else {
  388. $userUpdateData[$uid]['pv'] += $totalPv;
  389. $pvDataToInsert[] = [
  390. "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
  391. "order_type" => 22, // 确认 PV log 的 order_type 是否与贡献一致或有区分
  392. "order_id" => $order['order_id'],
  393. "mark" => "购买商品赠送PV(2.0)", // 标记调整为更通用
  394. 'settlement_time' => $settlementTimeNew
  395. ];
  396. }
  397. if (!empty($existingPvByUid[$uid])) {
  398. $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$order['order_id']]);
  399. }
  400. }
  401. }
  402. // end if isset($storeOrdersByUid[$uid])
  403. // --- 比较计算值与原值 (移到循环外处理) ---
  404. // (在此处比较并记录到 $result['contributeNot'] / $result['pvNot'])
  405. // 注意:浮点数比较可能需要容差
  406. $tolerance = 0.001; // 定义一个小的容差值
  407. if (abs($userUpdateData[$uid]['contribute'] - (float)$user['contribute']) > $tolerance) {
  408. $result['contributeNot'][] = [
  409. 'uid' => $uid,
  410. 'contribute_old' => (float)$user['contribute'], // 显式转换
  411. 'contribute_new' => $userUpdateData[$uid]['contribute']
  412. ];
  413. }
  414. if (abs($userUpdateData[$uid]['pv'] - (float)$user['pv']) > $tolerance) {
  415. $result['pvNot'][] = [
  416. 'uid' => $uid,
  417. 'pv_old' => (float)$user['pv'], // 显式转换
  418. 'pv_new' => $userUpdateData[$uid]['pv']
  419. ];
  420. }
  421. // per_contribute 是累加的,不需要与旧值比较,直接更新
  422. } // end foreach ($userList as $uid => $user)
  423. // *** 数据库批量操作 ***
  424. // 使用事务确保数据一致性
  425. Db::startTrans();
  426. try {
  427. $bill = [];
  428. foreach ($oldUserList as $item) {
  429. $bill[] = [
  430. 'uid' => $item['id'],
  431. 'link_id' => 0,//关联订单id
  432. 'pm' => 1,//0:支出,1:获得
  433. 'title' => '佣金',//账单标题
  434. 'category' => 'now_money',//明细种类
  435. 'type' => 'commission',//明细类型
  436. 'number' => $item['amount'],//明细数字
  437. 'balance' => 0,//剩余
  438. 'mark' => '1.0佣金记录',//备注
  439. 'create_time' => '2025-02-04 00:00:00',//添加时间
  440. 'status' => 1,//0待确定,1有效,-1无效
  441. 'commission_type' => 21,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
  442. //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
  443. //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
  444. 'order_sn' => 0,//订单号
  445. 'tripartite' => 0,//
  446. 'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
  447. 'mer_id' => 0,//商户id
  448. 'source' => 0,//1线下 0线上
  449. 'order_type' => 1,//1自营 2 第三方 订单类型
  450. 'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
  451. 'gzc' => 3,//养老金是否已进入公证处log表0:未进入。1:已进入
  452. 'take_time' => '',//结算时间
  453. 'district_id' => '',//
  454. 'street_id' => '',//
  455. 'month' => '',//月份
  456. ];
  457. }
  458. $chunkedBill = array_chunk($bill, 500);
  459. foreach ($chunkedBill as $chunk) {
  460. Db::name('user_bill')->insertAll($chunk);
  461. }
  462. if (!empty($existingGongXianByUid)) {
  463. foreach ($existingGongXianByUid as $uid => $orderList) {
  464. if (!empty($orderList)) {
  465. Db::name("user_sign_gongxian")
  466. ->where('uid', $uid)
  467. ->whereIn('order_id', $orderList)
  468. ->update(['status' => 0]);
  469. }
  470. }
  471. }
  472. if (!empty($existingPvByUid)) {
  473. foreach ($existingPvByUid as $uid => $orderList) {
  474. if (!empty($orderList)) {
  475. Db::name("user_pv_log")
  476. ->where('uid', $uid)
  477. ->whereIn('order_id', $orderList)
  478. ->update(['status' => 0]);
  479. }
  480. }
  481. }
  482. // --- 批量插入贡献值 ---
  483. if (!empty($gongXianDataToInsert)) {
  484. // 分块插入,避免单次插入过多数据 (例如一次500条)
  485. $chunkedGongXian = array_chunk($gongXianDataToInsert, 500);
  486. foreach ($chunkedGongXian as $chunk) {
  487. $insertedGongXianCount = Db::name('user_sign_gongxian')->insertAll($chunk);
  488. $result['insertGongXianSummary']['success'] += $insertedGongXianCount;
  489. }
  490. if ($result['insertGongXianSummary']['success'] < count($gongXianDataToInsert)) {
  491. $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert) - $result['insertGongXianSummary']['success'];
  492. // 可以考虑记录更详细的失败信息,但这比较复杂,需要知道哪些失败了
  493. $result['errors'][] = "GongXian insertion partially failed or failed completely.";
  494. // 根据业务决定是否回滚
  495. // throw new Exception("GongXian insertion failed");
  496. }
  497. } else {
  498. $result['insertGongXianSummary']['skipped'] = true; // 标记为跳过(无数据)
  499. }
  500. // --- 批量插入PV ---
  501. if (!empty($pvDataToInsert)) {
  502. $chunkedPv = array_chunk($pvDataToInsert, 500);
  503. foreach ($chunkedPv as $chunk) {
  504. $insertedPvCount = Db::name('user_pv_log')->insertAll($chunk);
  505. $result['insertPvSummary']['success'] += $insertedPvCount;
  506. }
  507. if ($result['insertPvSummary']['success'] < count($pvDataToInsert)) {
  508. $result['insertPvSummary']['failed'] = count($pvDataToInsert) - $result['insertPvSummary']['success'];
  509. $result['errors'][] = "PV Log insertion partially failed or failed completely.";
  510. // throw new Exception("PV Log insertion failed");
  511. }
  512. } else {
  513. $result['insertPvSummary']['skipped'] = true; // 标记为跳过(无数据)
  514. }
  515. // --- 批量更新用户信息 ---
  516. $usersToUpdate = [];
  517. // 筛选出实际需要更新的用户数据 (值有变化或 per_contribute > 0)
  518. foreach ($userUpdateData as $uid => $updateInfo) {
  519. $originalUser = $userList[$uid]; // 获取原始用户信息
  520. // 检查 contribute 或 pv 是否变化(使用容差),或者 per_contribute 是否需要更新
  521. $needsUpdate = false;
  522. if (abs($updateInfo['contribute'] - (float)$originalUser['contribute']) > $tolerance) $needsUpdate = true;
  523. if (abs($updateInfo['pv'] - (float)$originalUser['pv']) > $tolerance) $needsUpdate = true;
  524. // per_contribute 始终更新,因为它是在现有基础上累加的(除非业务定义不同)
  525. // 如果 per_contribute 数据库设计是直接覆盖,那只有 > 0 时才需要更新
  526. // 假设是覆盖更新,且只有大于0时才需要更新变动(如果一直是0则不用更新)
  527. if ($updateInfo['per_contribute'] > 0.0) { // 只有当推广业绩>0时才触发更新
  528. // 这里需要确认 per_contribute 是覆盖还是累加?
  529. // 如果是数据库累加: Db::name("user")->where('uid', $uid)->inc('per_contribute', $amount)->update(); 需要单独处理
  530. // 如果是覆盖: 直接放入 saveAll
  531. // 假设是覆盖,我们只更新有变化的或per_contribute > 0 的
  532. $needsUpdate = true;
  533. } else {
  534. // 如果 per_contribute 计算结果为0,且 contribute 和 pv 也未变,则不需要更新 per_contribute 字段
  535. unset($updateInfo['per_contribute']); // 移除无需更新的 per_contribute
  536. if (empty($updateInfo)) $needsUpdate = false; // 如果移除后为空,则不更新
  537. }
  538. if ($needsUpdate) {
  539. // 确保只包含需要更新的字段,并且包含主键 'uid'
  540. $finalUpdateData = ['uid' => $uid];
  541. if (isset($updateInfo['contribute'])) $finalUpdateData['contribute'] = $updateInfo['contribute'];
  542. if (isset($updateInfo['pv'])) $finalUpdateData['pv'] = $updateInfo['pv'];
  543. if (isset($updateInfo['per_contribute']) && $updateInfo['per_contribute'] > 0.0) { // 再次确认只更新大于0的推广业绩
  544. $finalUpdateData['per_contribute'] = $updateInfo['per_contribute'];
  545. }
  546. if (count($finalUpdateData) > 1) { // 确保除了uid还有其他字段要更新
  547. $usersToUpdate[] = $finalUpdateData;
  548. } else {
  549. $result['userUpdateSummary']['skipped']++; // 记录跳过的更新(无变化)
  550. }
  551. } else {
  552. $result['userUpdateSummary']['skipped']++; // 记录跳过的更新(无变化)
  553. }
  554. }
  555. if (!empty($usersToUpdate)) {
  556. // 使用 saveAll 进行批量更新 (要求 PHP >= 7.1.8 for MySQL)
  557. // saveAll 会根据主键 'uid' 更新对应记录
  558. $userModel = new User();
  559. $updatedCount = $userModel->saveAll($usersToUpdate); // TP6 支持 saveAll
  560. // 注意: saveAll 返回的是成功保存或更新的 *对象集合* 或 *布尔值*,不是影响的行数。
  561. // 需要检查返回类型并判断成功数量。通常返回集合时 count(集合) 是成功数。
  562. // 如果是 TP5,可能需要循环 update 或构造复杂 SQL。
  563. // 假设 TP6 saveAll 成功会返回包含更新后数据的集合或true,失败是false
  564. if ($updatedCount !== false) {
  565. // 这里需要一种方法来确定实际更新了多少条记录。
  566. // saveAll 的返回值可能需要进一步处理。
  567. // 简单假设:如果返回不是 false,就认为请求中的都成功了(可能不准确)
  568. // 更精确的方法是 saveAll 后再查询一次确认。
  569. // 这里我们暂时认为 saveAll 返回非 false 即为大部分成功
  570. $result['userUpdateSummary']['success'] = count($usersToUpdate); // 乐观估计
  571. } else {
  572. $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 全部失败
  573. $result['errors'][] = "User batch update failed using saveAll.";
  574. // throw new Exception("User batch update failed");
  575. }
  576. }
  577. // 更新统计:失败数等于总数减去成功和跳过的
  578. //$result['userUpdateSummary']['failed'] = count($userList) - $result['userUpdateSummary']['success'] - $result['userUpdateSummary']['skipped'];
  579. // 如果所有操作都成功,提交事务
  580. Db::commit();
  581. } catch
  582. (\Exception $e) {
  583. // 如果任何数据库操作失败,回滚事务
  584. Db::rollback();
  585. // 记录错误信息
  586. $result['errors'][] = "Transaction failed: " . $e->getMessage();
  587. // 可以根据需要将 insert/update 摘要设置为失败
  588. $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 假设更新失败
  589. $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert); // 假设插入失败
  590. $result['insertPvSummary']['failed'] = count($pvDataToInsert); // 假设插入失败
  591. }
  592. // --- 清理/最终结果赋值 (可选) ---
  593. // $result['gongXianDataOldList'] = $gongXianDataOldList; // 这些已合并到 ToInsert
  594. // $result['gongXianDataList'] = $gongXianDataList;
  595. // $result['pvDataOldList'] = $pvDataOldList;
  596. // $result['pvDataList'] = $pvDataList;
  597. return json($result);
  598. // // 计算总业绩
  599. // $totalPv = [];
  600. // foreach ($user_team_amount as $order) {
  601. // if (!isset($totalPv[$order['user_id']])) {
  602. // $totalPv[$order['user_id']] = 0;
  603. // }
  604. // switch ($order['money']) {
  605. // case 1180:
  606. // $totalPv[$order['user_id']] += 700;
  607. // break;
  608. // case 11800:
  609. // $totalPv[$order['user_id']] += 7000;
  610. // break;
  611. // case 10620:
  612. // $totalPv[$order['user_id']] += 6300;
  613. // break;
  614. // case 2360:
  615. // $totalPv[$order['user_id']] += 1400;
  616. // break;
  617. // case 9440:
  618. // $totalPv[$order['user_id']] += 5600;
  619. // break;
  620. // default:
  621. // if ($order['money'] == 2344.99) {
  622. // break;
  623. // }
  624. // $totalPv[$order['user_id']] += round($order['money'] * 0.7, 2);
  625. // break;
  626. // }
  627. // }
  628. // foreach ($totalPv as $uid => $pv) {
  629. // Db::name("user")->where('is_old', 1)->where("uid", $uid)->update(['pv' => $pv]);
  630. // }
  631. //
  632. // return;
  633. // /**
  634. // * 周金花200(13959100621)
  635. // * 黄金花200(18603401312)
  636. // * 徐立苹100(13521438652)
  637. // * 李素红200(13701061395)
  638. // * 周行体200(13231658486)
  639. // * 刘银霞100(13161909228)
  640. // * 李卫东100(13911601230)
  641. // * 金 波100(13801358713)
  642. // * 王 玲 150(15810064711)
  643. // * 侯玉兰150(15232797965)
  644. // * 吕丽娣100(15960349667)
  645. // * 张传莲100(15332507711)
  646. // * 刘春梅100(18760167163)
  647. // * 付天如100(18863873000)
  648. // * 付绍先100(15324059286)
  649. // * 黄桂林100(15960196876)
  650. // * 温 煌100(18350134089)
  651. // * 谭英先100(13978627072)
  652. // * 陈玉珍100(19858353660)
  653. // * 黄雪云100(18650055445)
  654. // * 黄 玲100(13877193411)
  655. // * 邱佳珍100(13960379098)
  656. // * 隋彩云100(13601071082)
  657. // */
  658. // $data = [
  659. // '13959100621' => 200,
  660. // '18603401312' => 200,
  661. // '13521438652' => 100,
  662. // '13701061395' => 200,
  663. // '13231658486' => 200,
  664. // '13161909228' => 100,
  665. // '13911601230' => 100,
  666. // '13801358713' => 100,
  667. // '15810064711' => 150,
  668. // '15232797965' => 150,
  669. // '15960349667' => 100,
  670. // '15332507711' => 100,
  671. // '18760167163' => 100,
  672. // '18863873000' => 100,
  673. // '15324059286' => 100,
  674. // '15960196876' => 100,
  675. // '18350134089' => 100,
  676. // '13978627072' => 100,
  677. // '19858353660' => 100,
  678. // '18650055445' => 100,
  679. // '13877193411' => 100,
  680. // '13960379098' => 100,
  681. // '13601071082' => 100,
  682. // ];
  683. // $result = Db::name("user")
  684. // ->whereIn("account", array_keys($data))
  685. // ->where('is_del', 0)
  686. // ->field('uid, brokerage_price, account, nickname')
  687. // ->select();
  688. // $res = [];
  689. // foreach ($result as $v) {
  690. // Db::name("user")->where("uid", $v['uid'])->inc("brokerage_price", $data[$v['account']])->save();
  691. // $this->bill_user_log111111($v['uid'], "佣金补贴", $data[$v['account']], "佣金补贴", 8);//股权分佣明细2.0系统
  692. // $res[] = [
  693. // 'uid' => $v['uid'],
  694. // 'account' => $v['account'],
  695. // 'brokerage_price_pre' => $v['brokerage_price'],
  696. // 'brokerage_price' => $data[$v['account']],
  697. // 'nickname' => $v['nickname']
  698. // ];
  699. // }
  700. // return json($res);
  701. }
  702. public function lst6(Request $request)
  703. {
  704. $startTime = $request->param('startTime', null);
  705. $endTime = $request->param('endTime', null);
  706. $isTest = $request->param('isTest', 1);
  707. $maxAllocationAmount = $request->param('maxAllocationAmount', null);
  708. // 查询测试人员账号信息
  709. //18973958920
  710. //15186694339
  711. //18833633835
  712. //19525470098
  713. //17756507016
  714. //18226705337
  715. $testAccount = ['18973958920', '15186694339', '18833633835', '19525470098', '17756507016', '18226705337', '17855366921'];
  716. $removeUserList = Db::name("user")
  717. ->whereIn('account', $testAccount)
  718. ->where("status", "<>", 0)
  719. ->where('is_del', '<>', 1)
  720. ->select()
  721. ->toArray();
  722. $removeUserIdList = array_column($removeUserList, 'uid');
  723. $zeroLineUidList = [1420, 2328, 1720];
  724. foreach ($zeroLineUidList as $uid) {
  725. //查询当前团队的用户列表
  726. $sql = "select getUserLevelId($uid) as uids";
  727. //\think\facade\Log::info("lplpDB".$sql);
  728. try {
  729. $spread_user_list = Db::query($sql);
  730. } catch (\Exception $exception) {
  731. return json($exception->getMessage());
  732. }
  733. $removeUserIdList = array_merge(explode(",", trim($spread_user_list[0]['uids'], '$,')), $removeUserIdList);
  734. }
  735. if (empty($startTime) || empty($endTime)) {
  736. $timeMap = $this->getTime('last_week');
  737. $startTime = $timeMap['startTime'] . ' 00:00:00';
  738. $endTime = $timeMap['endTime'] . ' 23:59:59';
  739. }
  740. // 定义分红金额
  741. $weekRecord = $this->getTeamPvByTime($startTime, $endTime, $removeUserIdList);
  742. // 分红金额 - 红包金额
  743. $redEnvelope = $this->getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList);
  744. $weekRecord -= $redEnvelope;
  745. if (!is_null($maxAllocationAmount)) {
  746. $weekRecord = $maxAllocationAmount;
  747. }
  748. if ($weekRecord <= 0) {
  749. return json('无效分红金额');
  750. }
  751. // $stock_comm = round($weekRecord * 0.05 ,2);
  752. $stock_comm = floor(($weekRecord * 0.05) * 100) / 100;
  753. //获取股权分红的人
  754. $GetAllUserPackNum = db::name("old_user_stock")->sum("pack");//计算所有用户的份数总和
  755. $stockuserdatas = db::name("old_user_stock")->select();//获取所有用户
  756. $salesArr = [];
  757. if (count($stockuserdatas) > 0) {
  758. // $one_pack_comm_data = round($stock_comm / $GetAllUserPackNum,2);//获取每份的单佣金
  759. $one_pack_comm_data = floor(($stock_comm / $GetAllUserPackNum) * 100) / 100;
  760. foreach ($stockuserdatas as &$v) {
  761. $salesArr[] = [
  762. 'stock_comm' => $stock_comm,
  763. 'GetAllUserPackNum' => $GetAllUserPackNum,
  764. 'uid' => $v['user_id'],
  765. 'pack' => $v['pack'],
  766. 'one_pack_comm_data' => $one_pack_comm_data,
  767. 'getcomm' => floor(($v['pack'] * $one_pack_comm_data) * 100) / 100
  768. ];
  769. $v['getcomm'] = floor(($v['pack'] * $one_pack_comm_data) * 100) / 100;
  770. $v['allgetcomm'] = $v['allgetcomm'] + $v['getcomm'];
  771. $v['update_time'] = time();
  772. $yj_90 = $v['getcomm'] * 0.9;
  773. $fg_10 = $v['getcomm'] * 0.1;
  774. if ($isTest == 0) {
  775. // // 更新 user_stock 表中的记录
  776. $res = db::name("old_user_stock")->where("id", $v['id'])->update([
  777. 'getcomm' => $v['getcomm'],
  778. 'allgetcomm' => $v['allgetcomm'],
  779. 'update_time' => $v['update_time']
  780. ]);
  781. $res1 = Db::name("user")->where("uid", $v['user_id'])->inc("total_amount_old", $yj_90)->save();
  782. $res2 = Db::name("user")->where("uid", $v['user_id'])->inc("amount_old", $yj_90)->save();
  783. Db::name("user")->where("uid", $v['user_id'])->inc("brokerage_price", $yj_90)->save();
  784. $res3 = Db::name("user")->where("uid", $v['user_id'])->inc("fugou", $fg_10)->save();
  785. $res = true;
  786. if ($res) {
  787. $das = $this->change_user_log($v['user_id'], 'amount_old', 1, $yj_90, "member_award_stock", "股权分红入账" . "-" . $v['pack']);//释放佣金
  788. //入账星级分红记录表
  789. $week_data = [];
  790. $week_data['user_id'] = $v['user_id'];
  791. $week_data['user_star_id'] = 0;
  792. $week_data['award_num'] = 0;
  793. $week_data['award_num_sm'] = 0;
  794. $week_data['remark'] = "股权分红主动执行" . $yj_90;
  795. $week_data['week_record'] = $weekRecord;
  796. $week_data['all_amount'] = $stock_comm;
  797. $week_data['radio'] = 2;
  798. $week_data['owner_bill'] = 0; //总流水金额
  799. $week_data['my_bill'] = 0; //我的流水
  800. $week_data['create_time'] = time();
  801. Db::name("old_user_weekaward")->insert($week_data);
  802. $userdatassss = db::name("old_user_jbp")->where("id", $v['user_id'])->find();
  803. $datas_log = [
  804. 'note' => "名称:" . $userdatassss['nick_name'] . " 用户:" . $v['user_id'] . " 新增股权佣金:" . $yj_90,
  805. 'create_time' => date('Y-m-d H:i:s')
  806. ];
  807. $con_data = Db::name('test_log')->insert($datas_log); //数据存到2.0数据表中
  808. $this->bill_user_log111111($v['user_id'], "股权分佣", $yj_90, "股权明细入账", 13);//股权分佣明细2.0系统
  809. $this->fugou_user_log($v['user_id'], $fg_10, 16, 1, 1);//复购金明细入账
  810. }
  811. }
  812. }
  813. }
  814. return json($salesArr);
  815. //股权分红 end
  816. }
  817. //添加复购金
  818. public function fugou_user_log($uid, $num, $order_id, $type_inc_des, $status = -1)
  819. {
  820. $fugou_data = Db::name('user')->where("uid", $uid)->find();
  821. $bill = [
  822. 'uid' => $uid,
  823. 'number' => $num,//数量
  824. 'status' => $status,//复购金状态1-有效 0-失效 -1待确认
  825. 'mark' => "复购金",//备注
  826. 'desc' => "10%作为复购金",//描述
  827. 'order_id' => $order_id,//订单id
  828. 'surplus' => 0,//剩余
  829. 'order_type' => 11,//关联订单ID
  830. 'type' => $type_inc_des,//复购金类型 :1赠送,2消耗
  831. 'settlement_time' => date('Y-m-d H:i:s'),//添加时间,
  832. 'addtime' => time(),
  833. ];
  834. Db::name('user_sign_fugou')->insert($bill);
  835. }
  836. //添加平台分佣2.0系统收益明细日志(养老金金额)
  837. public function bill_user_log111111($uid, $name, $num, $mark, $comm)
  838. {
  839. $con_data = Db::name('user')->where("uid", $uid)->find();
  840. //如果是会员专区就即刻到账
  841. // Db::name('user')->where("uid",$con_data['uid'])->update(['brokerage_price'=> $con_data['brokerage_price'] + $num]);
  842. $bill = [
  843. 'uid' => $uid,
  844. 'link_id' => 0,//关联订单id
  845. 'pm' => 1,//0:支出,1:获得
  846. 'title' => $name,//账单标题
  847. 'category' => 'now_money',//明细种类
  848. 'type' => 'commission',//明细类型
  849. 'number' => $num,//明细数字
  850. 'balance' => 0,//剩余
  851. 'mark' => $mark,//备注
  852. 'create_time' => date('Y-m-d H:i:s'),//添加时间
  853. 'status' => 1,//0待确定,1有效,-1无效
  854. 'commission_type' => $comm,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
  855. //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
  856. //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
  857. 'order_sn' => 0,//订单号
  858. 'tripartite' => 0,//
  859. 'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
  860. 'mer_id' => 0,//商户id
  861. 'source' => 0,//1线下 0线上
  862. 'order_type' => 1,//1自营 2 第三方 订单类型
  863. 'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
  864. 'gzc' => 3,//养老金是否已进入公证处log表0:未进入。1:已进入
  865. 'take_time' => time(),//结算时间
  866. 'district_id' => '',//
  867. 'street_id' => '',//
  868. 'month' => '',//月份
  869. ];
  870. Db::name('user_bill')->insert($bill);
  871. }
  872. //发放佣金 示例: $this->change_user_log($v,'amount',1,$all_award,"member_award","星级分红入账"."-".$value['title']);//释放佣金
  873. function change_user_log($user_id, $type, $change_status, $money, $routine, $remark = "", $is_admin = 1, $appoint_money = 0)
  874. {
  875. $transition = [
  876. 'pv' => 1,
  877. "gb" => 2,
  878. "df" => 3,
  879. "vr" => 4,
  880. "bt" => 5,
  881. "withdraw_quota_old" => 6,//提现
  882. "unsettled_pension" => 7,
  883. "amount_old" => 8//发放佣金
  884. ];
  885. $routineInfo = Db::name("old_routine_log_of_key")->where("key", $routine)->find();
  886. if (empty($routineInfo)) {
  887. return false;
  888. }
  889. $key_id = isset($routineInfo['id']) ? $routineInfo['id'] : 0;
  890. if ($appoint_money > 0) {
  891. $alter_money = $appoint_money;
  892. } else {
  893. //再去查询变更前的 金额
  894. $alter_money = Db::name("user")->where('uid', $user_id)->value($type);
  895. }
  896. if ($change_status == 1) {
  897. //新增前
  898. $alter_money = $alter_money - $money;
  899. } else if ($change_status == 2) {
  900. //减少前
  901. $alter_money = $alter_money + $money;
  902. }
  903. if ($alter_money < 0) {
  904. $alter_money = 0;
  905. }
  906. $inser_data = [];
  907. $inser_data['user_id'] = $user_id;
  908. $inser_data['type'] = $transition[$type];
  909. $inser_data['change_status'] = $change_status;
  910. $inser_data['money'] = $money;
  911. $inser_data['routine_log_of_key_id'] = $key_id;
  912. $inser_data['remark'] = $remark;
  913. $inser_data['is_admin'] = $is_admin;
  914. $inser_data['create_time'] = time();
  915. $inser_data['alter_money'] = isset($alter_money) ? $alter_money : 0;
  916. Db::name("old_user_log")->insert($inser_data);
  917. }
  918. public function getTime($timePeriod)
  919. {
  920. // 定义时间区间
  921. $now = time();
  922. $startTime = '';
  923. $endTime = '';
  924. if ($timePeriod == 'last_week') {
  925. // 上周的时间区间
  926. $startTime = date('Y-m-d', strtotime('monday last week', $now)); // 上周星期一的开始时间
  927. $endTime = date('Y-m-d', strtotime('sunday last week', $now)); // 上周星期日的结束时间
  928. } elseif ($timePeriod == 'this_week') {
  929. // 这周的时间区间
  930. $startTime = date('Y-m-d', strtotime('monday this week', $now)); // 这周星期一的开始时间
  931. $endTime = date('Y-m-d', strtotime('sunday this week', $now)); // 这周星期日的结束时间
  932. }
  933. // return ['startTime' => '2025-03-10', 'endTime' => '2025-03-23'];
  934. return ['startTime' => $startTime, 'endTime' => $endTime];
  935. }
  936. public function getTeamPvByTime($startTime, $endTime, $removeUserIdList = [])
  937. {
  938. // 查询指定时间区间内的所有订单,并排除 pay_time 为 NULL 的订单
  939. $orders = Db::name("store_order")
  940. ->alias('a')
  941. ->where('a.mer_id', 496)
  942. ->whereNotIn('a.uid', $removeUserIdList)
  943. ->whereIn('a.status', [0, 1, 2, 3])
  944. // ->whereIn("a.total_price", [1180, 11800, 10620, 2360, 9440])
  945. ->whereBetween("a.pay_time", [$startTime, $endTime])
  946. ->whereNotNull("a.pay_time") // 排除 pay_time 为 NULL 的订单
  947. ->leftJoin('rrx_store_cart b', 'a.cart_id = b.cart_id')
  948. ->field('a.mer_id, a.cart_id, a.status, a.pay_time, a.total_price, b.product_id')
  949. ->select();
  950. // 计算总业绩
  951. $totalPv = 0;
  952. foreach ($orders as $order) {
  953. switch ($order['product_id']) {
  954. case in_array($order['product_id'], [15762, 15763]):
  955. $totalPv += 700;
  956. break;
  957. case in_array($order['product_id'], [15813, 15820]):
  958. $totalPv += 7000;
  959. break;
  960. case in_array($order['product_id'], [15814, 15819]):
  961. $totalPv += 6300;
  962. break;
  963. case in_array($order['product_id'], [15815, 15817]):
  964. $totalPv += 1400;
  965. break;
  966. case in_array($order['product_id'], [15816, 15818]):
  967. $totalPv += 5600;
  968. break;
  969. case in_array($order['product_id'], [17610]):
  970. $totalPv += 35;
  971. break;
  972. case in_array($order['product_id'], [17611]):
  973. $totalPv += 175;
  974. break;
  975. case in_array($order['product_id'], [17612]):
  976. $totalPv += 350;
  977. break;
  978. }
  979. }
  980. return $totalPv;
  981. }
  982. public function getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList = [])
  983. {
  984. // 查询指定时间区间内的所有订单,并排除 pay_time 为 NULL 的订单
  985. $redEnvelopeList = Db::name("user_sign_hongbao")
  986. ->whereNotIn('uid', $removeUserIdList)
  987. ->where('status', 1)
  988. ->whereBetween("settlement_time", [$startTime, $endTime])
  989. ->select()
  990. ->toArray();
  991. return floor(array_sum(array_column($redEnvelopeList, 'number')) * 100) / 100;
  992. }
  993. }