Taskorderguquan.php 55 KB

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