Taskorderguquan.php 54 KB

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