FinancialService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. namespace App\Services\Common;
  3. use App\Models\OrderModel;
  4. use App\Models\MemberModel;
  5. use App\Models\WithdrawModel;
  6. use App\Models\AccountLogModel;
  7. use App\Services\BaseService;
  8. use Illuminate\Support\Facades\DB;
  9. /**
  10. * 财务服务
  11. */
  12. class FinancialService extends BaseService
  13. {
  14. /**
  15. * 获取数据统计
  16. * @param int $storeId 商户ID,0表示平台管理员
  17. */
  18. public function getStatistics($storeId = 0)
  19. {
  20. try {
  21. // 获取当前时间范围
  22. $today = date('Y-m-d');
  23. $todayStart = strtotime($today . ' 00:00:00');
  24. $todayEnd = strtotime($today . ' 23:59:59');
  25. $monthStart = strtotime(date('Y-m-01 00:00:00'));
  26. $monthEnd = strtotime(date('Y-m-t 23:59:59'));
  27. // 1. 订单统计(基于订单表)
  28. $orderStats = $this->getOrderStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId);
  29. // 2. 营业额统计(基于订单表的实付金额)
  30. $revenueStats = $this->getRevenueStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId);
  31. // 3. 退款统计(基于订单表的退款状态)
  32. $refundStats = $this->getRefundStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId);
  33. // 4. 结算统计(基于订单表的商家佣金)
  34. $settlementStats = $this->getSettlementStatistics($storeId);
  35. // 5. 会员统计(商户端不显示,返回0)
  36. $memberStats = $storeId > 0 ? [
  37. 'total' => 0,
  38. 'month' => 0,
  39. 'today' => 0
  40. ] : $this->getMemberStatistics($todayStart, $todayEnd, $monthStart, $monthEnd);
  41. return [
  42. 'code' => 0,
  43. 'msg' => '获取成功',
  44. 'data' => [
  45. 'order' => $orderStats,
  46. 'revenue' => $revenueStats,
  47. 'refund' => $refundStats,
  48. 'settlement' => $settlementStats,
  49. 'member' => $memberStats
  50. ]
  51. ];
  52. } catch (\Exception $e) {
  53. return [
  54. 'code' => 1,
  55. 'msg' => '获取失败:' . $e->getMessage()
  56. ];
  57. }
  58. }
  59. /**
  60. * 订单统计(基于订单表)
  61. * @param int $storeId 商户ID,0表示平台管理员
  62. */
  63. private function getOrderStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId = 0)
  64. {
  65. $orderModel = new OrderModel();
  66. // 总订单数
  67. $total = $orderModel->where('mark', 1)
  68. ->when($storeId > 0, function ($query) use ($storeId) {
  69. return $query->where('store_id', $storeId);
  70. })
  71. ->count();
  72. // 月订单数
  73. $month = $orderModel->where('mark', 1)
  74. ->when($storeId > 0, function ($query) use ($storeId) {
  75. return $query->where('store_id', $storeId);
  76. })
  77. ->whereBetween('create_time', [$monthStart, $monthEnd])
  78. ->count();
  79. // 当日订单数
  80. $today = $orderModel->where('mark', 1)
  81. ->when($storeId > 0, function ($query) use ($storeId) {
  82. return $query->where('store_id', $storeId);
  83. })
  84. ->whereBetween('create_time', [$todayStart, $todayEnd])
  85. ->count();
  86. return [
  87. 'total' => $total,
  88. 'month' => $month,
  89. 'today' => $today
  90. ];
  91. }
  92. /**
  93. * 营业额统计(基于订单表的实付金额pay_total)
  94. * @param int $storeId 商户ID,0表示平台管理员
  95. */
  96. private function getRevenueStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId = 0)
  97. {
  98. $orderModel = new OrderModel();
  99. // 总营业额(已完成订单的实付金额)
  100. $total = $orderModel->where('mark', 1)
  101. ->where('status', 4) // 4-确认收货(已完成)
  102. ->when($storeId > 0, function ($query) use ($storeId) {
  103. return $query->where('store_id', $storeId);
  104. })
  105. ->sum('pay_total');
  106. // 月营业额
  107. $month = $orderModel->where('mark', 1)
  108. ->where('status', 4)
  109. ->when($storeId > 0, function ($query) use ($storeId) {
  110. return $query->where('store_id', $storeId);
  111. })
  112. ->whereBetween('create_time', [$monthStart, $monthEnd])
  113. ->sum('pay_total');
  114. // 当日营业额
  115. $today = $orderModel->where('mark', 1)
  116. ->where('status', 4)
  117. ->when($storeId > 0, function ($query) use ($storeId) {
  118. return $query->where('store_id', $storeId);
  119. })
  120. ->whereBetween('create_time', [$todayStart, $todayEnd])
  121. ->sum('pay_total');
  122. return [
  123. 'total' => number_format($total, 2, '.', ''),
  124. 'month' => number_format($month, 2, '.', ''),
  125. 'today' => number_format($today, 2, '.', '')
  126. ];
  127. }
  128. /**
  129. * 退款统计(基于订单表的退款状态refund_status=1)
  130. * @param int $storeId 商户ID,0表示平台管理员
  131. */
  132. private function getRefundStatistics($todayStart, $todayEnd, $monthStart, $monthEnd, $storeId = 0)
  133. {
  134. $orderModel = new OrderModel();
  135. // 总退款订单数和金额(refund_status=1表示已退款)
  136. $totalRefund = $orderModel->where('mark', 1)
  137. ->where('refund_status', 1) // 1-已退款
  138. ->when($storeId > 0, function ($query) use ($storeId) {
  139. return $query->where('store_id', $storeId);
  140. })
  141. ->selectRaw('COUNT(*) as count, SUM(pay_total) as amount')
  142. ->first();
  143. // 月退款订单数和金额
  144. $monthRefund = $orderModel->where('mark', 1)
  145. ->where('refund_status', 1)
  146. ->when($storeId > 0, function ($query) use ($storeId) {
  147. return $query->where('store_id', $storeId);
  148. })
  149. ->whereBetween('create_time', [$monthStart, $monthEnd])
  150. ->selectRaw('COUNT(*) as count, SUM(pay_total) as amount')
  151. ->first();
  152. // 当日退款订单数和金额
  153. $todayRefund = $orderModel->where('mark', 1)
  154. ->where('refund_status', 1)
  155. ->when($storeId > 0, function ($query) use ($storeId) {
  156. return $query->where('store_id', $storeId);
  157. })
  158. ->whereBetween('create_time', [$todayStart, $todayEnd])
  159. ->selectRaw('COUNT(*) as count, SUM(pay_total) as amount')
  160. ->first();
  161. return [
  162. 'total_count' => $totalRefund->count ?? 0,
  163. 'total_amount' => number_format($totalRefund->amount ?? 0, 2, '.', ''),
  164. 'month_count' => $monthRefund->count ?? 0,
  165. 'month_amount' => number_format($monthRefund->amount ?? 0, 2, '.', ''),
  166. 'today_count' => $todayRefund->count ?? 0,
  167. 'today_amount' => number_format($todayRefund->amount ?? 0, 2, '.', '')
  168. ];
  169. }
  170. /**
  171. * 结算统计(基于订单表的商家佣金bonus字段)
  172. * @param int $storeId 商户ID,0表示平台管理员
  173. */
  174. private function getSettlementStatistics($storeId = 0)
  175. {
  176. $orderModel = new OrderModel();
  177. // 已结算金额总数(已完成订单的商家佣金)
  178. $total = $orderModel->where('mark', 1)
  179. ->where('status', 4) // 4-确认收货(已完成)
  180. ->when($storeId > 0, function ($query) use ($storeId) {
  181. return $query->where('store_id', $storeId);
  182. })
  183. ->sum('bonus');
  184. return [
  185. 'total' => number_format($total, 2, '.', '')
  186. ];
  187. }
  188. /**
  189. * 会员统计
  190. */
  191. private function getMemberStatistics($todayStart, $todayEnd, $monthStart, $monthEnd)
  192. {
  193. $memberModel = new MemberModel();
  194. // 总会员数
  195. $total = $memberModel->where('mark', 1)->count();
  196. // 月新增会员
  197. $month = $memberModel->where('mark', 1)
  198. ->whereBetween('create_time', [$monthStart, $monthEnd])
  199. ->count();
  200. // 当日新增会员
  201. $today = $memberModel->where('mark', 1)
  202. ->whereBetween('create_time', [$todayStart, $todayEnd])
  203. ->count();
  204. return [
  205. 'total' => $total,
  206. 'month' => $month,
  207. 'today' => $today
  208. ];
  209. }
  210. /**
  211. * 获取统计列表(按年月日分组)
  212. */
  213. public function getStatisticsList($params)
  214. {
  215. $type = $params['type'] ?? 'order';
  216. $groupBy = $params['group_by'] ?? 'day';
  217. $startDate = $params['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
  218. $endDate = $params['end_date'] ?? date('Y-m-d');
  219. $page = $params['page'] ?? 1;
  220. $limit = $params['limit'] ?? 20;
  221. $storeId = $params['store_id'] ?? 0; // 商户ID,0表示平台管理员
  222. $startTime = strtotime($startDate . ' 00:00:00');
  223. $endTime = strtotime($endDate . ' 23:59:59');
  224. try {
  225. switch ($type) {
  226. case 'order':
  227. return $this->getOrderList($groupBy, $startTime, $endTime, $page, $limit, $storeId);
  228. case 'revenue':
  229. return $this->getRevenueList($groupBy, $startTime, $endTime, $page, $limit, $storeId);
  230. case 'refund':
  231. return $this->getRefundList($groupBy, $startTime, $endTime, $page, $limit, $storeId);
  232. case 'settlement':
  233. return $this->getSettlementList($groupBy, $startTime, $endTime, $page, $limit, $storeId);
  234. case 'member':
  235. return $this->getMemberList($groupBy, $startTime, $endTime, $page, $limit, $storeId);
  236. default:
  237. return ['code' => 1, 'msg' => '未知的统计类型'];
  238. }
  239. } catch (\Exception $e) {
  240. return ['code' => 1, 'msg' => '查询失败:' . $e->getMessage()];
  241. }
  242. }
  243. /**
  244. * 订单统计列表
  245. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  246. */
  247. private function getOrderList($groupBy, $startTime, $endTime, $page, $limit, $storeId = 0)
  248. {
  249. $dateFormat = $this->getDateFormat($groupBy);
  250. $query = OrderModel::where('mark', 1)
  251. ->when($storeId > 0, function ($query) use ($storeId) {
  252. return $query->where('store_id', $storeId);
  253. })
  254. ->whereBetween('create_time', [$startTime, $endTime])
  255. ->selectRaw("FROM_UNIXTIME(create_time, '{$dateFormat}') as date, COUNT(*) as count")
  256. ->groupBy('date')
  257. ->orderBy('date', 'desc');
  258. $total = $query->get()->count();
  259. $data = $query->offset(($page - 1) * $limit)->limit($limit)->get()->toArray();
  260. return [
  261. 'code' => 0,
  262. 'msg' => '获取成功',
  263. 'data' => $data,
  264. 'count' => $total
  265. ];
  266. }
  267. /**
  268. * 营业额统计列表(基于订单表的实付金额pay_total)
  269. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  270. */
  271. private function getRevenueList($groupBy, $startTime, $endTime, $page, $limit, $storeId = 0)
  272. {
  273. $dateFormat = $this->getDateFormat($groupBy);
  274. $query = OrderModel::where('mark', 1)
  275. ->where('status', 4) // 4-确认收货(已完成)
  276. ->when($storeId > 0, function ($query) use ($storeId) {
  277. return $query->where('store_id', $storeId);
  278. })
  279. ->whereBetween('create_time', [$startTime, $endTime])
  280. ->selectRaw("FROM_UNIXTIME(create_time, '{$dateFormat}') as date, SUM(pay_total) as amount")
  281. ->groupBy('date')
  282. ->orderBy('date', 'desc');
  283. $allResults = $query->get();
  284. $total = $allResults->count();
  285. $list = $allResults->slice(($page - 1) * $limit, $limit)->values()->toArray();
  286. foreach ($list as &$item) {
  287. $item['amount'] = number_format($item['amount'], 2, '.', '');
  288. }
  289. return [
  290. 'code' => 0,
  291. 'msg' => '获取成功',
  292. 'data' => $list,
  293. 'count' => $total
  294. ];
  295. }
  296. /**
  297. * 退款统计列表(基于订单表的退款状态refund_status=1)
  298. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  299. */
  300. private function getRefundList($groupBy, $startTime, $endTime, $page, $limit, $storeId = 0)
  301. {
  302. $dateFormat = $this->getDateFormat($groupBy);
  303. $query = OrderModel::where('mark', 1)
  304. ->where('refund_status', 1) // 1-已退款
  305. ->when($storeId > 0, function ($query) use ($storeId) {
  306. return $query->where('store_id', $storeId);
  307. })
  308. ->whereBetween('create_time', [$startTime, $endTime])
  309. ->selectRaw("FROM_UNIXTIME(create_time, '{$dateFormat}') as date, COUNT(*) as count, SUM(pay_total) as amount")
  310. ->groupBy('date')
  311. ->orderBy('date', 'desc');
  312. $allResults = $query->get();
  313. $total = $allResults->count();
  314. $list = $allResults->slice(($page - 1) * $limit, $limit)->values()->toArray();
  315. foreach ($list as &$item) {
  316. $item['amount'] = number_format($item['amount'], 2, '.', '');
  317. }
  318. return [
  319. 'code' => 0,
  320. 'msg' => '获取成功',
  321. 'data' => $list,
  322. 'count' => $total
  323. ];
  324. }
  325. /**
  326. * 结算统计列表(基于订单表的商家佣金bonus字段)
  327. * @param int $storeId 商户ID,0表示平台管理员查看全部数据
  328. */
  329. private function getSettlementList($groupBy, $startTime, $endTime, $page, $limit, $storeId = 0)
  330. {
  331. $dateFormat = $this->getDateFormat($groupBy);
  332. $query = OrderModel::where('mark', 1)
  333. ->where('status', 4) // 4-确认收货(已完成)
  334. ->when($storeId > 0, function ($query) use ($storeId) {
  335. return $query->where('store_id', $storeId);
  336. })
  337. ->whereBetween('create_time', [$startTime, $endTime])
  338. ->selectRaw("FROM_UNIXTIME(create_time, '{$dateFormat}') as date, SUM(bonus) as amount")
  339. ->groupBy('date')
  340. ->orderBy('date', 'desc');
  341. $allResults = $query->get();
  342. $total = $allResults->count();
  343. $list = $allResults->slice(($page - 1) * $limit, $limit)->values()->toArray();
  344. foreach ($list as &$item) {
  345. $item['amount'] = number_format($item['amount'], 2, '.', '');
  346. }
  347. return [
  348. 'code' => 0,
  349. 'msg' => '获取成功',
  350. 'data' => $list,
  351. 'count' => $total
  352. ];
  353. }
  354. /**
  355. * 会员统计列表
  356. * @param int $storeId 商户ID,0表示平台管理员查看全部数据(会员数据商户端不显示)
  357. */
  358. private function getMemberList($groupBy, $startTime, $endTime, $page, $limit, $storeId = 0)
  359. {
  360. // 商户端不显示会员数据
  361. if ($storeId > 0) {
  362. return [
  363. 'code' => 0,
  364. 'msg' => '获取成功',
  365. 'data' => [],
  366. 'count' => 0
  367. ];
  368. }
  369. $dateFormat = $this->getDateFormat($groupBy);
  370. $query = MemberModel::where('mark', 1)
  371. ->whereBetween('create_time', [$startTime, $endTime])
  372. ->selectRaw("FROM_UNIXTIME(create_time, '{$dateFormat}') as date, COUNT(*) as count")
  373. ->groupBy('date')
  374. ->orderBy('date', 'desc');
  375. $allResults = $query->get();
  376. $total = $allResults->count();
  377. $data = $allResults->slice(($page - 1) * $limit, $limit)->values()->toArray();
  378. return [
  379. 'code' => 0,
  380. 'msg' => '获取成功',
  381. 'data' => $data,
  382. 'count' => $total
  383. ];
  384. }
  385. /**
  386. * 获取日期格式
  387. */
  388. private function getDateFormat($groupBy)
  389. {
  390. switch ($groupBy) {
  391. case 'year':
  392. return '%Y';
  393. case 'month':
  394. return '%Y-%m';
  395. case 'day':
  396. default:
  397. return '%Y-%m-%d';
  398. }
  399. }
  400. }