Taskorderguquan.php 55 KB

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