Taskorderguquan.php 55 KB

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