Taskorderguquan.php 55 KB

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