| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969 |
- <?php
- /**
- * @package merchant
- * @Author: Qinii
- * @Date: 2020/5/28
- */
- namespace app\controller\api\store\merchant;
- use app\common\model\user\User;
- use think\facade\Db;
- class Taskorderguquan
- {
- public function assignment()
- {
- $result = [
- 'oldOrderExistGongXian' => [],
- 'orderExistGongXian' => [],
- 'oldOrderExistPv' => [],
- 'orderExistPv' => [],
- 'gongXianDataOldList' => [],
- 'gongXianDataList' => [],
- 'pvDataOldList' => [],
- 'pvDataList' => [],
- 'contributeNot' => [],
- 'pvNot' => [],
- 'userUpdateSummary' => ['success' => 0, 'failed' => 0, 'skipped' => 0], // 优化: 汇总用户更新结果
- 'insertGongXianSummary' => ['success' => 0, 'failed' => 0], // 优化: 汇总贡献插入结果
- 'insertPvSummary' => ['success' => 0, 'failed' => 0], // 优化: 汇总PV插入结果
- 'errors' => [], // 优化: 统一记录错误信息
- ];
- // --- 数据库查询部分 (保持不变,已优化) ---
- // 1. 查询用户
- $userList = Db::name("user")
- ->where('is_del', 0)
- // ->whereIn('uid', [277, 1593])
- ->column('uid, spread_uid, contribute, per_contribute, pv', 'uid');
- // $userIds = array_keys($userList);
- $oldUserList = Db::name("old_user_jbp")
- ->column('id, amount');
- // 2. 查询老订单
- $userOfGoodsListRaw = Db::name("old_user_of_goods")
- ->where('status', 1)
- // 优化: 如果用户量大,可以考虑只查相关用户的订单
- // ->whereIn('user_id', $userIds)
- ->field('user_id, money, order_id, create_time')
- ->select()
- ->toArray();
- // 3. 查询新订单
- $storeOrderListRaw = Db::name("store_order")
- ->whereIn('status', [0, 1, 2, 3])
- // 优化: 如果用户量大,可以考虑只查相关用户的订单
- // ->whereIn('uid', $userIds)
- ->field('uid, pay_price, mer_id, status, order_id, create_time')
- ->select()
- ->toArray();
- // 4. 查询已存在的贡献值记录
- $gongXianListRaw = Db::name("user_sign_gongxian")
- ->where('status', '<>', -1)
- // 优化: 如果记录非常多,可以分批查询或只查相关用户的
- // ->whereIn('uid', array_merge($userIds, array_column($userList, 'spread_uid'))) // 查询购买者和潜在推广者
- ->field('uid, order_id, number, status, type')
- ->select()
- ->toArray();
- // 5. 查询已存在的PV记录
- $pvListRaw = Db::name("user_pv_log")
- ->where('status', '<>', -1)
- // 优化: 同上
- // ->whereIn('uid', $userIds)
- ->field('uid, order_id, pv, status')
- ->select()
- ->toArray();
- // --- 数据预处理部分
- $existingGongXian = [];
- $existingGongXianByUid = [];
- foreach ($gongXianListRaw as $gx) {
- $existingGongXian[$gx['uid'] . '_' . $gx['order_id']] = ['number' => $gx['number'], 'status' => $gx['status'], 'type' => $gx['type']];
- // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
- if ((1 <= $gx['order_id'] && $gx['order_id'] <= 900) || (4868 <= $gx['order_id'] && $gx['order_id'] <= 6869)) {
- $existingGongXianByUid[$gx['uid']][] = $gx['order_id'];
- }
- }
- unset($gongXianListRaw);
- $existingPv = [];
- $existingPvByUid = [];
- foreach ($pvListRaw as $pv) {
- $existingPv[$pv['uid'] . '_' . $pv['order_id']] = ['pv' => $pv['pv'], 'status' => $pv['status']];
- // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
- if ((1 <= $pv['order_id'] && $pv['order_id'] <= 900) || (4868 <= $pv['order_id'] && $pv['order_id'] <= 6869)) {
- $existingPvByUid[$pv['uid']][] = $pv['order_id'];
- }
- }
- unset($pvListRaw);
- $userOfGoodsByUid = [];
- foreach ($userOfGoodsListRaw as $oldOrder) $userOfGoodsByUid[$oldOrder['user_id']][] = $oldOrder;
- unset($userOfGoodsListRaw);
- $storeOrdersByUid = [];
- foreach ($storeOrderListRaw as $order) $storeOrdersByUid[$order['uid']][] = $order;
- unset($storeOrderListRaw);
- // *** 主逻辑处理与数据收集 ***
- $gongXianDataToInsert = []; // 优化: 合并新旧贡献插入列表
- $pvDataToInsert = []; // 优化: 合并新旧PV插入列表
- $userUpdateData = []; // 优化: 收集所有需要更新的用户数据 [uid => ['contribute'=>float, 'pv'=>float, 'per_contribute'=>float]]
- // 初始化所有用户的待更新数据
- foreach ($userList as $uid => $user) {
- // 预先设置初始值,确保即使没有订单的用户也能被包含在后续可能的更新逻辑中(如果需要)
- // 如果用户没有任何订单,他们的 contribute 和 pv 应该保持数据库原始值或根据业务逻辑设为0
- // 这里我们先假设如果没有订单,他们的计算值就是0
- $userUpdateData[$uid] = [
- 'uid' => $uid,
- 'contribute' => 0.0,
- 'pv' => 0.0,
- 'per_contribute' => 0.0,
- ];
- // 初始化推广者的 per_contribute 累加器
- if (!empty($user['spread_uid'])) {
- $spreadUid = $user['spread_uid'];
- if (!isset($userUpdateData[$spreadUid])) {
- if (isset($userList[$spreadUid])) {
- if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
- $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
- }
- } else {
- // 记录或处理推广者不在当前用户列表的情况
- $result['errors'][] = "执行{$uid}时,没找到 推荐人 {$spreadUid}";
- // 可以选择跳过给这个推广者增加 per_contribute
- }
- } else if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
- $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
- }
- }
- }
- // 遍历用户列表进行计算和数据收集
- foreach ($userList as $uid => $user) {
- $spreadUid = $user['spread_uid'];
- $existingGongXianByUid[$uid] = $existingGongXianByUid[$uid] ?? [];
- $existingPvByUid[$uid] = $existingPvByUid[$uid] ?? [];
- if (isset($userOfGoodsByUid[$uid])) {
- foreach ($userOfGoodsByUid[$uid] as $oldOrder) {
- switch ($oldOrder['money']) {
- case 1180:
- $totalPv = 700.0;
- break;
- case 11800:
- $totalPv = 7000.0;
- break;
- case 10620:
- $totalPv = 6300.0;
- break;
- case 2360:
- $totalPv = 1400.0;
- break;
- case 9440:
- $totalPv = 5600.0;
- break;
- default:
- $totalPv = round($oldOrder['money'] * 0.7, 2);
- break;
- }
- $settlementTimeOld = $oldOrder['create_time'] ? date('Y-m-d H:i:s', $oldOrder['create_time']) : strtotime($user['create_time']);
- // --- 收集贡献值插入数据 ---
- $orderKey = $uid . '_' . $oldOrder['order_id'];
- // 一个人 同一个订单 可能有多条记录 有问题
- if (isset($existingGongXian[$orderKey])) {
- $result['oldOrderExistGongXian'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
- $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
- if ($existingGongXian[$orderKey]['status'] == 1) {
- if ($existingGongXian[$orderKey]['type'] == 1) {
- $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
- } else if ($existingGongXian[$orderKey]['type'] == 2) {
- $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
- }
- }
- if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
- $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
- if (isset($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']])) {
- if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['status'] == 1) {
- if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 1) {
- $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
- } else if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 2) {
- $userUpdateData[$spreadUid]['per_contribute'] -= $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
- }
- }
- }
- }
- } else {
- if ($totalPv > 0) {
- $userUpdateData[$uid]['contribute'] += $totalPv;
- // --- 收集贡献值插入数据 ---
- $gongXianBase = [
- "number" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
- "order_type" => 21, "order_id" => $oldOrder['order_id'],
- "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeOld
- ];
- // 本人
- $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买会员专区商品赠送贡献值(1.0)"], $gongXianBase);
- $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
- // 推广人
- if (!empty($user['spread_uid'])) {
- if (isset($userUpdateData[$spreadUid])) {
- $userUpdateData[$spreadUid]['per_contribute'] += $totalPv;
- $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广会员专区商品赠送贡献值(1.0)"], $gongXianBase);
- $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
- }
- }
- }
- }
- // --- 收集 PV 插入数据 ---
- if (isset($existingPv[$orderKey])) {
- $result['oldOrderExistPv'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
- if ($existingPv[$orderKey]['status'] == 1) {
- $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
- }
- } else {
- $userUpdateData[$uid]['pv'] += $totalPv;
- $pvDataToInsert[] = [
- "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
- "order_type" => 21, "order_id" => $oldOrder['order_id'],
- "mark" => "购买会员专区商品赠送PV(1.0)", 'settlement_time' => $settlementTimeOld
- ];
- }
- if (!empty($existingPvByUid[$uid])) {
- $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$oldOrder['order_id']]);
- }
- }
- } // end if isset($userOfGoodsByUid[$uid])
- // --- 处理新订单 ---
- if (isset($storeOrdersByUid[$uid])) {
- foreach ($storeOrdersByUid[$uid] as $order) {
- $totalPv = 0.0;
- // ... (if/else logic and switch case for $totalPv calculation - same as before)
- if ($order['mer_id'] == 496) {
- switch ($order['pay_price']) {
- case 1180:
- $totalPv = 700.0;
- break;
- case 11800:
- $totalPv = 7000.0;
- break;
- case 10620:
- $totalPv = 6300.0;
- break;
- case 2360:
- $totalPv = 1400.0;
- break;
- case 9440:
- $totalPv = 5600.0;
- break;
- default:
- $totalPv = round($order['pay_price'] * 0.7, 2);
- break;
- }
- } else if ($order['status'] == 3) {
- $totalPv = round($order['pay_price'] * 0.7, 2);
- }
- // --- 收集贡献值插入数据 ---
- $orderKey = $uid . '_' . $order['order_id'];
- $settlementTimeNew = $order['create_time'] ?: date('Y-m-d H:i:s', $user['create_time']);
- // --- 收集贡献值插入数据 ---
- if (isset($existingGongXian[$orderKey])) {
- $result['orderExistGongXian'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
- $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
- // 累加计算值
- if ($existingGongXian[$orderKey]['status'] == 1) {
- if ($existingGongXian[$orderKey]['type'] == 1) {
- $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
- } else if ($existingGongXian[$orderKey]['type'] == 2) {
- $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
- }
- }
- if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
- $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
- if (isset($existingGongXian[$spreadUid . '_' . $order['order_id']])) {
- if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['status'] == 1) {
- if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 1) {
- $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
- } else if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 2) {
- $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
- }
- }
- }
- }
- } else {
- if ($totalPv > 0) {
- $userUpdateData[$uid]['contribute'] += $totalPv;
- $gongXianBase = [ // 优化: 提取公共字段
- "number" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
- "order_type" => 22, "order_id" => $order['order_id'],
- "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeNew
- ];
- // 本人
- $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买商品赠送贡献值(2.0)"], $gongXianBase);
- $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
- // 推广人
- if (!empty($user['spread_uid'])) {
- $spreadUid = $user['spread_uid'];
- if (isset($userUpdateData[$spreadUid])) { // 确保推广者存在
- $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广商品赠送贡献值(2.0)"], $gongXianBase);
- $userUpdateData[$spreadUid]['per_contribute'] += $totalPv; // 累加推广者业绩
- $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
- }
- }
- }
- }
- // --- 收集 PV 插入数据 ---
- if (isset($existingPv[$orderKey])) {
- $result['orderExistPv'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
- if ($existingPv[$orderKey]['status'] == 1) {
- $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
- }
- } else {
- $userUpdateData[$uid]['pv'] += $totalPv;
- $pvDataToInsert[] = [
- "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
- "order_type" => 22, // 确认 PV log 的 order_type 是否与贡献一致或有区分
- "order_id" => $order['order_id'],
- "mark" => "购买商品赠送PV(2.0)", // 标记调整为更通用
- 'settlement_time' => $settlementTimeNew
- ];
- }
- if (!empty($existingPvByUid[$uid])) {
- $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$order['order_id']]);
- }
- }
- }
- // end if isset($storeOrdersByUid[$uid])
- // --- 比较计算值与原值 (移到循环外处理) ---
- // (在此处比较并记录到 $result['contributeNot'] / $result['pvNot'])
- // 注意:浮点数比较可能需要容差
- $tolerance = 0.001; // 定义一个小的容差值
- if (abs($userUpdateData[$uid]['contribute'] - (float)$user['contribute']) > $tolerance) {
- $result['contributeNot'][] = [
- 'uid' => $uid,
- 'contribute_old' => (float)$user['contribute'], // 显式转换
- 'contribute_new' => $userUpdateData[$uid]['contribute']
- ];
- }
- if (abs($userUpdateData[$uid]['pv'] - (float)$user['pv']) > $tolerance) {
- $result['pvNot'][] = [
- 'uid' => $uid,
- 'pv_old' => (float)$user['pv'], // 显式转换
- 'pv_new' => $userUpdateData[$uid]['pv']
- ];
- }
- // per_contribute 是累加的,不需要与旧值比较,直接更新
- } // end foreach ($userList as $uid => $user)
- // *** 数据库批量操作 ***
- // 使用事务确保数据一致性
- Db::startTrans();
- try {
- $bill = [];
- foreach ($oldUserList as $item) {
- $bill[] = [
- 'uid' => $item['id'],
- 'link_id' => 0,//关联订单id
- 'pm' => 1,//0:支出,1:获得
- 'title' => '佣金',//账单标题
- 'category' => 'now_money',//明细种类
- 'type' => 'commission',//明细类型
- 'number' => $item['amount'],//明细数字
- 'balance' => 0,//剩余
- 'mark' => '1.0佣金记录',//备注
- 'create_time' => '2025-02-04 00:00:00',//添加时间
- 'status' => 1,//0待确定,1有效,-1无效
- 'commission_type' => 21,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
- //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
- //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
- 'order_sn' => 0,//订单号
- 'tripartite' => 0,//
- 'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
- 'mer_id' => 0,//商户id
- 'source' => 0,//1线下 0线上
- 'order_type' => 1,//1自营 2 第三方 订单类型
- 'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
- 'gzc' => 3,//养老金是否已进入公证处log表0:未进入。1:已进入
- 'take_time' => '',//结算时间
- 'district_id' => '',//
- 'street_id' => '',//
- 'month' => '',//月份
- ];
- }
- $chunkedBill = array_chunk($bill, 500);
- foreach ($chunkedBill as $chunk) {
- Db::name('user_bill')->insertAll($chunk);
- }
- if (!empty($existingGongXianByUid)) {
- foreach ($existingGongXianByUid as $uid => $orderList) {
- if (!empty($orderList)) {
- Db::name("user_sign_gongxian")
- ->where('uid', $uid)
- ->whereIn('order_id', $orderList)
- ->update(['status' => 0]);
- }
- }
- }
- if (!empty($existingPvByUid)) {
- foreach ($existingPvByUid as $uid => $orderList) {
- if (!empty($orderList)) {
- Db::name("user_pv_log")
- ->where('uid', $uid)
- ->whereIn('order_id', $orderList)
- ->update(['status' => 0]);
- }
- }
- }
- // --- 批量插入贡献值 ---
- if (!empty($gongXianDataToInsert)) {
- // 分块插入,避免单次插入过多数据 (例如一次500条)
- $chunkedGongXian = array_chunk($gongXianDataToInsert, 500);
- foreach ($chunkedGongXian as $chunk) {
- $insertedGongXianCount = Db::name('user_sign_gongxian')->insertAll($chunk);
- $result['insertGongXianSummary']['success'] += $insertedGongXianCount;
- }
- if ($result['insertGongXianSummary']['success'] < count($gongXianDataToInsert)) {
- $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert) - $result['insertGongXianSummary']['success'];
- // 可以考虑记录更详细的失败信息,但这比较复杂,需要知道哪些失败了
- $result['errors'][] = "GongXian insertion partially failed or failed completely.";
- // 根据业务决定是否回滚
- // throw new Exception("GongXian insertion failed");
- }
- } else {
- $result['insertGongXianSummary']['skipped'] = true; // 标记为跳过(无数据)
- }
- // --- 批量插入PV ---
- if (!empty($pvDataToInsert)) {
- $chunkedPv = array_chunk($pvDataToInsert, 500);
- foreach ($chunkedPv as $chunk) {
- $insertedPvCount = Db::name('user_pv_log')->insertAll($chunk);
- $result['insertPvSummary']['success'] += $insertedPvCount;
- }
- if ($result['insertPvSummary']['success'] < count($pvDataToInsert)) {
- $result['insertPvSummary']['failed'] = count($pvDataToInsert) - $result['insertPvSummary']['success'];
- $result['errors'][] = "PV Log insertion partially failed or failed completely.";
- // throw new Exception("PV Log insertion failed");
- }
- } else {
- $result['insertPvSummary']['skipped'] = true; // 标记为跳过(无数据)
- }
- // --- 批量更新用户信息 ---
- $usersToUpdate = [];
- // 筛选出实际需要更新的用户数据 (值有变化或 per_contribute > 0)
- foreach ($userUpdateData as $uid => $updateInfo) {
- $originalUser = $userList[$uid]; // 获取原始用户信息
- // 检查 contribute 或 pv 是否变化(使用容差),或者 per_contribute 是否需要更新
- $needsUpdate = false;
- if (abs($updateInfo['contribute'] - (float)$originalUser['contribute']) > $tolerance) $needsUpdate = true;
- if (abs($updateInfo['pv'] - (float)$originalUser['pv']) > $tolerance) $needsUpdate = true;
- // per_contribute 始终更新,因为它是在现有基础上累加的(除非业务定义不同)
- // 如果 per_contribute 数据库设计是直接覆盖,那只有 > 0 时才需要更新
- // 假设是覆盖更新,且只有大于0时才需要更新变动(如果一直是0则不用更新)
- if ($updateInfo['per_contribute'] > 0.0) { // 只有当推广业绩>0时才触发更新
- // 这里需要确认 per_contribute 是覆盖还是累加?
- // 如果是数据库累加: Db::name("user")->where('uid', $uid)->inc('per_contribute', $amount)->update(); 需要单独处理
- // 如果是覆盖: 直接放入 saveAll
- // 假设是覆盖,我们只更新有变化的或per_contribute > 0 的
- $needsUpdate = true;
- } else {
- // 如果 per_contribute 计算结果为0,且 contribute 和 pv 也未变,则不需要更新 per_contribute 字段
- unset($updateInfo['per_contribute']); // 移除无需更新的 per_contribute
- if (empty($updateInfo)) $needsUpdate = false; // 如果移除后为空,则不更新
- }
- if ($needsUpdate) {
- // 确保只包含需要更新的字段,并且包含主键 'uid'
- $finalUpdateData = ['uid' => $uid];
- if (isset($updateInfo['contribute'])) $finalUpdateData['contribute'] = $updateInfo['contribute'];
- if (isset($updateInfo['pv'])) $finalUpdateData['pv'] = $updateInfo['pv'];
- if (isset($updateInfo['per_contribute']) && $updateInfo['per_contribute'] > 0.0) { // 再次确认只更新大于0的推广业绩
- $finalUpdateData['per_contribute'] = $updateInfo['per_contribute'];
- }
- if (count($finalUpdateData) > 1) { // 确保除了uid还有其他字段要更新
- $usersToUpdate[] = $finalUpdateData;
- } else {
- $result['userUpdateSummary']['skipped']++; // 记录跳过的更新(无变化)
- }
- } else {
- $result['userUpdateSummary']['skipped']++; // 记录跳过的更新(无变化)
- }
- }
- if (!empty($usersToUpdate)) {
- // 使用 saveAll 进行批量更新 (要求 PHP >= 7.1.8 for MySQL)
- // saveAll 会根据主键 'uid' 更新对应记录
- $userModel = new User();
- $updatedCount = $userModel->saveAll($usersToUpdate); // TP6 支持 saveAll
- // 注意: saveAll 返回的是成功保存或更新的 *对象集合* 或 *布尔值*,不是影响的行数。
- // 需要检查返回类型并判断成功数量。通常返回集合时 count(集合) 是成功数。
- // 如果是 TP5,可能需要循环 update 或构造复杂 SQL。
- // 假设 TP6 saveAll 成功会返回包含更新后数据的集合或true,失败是false
- if ($updatedCount !== false) {
- // 这里需要一种方法来确定实际更新了多少条记录。
- // saveAll 的返回值可能需要进一步处理。
- // 简单假设:如果返回不是 false,就认为请求中的都成功了(可能不准确)
- // 更精确的方法是 saveAll 后再查询一次确认。
- // 这里我们暂时认为 saveAll 返回非 false 即为大部分成功
- $result['userUpdateSummary']['success'] = count($usersToUpdate); // 乐观估计
- } else {
- $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 全部失败
- $result['errors'][] = "User batch update failed using saveAll.";
- // throw new Exception("User batch update failed");
- }
- }
- // 更新统计:失败数等于总数减去成功和跳过的
- //$result['userUpdateSummary']['failed'] = count($userList) - $result['userUpdateSummary']['success'] - $result['userUpdateSummary']['skipped'];
- // 如果所有操作都成功,提交事务
- Db::commit();
- } catch
- (\Exception $e) {
- // 如果任何数据库操作失败,回滚事务
- Db::rollback();
- // 记录错误信息
- $result['errors'][] = "Transaction failed: " . $e->getMessage();
- // 可以根据需要将 insert/update 摘要设置为失败
- $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 假设更新失败
- $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert); // 假设插入失败
- $result['insertPvSummary']['failed'] = count($pvDataToInsert); // 假设插入失败
- }
- // --- 清理/最终结果赋值 (可选) ---
- // $result['gongXianDataOldList'] = $gongXianDataOldList; // 这些已合并到 ToInsert
- // $result['gongXianDataList'] = $gongXianDataList;
- // $result['pvDataOldList'] = $pvDataOldList;
- // $result['pvDataList'] = $pvDataList;
- return json($result);
- // // 计算总业绩
- // $totalPv = [];
- // foreach ($user_team_amount as $order) {
- // if (!isset($totalPv[$order['user_id']])) {
- // $totalPv[$order['user_id']] = 0;
- // }
- // switch ($order['money']) {
- // case 1180:
- // $totalPv[$order['user_id']] += 700;
- // break;
- // case 11800:
- // $totalPv[$order['user_id']] += 7000;
- // break;
- // case 10620:
- // $totalPv[$order['user_id']] += 6300;
- // break;
- // case 2360:
- // $totalPv[$order['user_id']] += 1400;
- // break;
- // case 9440:
- // $totalPv[$order['user_id']] += 5600;
- // break;
- // default:
- // if ($order['money'] == 2344.99) {
- // break;
- // }
- // $totalPv[$order['user_id']] += round($order['money'] * 0.7, 2);
- // break;
- // }
- // }
- // foreach ($totalPv as $uid => $pv) {
- // Db::name("user")->where('is_old', 1)->where("uid", $uid)->update(['pv' => $pv]);
- // }
- //
- // return;
- // /**
- // * 周金花200(13959100621)
- // * 黄金花200(18603401312)
- // * 徐立苹100(13521438652)
- // * 李素红200(13701061395)
- // * 周行体200(13231658486)
- // * 刘银霞100(13161909228)
- // * 李卫东100(13911601230)
- // * 金 波100(13801358713)
- // * 王 玲 150(15810064711)
- // * 侯玉兰150(15232797965)
- // * 吕丽娣100(15960349667)
- // * 张传莲100(15332507711)
- // * 刘春梅100(18760167163)
- // * 付天如100(18863873000)
- // * 付绍先100(15324059286)
- // * 黄桂林100(15960196876)
- // * 温 煌100(18350134089)
- // * 谭英先100(13978627072)
- // * 陈玉珍100(19858353660)
- // * 黄雪云100(18650055445)
- // * 黄 玲100(13877193411)
- // * 邱佳珍100(13960379098)
- // * 隋彩云100(13601071082)
- // */
- // $data = [
- // '13959100621' => 200,
- // '18603401312' => 200,
- // '13521438652' => 100,
- // '13701061395' => 200,
- // '13231658486' => 200,
- // '13161909228' => 100,
- // '13911601230' => 100,
- // '13801358713' => 100,
- // '15810064711' => 150,
- // '15232797965' => 150,
- // '15960349667' => 100,
- // '15332507711' => 100,
- // '18760167163' => 100,
- // '18863873000' => 100,
- // '15324059286' => 100,
- // '15960196876' => 100,
- // '18350134089' => 100,
- // '13978627072' => 100,
- // '19858353660' => 100,
- // '18650055445' => 100,
- // '13877193411' => 100,
- // '13960379098' => 100,
- // '13601071082' => 100,
- // ];
- // $result = Db::name("user")
- // ->whereIn("account", array_keys($data))
- // ->where('is_del', 0)
- // ->field('uid, brokerage_price, account, nickname')
- // ->select();
- // $res = [];
- // foreach ($result as $v) {
- // Db::name("user")->where("uid", $v['uid'])->inc("brokerage_price", $data[$v['account']])->save();
- // $this->bill_user_log111111($v['uid'], "佣金补贴", $data[$v['account']], "佣金补贴", 8);//股权分佣明细2.0系统
- // $res[] = [
- // 'uid' => $v['uid'],
- // 'account' => $v['account'],
- // 'brokerage_price_pre' => $v['brokerage_price'],
- // 'brokerage_price' => $data[$v['account']],
- // 'nickname' => $v['nickname']
- // ];
- // }
- // return json($res);
- }
- public function lst6()
- {
- $startTime = '2025-03-10';
- $endTime = '2025-03-30';
- // 查询测试人员账号信息
- //18973958920
- //15186694339
- //18833633835
- //19525470098
- //17756507016
- //18226705337
- $testAccount = ['18973958920', '15186694339', '18833633835', '19525470098', '17756507016', '18226705337'];
- $removeUserList = Db::name("user")
- ->whereIn('account', $testAccount)
- ->where("status", "<>", 0)
- ->where('is_del', '<>', 1)
- ->select()
- ->toArray();
- $removeUserIdList = array_column($removeUserList, 'uid');
- if (empty($startTime) || empty($endTime)) {
- $timeMap = $this->getTime('last_week');
- $startTime = $timeMap['startTime'] . ' 00:00:00';
- $endTime = $timeMap['endTime'] . ' 23:59:59';
- }
- // 定义分红金额
- $weekRecord = $this->getTeamPvByTime($startTime, $endTime, $removeUserIdList);
- // 分红金额 - 红包金额
- $redEnvelope = $this->getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList);
- $weekRecord -= $redEnvelope;
- if ($weekRecord <= 0) {
- return json('无效分红金额');
- }
- // $stock_comm = round($weekRecord * 0.05 ,2);
- $stock_comm = floor(($weekRecord * 0.05) * 100) / 100;
- //获取股权分红的人
- $GetAllUserPackNum = db::name("old_user_stock")->sum("pack");//计算所有用户的份数总和
- $stockuserdatas = db::name("old_user_stock")->select();//获取所有用户
- $salesArr = [];
- if (count($stockuserdatas) > 0) {
- // $one_pack_comm_data = round($stock_comm / $GetAllUserPackNum,2);//获取每份的单佣金
- $one_pack_comm_data = floor(($stock_comm / $GetAllUserPackNum) * 100) / 100;
- foreach ($stockuserdatas as &$v) {
- $salesArr[] = [
- 'stock_comm' => $stock_comm,
- 'GetAllUserPackNum' => $GetAllUserPackNum,
- 'uid' => $v['user_id'],
- 'pack' => $v['pack'],
- 'one_pack_comm_data' => $one_pack_comm_data,
- 'getcomm' => floor(($v['pack'] * $one_pack_comm_data) * 100) / 100
- ];
- $v['getcomm'] = floor(($v['pack'] * $one_pack_comm_data) * 100) / 100;
- $v['allgetcomm'] = $v['allgetcomm'] + $v['getcomm'];
- $v['update_time'] = time();
- $yj_90 = $v['getcomm'] * 0.9;
- $fg_10 = $v['getcomm'] * 0.1;
- // // 更新 user_stock 表中的记录
- $res = db::name("old_user_stock")->where("id", $v['id'])->update([
- 'getcomm' => $v['getcomm'],
- 'allgetcomm' => $v['allgetcomm'],
- 'update_time' => $v['update_time']
- ]);
- Db::name("user")->where("uid", $v['user_id'])->inc("brokerage_price", $yj_90)->save();
- $res1 = Db::name("user")->where("uid", $v['user_id'])->inc("total_amount_old", $yj_90)->save();
- $res2 = Db::name("user")->where("uid", $v['user_id'])->inc("amount_old", $yj_90)->save();
- $res3 = Db::name("user")->where("uid", $v['user_id'])->inc("fugou", $fg_10)->save();
- $res = true;
- if ($res) {
- $das = $this->change_user_log($v['user_id'], 'amount_old', 1, $yj_90, "member_award_stock", "股权分红入账" . "-" . $v['pack']);//释放佣金
- //入账星级分红记录表
- $week_data = [];
- $week_data['user_id'] = $v['user_id'];
- $week_data['user_star_id'] = 0;
- $week_data['award_num'] = 0;
- $week_data['award_num_sm'] = 0;
- $week_data['remark'] = "股权分红主动执行" . $yj_90;
- $week_data['week_record'] = $weekRecord;
- $week_data['all_amount'] = $stock_comm;
- $week_data['radio'] = 2;
- $week_data['owner_bill'] = 0; //总流水金额
- $week_data['my_bill'] = 0; //我的流水
- $week_data['create_time'] = time();
- Db::name("old_user_weekaward")->insert($week_data);
- $userdatassss = db::name("old_user_jbp")->where("id", $v['user_id'])->find();
- $datas_log = [
- 'note' => "名称:" . $userdatassss['nick_name'] . " 用户:" . $v['user_id'] . " 新增股权佣金:" . $yj_90,
- 'create_time' => date('Y-m-d H:i:s')
- ];
- $con_data = Db::name('test_log')->insert($datas_log); //数据存到2.0数据表中
- $this->bill_user_log111111($v['user_id'], "股权分佣", $yj_90, "股权明细入账", 13);//股权分佣明细2.0系统
- $this->fugou_user_log($v['user_id'], $fg_10, 16, 1, 1);//复购金明细入账
- }
- }
- }
- return json($salesArr);
- //股权分红 end
- }
- //添加复购金
- public function fugou_user_log($uid, $num, $order_id, $type_inc_des, $status = -1)
- {
- $fugou_data = Db::name('user')->where("uid", $uid)->find();
- $bill = [
- 'uid' => $uid,
- 'number' => $num,//数量
- 'status' => $status,//复购金状态1-有效 0-失效 -1待确认
- 'mark' => "复购金",//备注
- 'desc' => "10%作为复购金",//描述
- 'order_id' => $order_id,//订单id
- 'surplus' => 0,//剩余
- 'order_type' => 11,//关联订单ID
- 'type' => $type_inc_des,//复购金类型 :1赠送,2消耗
- 'settlement_time' => date('Y-m-d H:i:s'),//添加时间,
- 'addtime' => time(),
- ];
- Db::name('user_sign_fugou')->insert($bill);
- }
- //添加平台分佣2.0系统收益明细日志(养老金金额)
- public function bill_user_log111111($uid, $name, $num, $mark, $comm)
- {
- $con_data = Db::name('user')->where("uid", $uid)->find();
- //如果是会员专区就即刻到账
- // Db::name('user')->where("uid",$con_data['uid'])->update(['brokerage_price'=> $con_data['brokerage_price'] + $num]);
- $bill = [
- 'uid' => $uid,
- 'link_id' => 0,//关联订单id
- 'pm' => 1,//0:支出,1:获得
- 'title' => $name,//账单标题
- 'category' => 'now_money',//明细种类
- 'type' => 'commission',//明细类型
- 'number' => $num,//明细数字
- 'balance' => 0,//剩余
- 'mark' => $mark,//备注
- 'create_time' => date('Y-m-d H:i:s'),//添加时间
- 'status' => 1,//0待确定,1有效,-1无效
- 'commission_type' => $comm,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
- //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
- //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
- 'order_sn' => 0,//订单号
- 'tripartite' => 0,//
- 'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
- 'mer_id' => 0,//商户id
- 'source' => 0,//1线下 0线上
- 'order_type' => 1,//1自营 2 第三方 订单类型
- 'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
- 'gzc' => 3,//养老金是否已进入公证处log表0:未进入。1:已进入
- 'take_time' => '',//结算时间
- 'district_id' => '',//
- 'street_id' => '',//
- 'month' => '',//月份
- ];
- Db::name('user_bill')->insert($bill);
- }
- //发放佣金 示例: $this->change_user_log($v,'amount',1,$all_award,"member_award","星级分红入账"."-".$value['title']);//释放佣金
- function change_user_log($user_id, $type, $change_status, $money, $routine, $remark = "", $is_admin = 1, $appoint_money = 0)
- {
- $transition = [
- 'pv' => 1,
- "gb" => 2,
- "df" => 3,
- "vr" => 4,
- "bt" => 5,
- "withdraw_quota_old" => 6,//提现
- "unsettled_pension" => 7,
- "amount_old" => 8//发放佣金
- ];
- $routineInfo = Db::name("old_routine_log_of_key")->where("key", $routine)->find();
- if (empty($routineInfo)) {
- return false;
- }
- $key_id = isset($routineInfo['id']) ? $routineInfo['id'] : 0;
- if ($appoint_money > 0) {
- $alter_money = $appoint_money;
- } else {
- //再去查询变更前的 金额
- $alter_money = Db::name("user")->where('uid', $user_id)->value($type);
- }
- if ($change_status == 1) {
- //新增前
- $alter_money = $alter_money - $money;
- } else if ($change_status == 2) {
- //减少前
- $alter_money = $alter_money + $money;
- }
- if ($alter_money < 0) {
- $alter_money = 0;
- }
- $inser_data = [];
- $inser_data['user_id'] = $user_id;
- $inser_data['type'] = $transition[$type];
- $inser_data['change_status'] = $change_status;
- $inser_data['money'] = $money;
- $inser_data['routine_log_of_key_id'] = $key_id;
- $inser_data['remark'] = $remark;
- $inser_data['is_admin'] = $is_admin;
- $inser_data['create_time'] = time();
- $inser_data['alter_money'] = isset($alter_money) ? $alter_money : 0;
- Db::name("old_user_log")->insert($inser_data);
- }
- public function getTime($timePeriod)
- {
- // 定义时间区间
- $now = time();
- $startTime = '';
- $endTime = '';
- if ($timePeriod == 'last_week') {
- // 上周的时间区间
- $startTime = date('Y-m-d', strtotime('monday last week', $now)); // 上周星期一的开始时间
- $endTime = date('Y-m-d', strtotime('sunday last week', $now)); // 上周星期日的结束时间
- } elseif ($timePeriod == 'this_week') {
- // 这周的时间区间
- $startTime = date('Y-m-d', strtotime('monday this week', $now)); // 这周星期一的开始时间
- $endTime = date('Y-m-d', strtotime('sunday this week', $now)); // 这周星期日的结束时间
- }
- // return ['startTime' => '2025-03-10', 'endTime' => '2025-03-23'];
- return ['startTime' => $startTime, 'endTime' => $endTime];
- }
- public function getTeamPvByTime($startTime, $endTime, $removeUserIdList = [])
- {
- // 查询指定时间区间内的所有订单,并排除 pay_time 为 NULL 的订单
- $orders = Db::name("store_order")
- ->where('mer_id', 496)
- ->whereNotIn('uid', $removeUserIdList)
- ->whereIn('status', [0, 1, 2, 3])
- ->whereIn("total_price", [1180, 11800, 10620, 2360, 9440])
- ->whereBetween("pay_time", [$startTime, $endTime])
- ->whereNotNull("pay_time") // 排除 pay_time 为 NULL 的订单
- ->select();
- // 计算总业绩
- $totalPv = 0;
- foreach ($orders as $order) {
- switch ($order['total_price']) {
- case 1180:
- $totalPv += 700;
- break;
- case 11800:
- $totalPv += 7000;
- break;
- case 10620:
- $totalPv += 6300;
- break;
- case 2360:
- $totalPv += 1400;
- break;
- case 9440:
- $totalPv += 5600;
- break;
- }
- }
- return $totalPv;
- }
- public function getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList = [])
- {
- // 查询指定时间区间内的所有订单,并排除 pay_time 为 NULL 的订单
- $redEnvelopeList = Db::name("user_sign_hongbao")
- ->whereNotIn('uid', $removeUserIdList)
- ->where('status', 1)
- ->whereBetween("settlement_time", [$startTime, $endTime])
- ->select()
- ->toArray();
- return floor(array_sum(array_column($redEnvelopeList, 'number')) * 100) / 100;
- }
- }
|