| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416 |
- <?php
- namespace app\api\controller\invitation;
- use app\common\controller\Frontend;
- use app\common\service\CommissionService;
- use think\facade\Db;
- class Order extends Frontend
- {
- protected array $noNeedPermission = ['purchaseRecordsSimple','orderDetail'];
- protected $commissionService;
- public function initialize(): void
- {
- parent::initialize();
- $this->commissionService = new CommissionService();
- }
- /**
- * 获取用户购买记录(简化版)
- */
- public function purchaseRecordsSimple(): void
- {
- // 确保用户已登录
- if (!$this->auth->isLogin()) {
- $this->error('请先登录');
- }
- $userId = $this->auth->id;
- if (!$userId) {
- $this->error('用户ID获取失败');
- }
- // try {
- // 获取查询参数
- $page = $this->request->get('page', 1);
- $pageSize = $this->request->get('pageSize', 10);
- $status = $this->request->get('status', 'all'); // all, paid, unpaid
- $order_no = $this->request->get('order_no', '');//订单号
- $star_time = $this->request->get('star_time', '');//创建订单开始时间
- $end_time = $this->request->get('end_time', '');//创建订单结束时间
- // 构建查询条件
- $query = Db::table('ba_order')
- ->where('user_id', $userId);
- // 根据状态筛选
- if ($status === 'paid') {
- $query->where('pay_status', 1); // 已支付
- } elseif ($status === 'unpaid') {
- $query->where('pay_status', 0); // 未支付
- }
- // 查询订单号
- if (!empty($order_no)) {
- $query->where('order_no', $order_no); // 订单号
- }
- if (!empty($star_time) && !empty($end_time)) {
- $where[] = ['order_time', 'between', [$star_time, $end_time]];
- $query->where($where); // 塞选时间
- } else {
- $yesterday = date('Y-m-d 00:00:00', strtotime('-1 day'));
- $yesterday_end = date('Y-m-d 23:59:00', strtotime('-1 day'));
- $where[] = ['order_time', 'between', [$yesterday, $yesterday_end]];
- $query->where($where); // 塞选时间
- }
- // 获取订单总数
- $total = $query->count();
- // 获取订单列表(只取必要字段)
- $orders = $query->field('order_no, pay_amount, pay_method, pay_status, order_time, pay_time')
- ->order('order_time', 'desc')
- ->page($page, $pageSize)
- ->select()
- ->toArray();
- // 处理每个订单的商品信息
- $orderNos = array_column($orders, 'order_no');
- if (!empty($orderNos)) {
- // 批量查询订单商品
- $orderItems = \think\facade\Db::table('ba_order_item')
- ->where('order_id', 'IN', Db::table('ba_order')
- ->where('order_no', 'IN', $orderNos)
- ->column('id'))
- ->field('order_id, item_name, quantity, unit_price, total_price')
- ->select()
- ->toArray();
- // 按order_id分组商品
- $itemsByOrderId = [];
- foreach ($orderItems as $item) {
- $itemsByOrderId[$item['order_id']][] = $item;
- }
- // 获取订单ID映射
- $orderIdMap = \think\facade\Db::table('ba_order')
- ->where('order_no', 'IN', $orderNos)
- ->column('id', 'order_no');
- // 合并商品信息到订单
- foreach ($orders as &$order) {
- // 注意:现在 $orderIdMap 的键是 order_no,值是对应的 id
- $orderId = $orderIdMap[$order['order_no']] ?? 0;
- // 取第一个商品作为主商品信息(根据您的截图,一单一个商品)
- $mainItem = $itemsByOrderId[$orderId][0] ?? [];
- // 商品名称(如果有多个商品,显示第一个)
- $order['product_name'] = $mainItem['item_name'] ?? '商品';
- // 数量
- $order['quantity'] = $mainItem['quantity'] ?? 1;
- // 格式化显示字段
- $order['amount'] = '¥' . number_format($order['pay_amount'], 2);
- $order['pay_method_text'] = $this->getSimplePayMethodText($order['pay_method']);
- $order['pay_status_text'] = $order['pay_status'] == 1 ? '已支付' : '未支付';
- $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
- $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
- // 移除不需要的原始字段
- unset($order['pay_amount'], $order['pay_method'], $order['pay_status'],
- $order['order_time'], $order['pay_time']);
- }
- }
- // 获取简单的统计信息
- $stats = [
- 'total_orders' => $total,
- 'paid_orders' =>Db::table('ba_order')
- ->where('user_id', $userId)
- ->where($where)
- ->where('order_no', 'IN', $orderNos)
- ->where('pay_status', 1)
- ->count(),
- 'unpaid_orders' =>Db::table('ba_order')
- ->where('user_id', $userId)
- ->where($where)
- ->where('order_no', 'IN', $orderNos)
- ->where('pay_status', 0)
- ->count(),
- ];
- // } catch (\Throwable $e) {
- // \think\facade\Log::error('获取购买记录失败: ' . $e->getMessage());
- // $this->error('获取购买记录失败');
- // }
- $this->success('', [
- 'list' => $orders,
- 'total' => $total,
- 'page' => $page,
- 'page_size' => $pageSize,
- 'stats' => $stats
- ]);
- }
- /**
- * 简化支付方式文本
- */
- private function getSimplePayMethodText(string $method): string
- {
- $methodMap = [
- 'wechat' => '微信',
- 'alipay' => '支付宝',
- 'bank' => '银行卡'
- ];
- return $methodMap[$method] ?? '其他';
- }
- /**
- * 获取购买统计信息
- */
- private function getPurchaseStats(int $userId, string $status = 'all', string $startDate = '', string $endDate = ''): array
- {
- try {
- // 全部订单统计
- $totalQuery = \think\facade\Db::table('ba_order')
- ->where('user_id', $userId);
- // 已支付订单统计
- $paidQuery = \think\facade\Db::table('ba_order')
- ->where('user_id', $userId)
- ->where('pay_status', 1);
- // 时间范围筛选
- if (!empty($startDate)) {
- $totalQuery->where('order_time', '>=', $startDate);
- $paidQuery->where('order_time', '>=', $startDate);
- }
- if (!empty($endDate)) {
- $totalQuery->where('order_time', '<=', $endDate . ' 23:59:59');
- $paidQuery->where('order_time', '<=', $endDate . ' 23:59:59');
- }
- $totalCount = $totalQuery->count();
- $paidCount = $paidQuery->count();
- $unpaidCount = $totalCount - $paidCount;
- // 支付总金额
- $totalAmount = $paidQuery->sum('pay_amount');
- $totalAmount = $totalAmount ?: 0;
- // 本月统计
- $monthStart = date('Y-m-01');
- $monthPaidAmount = \think\facade\Db::table('ba_order')
- ->where('user_id', $userId)
- ->where('pay_status', 1)
- ->where('order_time', '>=', $monthStart)
- ->sum('pay_amount');
- $monthPaidAmount = $monthPaidAmount ?: 0;
- return [
- 'total_orders' => $totalCount,
- 'paid_orders' => $paidCount,
- 'unpaid_orders' => $unpaidCount,
- 'total_amount' => $totalAmount,
- 'month_amount' => $monthPaidAmount
- ];
- } catch (\Throwable $e) {
- \think\facade\Log::error('获取购买统计失败: ' . $e->getMessage());
- return [
- 'total_orders' => 0,
- 'paid_orders' => 0,
- 'unpaid_orders' => 0,
- 'total_amount' => 0,
- 'month_amount' => 0
- ];
- }
- }
- /**
- * 获取支付状态文本
- */
- private function getPayStatusText(int $status): string
- {
- $statusMap = [
- 0 => '待支付',
- 1 => '已支付',
- 2 => '支付失败'
- ];
- return $statusMap[$status] ?? '未知状态';
- }
- /**
- * 获取订单状态文本
- */
- private function getOrderStatusText(int $status): string
- {
- $statusMap = [
- 0 => '待处理',
- 1 => '已确认',
- 2 => '已发货',
- 3 => '已完成',
- 4 => '已取消'
- ];
- return $statusMap[$status] ?? '未知状态';
- }
- /**
- * 获取支付方式文本
- */
- private function getPayMethodText(string $method): string
- {
- $methodMap = [
- 'wechat' => '微信支付',
- 'alipay' => '支付宝',
- 'bank' => '银行卡',
- 'balance' => '余额支付'
- ];
- return $methodMap[$method] ?? '其他支付';
- }
- /**
- * 获取订单详情(单个订单)
- */
- public function orderDetail(): void
- {
- if (!$this->auth->isLogin()) {
- $this->error('请先登录');
- }
- $userId = $this->auth->id;
- $orderId = $this->request->get('order_id', 0);
- $orderNo = $this->request->get('order_no', '');
- if (empty($orderId) && empty($orderNo)) {
- $this->error('参数错误');
- }
- try {
- // 查询订单
- if ($orderId) {
- $order = \think\facade\Db::table('ba_order')
- ->where('id', $orderId)
- ->where('user_id', $userId) // 只能查看自己的订单
- ->find();
- } else {
- $order = \think\facade\Db::table('ba_order')
- ->where('order_no', $orderNo)
- ->where('user_id', $userId) // 只能查看自己的订单
- ->find();
- }
- if (!$order) {
- $this->error('订单不存在或无权查看');
- }
- // 获取订单商品项
- $orderItems = \think\facade\Db::table('ba_order_item')
- ->where('order_id', $order['id'])
- ->select()
- ->toArray();
- // 格式化显示数据
- $order['pay_status_text'] = $this->getPayStatusText($order['pay_status']);
- $order['order_status_text'] = $this->getOrderStatusText($order['order_status']);
- $order['pay_method_text'] = $this->getPayMethodText($order['pay_method']);
- // 格式化时间
- $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
- $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
- $order['complete_time_formatted'] = $order['complete_time'] ? date('Y-m-d H:i:s', strtotime($order['complete_time'])) : '';
- $order['create_time_formatted'] = $order['create_time'] ? date('Y-m-d H:i:s', strtotime($order['create_time'])) : '';
- } catch (\Throwable $e) {
- \think\facade\Log::error('获取订单详情失败: ' . $e->getMessage());
- $this->error('获取订单详情失败');
- }
- $this->success('', [
- 'order' => $order,
- 'items' => $orderItems
- ]);
- }
- /**
- * 订单支付成功回调(处理佣金)
- */
- public function paymentCallback(): void
- {
- if (!$this->request->isPost()) {
- $this->error('非法请求');
- }
- $orderId = $this->request->post('order_id', 0);
- $orderNo = $this->request->post('order_no', '');
- if (empty($orderId) && empty($orderNo)) {
- $this->error('参数错误');
- }
- try {
- // 查找订单
- if (!empty($orderId)) {
- $order = \think\facade\Db::table('ba_order')
- ->where('id', $orderId)
- ->find();
- } else {
- $order = \think\facade\Db::table('ba_order')
- ->where('order_no', $orderNo)
- ->find();
- }
- if (!$order) {
- $this->error('订单不存在');
- }
- // 处理订单佣金
- $result = $this->commissionService->processOrderCommission($order['id']);
- if ($result) {
- $this->success('佣金处理成功');
- } else {
- $this->error('佣金处理失败');
- }
- } catch (\Throwable $e) {
- $this->error('处理失败:' . $e->getMessage());
- }
- }
- /**
- * 手动触发订单佣金处理(管理用)
- */
- public function processCommission(): void
- {
- if (!$this->auth->isLogin() || !$this->auth->isAdmin()) {
- $this->error('权限不足');
- }
- $orderId = $this->request->post('order_id', 0);
- if ($orderId <= 0) {
- $this->error('订单ID错误');
- }
- $result = $this->commissionService->processOrderCommission($orderId);
- if ($result) {
- $this->success('处理成功');
- } else {
- $this->error('处理失败');
- }
- }
- }
|