Taskorderguquan.php 55 KB

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