store_id)) { $this->store_id = get_store_id(); } } /** * 导入会员增加积分和佣金 * @return array */ public function importUserRecharge() { $admin = \Yii::$app->jwt->getAdmin(); $store_id = $this->store_id; // 获取活动类型参数 $activity_type = post_params('send_type', 'integral'); // 默认为积分活动 $activity_id = post_params('activity_id', 0); // 获取选择的活动ID set_time_limit(0); $filename = $_FILES['excel']['name']; $tmpname = $_FILES['excel']['tmp_name']; $path = \Yii::$app->basePath . '/web/temp/'; if(!is_dir($path)){ mkdir($path); } $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (($ext != 'xlsx') && ($ext != 'xls')) { return [ 'code' => 1, 'msg' => '请上传excel文件' ]; } $file = time() . $this->store_id . '.' . $ext; $uploadfile = $path . $file; move_uploaded_file($tmpname, $uploadfile); $rows = \Spatie\SimpleExcel\SimpleExcelReader::create($uploadfile) ->getRows(); $err = []; $success = []; // 如果指定了活动ID,则获取该活动 $activity = null; if ($activity_id) { $activity = ActivityOrderRebateSelf::findOne($activity_id); if (!$activity) { return [ 'code' => 1, 'msg' => '指定的活动不存在' ]; } // 获取活动关联的产品 $product = Goods::findOne($activity->goods_ids); if (!$product) { // 如果找不到产品,创建一个新产品 $product = $this->createProduct($store_id, $activity->name . '导入产品'); } } else { return [ 'code' => 1, 'msg' => '指定的活动不存在' ]; // 如果没有指定活动ID,则创建默认产品和活动 // $product = $this->createProduct($store_id, '积分余额导入产品'); // // // 根据活动类型创建不同的活动 // switch ($activity_type) { // case 'integral': // $activity = $this->createActivity($store_id, '积分导入活动', $product->id, [2], [2=>100]); // break; // case 'balance': // $activity = $this->createActivity($store_id, '余额导入活动', $product->id, [3], [3=>100]); // break; // case 'commission': // $activity = $this->createActivity($store_id, '佣金导入活动', $product->id, [1], [1=>100]); // break; // default: // $activity = $this->createActivity($store_id, '积分余额导入活动', $product->id, [1,2,3], [1=>33,2=>33,3=>34]); // } } // 统计每种类型的成功和失败数量 $stats = [ 'balance' => ['success' => 0, 'fail' => 0], 'integral' => ['success' => 0, 'fail' => 0], 'commission' => ['success' => 0, 'fail' => 0] ]; $rows->each(function (array $item) use ($admin, $store_id, &$err, &$success, &$stats, $activity, $activity_type, $product) { try { $mobile = trim($item['手机号']); $nickname = trim($item['昵称']); $change = isset($item['余额']) ? trim($item['余额']) : 0; $integral = isset($item['积分']) ? trim($item['积分']) : 0; $commission = isset($item['佣金']) ? trim($item['佣金']) : 0; $desc = trim($item['余额变动备注']) ? trim($item['余额变动备注']) : ''; if ($activity->send_type ==1 && $commission == 0) { throw new \Exception('导入失败:请用佣金模板导入' ); } if ($activity->send_type ==2 && $integral == 0) { throw new \Exception('导入失败:请用积分模板导入' ); } if ($activity->send_type ==3 && $change == 0) { throw new \Exception('导入失败:请用余额模板导入' ); } // 查找或创建用户 $user = $this->findOrCreateUser($mobile, $nickname, $store_id); // $product = $activity = []; // if (empty($product)) { // $product = $this->createProduct($store_id, '积分余额导入产品'); // $activity = $this->createActivity($store_id, '积分余额导入活动', $product->id, [1,2,3], [1=>33,2=>33,3=>34]); // } // 根据活动类型处理不同的数据 switch ($activity_type) { case 'integral': if ($integral != 0) { try { $this->createOrder($user, $product, $activity, abs($integral), $store_id, '积分'); $stats['integral']['success']++; } catch (\Exception $e) { $stats['integral']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理积分失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } break; case 'balance': if ($change != 0) { try { $this->createOrder($user, $product, $activity, abs($change), $store_id, '余额'); $stats['balance']['success']++; } catch (\Exception $e) { $stats['balance']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理余额失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } break; case 'commission': if ($commission != 0) { try { $this->createOrder($user, $product, $activity, abs($commission), $store_id, '佣金'); $stats['commission']['success']++; } catch (\Exception $e) { $stats['commission']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理佣金失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } break; default: // 处理所有类型 // 处理余额增减 if ($change != 0) { try { $this->createOrder($user, $product, $activity, abs($change), $store_id, '余额'); $stats['balance']['success']++; } catch (\Exception $e) { $stats['balance']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理余额失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } // 处理积分增减 if ($integral != 0) { try { $this->createOrder($user, $product, $activity, abs($integral), $store_id, '积分'); $stats['integral']['success']++; } catch (\Exception $e) { $stats['integral']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理积分失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } // 处理佣金增减 if ($commission != 0) { try { $this->createOrder($user, $product, $activity, abs($commission), $store_id, '佣金'); $stats['commission']['success']++; } catch (\Exception $e) { $stats['commission']['fail']++; $err[] = [ 'code' => 1, 'msg' => '处理佣金失败: ' . $e->getMessage(), 'mobile' => $mobile ]; } } } $success[] = [ 'mobile' => $mobile, 'nickname' => $nickname, 'change' => $change, 'integral' => $integral, 'commission' => $commission ]; } catch (\Exception $e){ debug_log($e->getMessage()); $err[] = [ 'code' => 1, 'msg' => $e->getMessage(), 'mobile' => $mobile ]; } }); $count = count($err); $successCount = count($success); @unlink($uploadfile); // 生成详细的统计信息 $statMsg = sprintf( "余额导入成功%d条,失败%d条;积分导入成功%d条,失败%d条;佣金导入成功%d条,失败%d条", $stats['balance']['success'], $stats['balance']['fail'], $stats['integral']['success'], $stats['integral']['fail'], $stats['commission']['success'], $stats['commission']['fail'] ); if ($activity->send_type == 1) { $statMsg = sprintf( "佣金导入成功%d条,失败%d条", $stats['commission']['success'], $stats['commission']['fail'] ); } if ($activity->send_type == 2) { $statMsg = sprintf( "积分导入成功%d条,失败%d条", $stats['integral']['success'], $stats['integral']['fail'] ); } if ($activity->send_type == 3) { $statMsg = sprintf( "余额导入成功%d条,失败%d条", $stats['balance']['success'], $stats['balance']['fail'] ); } return [ 'code' => $count ? 1 : 0, 'msg' => "操作完成,导入条数据" . ($err ? ",失败{$count}条数据" : '') . "\n{$statMsg}", 'err' => $err, 'success' => $success, ]; } /** * 创建活动产品 * @param int $store_id 店铺ID * @param string $name 产品名称 * @return Goods 产品对象 */ public function createProduct($store_id, $name) { $product = new Goods(); $product->store_id = $store_id; $product->name = $name; $product->detail = $name . '详情'; $product->price = 1; // 产品金额1元 $product->status = 0; $product->created_at = time(); $product->updated_at = time(); if (!$product->save()) { throw new \Exception('创建活动产品失败:' . json_encode($product->errors)); } return $product; } /** * 创建活动 * @param int $store_id 店铺ID * @param string $name 活动名称 * @param int $product_id 产品ID * @param array $send_types 返利类型 * @param array $send_type_percentages 返利比例 * @return ActivityOrderRebateSelf 活动对象 */ public function createActivity($store_id, $name, $product_id, $send_types, $send_type_percentages, $release_rate = 10) { $activity = new ActivityOrderRebateSelf(); $activity->store_id = $store_id; $activity->name = $name . '-' . date('YmdHis'); $activity->start_time = time(); $activity->end_time = time() + 86400 * 30; // 30天后结束 $activity->goods_ids = $product_id; // 产品 $activity->send_days = 1; // 周期 $activity->send_num = 100; // 返利比例 $activity->send_types = json_encode($send_types); // 返利类型 $activity->send_type_percentages = json_encode($send_type_percentages); // 返利比例 $activity->status = 1; // 活动状态:启用 $activity->release_rate = $release_rate; $activity->created_at = time(); $activity->updated_at = time(); if (!$activity->save()) { throw new \Exception('创建活动失败:' . json_encode($activity->errors)); } $gids = [$product_id]; if(!empty($gids)){ $result = ActivityOrderRebateSelfGoods::saveList($gids, $activity->id); if ($result['code'] !== 0) { throw new \Exception($result['msg']); } } return $activity; } /** * 查找或创建用户 * @param string $mobile 手机号 * @param string $nickname 昵称 * @param int $store_id 店铺ID * @return User 用户对象 */ private function findOrCreateUser($mobile, $nickname, $store_id) { $user = User::findOne(['binding' => $mobile, 'is_delete' => 0, 'store_id' => $store_id]); $saas_user = SaasUser::findOne(['mobile' => $mobile, 'is_delete' => 0]); if(!$user){ if (!$saas_user) { $saas_user = new SaasUser(); $saas_user->access_token = \Yii::$app->security->generateRandomString(); $saas_user->avatar = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/web/v1/statics/images/avatar.png'; $saas_user->mobile = $mobile ?: ''; $saas_user->name = $nickname ? $nickname : substr_replace($mobile, '******', 3, 6); $saas_user->store_id = $store_id; if (!$saas_user->save()) { throw new \Exception(array_shift($saas_user->getFirstErrors())); } } $user = new User(); $user->access_token = \Yii::$app->security->generateRandomString(); $user->binding = $saas_user->mobile; $user->nickname = $saas_user->name; $user->avatar_url = $saas_user->avatar; $user->username = \Yii::$app->security->generateRandomString(); $user->password = \Yii::$app->security->generatePasswordHash(\Yii::$app->security->generateRandomString(), 5); $user->auth_key = \Yii::$app->security->generateRandomString(); $user->store_id = $store_id; if (!$user->save()) { throw new \Exception(array_shift($user->getFirstErrors())); } } if($nickname && $nickname != $saas_user->name){ $saas_user->name = $nickname; if (!$saas_user->save()) { throw new \Exception(array_shift($saas_user->getFirstErrors())); } } if($nickname && $nickname != $user->nickname){ $user->nickname = $nickname; if (!$user->save()) { throw new \Exception(array_shift($user->getFirstErrors())); } } return $user; } /** * 处理余额增减 * @param User $user 用户对象 * @param float $change 变动金额 * @param string $desc 变动描述 * @param object $admin 管理员对象 * @param int $store_id 店铺ID */ private function processBalanceChange($user, $change, $desc, $admin, $store_id) { $recharge_type = ($change > 0) ? AccountLog::LOG_TYPE_INCOME : AccountLog::LOG_TYPE_EXPEND; $data = [ 'explain' => '', 'money' => abs($change), 'integral' => 0, 'recharge_type' => $recharge_type, 'type' => AccountLog::TYPE_BALANCE, 'user_id' => $user->id, 'desc' => $desc ]; if($recharge_type == AccountLog::LOG_TYPE_EXPEND && $user->money < $data['money']){ $data['money'] = $user->money; } if($data['money'] > 0){ $form = new AccountLogForm(); $form->store_id = $store_id; $form->admin = $admin; $form->attributes = $data; $res = $form->recharge(); if($res['code'] != 0){ throw new \Exception($res['msg']); } } } /** * 处理积分增减 * @param User $user 用户对象 * @param float $integral 变动积分 * @param string $desc 变动描述 * @param object $admin 管理员对象 * @param int $store_id 店铺ID */ private function processIntegralChange($user, $integral, $desc, $admin, $store_id) { $recharge_type = ($integral > 0) ? AccountLog::LOG_TYPE_INCOME : AccountLog::LOG_TYPE_EXPEND; $data = [ 'explain' => '', 'money' => 0, 'integral' => abs($integral), 'recharge_type' => $recharge_type, 'type' => AccountLog::TYPE_INTEGRAL, 'user_id' => $user->id, 'desc' => $desc ]; if($recharge_type == AccountLog::LOG_TYPE_EXPEND && $user->integral < $data['integral']){ $data['integral'] = $user->integral; } if($data['integral'] > 0){ $form = new AccountLogForm(); $form->store_id = $store_id; $form->admin = $admin; $form->attributes = $data; $res = $form->recharge(); if($res['code'] != 0){ throw new \Exception($res['msg']); } } } /** * 处理佣金增减 * @param User $user 用户对象 * @param float $commission 变动佣金 * @param string $desc 变动描述 * @param int $store_id 店铺ID */ private function processCommissionChange($user, $commission, $desc, $store_id) { // 使用 UserShareMoney 模型处理佣金变动 // 参数说明:金额, 用户ID, 订单ID(0表示无订单), 类型(0表示佣金), 来源(10表示后台修改), 店铺ID, 订单类型(0表示商城订单), 描述 $result = UserShareMoney::set( abs($commission), $user->id, 0, 0, 10, $store_id, 0, $desc ?: '后台导入佣金' . ($commission > 0 ? '增加' : '减少') ); if (!$result) { throw new \Exception('佣金' . ($commission > 0 ? '增加' : '减少') . '失败'); } } /** * 创建订单和返利记录 * @param User $user 用户对象 * @param Goods $product 产品对象 * @param ActivityOrderRebateSelf $activity 活动对象 * @param float $quantity 数量 * @param int $store_id 店铺ID * @param string $type_name 类型名称(用于日志) * @return Order 订单对象 */ public function createOrder($user, $product, $activity, $quantity, $store_id, $type_name) { // 创建订单 $order = new Order(); $order->user_id = $user->id; $order->store_id = $store_id; $order->order_no = 'AO' . date('YmdHis') . mt_rand(1000, 9999); // $order->total_price = $product->price * $quantity; $order->total_price = 1 * $quantity; $order->first_price = 0.00; $order->second_price = 0.00; $order->third_price = 0.00; $order->integral = json_encode(['forehead' => 0, 'forehead_integral' => 0]); $order->name = $user->nickname; $order->mobile = $user->binding; $order->is_pay = 1; // 已支付 $order->is_sale = 1; // 标记为已售后,以便触发返利 $order->created_at = time(); $order->updated_at = time(); if (!$order->save()) { throw new \Exception('创建订单失败:' . json_encode($order->errors)); } // 创建订单详情 $orderDetail = new OrderDetail(); $orderDetail->order_id = $order->id; $orderDetail->goods_id = $product->id; $orderDetail->num = $quantity; $orderDetail->attr = json_encode(["规格" => "默认规格"]); // 修改为JSON格式的规格信息 $orderDetail->pic = $product->cover_pic ?: 'default.jpg'; // 使用产品的封面图片,如果没有则使用默认图片 // $orderDetail->total_price = $product->price * $quantity; $orderDetail->total_price = 1 * $quantity; $orderDetail->goods_info = json_encode([ 'id' => $product->id, 'name' => $product->name, 'price' => $product->price, 'store_id' => $store_id ]); if (!$orderDetail->save()) { throw new \Exception('创建订单详情失败:' . json_encode($orderDetail->errors, JSON_UNESCAPED_UNICODE)); } // 调用afterOrderDetailSave函数处理返利 $result = self::afterOrderDetailSave([ 'orderDetail' => $orderDetail, 'goods' => json_encode([ 'id' => $product->id, 'name' => $product->name, 'price' => $product->price, 'store_id' => $store_id, 'user_id' => $user->id, ]), 'user' => $user, 'order' => $order, 'activity' => $activity, 'goods_id' => $product->id ]); if (isset($result['code']) && $result['code'] != 0) { throw new \Exception('处理返利失败:' . ($result['msg'] ?? '未知错误')); } } /** * 配置项 */ public function conf() { $conf = Option::get(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, $this->store_id, 'store')['value']; if ($conf) { $conf = json_decode($conf, true); if (isset($conf['conf'])) { if (!isset($conf['conf']['type'])) { $conf['conf']['type'] = 0; } } } else { $conf = ['conf' => [ 'is_open' => 0, 'type' => 0 ]]; } return [ 'code' => 0, 'msg' => 'ok', 'data' => $conf, ]; } public static function is_open($store_id = 0) { $is_open = (new self(['store_id' => $store_id ?: get_store_id()]))->conf()['data']['conf']['is_open']; return $is_open; } public function confSave($conf) { if (!is_array($conf)) { $conf = json_decode($conf, true); } if (!isset($conf['is_open'])) { $conf['is_open'] = 0; } $data = ['conf' => $conf]; Option::set(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, json_encode($data), $this->store_id, 'store'); return [ 'code' => 0, 'msg' => '保存成功' ]; } /** * 配置项结束 */ /** * 活动逻辑 */ //订单活动数据写入 public static function afterOrderDetailSave($od) { try { $goods = json_decode($od->goods_info, true); debug_log(['goods_store_id_01' => $goods->store_id, 'goods_store_id_02' => $goods['store_id']], 'ActivityOrderRebateSelfForm.log'); if (!self::is_open($goods['store_id'])) { return [ 'code' => 0, 'msg' => '功能未开启!' ]; } $order = $od->order; if (!$order->user_id) { return; } $activity = ActivityOrderRebateSelf::activityAt($order->store_id, $od->goods_id); if (!$activity) { return; } $add_rat = 0; $add_rebate = 0; $aUser = ActivityOrderRebateSelfUser::findOne(['user_id' => $order->user_id]); if ($aUser && $aUser->level) { $aUserLevel = ActivityOrderRebateSelfLevel::findOne(['store_id' => $order->store_id, 'level' => $aUser->level, 'is_delete' => 0, 'status' => 1]); if ($aUserLevel) { $add_rat = $aUserLevel['add_rat']; //释放加速比例 $add_rebate = $aUserLevel['add_rebate']; //返利赠送比例 } } $AF = $activity->send_num; $LF = $add_rebate; $P = $od->total_price; $type = 0; $conf = Option::get(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, $goods['store_id'], 'store')['value']; if ($conf) { $conf = json_decode($conf, true); $type = $conf['conf']['type']; } if (intval($type)) { $P = 0; // $goods_info = json_decode($order_detail['goods_info'], true); $goods_attr = json_decode($goods['attr'], true); $order_goods_attr = json_decode($od->attr, true); $order_goods_attr_id = array_column($order_goods_attr, 'attr_id'); sort($order_goods_attr_id); $goods_price = 0; foreach ($goods_attr as $item) { $goods_attr_list = $item['attr_list']; $goods_attr_id = array_column($goods_attr_list, 'attr_id'); sort($goods_attr_id); if (!array_diff($order_goods_attr_id, $goods_attr_id)) { $goods_price = $item['price']; } } if ($goods_price > 0) { $P = $goods_price * $od->num; } } $price_total = floor_num($P * $AF / 100 * (100 + $LF) / 100); if ($price_total <= 0) { return; } $ao = new ActivityOrderRebateSelfOrder(); $ao->store_id = $order->store_id; $ao->user_id = $order->user_id; $ao->act_id = $activity->id; $ao->order_id = $order->id; $ao->od_id = $od->id; $ao->goods_id = $od->goods_id; $ao->send_type = $activity->send_type; $ao->send_time = $activity->send_time; $ao->send_days = $activity->send_days; $ao->release_rate = $activity->release_rate; $ao->send_num = $activity->send_num; $ao->price_total = $price_total; $ao->price_send = 0; $ao->price_wait = $price_total; $ao->add_rat = $add_rat; $ao->add_rebate = $add_rebate; $ao->fixed_rebate_profit = $activity->fixed_rebate_profit; $ao->send_rebate_type = $activity->send_rebate_type; if (!$ao->save()) { throw new \Exception(array_shift($ao->getFirstErrors())); } if ($order->is_sale) { self::afterOrderSales($order); } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { \Yii::error($e); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } //处理订单售后(升级、返利) public static function afterOrderSales($order) { try { if (!self::is_open($order->store_id)) { return [ 'code' => 0, 'msg' => '功能未开启!' ]; } $levelUp = self::levelUp($order->user_id); if ($levelUp['code'] != 0) { debug_log([__METHOD__, $order->user_id, $levelUp['msg']], __CLASS__ . '.log'); return; } $time1 = strtotime('today midnight'); // 今天凌晨时间戳 $aos = ActivityOrderRebateSelfOrder::findAll(['order_id' => $order->id, 'is_sale' => 0, 'is_delete' => 0]); foreach ($aos as $ao) { $ao->is_sale = 1; if (!$ao->save()) { throw new \Exception(array_shift($ao->getFirstErrors())); } // $od = \app\models\OrderDetail::findOne($ao->od_id); $activity = ActivityOrderRebateSelf::findOne($ao->act_id); // 获取返利类型和比例 $send_types = $activity->send_types ? json_decode($activity->send_types, true) : [$activity->send_type]; $send_type_percentages = $activity->send_type_percentages ? json_decode($activity->send_type_percentages, true) : [$activity->send_type => 100]; $AC = $ao->send_days; //返利周期 $send_rebate_type = intval($ao->send_rebate_type); //全返类型:0=时间,1=固定比例 $fixed_rebate_profit = $ao->fixed_rebate_profit; //固定比例 $LA = $ao->add_rat; //释放加速比例 $price_total = $ao->price_total; //总金额 // $release_rate = isset($ao->release_rate) ? floatval($ao->release_rate) : 0; // 获取释放速率 $price_sends = []; //if ($release_rate > 0) { // // 按释放速率计算 // $remaining = $price_total; // $day = 1; // $AC = 90; //最多90天 // // while ($remaining > 0.01 && $day <= $AC) { // // 按释放速率计算当天释放金额 // $price_day = floor_num($remaining * $release_rate / 100); // // // 确保最小释放金额为0.01 // if ($price_day < 0.01) { // $price_day = 0.01; // } // // // 最后一天释放所有剩余金额 // if ($day == $AC) { // $price_day = $remaining; // } // // $price_sends[] = $price_day; // $remaining -= $price_day; // $day++; // } //} else { if ($send_rebate_type) { //固定比例类型 if ($fixed_rebate_profit > 0) { $p1 = $price_total; $day = 1; $AC = 90; //最多90天 while ($p1 >= 0.01 && $day <= $AC) { // $p1 = $price_total - array_sum($price_sends); //计算剩余还需要分多钱 //等同于 $price_once = ($p1 * $fixed_rebate_profit) / 100 ; $price_once = bcdiv(bcmul($p1, $fixed_rebate_profit, 2), 100, 2); //计算按照原进度的分红比例每次需要分多钱 //等同于$price_once += ($price_once * $LA) / 100; $price_once = bcadd($price_once, bcdiv(bcmul($price_once, $LA, 2), 100, 2), 2); //将每次的进度的钱再加速获取 // $price_sends[] = $price_once >= 0.01 ? $price_once : $p1; //获取结果 if ($p1 < 0.01) { $p1 = 0.01; } if ($day == $AC) { $price_once = $p1; } $price_sends[] = $p1; //获取结果 $p1 -= $price_once; //计算剩余还需要分多钱 $day++; }; } } else { //固定时间类型 $price_day_rate = (100 / $AC + $LA) / 100; $price_day = floor_num($price_total * $price_day_rate); if ($price_day < 0.01) { $price_day = 0; } $price_sends = []; for ($i = 1; $i <= $AC; $i++) { $p1 = $price_total - array_sum($price_sends); if ($p1 < 0.01) { break; } $price_sends[] = $i == $AC ? $p1 : $price_day; } } // } foreach ($price_sends as $i => $price_send) { if ($price_send <= 0.00) { continue; } // 按照返利类型比例分配返利金额 foreach($send_types as $type) { $percentage = isset($send_type_percentages[$type]) ? $send_type_percentages[$type] : 0; if ($percentage <= 0) continue; // 计算当前类型的返利金额 $type_price_send = floor_num($price_send * $percentage / 100); if ($type_price_send <= 0) continue; $al = new ActivityOrderRebateSelfLog(); $al->self_id = $ao->id; $al->store_id = $order->store_id; $al->user_id = $order->user_id; $al->act_id = $ao->act_id; $al->order_id = $order->id; $al->od_id = $od->id; $al->goods_id = $ao->goods_id; //$al->send_type = $ao->send_type; //$al->price_send = $price_send; $al->send_type = $type; // 使用当前循环的返利类型 $al->price_send = $type_price_send; // 按比例分配的返利金额 $al->day = $i + 1; $al->is_sale = 1; if ($ao->send_time == 1) { $al->pre_send_time = $time1 + $al['day'] * 86400 * 365; } else if ($ao->send_time == 2) { $al->pre_send_time = $time1 + $al['day'] * 86400 * 30; } else if ($ao->send_time == 4) { $al->pre_send_time = time() + $al['day'] * 60; } else { $al->pre_send_time = $time1 + $al['day'] * 86400; } if (!$al->save()) { throw new \Exception(array_shift($al->getFirstErrors())); } } } } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { \Yii::error($e); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } //返利 public static function rebate($time = 0, $queue = 0) { try { if (!$time) { $time = time(); } if ($queue) { $queue = queue_push(new \app\jobs\orderEvent\ActivityOrderRebateSelfRebateJob([ 'time' => $time, ]), 0, 1); return [ 'code' => 0, 'msg' => '操作成功!' . $queue ]; } $count = 100; $als = ActivityOrderRebateSelfLog::find()->where(['is_sale' => 1, 'is_send' => 0])->andWhere(['<=', 'pre_send_time', $time])->limit($count)->all(); foreach ($als as $al) { $al->is_send = 1; $al->send_time = time(); if (!$al->save()) { throw new \Exception(array_shift($al->getFirstErrors())); } $ao = ActivityOrderRebateSelfOrder::findOne(['is_sale' => 1, 'order_id' => $al->order_id, 'goods_id' => $al->goods_id, 'is_delete' => 0, 'id' => $al->self_id]); $ao->price_send += $al->price_send; $ao->price_wait -= $al->price_send; if (!$ao->save()) { throw new \Exception(array_shift($ao->getFirstErrors())); } $order = Order::findOne($al->order_id); $user = User::findOne(['id' => $al->user_id]); if ($al->send_type == 2) { $save = AccountLog::saveLog( $al->user_id, $al->price_send, AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "活动返利赠送积分, 订单号:{$order->order_no}" ); } else if ($al->send_type == 3) { $save = AccountLog::saveLog( $al->user_id, $al->price_send, AccountLog::TYPE_BALANCE, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "活动返利赠送余额, 订单号:{$order->order_no}" ); } else if ($al->send_type == 4) { $pool = IntegralAppreciationPool::findOne(['store_id' => $al->store_id]); if ($pool->integral_price > 0) { $save = AccountLog::saveLog( $al->user_id, floor_num($al->price_send/$pool->integral_price), AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER, $order->id, "活动返利赠送增值积分, 订单号:{$order->order_no}" ); } } else { $user->total_price += doubleval($al->price_send); $user->price += doubleval($al->price_send); $user->save(); $order->share_price += doubleval($al->price_send); UserShareMoney::set($al->price_send, $al->user_id, $order->id, 0, 4, $order->store_id, 0); } } if ($count == count($als)) { $queue = queue_push(new \app\jobs\orderEvent\ActivityOrderRebateSelfRebateJob([ 'time' => $time, ]), 0, 1); } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { \Yii::error($e); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } //升级(自己和上级) public static function levelUp($user_id) { try { $user = User::findOne($user_id); $store_id = $user->store_id; $aUser = ActivityOrderRebateSelfUser::findOne(['user_id' => $user_id]); $aUserLevel = 0; if ($aUser) { $aUserLevel = $aUser->level; } else { $aUser = new ActivityOrderRebateSelfUser(); $aUser->store_id = $store_id; $aUser->user_id = $user_id; $aUser->level = 0; } $aLevels = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'status' => 1])->orderBy('level DESC')->all(); if (!in_array($aUserLevel, array_column($aLevels, 'level'))) { $aUserLevel = 0; } $order_money = Order::find()->where([ 'store_id' => $store_id, 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_CONFIRM, 'user_id' => $user_id ])->andWhere(['or', ['is_pay' => 1], ['pay_type' => 2]])->sum('pay_price'); $childsLevel = ActivityOrderRebateSelfUser::find()->alias('au')->leftJoin(['u' => User::tableName()], 'au.user_id = u.id')->where([ 'u.old_parent_id' => $user_id, ])->groupBy('au.level')->select('au.level, count(1) acount')->asArray()->all(); foreach ($aLevels as $aLevel) { $moneyOk = $order_money > $aLevel['money']; $childOk = 0; if (!$aLevel['child_level'] || !$aLevel['child_num']) { $childOk = 1; } else { foreach ($childsLevel as $item) { $child_levelOk = $item['level'] >= $aLevel['child_level']; $child_numOk = $item['acount'] >= $aLevel['child_num']; if ($child_levelOk && $child_numOk) { $childOk = 1; break; } } } if ($moneyOk && $childOk) { $aUserLevel = $aLevel['level']; break; } } if ($aUser->level != $aUserLevel) { $aUser->level = $aUserLevel; if (!$aUser->save()) { throw new \Exception(array_shift($aUser->getFirstErrors())); } self::levelUp($user->old_parent_id); } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { \Yii::error($e); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } /** * 活动逻辑结束 */ /** * 活动信息 */ public function search() { try { $query = ActivityOrderRebateSelf::find()->where(['is_delete' => 0, 'store_id' => get_store_id()]); if ((int)$this->status === 1) { //未开始 $query->andWhere(['>', 'start_time', time()]); } if ((int)$this->status === 2) { //进行中 $query->andWhere(['AND', ['<', 'start_time', time()], ['>', 'end_time', time()]]); } if ((int)$this->status === 3) { //已结束 $query->andWhere(['<', 'end_time', time()]); } if (isset($this->send_type) && $this->send_type > 0) { $query->andWhere(['send_type' => $this->send_type]); } if (!empty($this->name)) { //名称 $query->andWhere(['LIKE', 'name', $this->name]); } if (!empty($this->start_time)) { $query->andWhere(['>', 'end_time', strtotime($this->start_time)]); } if (!empty($this->end_time)) { $query->andWhere(['<', 'start_time', strtotime($this->end_time)]); } $query->orderBy('id DESC'); $pagination = pagination_make($query); foreach ($pagination['list'] as &$item) { $item['publish'] = $item['status']; //获取活动状态 if ($item['start_time'] > time()) { $item['status'] = 1; } if ($item['start_time'] < time() && $item['end_time'] > time()) { $item['status'] = 2; } if ($item['end_time'] < time()) { $item['status'] = 3; } //格式化时间 $item['start_time'] = date("Y-m-d H:i:s", $item['start_time']); $item['end_time'] = date("Y-m-d H:i:s", $item['end_time']); $item['created_at'] = date("Y-m-d H:i:s", $item['created_at']); $item['updated_at'] = date("Y-m-d H:i:s", $item['updated_at']); $userCount = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->groupBy(['user_id'])->count(); $item['userCount'] = $userCount; $orderCount = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->count(); $item['orderCount'] = $orderCount; $orderSum = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->sum('price_total'); $item['orderSum'] = $orderSum; } return [ 'code' => 0, 'msg' => 'success', 'data' => [ 'data' => $pagination['list'], 'pageNo' => $pagination['pageNo'], 'totalCount' => $pagination['totalCount'], 'q' => $query->createCommand()->getRawSql(), ] ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } public function listSelect() { $query = ActivityOrderRebateSelf::find()->where(['is_delete' => 0]); $this->store_id && $query->andWhere(['store_id' => $this->store_id]); // 根据活动类型筛选活动 // $activity_type = get_params('activity_type'); if ($this->send_type) { switch ($this->send_type) { case 'integral': // 筛选积分类型的活动(send_type=2 或 send_types 包含 2) $query->andWhere(['or', ['send_type' => 2], ['like', 'send_types', '"2222"'] ]); break; case 'balance': // 筛选余额类型的活动(send_type=3 或 send_types 包含 3) $query->andWhere(['or', ['send_type' => 3], ['like', 'send_types', '"3333"'] ]); break; case 'commission': // 筛选佣金类型的活动(send_type=1 或 send_types 包含 1) $query->andWhere(['or', ['send_type' => 1], ['like', 'send_types', '"1111"'] ]); break; } } if($this->name){ $query->andWhere(['like', 'name', $this->name]); } if (!empty($this->start_time)) { $query->andWhere(['>', 'end_time', strtotime($this->start_time)]); } if (!empty($this->end_time)) { $query->andWhere(['<', 'start_time', strtotime($this->end_time)]); } $query->select('id, name'); $query->orderBy('id desc'); $res = $query->asArray()->all(); return [ 'code' => 0, 'msg' => 'success', 'data' => $res, ]; } public static function sortGoods($goods_ids, $goods) { $res = []; foreach ($goods_ids as $id) { foreach ($goods as $gitem) { if ($gitem['id'] == $id) { $res[] = $gitem; } } } return $res; } public function getInfo() { try { $activity = ActivityOrderRebateSelf::find()->where(['id' => $this->id])->asArray()->one(); if ($activity) { $gids = ActivityOrderRebateSelfGoods::find()->select('goods_id')->where(['act_id' => $activity['id']]); $activity_goods = Goods::find()->where(['id' => $gids])->andWhere(['is_delete' => 0])->asArray()->all(); $activity['start_time'] = date("Y-m-d H:i:s", $activity['start_time']); $activity['end_time'] = date("Y-m-d H:i:s", $activity['end_time']); $activity_goods = self::sortGoods(explode(',', $activity['goods_ids']), $activity_goods); $activity['send_rebate_type'] = intval($activity['send_rebate_type']); //$activity['send_type'] = intval($activity['send_type']); $activity['send_types'] = json_decode($activity['send_types'], true); $activity['send_type_percentages'] = json_decode($activity['send_type_percentages'], true); } return [ 'code' => 0, 'msg' => '获取成功', 'data' => [ 'activity_goods' => $activity_goods ?? [], 'activity' => $activity ?: [], ] ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() . $e->getFile() . $e->getLine() ]; } } public function save() { $t = \Yii::$app->db->beginTransaction(); try { if (!$this->name || !$this->start_time || !$this->end_time) { throw new \Exception("请将参数填充完整"); } $activity = ActivityOrderRebateSelf::findOne($this->id); if (empty($activity)) { $activity = new ActivityOrderRebateSelf(); $activity->store_id = $this->store_id; if (isset($this->send_rebate_type) && !in_array($this->send_rebate_type, ActivityOrderRebateSelf::SEND_REBATE_TYPE_ARR)) { throw new \Exception("请选择返利方式"); } $activity->send_rebate_type = $this->send_rebate_type ?: 0; } $activity->name = $this->name; $activity->start_time = strtotime($this->start_time); $activity->end_time = strtotime($this->end_time); $activity->goods_ids = $this->goods_ids ?: ''; $activity->send_type = $this->send_type ?: 0; $activity->send_time = $this->send_time; $activity->send_num = $this->send_num ?: 0; $activity->send_days = $this->send_days ?: 1; $activity->fixed_rebate_profit = $this->fixed_rebate_profit ?: 0; $activity->send_types = $this->send_types ? $this->send_types : null; $activity->send_type_percentages = $this->send_type_percentages ? $this->send_type_percentages : null; $activity->release_rate = $this->release_rate; if (!$activity->save()) { throw new \Exception(implode(';', array_values($activity->firstErrors))); } $gids = explode(',', $activity->goods_ids); if (!empty($gids)) { $result = ActivityOrderRebateSelfGoods::saveList($gids, $activity->id); if ($result['code'] !== 0) { throw new \Exception($result['msg']); } } $t->commit(); return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { $t->rollBack(); return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } public function status() { try { if ($this->ids) { $ids = explode(',', $this->ids); foreach ($ids as $id) { $model = ActivityOrderRebateSelf::findOne(['id' => $id, 'store_id' => $this->store_id]); $model->status = (int)$this->status; if (!$model->save()) { throw new \Exception(array_shift($model->getFirstErrors())); } } } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } public function del() { try { if ($this->ids) { $ids = explode(',', $this->ids); ActivityOrderRebateSelf::updateAll(['is_delete' => 1], ['and', ['in', 'id', $ids], ['store_id' => $this->store_id]]); } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } /** * 活动信息结束 */ /** * 等级信息 */ public function levelSearch() { if (!$this->validate()) { return [ 'code' => 1, 'msg' => '参数错误' ]; } $query = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $this->store_id, 'is_delete' => 0]); if (isset($this->status) && $this->status >= 0) { $query->andWhere(['status' => $this->status]); } if ($this->name) { $query->andWhere(['like', 'name', $this->name]); } if (!empty($this->start_time)) { $query->andWhere(['>', 'created_at', strtotime($this->start_time)]); } if (!empty($this->end_time)) { $query->andWhere(['<', 'created_at', strtotime($this->end_time)]); } $query->orderBy(['level' => SORT_ASC]); $pagination = pagination_make($query); $aul = ActivityOrderRebateSelfUser::find()->where(['store_id' => $this->store_id])->select('level, count(1) count')->groupBy('level')->asArray()->all(); foreach ($pagination['list'] as &$value) { $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']); $value['user_count'] = 0; foreach ($aul as $l) { if ($l['level'] == $value['level']) { $value['user_count'] = $l['count']; } } } return [ 'code' => 0, 'msg' => 'success', 'data' => $pagination, 'q' => $query->createCommand()->getRawSql(), ]; } public function levelListSelect() { $list = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $this->store_id, 'status' => 1, 'is_delete' => 0]) ->select('id, level, name') ->orderBy('level') ->asArray()->all(); return [ 'code' => 0, 'msg' => 'success', 'data' => $list, ]; } public function levelSave() { $level = ActivityOrderRebateSelfLevel::findOne($this->id); if (empty($level)) { $level = new ActivityOrderRebateSelfLevel(); $level->store_id = $this->store_id; } $level->store_id = $this->store_id; $level->level = $this->level; $level->name = $this->name; $level->money = $this->money; $level->child_num = (int)$this->child_num; $level->child_level = (int)$this->child_level; $level->add_rat = $this->add_rat; $level->add_rebate = $this->add_rebate; if (!$level->save()) { return [ 'code' => 1, 'msg' => '操作失败,' . array_shift($level->getFirstErrors()) ]; } return [ 'code' => 0, 'msg' => '成功' ]; } public function levelStatus() { try { if ($this->ids) { $ids = explode(',', $this->ids); foreach ($ids as $id) { $model = ActivityOrderRebateSelfLevel::findOne(['id' => $id, 'store_id' => $this->store_id]); $model->status = (int)$this->status; if (!$model->save()) { throw new \Exception(array_shift($model->getFirstErrors())); } } } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } public function levelDel() { try { if ($this->ids) { $ids = explode(',', $this->ids); foreach ($ids as $id) { $model = ActivityOrderRebateSelfLevel::findOne(['id' => $id, 'store_id' => $this->store_id]); $model->is_delete = 1; if (!$model->save()) { throw new \Exception(array_shift($model->getFirstErrors())); } } } return [ 'code' => 0, 'msg' => '操作成功!' ]; } catch (\Exception $e) { return [ 'code' => 1, 'msg' => $e->getMessage() ]; } } /** * 等级信息结束 */ /** * 用户信息 */ public function userSearch() { if (!$this->validate()) { return [ 'code' => 1, 'msg' => '参数错误' ]; } $store_id = $this->store_id; $query = ActivityOrderRebateSelfUser::find()->alias('au') ->leftJoin(['al' => ActivityOrderRebateSelfLevel::tableName()], 'au.level = al.level') ->leftJoin(['u' => User::tableName()], 'u.id = au.user_id') ->leftJoin(['su' => SaasUser::tableName()], 'u.binding = su.mobile AND su.mobile != ""') ->where(['au.store_id' => $store_id]); if (isset($this->level) && $this->level > 0) { $query->andWhere(['au.level' => $this->level]); } if ($this->name) { $query->andWhere(['like', 'su.name', $this->name]); } if ($this->phone) { $query->andWhere(['like', 'su.mobile', $this->phone]); } $query->orderBy('au.id desc'); $query->select('au.*, al.name level_name, su.mobile, su.name, su.avatar'); $pagination = pagination_make($query); foreach ($pagination['list'] as &$value) { $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']); $order_money = Order::find()->where([ 'store_id' => $store_id, 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_CONFIRM, 'user_id' => $value['user_id'], ])->andWhere(['or', ['is_pay' => 1], ['pay_type' => 2]])->sum('pay_price'); $value['user_order_money'] = $order_money; $childsLevel = User::find()->alias('u')->leftJoin(['au' => ActivityOrderRebateSelfUser::tableName()], 'au.user_id = u.id')->where([ 'u.old_parent_id' => $value['user_id'], ])->groupBy('au.level')->select(['IF(au.level>0,au.level,0) level', 'count(1) count'])->asArray()->all(); $value['childsLevel'] = $childsLevel; } return [ 'code' => 0, 'msg' => 'success', 'data' => $pagination, 'q' => $query->createCommand()->getRawSql(), ]; } /** * 用户信息结束 */ /** * 订单信息 */ public function orderList($getTotal = 1) { $query = ActivityOrderRebateSelfOrder::find()->alias('ao') ->leftJoin(['a' => ActivityOrderRebateSelf::tableName()], 'ao.act_id = a.id') ->leftJoin(['o' => Order::tableName()], 'ao.order_id = o.id') ->leftJoin(['u' => User::tableName()], 'ao.user_id = u.id') ->leftJoin(['su' => SaasUser::tableName()], 'su.mobile = u.binding'); // 新增的删除状态 $query->andWhere(['ao.is_delete' => ActivityOrderRebateSelfOrder::NOT_DELETE]); $query->andWhere(['!=', 'o.trade_status', Order::ORDER_FLOW_CANCEL]); $query->andWhere(['ao.store_id' => $this->store_id]); if ($this->user_id) { $query->andWhere(['ao.user_id' => $this->user_id]); $level = ActivityOrderRebateSelfUser::find()->alias('u') ->leftJoin(['l' => ActivityOrderRebateSelfLevel::tableName()], 'u.level = l.level AND u.store_id = l.store_id AND l.is_delete = 0 AND l.status = 1') ->where(['u.user_id' => $this->user_id]) ->select('l.*')->limit(1)->asArray()->one(); } if ($this->act_id) { $query->andWhere(['ao.act_id' => $this->act_id]); } if ($this->send_type > 0) { $query->andWhere(['ao.send_type' => $this->send_type]); } if (!empty($this->name)) { $query->andWhere(['LIKE', 'su.name', $this->name]); } if (!empty($this->order_no)) { $query->andWhere(['LIKE', 'o.order_no', $this->order_no]); } if (!empty($this->start_time)) { $query->andWhere(['>', 'o.created_at', strtotime($this->start_time)]); } if (!empty($this->end_time)) { $query->andWhere(['<', 'o.created_at', strtotime($this->end_time)]); } $total = null; if ($getTotal) { $select = ['IFNULL(SUM(ao.price_total),0) price_total', 'IFNULL(SUM(ao.price_wait),0) price_wait', 'IFNULL(SUM(ao.price_send),0) price_send', 'count(DISTINCT order_id) num']; $queryPrice = clone $query; $total['price'] = $queryPrice->andWhere(['ao.send_type' => 1])->select($select)->asArray()->one(); $queryJifen = clone $query; $total['jifen'] = $queryJifen->andWhere(['ao.send_type' => 2])->select($select)->asArray()->one(); $queryBalance = clone $query; $total['balance'] = $queryBalance->andWhere(['ao.send_type' => 3])->select($select)->asArray()->one(); } $query->select('ao.*, su.avatar, su.name, su.mobile, o.trade_status, o.order_type, o.is_pay, o.total_price, o.pay_price, o.order_no, o.created_at order_created_at')->orderBy('ao.id desc'); $res = pagination_make($query); foreach ($res['list'] as &$value) { $value['order_created_at'] = $value['order_created_at'] ? date('Y-m-d H:i:s', $value['order_created_at']) : '-'; } return [ 'code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total, 'level' => $level, 'q' => $query->createCommand()->getRawSql(), ]; } /** * 删除返利订单 */ public function orderDelete() { if(count($this->ids) <= 0){ return ['code' => 1, 'msg' => '请选择要删除的数据']; } $count = ActivityOrderRebateSelfOrder::updateAll(['is_delete' => ActivityOrderRebateSelfOrder::IS_DELETE], ['id' => $this->ids]); $ol = ActivityOrderRebateSelfOrder::findAll(['id' => $this->ids]); foreach($ol as $item){ if(!$item->is_delete){ continue; } ActivityOrderRebateSelfLog::deleteAll(['order_id' => $item['order_id'], 'act_id' => $item['act_id']]); } if($count == count($this->ids)){ return ['code' => 0, 'msg' => '删除成功']; }else{ return ['code' => 0, 'msg' => '部分删除成功']; } } /** * 订单信息结束 */ /** * 返利信息 */ public function logList($getTotal = 1) { $query = ActivityOrderRebateSelfLog::find()->alias('al') ->leftJoin(['a' => ActivityOrderRebateSelf::tableName()], 'al.act_id = a.id') ->leftJoin(['o' => Order::tableName()], 'al.order_id = o.id') ->leftJoin(['u' => User::tableName()], 'al.user_id = u.id') ->leftJoin(['su' => SaasUser::tableName()], 'su.mobile = u.binding'); $query->andWhere(['!=', 'o.trade_status', Order::ORDER_FLOW_CANCEL]); $query->andWhere(['al.store_id' => $this->store_id]); if ($this->user_id) { $query->andWhere(['al.user_id' => $this->user_id]); } if ($this->act_id) { $query->andWhere(['al.act_id' => $this->act_id]); } if ($this->send_type > 0) { $query->andWhere(['al.send_type' => $this->send_type]); } if (isset($this->is_send) && $this->is_send >= 0) { $query->andWhere(['al.is_send' => $this->is_send]); } if (!empty($this->name)) { $query->andWhere(['LIKE', 'su.name', $this->name]); } if (!empty($this->order_no)) { $query->andWhere(['LIKE', 'o.order_no', $this->order_no]); } if (!empty($this->start_time)) { $query->andWhere(['>', 'o.created_at', strtotime($this->start_time)]); } if (!empty($this->end_time)) { $query->andWhere(['<', 'o.created_at', strtotime($this->end_time)]); } $total = null; if ($getTotal) { $queryCountUser = clone $query; $totalCountUser = intval($queryCountUser->groupBy(['al.user_id'])->count()); $select = ['IFNULL(SUM(al.price_send),0) price_send', 'count(1) num']; $queryPrice = clone $query; $total['price'] = $queryPrice->andWhere(['al.send_type' => 1])->select($select)->asArray()->one(); $queryJifen = clone $query; $total['jifen'] = $queryJifen->andWhere(['al.send_type' => 2])->select($select)->asArray()->one(); $queryBalance = clone $query; $total['balance'] = $queryBalance->andWhere(['al.send_type' => 3])->select($select)->asArray()->one(); } $query->select('al.*, su.avatar, su.name, su.mobile, o.trade_status, o.order_type, o.is_pay, o.total_price, o.pay_price, o.order_no, o.created_at order_created_at') ->orderBy('al.pre_send_time DESC, al.id asc'); $res = pagination_make($query); foreach ($res['list'] as &$value) { $value['order_created_at'] = $value['order_created_at'] ? date('Y-m-d H:i:s', $value['order_created_at']) : '-'; $value['pre_send_time'] = $value['pre_send_time'] ? date('Y-m-d H:i:s', $value['pre_send_time']) : '-'; $value['send_time'] = $value['send_time'] ? date('Y-m-d H:i:s', $value['send_time']) : '-'; } return [ 'code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total, 'totalCountUser' => $totalCountUser ?? 0, 'q' => $query->createCommand()->getRawSql(), ]; } /** * 返利信息结束 */ }