Taskorderguquan.php 55 KB

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