BalanceRecordService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace app\frontend\modules\finance\services;
  3. use app\frontend\modules\finance\models\Balance;
  4. use Illuminate\Support\Collection;
  5. class BalanceRecordService
  6. {
  7. /**
  8. * 余额记录列表,支出与收入统计
  9. * @return array
  10. */
  11. public function getRecordData()
  12. {
  13. $record_list = Balance::getMemberRecordList();
  14. if(!$record_list['data']){
  15. return false;
  16. }
  17. $date_key = $this->getDateKey($record_list['data']);
  18. $money_arr = Balance::getExpendAndIncome($date_key);
  19. $this->fillDate($record_list['data'], $date_key, "record");
  20. $this->fillDate($money_arr, $date_key, "price");
  21. $data = [
  22. 'money_arr' => $money_arr,
  23. 'record_list' => $record_list,
  24. ];
  25. return $data;
  26. }
  27. /**
  28. * 补全没有数据的月份,让他们显示为空数组
  29. * @param Collection $data
  30. * @param $date_key
  31. * @param $type price = 月收入数据的补全; record = 详细数据的补全
  32. * @return void
  33. */
  34. private function fillDate(Collection &$data, $date_key, $type)
  35. {
  36. $all_date = $this->monthRange($date_key[1], $date_key[0]);
  37. //月份差,获得缺少的月份
  38. $diff_date = array_diff($all_date, $data->keys()->all());
  39. foreach ($diff_date as $date){
  40. if($type == 'price'){
  41. $data[$date] = [
  42. "income" => 0,
  43. "expend" => 0,
  44. ];
  45. }else{
  46. $data[$date] = [];
  47. }
  48. }
  49. //根据时间倒序
  50. $data = $data->sortByDesc(function ($record, $date){
  51. return strtotime($date);
  52. });
  53. }
  54. /**
  55. * 根据开始到结束得出全部月份
  56. * @param $start
  57. * @param $end
  58. * @return array
  59. */
  60. private function monthRange($start, $end)
  61. {
  62. $start = date('Y-m',$start); // 转换为月
  63. $range = [];
  64. $i = 0;
  65. do {
  66. $month = date('Y-m', strtotime(date('Y-m',$end) . ' + ' . $i . ' month'));
  67. //echo $i . ':' . $month . '<br>';
  68. $range[] = $month;
  69. $i++;
  70. } while ($month < $start);
  71. return $range;
  72. }
  73. /**
  74. * 获取分组的第一个月和最后一个月的日期
  75. * @param $record_list
  76. * @return array|void
  77. */
  78. private function getDateKey($record_list)
  79. {
  80. $date = $record_list->keys();
  81. if($record_list->isEmpty()){
  82. return;
  83. }
  84. if($date->count() > 1){
  85. return [
  86. strtotime($date->last()),
  87. strtotime("$date[0] +1 month -1 day") + 86399,
  88. ];
  89. }else{
  90. return [
  91. strtotime("$date[0]"),
  92. strtotime("$date[0] +1 month -1 day") + 86399,
  93. ];
  94. }
  95. }
  96. }