manghe/app/admin/controller/User.php
2025-07-04 15:39:09 +08:00

2074 lines
77 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\common\model\Coupon;
use app\common\model\UserVip;
use \think\Request;
use think\facade\View;
use app\common\model\User as UserModel;
use app\common\model\ProfitMoney;
use app\common\model\ProfitMoney2;
use app\common\model\ProfitIntegral;
use app\common\model\Shang;
use app\common\model\GoodsList;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\UserAccount;
use app\common\model\UserLoginIp;
use app\common\model\Goods;
use think\facade\Db;
use think\helper\Str;
class User extends Base
{
/**
* 用户列表
*/
public function index()
{
return View::fetch('User/index');
}
/**
* 获取用户列表
*/
public function list()
{
$param = $this->request->param();
$limit = request()->param('limit', '');
// 构建查询条件
$where = [];
if (!empty($param['user_id'])) {
$user_id = $this->convertUidToUserId($param['user_id']);
$where[] = ['id', '=', intval($user_id)];
}
if (!empty($param['mobile'])) {
$where[] = ['mobile', 'like', "%{$param['mobile']}%"];
}
if (!empty($param['nickname'])) {
$where[] = ['nickname', 'like', "%{$param['nickname']}%"];
}
if (!empty($param['last_login_ip'])) {
$where[] = ['last_login_ip', '=', $param['last_login_ip']];
}
if (!empty($param['addtime'])) {
$times = explode(' - ', $param['addtime']);
$where[] = ['addtime', 'between', [strtotime($times[0]), strtotime($times[1])]];
}
if (!empty($param['pid'])) {
$where[] = ['pid', '=', intval($param['pid'])];
}
$field = '*';
$order = 'id desc';
$data = UserModel::getList($where, $field, $order, $limit);
if ($data && $data['list']) {
foreach ($data['list'] as &$value) {
try {
$pid_info = UserModel::field('id,nickname,headimg,uid')->where(['id' => $value['pid']])->find();
$value['pid_info'] = $pid_info;
#关联user_account
$user_account = UserAccount::where(['user_id' => $value['id']])->field('last_login_ip1,last_login_ip,ip_adcode,ip_province,ip_city')->find();
// SELECT sum(goodslist_money) FROM order_list where user_id=4490 and status=0
$user_hegui = OrderList::where('user_id', '=', $value['id'])->where('status', '=', 0)->sum('goodslist_money');
//SELECT SUM(order_zhe_total) FROM `order` where `status`=1 and user_id=6153
$user_all_total = Order::where('user_id', '=', $value['id'])->where('status', '=', 1)->sum('order_zhe_total');
//SELECT *FROM `order` where `status`=1 and user_id=6153 and price>1 #微信支付
$user_weixin_total = Order::where('user_id', '=', $value['id'])->where('status', '=', 1)->where('price', '>', 1)->sum('price');
// SELECT sum(use_money) FROM `order` where `status`=1 and user_id=6153 # 余额支付
$user_use_money = Order::where('user_id', '=', $value['id'])->where('status', '=', 1)->sum('use_money');
//SELECT sum(use_integral) FROM `order` where `status`=1 and user_id=6153 #吧唧币抵扣
$user_use_integral = Order::where('user_id', '=', $value['id'])->where('status', '=', 1)->sum('use_integral');
// SELECT sum(goodslist_money) FROM `order_list` where `status`=1 and user_id=6153 # 回收货币
$user_goodslist_money = OrderList::where('user_id', '=', $value['id'])->where('status', '=', 1)->sum('goodslist_money');
// SELECT sum(goodslist_money) FROM `order_list` where `status`=2 and user_id=6153 # 发货价值
$user_goodslist_money2 = OrderList::where('user_id', '=', $value['id'])->where('status', '=', 2)->sum('goodslist_money');
//SELECT sum(goodslist_money) FROM order_list where user_id=4490 # 总出货价值
$user_goodslist_money3 = OrderList::where('user_id', '=', $value['id'])->sum('goodslist_money');
$last_login_ip = 0;
if ($user_account) {
if ($user_account['last_login_ip']) {
if ($user_account['last_login_ip1']) {
$last_login_ip = $user_account['last_login_ip1'];
} else {
$last_login_ip = long2ip($user_account['last_login_ip']);
}
}
}
if (empty($value['mobile'])) {
$value['mobile'] = '未绑定';
}
$value['user_hegui'] = $user_hegui;
$value['user_all_total'] = $user_all_total;
$value['user_weixin_total'] = $user_weixin_total;
$value['user_use_money'] = $user_use_money;
$value['user_use_integral'] = $user_use_integral;
$value['user_goodslist_money'] = $user_goodslist_money;
$value['user_goodslist_money2'] = $user_goodslist_money2;
$value['user_goodslist_money3'] = $user_goodslist_money3;
$value['last_login_ip'] = $last_login_ip;
$value['ip_adcode'] = $user_account['ip_adcode'];
$value['ip_province'] = $user_account['ip_province'];
$value['ip_city'] = $user_account['ip_city'];
} catch (\Throwable $th) {
//throw $th;
}
}
}
// 获取数据
$list = $data['list'];
$count = $data['count'];
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 资金变动
*/
public function chongzhi()
{
$id = request()->param('id', '');
$type = request()->param('type', '');
$user_info = UserModel::find($id);
if (!$user_info) {
$this->renderError('请求参数错误');
}
if (\request()->IsGet()) {
if ($type == 1) {
$money = $user_info['money'];
} elseif ($type == 2) {
$money = $user_info['integral'];
} elseif ($type == 3) {
$money = $user_info['money2'];
} else {
$this->renderError('请求参数错误1');
}
View::assign('id', $id);
View::assign('type', $type);
View::assign('money', $money);
return View::fetch('User/chongzhi');
} else {
$money = request()->param('money', '');
$type_is = request()->param('type_is', '');
if ($type_is != 1 && $type_is != 2) {
$this->renderError('请求参数错误1');
}
if (empty($money)) {
return $this->renderError('请输入修改数量');
}
Db::startTrans();
if ($type == 1) {#余额
if (RegMoney($money)) {
return $this->renderError('修改数量不规范,最多保留两位小数');
}
if ($type_is == 2) {
if ($money > $user_info['money']) {
return $this->renderError('账号余额扣除数量不足');
}
$money = $money * -1;
}
$res[] = UserModel::changeMoney($id, $money, 1, '后台变动');
} elseif ($type == 2) {#货币2
if (RegInt($money)) {
return $this->renderError('修改数量不规范,请输入大于0的整数');
}
if ($type_is == 2) {
if ($money > $user_info['integral']) {
return $this->renderError('账号货币扣除数量不足');
}
$money = $money * -1;
}
$res[] = UserModel::changeIntegral($id, $money, 1, '后台变动');
} elseif ($type == 3) {#积分
if (RegInt($money)) {
return $this->renderError('修改数量不规范,请输入大于0的整数');
}
if ($type_is == 2) {
if ($money > $user_info['money2']) {
return $this->renderError('账号积分扣除数量不足');
}
$money = $money * -1;
}
$res[] = UserModel::changeMoney2($id, $money, 1, '后台变动');
} else {
$this->renderError('请求参数错误2');
}
if (resCheck($res)) {
Db::commit();
return $this->renderSuccess("操作成功");
} else {
Db::rollback();
return $this->renderError("操作失败");
}
}
}
/**
* 封号、解封处理
*/
public function userdel(Request $request)
{
$id = request()->post('id/d', 0);
$type = request()->post('type/d', 0);
if ($type != 1 && $type != 2) {
return $this->renderError('请求参数错误');
}
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return $this->err('数据不存在');
}
$result = $user->save(["status" => $type]);
if ($result) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/**
* 封号、解封处理
*/
public function usertest(Request $request)
{
// \think\facade\Filesystem::disk('public')-/
$id = request()->post('id/d', 0);
$type = request()->post('type/d', 0);
if ($type != 1 && $type != 0 && $type != 2) {
return $this->renderError('请求参数错误');
}
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return $this->err('数据不存在');
}
$result = $user->save(["istest" => $type]);
if ($result) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/**
* 清空手机号
*/
public function usermobileclear(Request $request)
{
$id = request()->post('id/d', 0);
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return $this->err('数据不存在');
}
$result = $user->save(["mobile" => '']);
if ($result) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/**
* 清空UID
*/
public function userUidClear(Request $request)
{
$id = request()->post('id/d', 0);
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return $this->err('数据不存在');
}
$result = $user->save(["uid" => '']);
if ($result) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/**
* 清空微信登录数据
*/
public function userwxclear(Request $request)
{
$id = request()->post('id/d', 0);
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return $this->err('数据不存在');
}
$result = $user->save(["openid" => Str::random(32)]);
$useraccount = UserAccount::getInfo(['user_id' => $id]);
if ($useraccount != null) {
$useraccount->save(['account_token' => '']);
}
if ($result) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/*
ip转换
*/
public function ipzh(Request $request)
{
$id = request()->post('id/d', 0);
$user_account = UserAccount::where(['user_id' => $id])->field('last_login_ip1,ip_province,last_login_ip')->find();
if ($user_account) {
if (empty($user_account['ip_province'])) {
$last_login_ip = long2ip($user_account['last_login_ip']);
//$last_login_ip = $user_account['last_login_ip1'];
var_dump($last_login_ip);
$url = "https://restapi.amap.com/v3/ip?key=6a46ad822120e393956e89d498e8c40b&ip=" . "$last_login_ip" . "";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
var_dump($result);
exit;
if ($result['status'] == '1') {
$res = UserAccount::where(['user_id' => $id])->update([
'ip_adcode' => $result['adcode'],
'ip_province' => $result['province'],
'ip_city' => $result['city']
]);
} else {
$res = false;
}
}
} else {
$res = false;
}
if ($res) {
return $this->renderSuccess('操作成功');
} else {
return $this->renderError('操作失败');
}
}
/**
* 赠送卡牌查找
*/
public function give_goodslist_info()
{
$card_no = request()->param('card_no', '');
$goodslist = GoodsList::where('card_no', '=', $card_no)
->find();
if (!$goodslist) {
return $this->renderError('输入错误,未找到奖品信息');
}
#验证是否赠送是卡册盒子
$good_info = Goods::field('id,type')->where('id', '=', $goodslist['goods_id'])->find();
if ($good_info['type'] != 4) {
return $this->renderError('只可赠送卡册盒子');
}
$data = [
'title' => $goodslist['title'],
'imgurl' => imageUrl($goodslist['imgurl']),
];
return $this->renderSuccess('查找成功', $data);
}
/**
* 赠送卡牌
*/
public function give_goodslist()
{
$user_id = request()->param('id/d', 0);
$user_info = UserModel::find($user_id);
if (!$user_info) {
$this->renderError('请求参数错误');
}
if (request()->IsGet()) {
View::assign('id', $user_id);
return View::fetch('User/give_goodslist');
} else {
$card_no = request()->param('card_no', '');
$num = request()->param('num/d', 0);
$goodslist = GoodsList::where('card_no', '=', $card_no)
->find();
if (!$goodslist) {
return $this->renderError('输入错误,未找到奖品信息');
}
if (RegInt($num)) {
return $this->renderError('数量输入错误,请输入大于0的整数');
}
#验证是否赠送是卡册盒子
$good_info = Goods::field('id,type')->where('id', '=', $goodslist['goods_id'])->find();
if ($good_info['type'] != 4) {
return $this->renderError('只可赠送卡册盒子');
}
$save_prize = [
'order_id' => 0,
'user_id' => $user_id,
'status' => 0,#0未操作 1选择兑换 2选择发货
'goods_id' => $goodslist['goods_id'],
'num' => 0,
'shang_id' => $goodslist['shang_id'],
'goodslist_id' => $goodslist['id'],
'goodslist_title' => $goodslist['title'],
'goodslist_imgurl' => $goodslist['imgurl'],
'goodslist_price' => $goodslist['price'],
'goodslist_money' => $goodslist['money'],
'goodslist_type' => $goodslist['goods_type'],
'goodslist_sale_time' => $goodslist['sale_time'],
'addtime' => time(),
'prize_code' => $goodslist['prize_code'],
'order_type' => 9,
];
$all_save_prize = [];
for ($i = 0; $i < $num; $i++) {
$all_save_prize[] = $save_prize;
}
$res = OrderList::insertAll($all_save_prize);
if ($res) {
return $this->renderSuccess("操作成功");
} else {
return $this->renderError("操作失败");
}
}
}
/**
* 赠送
*/
public function give_add(Request $request)
{
if (!$request->isPost()) {
$w = [];
$w[] = ['status', '=', 0];
$coupon = Coupon::getAllList($w, 'id,title,price,man_price,ttype');
View::assign('coupon', $coupon);
$user_id = $request->param("user_id");
View::assign("user_id", $user_id);
return View::fetch("User/give_add");
} else {
$data = input('post.');
if (empty($data['give_id'])) {
return $this->renderError("请选择赠送的物品");
}
$coupon = Coupon::getInfo(['id' => $data['give_id']]);
if (!$coupon || $coupon['status'] != 0) {
return $this->renderError("优惠券不存在或者已下架");
}
//赠送优惠卷
$data2 = [];
for ($i = 0; $i < $data['num']; $i++) {
$data2[$i]['title'] = $coupon['title'];
$data2[$i]['price'] = $coupon['price'];
$data2[$i]['man_price'] = $coupon['man_price'];
$data2[$i]['end_time'] = $coupon['effective_day'] * 86400 + time();
$data2[$i]['addtime'] = time();
$data2[$i]['status'] = 0;
$data2[$i]['user_id'] = $data['user_id'];
$data2[$i]['coupon_id'] = $data['give_id'];
$data2[$i]['state'] = $coupon['ttype'];
}
$dd = Db::name('coupon_receive')->insertAll($data2);
if ($dd) {
return $this->renderSuccess("赠送成功");
} else {
return $this->renderError("赠送失败");
}
}
}
/**
* 用户盈亏
*/
public function user_profit_loss()
{
$whe = [];
$where = [];
$addtime = trim(input('get.addtime'));
$uid = trim(input('get.uid'));
if (!empty($uid)) {
$user_id = $this->convertUidToUserId($uid);
$whe[] = ['id', '=', $user_id];
}
if (!empty($addtime)) {
$addtime = explode(' - ', $addtime);
$start_time = strtotime($addtime[0]);
$end_time = strtotime($addtime[1]) - 1;
$where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
}
// else {
// $start_time = strtotime(date('Y-m-d', time()));
// $end_time = $start_time + 86399;
// $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
// }
$data = UserModel::getList($whe, '*', 'id desc', 20);
$cz_money_total = 0;
$wx_money_total = 0;
$cz_yue_total = 0;
$cz_integral_total = 0;
$price_total = 0;
$shang_money_total = 0;
$fh_money_total = 0;
$tx_money_total = 0;
$profit_loss_total = 0;
$money = 0;
foreach ($data['list'] as $k => &$v) {
#收入(800) - 发货金额(0) - 用户剩余达达券(2741.86) - 盒柜剩余(20254.15)
$cz_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
$wx_money = ProfitMoney::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 2)->where('change_money', '>', 0)->where($where)->sum('change_money');
$cz_yue = $cz_money + $wx_money;
$cz_integral = ProfitIntegral::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 1)->where('change_money', '>', 0)->where($where)->sum('change_money');
# 钻石支付
$use_money = Order::field('use_money')
->where('user_id', '=', $v['id'])
->where('status', '=', 1)
->where('use_money', '>', 0)
->where($where)
->sum('use_money');
# 微信支付
$price = Order::field('price')
->where('user_id', '=', $v['id'])
->where('status', '=', 1)
->where('price', '>', 0)
->where($where)
->sum('price');
$shouru = $use_money ?? 0 + $price ?? 0;
# 盒柜剩余
$shang_money = OrderList::field('goodslist_money')
->where('user_id', '=', $v['id'])
->whereIn('status', [0])
->where('goodslist_money', '>', 0)
->where($where)->sum('goodslist_money') ?? 0;
# 发货价值
$fh_money = OrderList::field('goodslist_money')
->where('user_id', '=', $v['id'])
->where('status', '=', 2)
->where('goodslist_money', '>', 0)
->where($where)->sum('goodslist_money') ?? 0;
# 用户剩余达达券
$money2 = $v['money2'];
$lirun = $shouru - $shang_money - $fh_money - $money2;
$tx_money = ProfitMoney2::field('change_money')->where('user_id', '=', $v['id'])->where('type', '=', 5)->where('change_money', '<', 0)->where($where)->sum('change_money');
$profit_loss = $cz_yue + $price - $v['money'] - $shang_money - $fh_money;
$profit_loss = $profit_loss + $tx_money;
$v['cz_money'] = $cz_yue;
$v['wx_money'] = $wx_money;
$v['cz_integral'] = $cz_integral;
$v['price'] = $price;
$v['shang_money'] = $shang_money;
$v['fh_money'] = $fh_money;
$v['tx_money'] = $tx_money;
$v['profit_loss'] = $profit_loss;
$v['lirun'] = $lirun;
$v['liruntips'] = '收入(' . $shouru . '- 发货金额(' . $fh_money . ') - 用户剩余达达券(' . $money2 . ') - 盒柜剩余(' . $shang_money . ' ) ;';
$v['shouru'] = $shouru;
$cz_money_total += $cz_yue;
$wx_money_total += $wx_money;
$cz_yue_total += $cz_yue;
$cz_integral_total += $cz_integral;
$price_total += $price;
$shang_money_total += $shang_money;
$fh_money_total += $fh_money;
$tx_money_total += $tx_money;
$profit_loss_total += $profit_loss;
$money += $v['money'];
}
$total_money[1]['cz_money_total'] = $cz_money_total;
$total_money[1]['cz_integral_total'] = $cz_integral_total;
// $total_money[1]['wx_money_total'] = $wx_money_total;
$total_money[1]['price_total'] = $price_total;
$total_money[1]['total_money'] = $money;
// $total_money[1]['cz_yue_total'] = $cz_yue_total;
$total_money[1]['shang_money_total'] = $shang_money_total;
$total_money[1]['fh_money_total'] = $fh_money_total;
$total_money[1]['tx_money_total'] = $tx_money_total;
$total_money[1]['profit_loss_total'] = $profit_loss_total;
View::assign('list', $data['list']);
View::assign('count', $data['count']);
View::assign('page', $data['page']);
View::assign('total_money', $total_money);
return View::fetch("User/user_profit_loss");
}
/**
* vip管理
*/
public function vip()
{
$list = UserVip::order('id asc')->select();
View::assign('list', $list);
View::assign('count', count($list));
return View::fetch("User/vip");
}
/**
* vip编辑
*/
public function vip_edit(Request $request)
{
if (!$request->isPost()) {
$id = request()->param('id/d', 0);
$info = UserVip::where(['id' => $id])->find();
if (!$info) {
return $this->renderError('请求参数错误');
}
View::assign('info', $info);
return View::fetch('User/vip_edit');
} else {
$data = input('post.');
if (empty($data['id'])) {
return $this->renderError('请求参数错误');
}
$info = UserVip::where(['id' => $data['id']])->find();
if (!$info) {
return $this->renderError('请求参数错误1');
}
if (empty($data['title'])) {
return $this->renderError('请输入vip名称');
}
if (RegZero($data['condition'])) {
return $this->renderError('升级消费设置错误,请设置整数');
}
if (RegMoney($data['discount'])) {
return $this->renderError('vip折扣设置错误,最多保留两位小数');
}
// if (empty($data['imgurl'])) {
// return $this->renderError('请上传图标');
// }
$data['update_time'] = time();
unset($data['id']);
$dd = $info->allowField([])->save($data);
if ($dd) {
return $this->renderSuccess('编辑成功');
} else {
return $this->renderError('编辑失败');
}
}
}
/**
* 流水明细
*created by Admin at 2023/2/10 14:23
*/
public function detailed_flow()
{
$whe = [];
$where = [];
// $addtime = trim(input('get.addtime'));
$uid = trim(input('get.uid'));
if (!empty($uid)) {
// 将UID转换为用户ID
$uid = $this->convertUidToUserId($uid);
$whe[] = ['user_id', '=', $uid];
}
// if (!empty($addtime)) {
// $addtime = explode(' - ', $addtime);
// $start_time = strtotime($addtime[0]);
// $end_time = strtotime($addtime[1]) - 1;
// $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
// } else {
// $start_time = strtotime(date('Y-m-d', time()));
// $end_time = $start_time + 86399;
// $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
// }
// $data = ProfitMoney::getList($whe, 'id,user_id,change_money,addtime', '', 20);
$list = ProfitMoney::field('user_id,sum(change_money) as new_money')
// ->whereIn('type',[])
->group('user_id')
->order('new_money desc')
->paginate(20);
$page = $list->render();
$data['list'] = $list->toArray()['data'];
$data['count'] = $list->total();
$data['page'] = $page;
$num = 1;
foreach ($data['list'] as &$value) {
// dd($value['user_id']);
$user = \app\common\model\User::where('id', $value['user_id'])->find();
$value['nick_name'] = $user['nickname'];
$value['headimg'] = $user['headimg'];
$value['openid'] = $user['openid'];
$value['uid'] = $user['uid'] ?: $user['id'];
$value['num'] = $num;
// $value['addtime'] =$user['addtime'];
$num++;
}
// dd($data);
View::assign('list', $data['list']);
View::assign('count', $data['count']);
View::assign('page', $data['page']);
return View::fetch("User/detailed_flow");
}
/**
* 下级用户
*created by Admin at 2023/2/16 15:55
*/
public function user_team(Request $request)
{
$id = $request->param('id');
$addtime = $request->param('addtime');
// 将UID转换为用户ID
$id = $this->convertUidToUserId($id);
// dd($id);
// 获取当前页码
$page_num = $request->param('page', 1);
$list_rows = 20;
// 修复分页明确指定包含id参数
$query = ['id' => $id]; // 确保id参数被保留
$list = \app\common\model\User::where('pid', $id)->paginate([
'list_rows' => $list_rows,
'query' => $query
]);
// 计算基础序号
$start_index = ($page_num - 1) * $list_rows;
$page = $list->render();
$data['list'] = $list->toArray()['data'];
$data['count'] = $list->total();
$data['page'] = $page;
$start_time = 0;
$end_time = 0;
if ($addtime) {
$addtime = explode(' - ', $addtime);
$start_time = strtotime($addtime[0]);
$end_time = strtotime($addtime[1]);
// $where[] = ['addtime', 'BETWEEN', [$start_time, $end_time]];
}
foreach ($data['list'] as &$value) {
$value['total'] = ProfitMoney::where('type', 5)
->where('user_id', $id)
->where('share_uid', $value['id'])
->sum('change_money');
$order_user_id = $value['id'];
// select IFNULL(sum(price),0) price,IFNULL(sum(use_money),0) use_money from `order` where user_id=23796 and status=1 addtime> 1745550000 and addtime<1746374399 ;
// 订单统计查询
$orderQuery = \app\common\model\Order::where('user_id', $value['id'])
->where('status', 1);
// 添加时间筛选条件
if ($start_time > 0 && $end_time > 0) {
$orderQuery->where('addtime', 'between', [$start_time, $end_time]);
}
// 执行查询并获取结果
$orderStats = $orderQuery->field('IFNULL(sum(price),0) as price, IFNULL(sum(use_money),0) as use_money')
->find();
$value['order_price'] = $orderStats['price'];
$value['order_use_money'] = $orderStats['use_money'];
}
View::assign('list', $data['list']);
View::assign('count', $data['count']);
View::assign('page', $page);
View::assign('start_index', $start_index);
return View::fetch("User/user_team");
}
public function ip_list(Request $request)
{
$id = $request->param('id');
// 将UID转换为用户ID
$id = $this->convertUidToUserId($id);
// dd($id);
$list = UserLoginIp::where('user_id', $id)->order('id desc')->paginate(20);
$page = $list->render();
$data['list'] = $list->toArray()['data'];
$data['count'] = $list->total();
$data['page'] = $page;
// 获取用户UID
$user = UserModel::where('id', $id)->find();
$uid = $user ? $user['uid'] : '';
foreach ($data['list'] as &$item) {
$item['uid'] = $uid ?: $item['user_id'];
}
View::assign('list', $data['list']);
View::assign('count', $data['count']);
View::assign('page', $data['page']);
return View::fetch("User/ip_list");
}
public function user_invite(Request $request)
{
$whe = array();
$whe1 = array();
$user_id = trim(input('get.user_id'));
if (!empty($user_id)) {
// 将UID转换为用户ID
$user_id = $this->convertUidToUserId($user_id);
$whe[] = ['pid', '=', $user_id];
}
$profit_date = trim(input('get.profit_date'));
if (!empty($profit_date)) {
$profit_date = explode(' - ', $profit_date);
$start_time = strtotime($profit_date[0]);
$end_time = strtotime($profit_date[1]);
$whe1[] = ['addtime', 'BETWEEN', [intval($start_time), intval($end_time)]];
}
//select * from ( SELECT pid,count(1) n FROM xinglanmh_shequt_test.`user` where pid>0 group by pid ) t where n>1 order by n desc LIMIT 10
$list = UserModel::where($whe)->
where('pid', '>', 0)
->field('pid, COUNT(1) as n') // 选取 pid 和 计数字段
->group('pid')
// ->having('n', '>', 1) // `having` 需要使用 `as` 取别名
->order('n desc')
->limit(1000) // 添加限制条数
->select();
$count = UserModel::where($whe)->where('pid', '>', 0)
->field('pid, COUNT(1) as n') // 选取 pid 和 计数字段
->group('pid')
->count();
$data = array();
$index = 1;
foreach ($list as $item) {
$pid = $item['pid'];
$user_info = UserModel::field('nickname,headimg,mobile,uid')->where('id', '=', $pid)->find();
if ($user_info != null) {
$user_list = UserModel::field('id,nickname,addtime,mobile,uid')->where($whe1)->where('pid', '=', $pid)->order('addtime desc')->select();
$u_index = 1;
$u_price = 0;
$u_order = 0;
$u_mobile_count = 0;
foreach ($user_list as $user_item) {
$user_item['adddate'] = date('Y-m-d H:i:s', $user_item['addtime']);
$user_item['index'] = $u_index;
$user_item_order = Order::where('user_id', '=', $user_item['id'])->where('status', '=', $user_item['id'])->count();
$user_item_price = Order::where('user_id', '=', $user_item['id'])->where('status', '=', $user_item['id'])->sum('price');
$user_item['user_item_order'] = $user_item_order;
$user_item['user_item_price'] = $user_item_price;
$u_index++;
$u_price += $user_item_price;
if ($user_item_order && $user_item_order > 0) {
$u_order++;
}
if ($user_item['mobile'] && $user_item['mobile'] != "") {
$u_mobile_count++;
}
}
$data[] = [
'index' => $index,
'user_id' => $pid,
'uid' => $user_info['uid'] ?: $pid,
'invitenumber' => $item['n'],
'nickname' => $user_info['nickname'],
'headimg' => imageUrl($user_info['headimg']),
'info' => $user_list,
'sum_order' => $u_order,
'sum_price' => $u_price,
'count_mobile' => $u_mobile_count,
];
$index++;
}
}
View::assign('data', $data);
View::assign('count', $count);
return View::fetch("User/user_invite");
}
/**
* //用户列表页面表格操作一列增加查询用户盒柜传入用户的id,点击显示一个弹出层,弹出层中有一个表格,这个弹出层有有查询条件(奖品状态(下拉框),奖品名称(输入框),盒子名称输入框下面的sql语句是查询盒柜列表
* goodslist_title 奖品名称goodslist_money 回收价格goodslist_price 售价shang_id 奖品等级order_id 订单id,order_num 订单编号,goods_id 盒子id,good_title 盒子名称status奖品状态 0盒柜中 1回收 2选择发货
*SELECT goodslist_title,goodslist_money, goodslist_price,goodslist_imgurl,shang_id,addtime,order_id,(select order_num from `order` where id=order_list.order_id) order_num,goods_id,(select title from goods where id=order_list.goods_id ) good_title,`status` FROM order_list where user_id=6153 order by`status`
* 获取用户盒柜列表
*/
public function user_box_list()
{
$param = $this->request->param();
$user_id = isset($param['user_id']) ? intval($param['user_id']) : 0;
// 将UID转换为用户ID
$user_id = $this->convertUidToUserId($user_id);
if (empty($user_id)) {
return json(['code' => 1, 'msg' => '参数错误', 'count' => 0, 'data' => []]);
}
$where = [['user_id', '=', $user_id]];
// 添加筛选条件
if (!empty($param['status'])) {
$where[] = ['status', '=', $param['status']];
}
if (!empty($param['goodslist_title'])) {
$where[] = ['goodslist_title', 'like', "%{$param['goodslist_title']}%"];
}
if (!empty($param['good_title'])) {
// 通过goods表查询包含该名称的盒子ID
$goods_ids = Db::name('goods')->where('title', 'like', "%{$param['good_title']}%")->column('id');
if (!empty($goods_ids)) {
$where[] = ['goods_id', 'in', $goods_ids];
} else {
// 如果没有找到匹配的盒子,返回空结果
return json(['code' => 0, 'msg' => '未找到匹配的盒子', 'count' => 0, 'data' => []]);
}
}
// 添加获取时间查询条件
if (!empty($param['addtime'])) {
$times = explode(' - ', $param['addtime']);
$where[] = ['addtime', 'between', [strtotime($times[0]), strtotime($times[1])]];
}
// 构建查询 - 添加了shang_title字段和发货状态字段
$query = Db::name('order_list')
->where($where)
->field('goodslist_title, goodslist_money, goodslist_price, goodslist_imgurl, shang_id, addtime, order_id, goods_id, status, fh_status, fh_remarks');
// 获取总数
$count = $query->count();
// 分页查询
$page = isset($param['page']) ? intval($param['page']) : 1;
$limit = isset($param['limit']) ? intval($param['limit']) : 20;
$list = $query->page($page, $limit)
->order('status, addtime desc')
->select()
->toArray();
// 处理订单编号、盒子名称和奖品类型
foreach ($list as &$item) {
// 获取订单编号
$order = Db::name('order')->where('id', $item['order_id'])->value('order_num');
$item['order_num'] = $order ?: '无订单号';
// 获取盒子名称
$good = Db::name('goods')->where('id', $item['goods_id'])->value('title');
$item['good_title'] = $good ?: '未知盒子';
// 获取奖品类型名称
$shang = Db::name('shang')->where('id', $item['shang_id'])->value('title');
$item['shang_title'] = $shang ?: '未知类型';
// 处理发货状态,确保数据存在
if ($item['status'] == 2) {
$item['fh_status'] = isset($item['fh_status']) ? intval($item['fh_status']) : 0;
} else {
$item['fh_status'] = null;
$item['fh_remarks'] = null;
}
}
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 用户盒柜页面
*/
public function user_box()
{
$user_id = request()->param('id', 0);
$nickname = request()->param('nickname', '');
// 将UID转换为用户ID
$user_id = $this->convertUidToUserId($user_id);
// 验证参数
if (empty($user_id)) {
$this->renderError('参数错误');
}
// 传递用户ID和昵称到模板
View::assign('user_id', $user_id);
View::assign('nickname', $nickname);
return View::fetch('User/user_box');
}
/**
* 用户订单页面
*/
public function user_order()
{
$id = input('id');
View::assign('id', $id);
View::assign('user_id', $id);
$nickname = input('nickname');
View::assign('nickname', $nickname);
return View::fetch('User/user_order');
}
/**
* 获取用户订单列表
*/
public function user_order_list()
{
$param = $this->request->param();
$user_id = isset($param['user_id']) ? intval($param['user_id']) : 0;
// 将UID转换为用户ID
$user_id = $this->convertUidToUserId($user_id);
if (empty($user_id)) {
return json(['code' => 1, 'msg' => '参数错误', 'count' => 0, 'data' => []]);
}
$where = [['user_id', '=', $user_id]];
// 添加筛选条件
if (isset($param['status']) && $param['status'] !== '') {
$where[] = ['status', '=', $param['status']];
}
if (!empty($param['goods_title'])) {
$where[] = ['goods_title', 'like', "%{$param['goods_title']}%"];
}
// 添加支付时间查询条件
if (!empty($param['pay_time'])) {
$times = explode(' - ', $param['pay_time']);
$where[] = ['pay_time', 'between', [strtotime($times[0]), strtotime($times[1])]];
}
// 构建查询
$query = Db::name('order')
->where($where)
->field('id, order_num, order_total, order_zhe_total, price, use_money, use_integral, use_score, goods_id, goods_title, num, goods_price, addtime, pay_time, status');
// 获取总数
$count = $query->count();
// 分页查询
$page = isset($param['page']) ? intval($param['page']) : 1;
$limit = isset($param['limit']) ? intval($param['limit']) : 20;
$list = $query->page($page, $limit)
->order('id desc')
->select()
->toArray();
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 用户余额流水明细
*/
public function user_money_detail()
{
$user_id = input('user_id');
$nickname = input('nickname', '');
View::assign('user_id', $user_id);
View::assign('nickname', $nickname);
return View::fetch('User/user_money_detail');
}
/**
* 获取用户余额流水明细数据
*/
public function user_money_detail_data()
{
$param = input();
$user_id = isset($param['user_id']) ? intval($param['user_id']) : 0;
if (empty($user_id)) {
return json(['code' => 1, 'msg' => '参数错误', 'count' => 0, 'data' => []]);
}
$where = [
['user_id', '=', $user_id]
];
// 时间范围
if (!empty($param['start_time']) && !empty($param['end_time'])) {
$start_time = strtotime($param['start_time']);
$end_time = strtotime($param['end_time']);
$where[] = ['addtime', 'between', [$start_time, $end_time]];
}
// 类型筛选
if (isset($param['type']) && $param['type'] !== '') {
$where[] = ['type', '=', intval($param['type'])];
}
// 变化类型(收入/消耗)
if (isset($param['change_type']) && $param['change_type'] !== '') {
if ($param['change_type'] === 'add') {
$where[] = ['change_money', '>', 0];
} elseif ($param['change_type'] === 'sub') {
$where[] = ['change_money', '<', 0];
}
}
// 备注搜索
if (isset($param['content']) && $param['content'] !== '') {
$where[] = ['content|other', 'like', '%' . $param['content'] . '%'];
}
// 获取数据
$model = new \app\common\model\ProfitMoney();
// 获取总数
$count = $model->where($where)->count();
// 分页
$page = isset($param['page']) ? max(1, intval($param['page'])) : 1;
$limit = isset($param['limit']) ? max(1, intval($param['limit'])) : 50;
$list = $model->where($where)
->order('id desc')
->page($page, $limit)
->select()
->toArray();
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 用户货币2流水明细
*/
public function user_integral_detail()
{
$user_id = input('user_id');
$nickname = input('nickname', '');
View::assign('user_id', $user_id);
View::assign('nickname', $nickname);
View::assign('currency_name', getConfig('app_setting')['currency1_name'] ?? '货币2');
return View::fetch('User/user_integral_detail');
}
/**
* 获取用户货币2流水明细数据
*/
public function user_integral_detail_data()
{
$param = input();
$user_id = isset($param['user_id']) ? intval($param['user_id']) : 0;
if (empty($user_id)) {
return json(['code' => 1, 'msg' => '参数错误', 'count' => 0, 'data' => []]);
}
$where = [
['user_id', '=', $user_id]
];
// 时间范围
if (!empty($param['start_time']) && !empty($param['end_time'])) {
$start_time = strtotime($param['start_time']);
$end_time = strtotime($param['end_time']);
$where[] = ['addtime', 'between', [$start_time, $end_time]];
}
// 类型筛选
if (isset($param['type']) && $param['type'] !== '') {
$where[] = ['type', '=', intval($param['type'])];
}
// 变化类型(收入/消耗)
if (isset($param['change_type']) && $param['change_type'] !== '') {
if ($param['change_type'] === 'add') {
$where[] = ['change_money', '>', 0];
} elseif ($param['change_type'] === 'sub') {
$where[] = ['change_money', '<', 0];
}
}
// 备注搜索
if (isset($param['content']) && $param['content'] !== '') {
// 使用content字段进行搜索
$where[] = ['content', 'like', '%' . $param['content'] . '%'];
}
try {
// 使用DB类进行查询避免使用模型方法
$list = Db::name('profit_integral')
->where($where)
->order('id desc')
->page(isset($param['page']) ? max(1, intval($param['page'])) : 1, isset($param['limit']) ? max(1, intval($param['limit'])) : 50)
->select()
->toArray();
$count = Db::name('profit_integral')
->where($where)
->count();
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '数据查询出错: ' . $e->getMessage(), 'count' => 0, 'data' => []]);
}
}
/**
* 用户货币3流水明细
*/
public function user_score_detail()
{
$user_id = input('user_id');
$nickname = input('nickname', '');
View::assign('user_id', $user_id);
View::assign('nickname', $nickname);
View::assign('currency_name', getConfig('app_setting')['currency2_name'] ?? '货币3');
return View::fetch('User/user_score_detail');
}
/**
* 获取用户货币3流水明细数据
*/
public function user_score_detail_data()
{
$param = input();
$user_id = isset($param['user_id']) ? intval($param['user_id']) : 0;
if (empty($user_id)) {
return json(['code' => 1, 'msg' => '参数错误', 'count' => 0, 'data' => []]);
}
$where = [
['user_id', '=', $user_id]
];
// 时间范围
if (!empty($param['start_time']) && !empty($param['end_time'])) {
$start_time = strtotime($param['start_time']);
$end_time = strtotime($param['end_time']);
$where[] = ['addtime', 'between', [$start_time, $end_time]];
}
// 类型筛选
if (isset($param['type']) && $param['type'] !== '') {
$where[] = ['type', '=', intval($param['type'])];
}
// 变化类型(收入/消耗)
if (isset($param['change_type']) && $param['change_type'] !== '') {
if ($param['change_type'] === 'add') {
$where[] = ['change_money', '>', 0];
} elseif ($param['change_type'] === 'sub') {
$where[] = ['change_money', '<', 0];
}
}
// 备注搜索
if (isset($param['content']) && $param['content'] !== '') {
// 使用content字段进行搜索
$where[] = ['content', 'like', '%' . $param['content'] . '%'];
}
try {
// 使用DB类进行查询避免使用模型方法
$list = Db::name('profit_money2')
->where($where)
->order('id desc')
->page(isset($param['page']) ? max(1, intval($param['page'])) : 1, isset($param['limit']) ? max(1, intval($param['limit'])) : 50)
->select()
->toArray();
$count = Db::name('profit_money2')
->where($where)
->count();
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '数据查询出错: ' . $e->getMessage(), 'count' => 0, 'data' => []]);
}
}
/**
* 用户登录统计
*/
public function loginStat()
{
if (request()->isAjax()) {
try {
$type = input('type', 'day');
$year = input('year', date('Y'));
$month = input('month', date('m'));
$start_date = input('start_date', date('Y-m-d', strtotime('-30 days')));
$end_date = input('end_date', date('Y-m-d'));
switch ($type) {
case 'day':
// 日登录统计
$data = \app\common\model\UserLoginLog::getDailyLoginCount($start_date, $end_date);
$chart_data = [];
$labels = [];
$values = [];
foreach ($data as $item) {
$labels[] = $item['login_date'];
$values[] = $item['count'];
}
$chart_data = [
'labels' => $labels,
'values' => $values,
];
// 计算活跃用户数
$active_user_count = \app\common\model\UserLoginLog::getActiveUserCount($start_date, $end_date);
return json([
'code' => 0,
'msg' => 'ok',
'data' => [
'chart' => $chart_data,
'active_users' => $active_user_count,
'total_logins' => array_sum($values),
]
]);
break;
case 'week':
// 周登录统计
$data = \app\common\model\UserLoginLog::getWeeklyLoginCount($year);
$chart_data = [];
$labels = [];
$values = [];
foreach ($data as $item) {
$labels[] = $item['year'] . '年第' . $item['week'] . '周';
$values[] = $item['count'];
}
$chart_data = [
'labels' => $labels,
'values' => $values,
];
return json([
'code' => 0,
'msg' => 'ok',
'data' => [
'chart' => $chart_data,
'total_logins' => array_sum($values),
]
]);
break;
case 'month':
// 月登录统计
$data = \app\common\model\UserLoginLog::getMonthlyLoginCount($year);
$chart_data = [];
$labels = [];
$values = [];
foreach ($data as $item) {
$labels[] = $item['year'] . '年' . $item['month'] . '月';
$values[] = $item['count'];
}
$chart_data = [
'labels' => $labels,
'values' => $values,
];
return json([
'code' => 0,
'msg' => 'ok',
'data' => [
'chart' => $chart_data,
'total_logins' => array_sum($values),
]
]);
break;
default:
return json(['code' => 1, 'msg' => '统计类型错误']);
}
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => $e->getMessage()]);
}
}
return view('User/login_stat', [
'year' => date('Y'),
'month' => date('m'),
'start_date' => date('Y-m-d', strtotime('-30 days')),
'end_date' => date('Y-m-d'),
]);
}
/**
* 重置用户签到数据
*/
public function resetUserSign(Request $request)
{
$id = $request->param('id');
$user = UserModel::find($id);
if (!$user) {
return json(['status' => 0, 'msg' => '用户不存在']);
}
// 计算上一天的日期
$yesterday = date('Y-m-d', strtotime('-1 day'));
try {
// 更新用户的签到数据
$result = \app\common\model\UserSign::where('user_id', $id)
->where('sign_date', date('Y-m-d'))
->update([
'sign_date' => $yesterday,
'update_time' => time()
]);
if ($result) {
return json(['status' => 1, 'msg' => '签到数据重置成功']);
} else {
// 如果没有今日签到记录
return json(['status' => 1, 'msg' => '用户今日未签到或已重置']);
}
} catch (\Exception $e) {
return json(['status' => 0, 'msg' => '重置失败:' . $e->getMessage()]);
}
}
/**
* 绑定用户手机号
*/
public function bindUserMobile(Request $request)
{
$id = $request->post('id/d', 0);
$mobile = $request->post('mobile', '');
// 验证手机号格式
if (!preg_match('/^1\d{10}$/', $mobile)) {
return json(['status' => 0, 'msg' => '手机号格式不正确']);
}
$user = UserModel::getInfo(['id' => $id]);
if (!$user) {
return json(['status' => 0, 'msg' => '用户不存在']);
}
// 检查手机号是否已被其他用户使用
$existUser = UserModel::where('mobile', $mobile)
->where('id', '<>', $id)
->find();
if ($existUser) {
return json(['status' => 0, 'msg' => '该手机号已被其他用户使用']);
}
// 更新用户手机号
$result = $user->save(['mobile' => $mobile]);
if ($result) {
return json(['status' => 1, 'msg' => '手机号绑定成功']);
} else {
return json(['status' => 0, 'msg' => '手机号绑定失败']);
}
}
/**
* 用户盈亏列表页面
*/
public function userProfitLossList()
{
return View::fetch('User/user_profit_loss_list');
}
/**
* 获取用户盈亏数据
*/
public function getUserProfitLoss()
{
$param = input();
// 构建查询条件
$where = [];
$whereUser = 'u.status=1 and u.istest=0 and o.status=1';
$whereUser1 = '';
$whereUser2 = '';
$whereUser3 = '';
// 处理时间范围参数
if (!empty($param['time_range'])) {
$dates = explode(' - ', $param['time_range']);
if (count($dates) == 2) {
$start_time = strtotime($dates[0]);
// 结束日期加一天减1秒确保包含当天所有数据
$end_time = strtotime($dates[1] . ' 23:59:59');
// 只有当提供了时间范围时,才添加时间条件
$whereUser .= " and o.addtime > {$start_time} and o.addtime < {$end_time}";
$whereUser1 = " and addtime > {$start_time} and addtime < {$end_time}";
$whereUser2 = " and choice_time > {$start_time} and choice_time < {$end_time}";
$whereUser3 = " and addtime < {$end_time} ";
}
}
// 处理用户ID/UID参数
if (!empty($param['uid'])) {
$uid = trim($param['uid']);
// 判断是否为数字UID或者字符串UID
if (is_numeric($uid)) {
$user = \app\common\model\User::where('id', $uid)->whereOr('uid', $uid)->find();
if ($user) {
$whereUser .= " and o.user_id = {$user['id']}";
}
} else {
$user = \app\common\model\User::where('uid', $uid)->find();
if ($user) {
$whereUser .= " and o.user_id = {$user['id']}";
}
}
}
// 构建SQL查询
// 构建SQL查询 - 不应用分页限制,获取全部数据
$sql = "select c.* from (
select t.*,
(CASE
WHEN t.use_money>0 THEN (t.use_money-t.fh_money-t.bb_money-t.sy_money)
ELSE 0
END) yue_money
from (
SELECT o.user_id, u.uid, u.nickname, u.headimg, u.mobile,
u.money,
u.integral,
count(1) orderCount,
sum(IFNULL(order_zhe_total,0)) order_zhe_total,
IFNULL(sum(price),0) money_1,
IFNULL(sum(use_money),0) money_2,
IFNULL(sum(price)+SUM(use_money),0) use_money,
(select IFNULL(sum(goodslist_money),0) sc_money from order_list where user_id=o.user_id and status=2 and goodslist_type<3 {$whereUser2}) fh_money,
(select IFNULL(sum(goodslist_money),0) sc_money from order_list where user_id=o.user_id and status=0 and goodslist_type<3 {$whereUser3}) bb_money,
(TRUNCATE(u.money2/100, 2)) money2,
(TRUNCATE(IFNULL((SELECT money FROM profit_money2 where user_id=o.user_id {$whereUser1} order by id desc LIMIT 1),0)/100, 2)) sy_money
FROM `order` o LEFT join `user` u ON o.user_id=u.id where {$whereUser} group by o.user_id ) t where use_money>0
) c order by yue_money desc";
//添加日志记录
\think\facade\Log::info($sql);
// 分页处理
$page = isset($param['page']) ? intval($param['page']) : 1;
$limit = isset($param['limit']) ? intval($param['limit']) : 20;
// 获取总记录数
$countSql = "SELECT COUNT(*) as count FROM ({$sql}) as temp";
$count = \think\facade\Db::query($countSql)[0]['count'];
// 添加分页
$sql .= " LIMIT " . (($page - 1) * $limit) . ", {$limit}";
// 执行查询
$list = \think\facade\Db::query($sql);
// 处理结果数据
foreach ($list as &$item) {
// 处理图片URL
$item['headimg'] = empty($item['headimg']) ? '' : imageUrl($item['headimg']);
// 格式化数值
$item['money'] = floatval($item['money']);
$item['integral'] = floatval($item['integral']);
$item['money2'] = floatval($item['money2']);
$item['order_zhe_total'] = floatval($item['order_zhe_total']);
$item['money_1'] = floatval($item['money_1']);
$item['money_2'] = floatval($item['money_2']);
$item['use_money'] = floatval($item['use_money']);
$item['fh_money'] = floatval($item['fh_money']);
$item['bb_money'] = floatval($item['bb_money']);
$item['yue_money'] = floatval($item['yue_money']);
// 处理盈亏状态
$item['profit_status'] = $item['yue_money'] > 0 ? '亏损' : '盈利';
$item['profit_value'] = abs($item['yue_money']);
}
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 导出用户盈亏列表到Excel
*/
public function exportUserProfitLoss()
{
$param = input();
// 构建查询条件
$where = [];
$whereUser = 'u.status=1 and u.istest=0 and o.status=1';
$whereUser1 = '';
$whereUser2 = '';
$whereUser3 = '';
// 处理时间范围参数
if (!empty($param['time_range'])) {
$dates = explode(' - ', $param['time_range']);
if (count($dates) == 2) {
$start_time = strtotime($dates[0]);
// 结束日期加一天减1秒确保包含当天所有数据
$end_time = strtotime($dates[1] . ' 23:59:59');
// 只有当提供了时间范围时,才添加时间条件
$whereUser .= " and o.addtime > {$start_time} and o.addtime < {$end_time}";
$whereUser1 = " and addtime > {$start_time} and addtime < {$end_time}";
$whereUser2 = " and choice_time > {$start_time} and choice_time < {$end_time}";
$whereUser3 = " and addtime < {$end_time} ";
}
}
// 处理用户ID/UID参数
if (!empty($param['uid'])) {
$uid = trim($param['uid']);
// 判断是否为数字UID或者字符串UID
if (is_numeric($uid)) {
$user = \app\common\model\User::where('id', $uid)->whereOr('uid', $uid)->find();
if ($user) {
$whereUser .= " and o.user_id = {$user['id']}";
}
} else {
$user = \app\common\model\User::where('uid', $uid)->find();
if ($user) {
$whereUser .= " and o.user_id = {$user['id']}";
}
}
}
// 构建SQL查询 - 不应用分页限制,获取全部数据
$sql = "select c.* from (
select t.*,
(CASE
WHEN t.use_money>0 THEN (t.use_money-t.fh_money-t.bb_money-t.sy_money)
ELSE 0
END) yue_money
from (
SELECT o.user_id, u.uid, u.nickname, u.headimg, u.mobile,
u.money,
u.integral,
count(1) orderCount,
sum(IFNULL(order_zhe_total,0)) order_zhe_total,
IFNULL(sum(price),0) money_1,
IFNULL(sum(use_money),0) money_2,
IFNULL(sum(price)+SUM(use_money),0) use_money,
(select IFNULL(sum(goodslist_money),0) sc_money from order_list where user_id=o.user_id and status=2 and goodslist_type<3 {$whereUser2}) fh_money,
(select IFNULL(sum(goodslist_money),0) sc_money from order_list where user_id=o.user_id and status=0 and goodslist_type<3 {$whereUser3}) bb_money,
(TRUNCATE(u.money2/100, 2)) money2,
(TRUNCATE(IFNULL((SELECT money FROM profit_money2 where user_id=o.user_id {$whereUser1} order by id desc LIMIT 1),0)/100, 2)) sy_money
FROM `order` o LEFT join `user` u ON o.user_id=u.id where {$whereUser} group by o.user_id ) t where use_money>0
) c order by yue_money desc";
//添加日志记录
\think\facade\Log::info($sql);
// 执行查询
$list = \think\facade\Db::query($sql);
// 处理结果数据
foreach ($list as &$item) {
// 处理图片URL
$item['headimg'] = empty($item['headimg']) ? '' : imageUrl($item['headimg']);
// 格式化数值
$item['money'] = floatval($item['money']);
$item['integral'] = floatval($item['integral']);
$item['money2'] = floatval($item['money2']);
$item['order_zhe_total'] = floatval($item['order_zhe_total']);
$item['money_1'] = floatval($item['money_1']);
$item['money_2'] = floatval($item['money_2']);
$item['use_money'] = floatval($item['use_money']);
$item['fh_money'] = floatval($item['fh_money']);
$item['bb_money'] = floatval($item['bb_money']);
$item['yue_money'] = floatval($item['yue_money']);
// 处理盈亏状态
$item['profit_status'] = $item['yue_money'] > 0 ? '亏损' : '盈利';
$item['profit_value'] = abs($item['yue_money']);
}
// 引入PHPExcel
// ThinkPHP 6.0使用composer自动加载
if (!class_exists('\\PhpOffice\\PhpSpreadsheet\\Spreadsheet')) {
return json(['code' => 1, 'msg' => '请先安装PhpSpreadsheet扩展']);
}
// 使用PhpSpreadsheet
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 设置文档属性
$spreadsheet->getProperties()
->setCreator("系统")
->setLastModifiedBy("系统")
->setTitle("用户盈亏列表")
->setSubject("用户盈亏列表")
->setDescription("用户盈亏列表导出数据");
// 设置表头
$headers = [
'A' => '序号',
'B' => 'UID',
'C' => '用户ID',
'D' => '用户昵称',
'E' => '手机号',
'F' => '钻石',
'G' => 'UU币',
'H' => '达达券',
'I' => '订单数',
'J' => '订单总额',
'K' => 'RMB支付',
'L' => '钻石支付',
'M' => '用户支付金额',
'N' => '用户发货金额',
'O' => '用户背包金额',
'P' => '剩余达达券',
'Q' => '亏损/盈利状态',
'R' => '亏损/盈利金额',
// 'S' => '利润值'
];
foreach ($headers as $key => $val) {
$sheet->setCellValue($key . '1', $val);
// 设置表头单元格样式
$sheet->getStyle($key . '1')->getFont()->setBold(true);
$sheet->getStyle($key . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
// 写入数据
$row = 2;
foreach ($list as $index => $item) {
$sheet->setCellValue('A' . $row, $index + 1);
$sheet->setCellValue('B' . $row, $item['uid']);
$sheet->setCellValue('C' . $row, $item['user_id']);
$sheet->setCellValue('D' . $row, $item['nickname']);
$sheet->setCellValue('E' . $row, $item['mobile']);
$sheet->setCellValue('F' . $row, $item['money']);
$sheet->setCellValue('G' . $row, $item['integral']);
$sheet->setCellValue('H' . $row, $item['money2']);
$sheet->setCellValue('I' . $row, $item['orderCount']);
$sheet->setCellValue('J' . $row, $item['order_zhe_total']);
$sheet->setCellValue('K' . $row, $item['money_1']);
$sheet->setCellValue('L' . $row, $item['money_2']);
$sheet->setCellValue('M' . $row, $item['use_money']);
$sheet->setCellValue('N' . $row, $item['fh_money']);
$sheet->setCellValue('O' . $row, $item['bb_money']);
$sheet->setCellValue('P' . $row, $item['sy_money']);
$sheet->setCellValue('Q' . $row, $item['profit_status']);
$sheet->setCellValue('R' . $row, $item['profit_value']);
$sheet->setCellValue('S' . $row, $item['yue_money']);
// 为亏损和盈利设置不同颜色
if ($item['yue_money'] > 0) {
// 亏损标红
$sheet->getStyle('Q' . $row)->getFont()->getColor()->setARGB('FFFF0000');
$sheet->getStyle('R' . $row)->getFont()->getColor()->setARGB('FFFF0000');
// $sheet->getStyle('S' . $row)->getFont()->getColor()->setARGB('FFFF0000');
} else {
// 盈利标绿
$sheet->getStyle('Q' . $row)->getFont()->getColor()->setARGB('FF008000');
$sheet->getStyle('R' . $row)->getFont()->getColor()->setARGB('FF008000');
// $sheet->getStyle('S' . $row)->getFont()->getColor()->setARGB('FF008000');
}
$row++;
}
// 调整列宽
foreach ($headers as $key => $val) {
$sheet->getColumnDimension($key)->setAutoSize(true);
}
// 设置sheet名称
$sheet->setTitle('用户盈亏列表');
// 输出Excel文件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="用户盈亏列表_' . date('YmdHis') . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
/**
* 将UID转换为用户ID
*/
protected function convertUidToUserId($uid)
{
if (empty($uid)) {
return 0;
}
// 如果是数字可能是用户ID或UID
if (is_numeric($uid)) {
$user = \app\common\model\User::where('id', $uid)->whereOr('uid', $uid)->find();
return $user ? $user['id'] : 0;
} else {
// 如果是字符串尝试查找UID
$user = \app\common\model\User::where('uid', $uid)->find();
return $user ? $user['id'] : 0;
}
}
/**
* 获取用户达达券记录
*/
public function getUserMoney2Records()
{
$param = input();
// 验证参数
if (empty($param['user_id'])) {
return json(['code' => 1, 'msg' => '缺少用户ID参数']);
}
// 分页参数
$page = isset($param['page']) ? intval($param['page']) : 1;
$limit = isset($param['limit']) ? intval($param['limit']) : 10;
$offset = ($page - 1) * $limit;
// 时间范围处理
$whereTime = '';
if (!empty($param['time_range'])) {
$dates = explode(' - ', $param['time_range']);
if (count($dates) == 2) {
$start_time = strtotime($dates[0]);
$end_time = strtotime($dates[1] . ' 23:59:59');
$whereTime = " and addtime > {$start_time} and addtime < {$end_time}";
}
}
// 获取总记录数
$countSql = "SELECT COUNT(*) as count FROM profit_money2 WHERE user_id = :user_id {$whereTime}";
$count = \think\facade\Db::query($countSql, ['user_id' => $param['user_id']])[0]['count'];
// 构建SQL查询并添加分页
$sql = "SELECT (change_money/100) change_money, (money/100) money, content, FROM_UNIXTIME(addtime) as addtime_fmt, addtime
FROM profit_money2
WHERE user_id = :user_id {$whereTime}
ORDER BY id desc
LIMIT {$offset}, {$limit}";
// 执行查询
$list = \think\facade\Db::query($sql, ['user_id' => $param['user_id']]);
// 处理数据将达达券值转换为显示格式乘以100
foreach ($list as &$item) {
$item['change_money'] = floatval($item['change_money']) * 100;
$item['money'] = floatval($item['money']) * 100;
}
return json([
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list
]);
}
/**
* 导出团队用户列表到Excel
*/
public function exportUserTeam(Request $request)
{
$id = $request->param('id');
$addtime = $request->param('addtime');
// 将UID转换为用户ID
$id = $this->convertUidToUserId($id);
// 查询数据(不分页,获取全部)
$list = \app\common\model\User::where('pid', $id)->select();
$start_time = 0;
$end_time = 0;
if ($addtime) {
$addtime = explode(' - ', $addtime);
$start_time = strtotime($addtime[0]);
$end_time = strtotime($addtime[1]);
}
// 处理数据
foreach ($list as &$value) {
$value['total'] = ProfitMoney::where('type', 5)
->where('user_id', $id)
->where('share_uid', $value['id'])
->sum('change_money');
// 订单统计查询
$orderQuery = \app\common\model\Order::where('user_id', $value['id'])
->where('status', 1);
// 添加时间筛选条件
if ($start_time > 0 && $end_time > 0) {
$orderQuery->where('addtime', 'between', [$start_time, $end_time]);
}
// 执行查询并获取结果
$orderStats = $orderQuery->field('IFNULL(sum(price),0) as price, IFNULL(sum(use_money),0) as use_money')
->find();
$value['order_price'] = $orderStats['price'];
$value['order_use_money'] = $orderStats['use_money'];
// 格式化时间
// $value['addtime_format'] = date('Y-m-d H:i:s', $value['addtime']);
// 处理状态
$value['status_text'] = $value['status'] == 1 ? '正常' : '封号';
}
// 引入PHPExcel
if (!class_exists('\\PhpOffice\\PhpSpreadsheet\\Spreadsheet')) {
return json(['code' => 1, 'msg' => '请先安装PhpSpreadsheet扩展']);
}
// 使用PhpSpreadsheet
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 设置文档属性
$spreadsheet->getProperties()
->setCreator("系统")
->setLastModifiedBy("系统")
->setTitle("下级用户列表")
->setSubject("下级用户列表")
->setDescription("下级用户列表导出数据");
// 设置表头
$headers = [
'A' => '序号',
'B' => '用户ID',
'C' => 'UID',
'D' => '手机号',
'E' => '昵称',
'F' => 'RMB消费',
'G' => '钻石消费',
'H' => '钻石',
'I' => 'UU币',
'J' => '达达卷',
'K' => '佣金',
'L' => '状态',
// 'M' => '时间'
];
foreach ($headers as $key => $val) {
$sheet->setCellValue($key . '1', $val);
// 设置表头单元格样式
$sheet->getStyle($key . '1')->getFont()->setBold(true);
$sheet->getStyle($key . '1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
// 写入数据
$row = 2;
foreach ($list as $index => $item) {
$sheet->setCellValue('A' . $row, $index + 1);
$sheet->setCellValue('B' . $row, $item['id']);
$sheet->setCellValue('C' . $row, isset($item['uid']) ? $item['uid'] : $item['id']);
$sheet->setCellValue('D' . $row, $item['mobile']);
$sheet->setCellValue('E' . $row, $item['nickname']);
$sheet->setCellValue('F' . $row, $item['order_price']);
$sheet->setCellValue('G' . $row, $item['order_use_money']);
$sheet->setCellValue('H' . $row, $item['money']);
$sheet->setCellValue('I' . $row, $item['integral']);
$sheet->setCellValue('J' . $row, $item['money2']);
$sheet->setCellValue('K' . $row, $item['total']);
$sheet->setCellValue('L' . $row, $item['status_text']);
// $sheet->setCellValue('M' . $row, $item['addtime_format']);
// 为不同状态设置不同颜色
if ($item['status'] != 1) {
// 封号标红
$sheet->getStyle('L' . $row)->getFont()->getColor()->setARGB('FFFF0000');
}
$row++;
}
// 调整列宽
foreach ($headers as $key => $val) {
$sheet->getColumnDimension($key)->setAutoSize(true);
}
// 设置sheet名称
$sheet->setTitle('下级用户列表');
// 输出Excel文件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="下级用户列表_' .$id.'_' . date('YmdHis') . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
}