Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. namespace app\api\controller\invitation;
  3. use app\common\controller\Frontend;
  4. use app\common\service\CommissionService;
  5. use think\facade\Db;
  6. class Order extends Frontend
  7. {
  8. protected array $noNeedPermission = ['purchaseRecordsSimple','orderDetail'];
  9. protected $commissionService;
  10. public function initialize(): void
  11. {
  12. parent::initialize();
  13. $this->commissionService = new CommissionService();
  14. }
  15. /**
  16. * 获取用户购买记录(简化版)
  17. */
  18. public function purchaseRecordsSimple(): void
  19. {
  20. // 确保用户已登录
  21. if (!$this->auth->isLogin()) {
  22. $this->error('请先登录');
  23. }
  24. $userId = $this->auth->id;
  25. if (!$userId) {
  26. $this->error('用户ID获取失败');
  27. }
  28. // try {
  29. // 获取查询参数
  30. $page = $this->request->get('page', 1);
  31. $pageSize = $this->request->get('pageSize', 10);
  32. $status = $this->request->get('status', 'all'); // all, paid, unpaid
  33. $order_no = $this->request->get('order_no', '');//订单号
  34. $star_time = $this->request->get('star_time', '');//创建订单开始时间
  35. $end_time = $this->request->get('end_time', '');//创建订单结束时间
  36. // 构建查询条件
  37. $query = Db::table('ba_order')
  38. ->where('user_id', $userId);
  39. // 根据状态筛选
  40. if ($status === 'paid') {
  41. $query->where('pay_status', 1); // 已支付
  42. } elseif ($status === 'unpaid') {
  43. $query->where('pay_status', 0); // 未支付
  44. }
  45. // 查询订单号
  46. if (!empty($order_no)) {
  47. $query->where('order_no', $order_no); // 订单号
  48. }
  49. if (!empty($star_time) && !empty($end_time)) {
  50. $where[] = ['order_time', 'between', [$star_time.' 00:00:00', $end_time.' 23:59:59']];
  51. $query->where($where); // 塞选时间
  52. } else {
  53. $yesterday = date('Y-m-d 00:00:00', strtotime('-1 day'));
  54. $yesterday_end = date('Y-m-d 23:59:00', strtotime('-1 day'));
  55. $where[] = ['order_time', 'between', [$yesterday, $yesterday_end]];
  56. $query->where($where); // 塞选时间
  57. }
  58. // 获取订单总数
  59. $total = $query->count();
  60. // 获取订单列表(只取必要字段)
  61. $orders = $query->field('order_no, pay_amount, pay_method, pay_status, order_time, pay_time')
  62. ->order('order_time', 'desc')
  63. ->page($page, $pageSize)
  64. ->select()
  65. ->toArray();
  66. // 处理每个订单的商品信息
  67. $orderNos = array_column($orders, 'order_no');
  68. if (!empty($orderNos)) {
  69. // 批量查询订单商品
  70. $orderItems = \think\facade\Db::table('ba_order_item')
  71. ->where('order_id', 'IN', Db::table('ba_order')
  72. ->where('order_no', 'IN', $orderNos)
  73. ->column('id'))
  74. ->field('order_id, item_name, quantity, unit_price, total_price')
  75. ->select()
  76. ->toArray();
  77. // 按order_id分组商品
  78. $itemsByOrderId = [];
  79. foreach ($orderItems as $item) {
  80. $itemsByOrderId[$item['order_id']][] = $item;
  81. }
  82. // 获取订单ID映射
  83. $orderIdMap = \think\facade\Db::table('ba_order')
  84. ->where('order_no', 'IN', $orderNos)
  85. ->column('id', 'order_no');
  86. // 合并商品信息到订单
  87. foreach ($orders as &$order) {
  88. // 注意:现在 $orderIdMap 的键是 order_no,值是对应的 id
  89. $orderId = $orderIdMap[$order['order_no']] ?? 0;
  90. // 取第一个商品作为主商品信息(根据您的截图,一单一个商品)
  91. $mainItem = $itemsByOrderId[$orderId][0] ?? [];
  92. // 商品名称(如果有多个商品,显示第一个)
  93. $order['product_name'] = $mainItem['item_name'] ?? '商品';
  94. // 数量
  95. $order['quantity'] = $mainItem['quantity'] ?? 1;
  96. // 格式化显示字段
  97. $order['amount'] = '¥' . number_format($order['pay_amount'], 2);
  98. $order['pay_method_text'] = $this->getSimplePayMethodText($order['pay_method']);
  99. $order['pay_status_text'] = $order['pay_status'] == 1 ? '已支付' : '未支付';
  100. $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
  101. $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
  102. // 移除不需要的原始字段
  103. unset($order['pay_amount'], $order['pay_method'], $order['pay_status'],
  104. $order['order_time'], $order['pay_time']);
  105. }
  106. }
  107. // 获取简单的统计信息
  108. $stats = [
  109. 'total_orders' => $total,
  110. 'paid_orders' =>Db::table('ba_order')
  111. ->where('user_id', $userId)
  112. ->where($where)
  113. ->where('order_no', 'IN', $orderNos)
  114. ->where('pay_status', 1)
  115. ->count(),
  116. 'unpaid_orders' =>Db::table('ba_order')
  117. ->where('user_id', $userId)
  118. ->where($where)
  119. ->where('order_no', 'IN', $orderNos)
  120. ->where('pay_status', 0)
  121. ->count(),
  122. ];
  123. // } catch (\Throwable $e) {
  124. // \think\facade\Log::error('获取购买记录失败: ' . $e->getMessage());
  125. // $this->error('获取购买记录失败');
  126. // }
  127. $this->success('', [
  128. 'list' => $orders,
  129. 'total' => $total,
  130. 'page' => $page,
  131. 'page_size' => $pageSize,
  132. 'stats' => $stats
  133. ]);
  134. }
  135. /**
  136. * 简化支付方式文本
  137. */
  138. private function getSimplePayMethodText(string $method): string
  139. {
  140. $methodMap = [
  141. 'wechat' => '微信',
  142. 'alipay' => '支付宝',
  143. 'bank' => '银行卡'
  144. ];
  145. return $methodMap[$method] ?? '其他';
  146. }
  147. /**
  148. * 获取购买统计信息
  149. */
  150. private function getPurchaseStats(int $userId, string $status = 'all', string $startDate = '', string $endDate = ''): array
  151. {
  152. try {
  153. // 全部订单统计
  154. $totalQuery = \think\facade\Db::table('ba_order')
  155. ->where('user_id', $userId);
  156. // 已支付订单统计
  157. $paidQuery = \think\facade\Db::table('ba_order')
  158. ->where('user_id', $userId)
  159. ->where('pay_status', 1);
  160. // 时间范围筛选
  161. if (!empty($startDate)) {
  162. $totalQuery->where('order_time', '>=', $startDate);
  163. $paidQuery->where('order_time', '>=', $startDate);
  164. }
  165. if (!empty($endDate)) {
  166. $totalQuery->where('order_time', '<=', $endDate . ' 23:59:59');
  167. $paidQuery->where('order_time', '<=', $endDate . ' 23:59:59');
  168. }
  169. $totalCount = $totalQuery->count();
  170. $paidCount = $paidQuery->count();
  171. $unpaidCount = $totalCount - $paidCount;
  172. // 支付总金额
  173. $totalAmount = $paidQuery->sum('pay_amount');
  174. $totalAmount = $totalAmount ?: 0;
  175. // 本月统计
  176. $monthStart = date('Y-m-01');
  177. $monthPaidAmount = \think\facade\Db::table('ba_order')
  178. ->where('user_id', $userId)
  179. ->where('pay_status', 1)
  180. ->where('order_time', '>=', $monthStart)
  181. ->sum('pay_amount');
  182. $monthPaidAmount = $monthPaidAmount ?: 0;
  183. return [
  184. 'total_orders' => $totalCount,
  185. 'paid_orders' => $paidCount,
  186. 'unpaid_orders' => $unpaidCount,
  187. 'total_amount' => $totalAmount,
  188. 'month_amount' => $monthPaidAmount
  189. ];
  190. } catch (\Throwable $e) {
  191. \think\facade\Log::error('获取购买统计失败: ' . $e->getMessage());
  192. return [
  193. 'total_orders' => 0,
  194. 'paid_orders' => 0,
  195. 'unpaid_orders' => 0,
  196. 'total_amount' => 0,
  197. 'month_amount' => 0
  198. ];
  199. }
  200. }
  201. /**
  202. * 获取支付状态文本
  203. */
  204. private function getPayStatusText(int $status): string
  205. {
  206. $statusMap = [
  207. 0 => '待支付',
  208. 1 => '已支付',
  209. 2 => '支付失败'
  210. ];
  211. return $statusMap[$status] ?? '未知状态';
  212. }
  213. /**
  214. * 获取订单状态文本
  215. */
  216. private function getOrderStatusText(int $status): string
  217. {
  218. $statusMap = [
  219. 0 => '待处理',
  220. 1 => '已确认',
  221. 2 => '已发货',
  222. 3 => '已完成',
  223. 4 => '已取消'
  224. ];
  225. return $statusMap[$status] ?? '未知状态';
  226. }
  227. /**
  228. * 获取支付方式文本
  229. */
  230. private function getPayMethodText(string $method): string
  231. {
  232. $methodMap = [
  233. 'wechat' => '微信支付',
  234. 'alipay' => '支付宝',
  235. 'bank' => '银行卡',
  236. 'balance' => '余额支付'
  237. ];
  238. return $methodMap[$method] ?? '其他支付';
  239. }
  240. /**
  241. * 获取订单详情(单个订单)
  242. */
  243. public function orderDetail(): void
  244. {
  245. if (!$this->auth->isLogin()) {
  246. $this->error('请先登录');
  247. }
  248. $userId = $this->auth->id;
  249. $orderId = $this->request->get('order_id', 0);
  250. $orderNo = $this->request->get('order_no', '');
  251. if (empty($orderId) && empty($orderNo)) {
  252. $this->error('参数错误');
  253. }
  254. try {
  255. // 查询订单
  256. if ($orderId) {
  257. $order = \think\facade\Db::table('ba_order')
  258. ->where('id', $orderId)
  259. ->where('user_id', $userId) // 只能查看自己的订单
  260. ->find();
  261. } else {
  262. $order = \think\facade\Db::table('ba_order')
  263. ->where('order_no', $orderNo)
  264. ->where('user_id', $userId) // 只能查看自己的订单
  265. ->find();
  266. }
  267. if (!$order) {
  268. $this->error('订单不存在或无权查看');
  269. }
  270. // 获取订单商品项
  271. $orderItems = \think\facade\Db::table('ba_order_item')
  272. ->where('order_id', $order['id'])
  273. ->select()
  274. ->toArray();
  275. // 格式化显示数据
  276. $order['pay_status_text'] = $this->getPayStatusText($order['pay_status']);
  277. $order['order_status_text'] = $this->getOrderStatusText($order['order_status']);
  278. $order['pay_method_text'] = $this->getPayMethodText($order['pay_method']);
  279. // 格式化时间
  280. $order['order_time_formatted'] = $order['order_time'] ? date('Y-m-d H:i:s', strtotime($order['order_time'])) : '';
  281. $order['pay_time_formatted'] = $order['pay_time'] ? date('Y-m-d H:i:s', strtotime($order['pay_time'])) : '';
  282. $order['complete_time_formatted'] = $order['complete_time'] ? date('Y-m-d H:i:s', strtotime($order['complete_time'])) : '';
  283. $order['create_time_formatted'] = $order['create_time'] ? date('Y-m-d H:i:s', strtotime($order['create_time'])) : '';
  284. } catch (\Throwable $e) {
  285. \think\facade\Log::error('获取订单详情失败: ' . $e->getMessage());
  286. $this->error('获取订单详情失败');
  287. }
  288. $this->success('', [
  289. 'order' => $order,
  290. 'items' => $orderItems
  291. ]);
  292. }
  293. /**
  294. * 订单支付成功回调(处理佣金)
  295. */
  296. public function paymentCallback(): void
  297. {
  298. if (!$this->request->isPost()) {
  299. $this->error('非法请求');
  300. }
  301. $orderId = $this->request->post('order_id', 0);
  302. $orderNo = $this->request->post('order_no', '');
  303. if (empty($orderId) && empty($orderNo)) {
  304. $this->error('参数错误');
  305. }
  306. try {
  307. // 查找订单
  308. if (!empty($orderId)) {
  309. $order = \think\facade\Db::table('ba_order')
  310. ->where('id', $orderId)
  311. ->find();
  312. } else {
  313. $order = \think\facade\Db::table('ba_order')
  314. ->where('order_no', $orderNo)
  315. ->find();
  316. }
  317. if (!$order) {
  318. $this->error('订单不存在');
  319. }
  320. // 处理订单佣金
  321. $result = $this->commissionService->processOrderCommission($order['id']);
  322. if ($result) {
  323. $this->success('佣金处理成功');
  324. } else {
  325. $this->error('佣金处理失败');
  326. }
  327. } catch (\Throwable $e) {
  328. $this->error('处理失败:' . $e->getMessage());
  329. }
  330. }
  331. /**
  332. * 手动触发订单佣金处理(管理用)
  333. */
  334. public function processCommission(): void
  335. {
  336. if (!$this->auth->isLogin() || !$this->auth->isAdmin()) {
  337. $this->error('权限不足');
  338. }
  339. $orderId = $this->request->post('order_id', 0);
  340. if ($orderId <= 0) {
  341. $this->error('订单ID错误');
  342. }
  343. $result = $this->commissionService->processOrderCommission($orderId);
  344. if ($result) {
  345. $this->success('处理成功');
  346. } else {
  347. $this->error('处理失败');
  348. }
  349. }
  350. }