StatisticsService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. <?php
  2. namespace App\Service;
  3. use App\Model\EmployeeIndex;
  4. use App\Model\FreightFee;
  5. use App\Model\GiveOut;
  6. use App\Model\RevenueCost;
  7. use App\Model\RevenueCostTotal;
  8. use App\Model\SalaryEmployee;
  9. use Illuminate\Support\Facades\DB;
  10. class StatisticsService extends Service
  11. {
  12. public function statisticsRevenueCostCommon($data,$user, $field = []){
  13. if(empty($field)) $field = RevenueCostTotal::$field;
  14. $model = RevenueCostTotal::Clear($user,$data);
  15. $model = $model->where('del_time',0)
  16. ->select($field)
  17. ->orderby('id', 'desc');
  18. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  19. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  20. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  21. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  22. $model->where('order_time', '>=', $start_time)
  23. ->where('order_time', '<', $end_time);
  24. }
  25. if(! empty($data['order_type'])) $model->where('order_type',$data['order_type']);
  26. return [true, $model];
  27. }
  28. public function statisticsRevenueCost($data,$user){
  29. list($status, $model) = $this->statisticsRevenueCostCommon($data, $user);
  30. if(! $status) return [false, $model];
  31. $list = $this->limit($model,'',$data);
  32. $list = $this->statisticsRevenueCostFillData($list);
  33. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  34. return [true, $list];
  35. }
  36. public function statisticsRevenueCostFillData($data){
  37. if(empty($data['data'])) return $data;
  38. foreach ($data['data'] as $key => $value){
  39. $time = date("Y-m", $value['order_time']);
  40. $data['data'][$key]['order_time'] = $time;
  41. $data['data'][$key]['order_type_title'] = RevenueCost::$order_type[$value['order_type']] ?? "";
  42. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  43. }
  44. return $data;
  45. }
  46. public function statisticsRevenueCostOneAndTwoCommon($data,$user, $field = []){
  47. if(empty($data['order_type']) || ! isset(RevenueCost::$order_type[$data['order_type']])) return [false, '单据类型不存在或错误'];
  48. if(empty($field)) {
  49. if($data['order_type'] == 1){
  50. $field = RevenueCost::$field_xhd;
  51. }else{
  52. $field = RevenueCost::$field_xsfp;
  53. }
  54. }
  55. $model = RevenueCost::Clear($user,$data);
  56. $model = $model->where('del_time',0)
  57. ->where('order_type',$data['order_type'])
  58. ->select($field)
  59. ->orderby('id', 'desc');
  60. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  61. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  62. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  63. $model->where('order_time', '>=', $start_time)
  64. ->where('order_time', '<=', $end_time);
  65. }
  66. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  67. if(! empty($data['customer_title'])) $model->where('customer_title', 'LIKE', '%'.$data['customer_title'].'%');
  68. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  69. return [true, $model];
  70. }
  71. public function statisticsRevenueCostOneAndTwo($data,$user){
  72. list($status, $model) = $this->statisticsRevenueCostOneAndTwoCommon($data, $user);
  73. if(! $status) return [false, $model];
  74. $list = $this->limit($model,'',$data);
  75. $list = $this->statisticsRevenueCostOneAndTwoFillData($list);
  76. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  77. return [true, $list];
  78. }
  79. public function statisticsRevenueCostOneAndTwoFillData($data){
  80. if(empty($data['data'])) return $data;
  81. foreach ($data['data'] as $key => $value){
  82. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  83. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  84. }
  85. return $data;
  86. }
  87. public function statisticsRevenueCostThreeCommon($data,$user, $field = []){
  88. if(empty($field)) {
  89. $field = RevenueCost::$field_hkd_salary_main;
  90. $field[] = DB::raw('sum(payment_amount) as payment_amount');
  91. $field[] = DB::raw('sum(price_4_total) as price_4_total');
  92. $field[] = DB::raw('sum(profit) as profit');
  93. $field[] = DB::raw('max(employee_id_2) as employee_id_2');
  94. $field[] = DB::raw("MAX(COALESCE(employee_id_2_title, '')) as employee_id_2_title");
  95. }
  96. $model = RevenueCost::Clear($user,$data);
  97. $model = $model->where('del_time',0)
  98. ->where('order_type',RevenueCost::ORDER_THREE)
  99. ->select($field)
  100. ->groupby('order_id')
  101. ->orderby('id', 'desc');
  102. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  103. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  104. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  105. $model->where('order_time', '>=', $start_time)
  106. ->where('order_time', '<=', $end_time);
  107. }
  108. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  109. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  110. if(! empty($data['employee_id_1'])) $model->where('employee_id_1', 'LIKE', $data['employee_id_1']);
  111. if(! empty($data['employee_id_2'])) $model->where('employee_id_2', 'LIKE', $data['employee_id_2']);
  112. if(! empty($data['employee_id_2_title'])) $model->where('employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  113. if(! empty($data['channel_finance_array'])) {
  114. $array = explode("\n", str_replace(["\r\n", "\r"], "\n", $data['channel_finance_array']));
  115. $model->whereIn('channel_finance', $array);
  116. }
  117. return [true, $model];
  118. }
  119. public function statisticsRevenueCostThree($data,$user){
  120. list($status, $model) = $this->statisticsRevenueCostThreeCommon($data, $user);
  121. if(! $status) return [false, $model];
  122. $list = $this->limit($model,'',$data);
  123. $list = $this->statisticsRevenueCostThreeFillData($list);
  124. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  125. return [true, $list];
  126. }
  127. public function statisticsRevenueCostThreeFillData($data){
  128. if(empty($data['data'])) return $data;
  129. foreach ($data['data'] as $key => $value){
  130. $profit_rate = $value['payment_amount'] > 0 ? bcdiv($value['profit'], $value['payment_amount'],2) : 0;
  131. $data['data'][$key]['profit_rate'] = bcmul($profit_rate, 100,2);
  132. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  133. }
  134. return $data;
  135. }
  136. public function statisticsRevenueCostThreeDetail($data,$user){
  137. if(empty($data['order_number'])) return [false, '回款单号不能为空'];
  138. $result = RevenueCost::where('del_time',0)
  139. ->where('order_type',RevenueCost::ORDER_THREE)
  140. ->where('order_number',$data['order_number'])
  141. ->select(RevenueCost::$field_hkd_detail)
  142. ->get()->toArray();
  143. if(empty($result)) return [false, "回款单不存在或已被删除"];
  144. $detail = [];
  145. foreach ($result as $value){
  146. $detail[] = [
  147. 'order_number' => $value['order_number_upstream'],
  148. 'customer_code' => $value['customer_code'],
  149. 'customer_title' => $value['customer_title'],
  150. 'channel_finance' => $value['channel_finance'],
  151. 'product_code' => $value['product_code'],
  152. 'product_title' => $value['product_title'],
  153. 'product_size' => $value['product_size'],
  154. 'unit' => $value['unit'],
  155. 'quantity' => $value['quantity'],
  156. 'payment_amount' => $value['payment_amount'],
  157. 'price_1' => $value['price_1'],
  158. 'price_1_total' => $value['price_1_total'],
  159. 'price_4' => $value['price_4'],
  160. 'price_4_total' => $value['price_4_total'],
  161. 'profit' => $value['profit'],
  162. 'profit_rate' => bcmul($value['profit_rate'],100,2) . '%',
  163. 'customer_profit_rate' => bcmul($value['customer_profit_rate'],100,2) . '%',
  164. 'voucher_type_title' => RevenueCost::$voucher_type[$value['voucher_type']] ?? "",
  165. ];
  166. }
  167. $first = $result[0];
  168. $order = [
  169. 'order_number' => $data['order_number'],
  170. 'order_time' => date("Y-m-d",$first['order_time']),
  171. 'employee_id_1_title' => $first['employee_id_1_title'],
  172. 'detail' => $detail
  173. ];
  174. return [true, $order];
  175. }
  176. public function statisticsProfitCommon($data,$user, $field = []){
  177. if(empty($field)) {
  178. $field = RevenueCost::$field_hkd_profit_main;
  179. $field[] = DB::raw('COALESCE(SUM(rc.payment_amount), 0) AS payment_amount');
  180. }
  181. $type = RevenueCost::ORDER_THREE;
  182. $model = EmployeeIndex::Clear($user, $data)
  183. ->where('employee_index.del_time', 0)
  184. ->where('employee_index.type', EmployeeIndex::TYPE_THREE)
  185. ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  186. $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  187. ->where('rc.del_time', 0)
  188. ->where('rc.order_type', $type)
  189. ->whereNotNull('rc.employee_id_2')
  190. ->where('rc.employee_id_2', '<>', '')
  191. ->whereRaw('rc.order_time >= employee_index.start_time')
  192. ->whereRaw('rc.order_time <= employee_index.end_time');
  193. })
  194. ->select($field)
  195. ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  196. ->orderBy('employee_index.end_time', 'desc');
  197. // $type = RevenueCost::ORDER_THREE;
  198. // $model = EmployeeIndex::where('employee_index.del_time',0)
  199. // ->where('employee_index.type',EmployeeIndex::TYPE_THREE)
  200. // ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  201. // $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  202. // ->where('rc.del_time', 0)
  203. // ->where('rc.order_type', $type)
  204. // ->whereRaw('rc.order_time >= employee_index.start_time')
  205. // ->whereRaw('rc.order_time <= employee_index.end_time');
  206. // })
  207. // ->select($field)
  208. // ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  209. // ->orderBy('employee_index.end_time','desc');
  210. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){;
  211. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  212. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  213. $model->where('employee_index.start_time', '<=', $end_time)
  214. ->where('employee_index.end_time', '>=', $start_time);
  215. }
  216. if(! empty($data['employee_id_2_title'])) $model->where('rc.employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  217. return [true, $model];
  218. }
  219. public function statisticsProfit($data,$user){
  220. list($status, $model) = $this->statisticsProfitCommon($data, $user);
  221. if(! $status) return [false, $model];
  222. $list = $this->limit($model,'',$data);
  223. $list = $this->statisticsProfitFillData($list);
  224. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  225. return [true, $list];
  226. }
  227. public function statisticsProfitFillData($data){
  228. if(empty($data['data'])) return $data;
  229. //获取应发放金额需要的指标
  230. $indexes = $this->getEmployeeIndex($data['data']);
  231. //已发
  232. $indexes_give = $this->getEmployeeGiveOut($data['data']);
  233. foreach ($data['data'] as $key => $value){
  234. $start = $value['start_time'] ? date('Y-m-d',$value['start_time']) : '';
  235. $end = $value['end_time'] ? date('Y-m-d',$value['end_time']) : '';
  236. $string = "";
  237. if(! empty($start) && ! empty($end)) $string = $start . "-" . $end;
  238. $value['check_time'] = $string;
  239. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  240. $value['index_' . EmployeeIndex::TYPE_FIVE] = 0;
  241. //指标
  242. $this->makeIndex($indexes, $value, $data['data'][$key]);
  243. //应付
  244. $this->makeShouldPay($value,$data['data'][$key]);
  245. //已付
  246. $this->makePayed($indexes_give, $value,$data['data'][$key]);
  247. //未付
  248. $not_pay = bcsub($data['data'][$key]['should_pay'], $data['data'][$key]['payed'],2);
  249. $data['data'][$key]['not_pay'] = $not_pay;
  250. }
  251. return $data;
  252. }
  253. private function getEmployeeIndex($existingData)
  254. {
  255. if (empty($existingData)) {
  256. return collect();
  257. }
  258. // 取出所有涉及的 employee_id 和时间区间
  259. $employeeIds = array_column($existingData, 'employee_id_2');
  260. $start_time = array_column($existingData, 'start_time');
  261. $minStart = ! empty($start_time) ? min($start_time) : 0;
  262. $end_time = array_column($existingData, 'end_time');
  263. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  264. // 一次性查出这些员工在最大区间范围内的所有指标
  265. $results = EmployeeIndex::where('del_time', 0)
  266. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_FIVE])
  267. ->whereIn('employee_id', $employeeIds)
  268. ->where('start_time', '<=', $maxEnd)
  269. ->where('end_time', '>=', $minStart)
  270. ->select('start_time','end_time','employee_id','index','type')
  271. ->get();
  272. return $results;
  273. }
  274. private function getEmployeeGiveOut($existingData)
  275. {
  276. if (empty($existingData)) {
  277. return collect();
  278. }
  279. // 取出所有涉及的 employee_id 和时间区间
  280. $employeeIds = array_column($existingData, 'employee_id_2');
  281. $start_time = array_column($existingData, 'start_time');
  282. $minStart = ! empty($start_time) ? min($start_time) : 0;
  283. $end_time = array_column($existingData, 'end_time');
  284. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  285. // 一次性查出这些员工在最大区间范围内的所有指标
  286. $results = GiveOut::where('del_time', 0)
  287. ->whereIn('employee_id_1', $employeeIds)
  288. ->where('start_time', '<=', $maxEnd)
  289. ->where('end_time', '>=', $minStart)
  290. ->select('start_time','end_time','employee_id_1 as employee_id','give_out_amount')
  291. ->get();
  292. return $results;
  293. }
  294. private function makeIndex($indexes, $value, &$data){
  295. // 找到所有符合条件的 index(可能多个 type)
  296. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  297. return $item['employee_id'] == $value['employee_id_2']
  298. && $item['start_time'] <= $value['end_time']
  299. && $item['end_time'] >= $value['start_time'];
  300. });
  301. // 按 type 去重,只保留第一次出现的
  302. $uniqueByType = [];
  303. foreach ($matchedIndexes as $item) {
  304. $index = "index_" . $item['type'];
  305. if (! isset($uniqueByType[$index])) {
  306. $uniqueByType[$index] = $item['index'];
  307. }
  308. }
  309. $data = array_merge($value, $uniqueByType);
  310. }
  311. private function makeShouldPay($value, &$data){
  312. $index_1 = bcdiv($data['index_1'],100,2);
  313. $index_5 = bcdiv($data['index_5'],100,2);
  314. // 分红比例/2
  315. $a = bcdiv($index_5,2,2);
  316. // 季度预支分红比例/2
  317. $b = bcdiv($index_1,2,2);
  318. //(分红比例/2-季度预支分红比例/2)
  319. $c = bcsub($a, $b,2);
  320. $data['part_left'] = $c;
  321. if($value['payment_amount'] < $value['index']){
  322. //回款金额*(分红比例/2-季度预支分红比例/2);
  323. $shouldPay = bcmul($value['payment_amount'], $c,2);
  324. }else{
  325. //回款金额-季度指标金额
  326. $d = bcsub($value['payment_amount'], $value['index'],2);
  327. //(回款金额-季度指标金额)*15%
  328. $e = bcmul($d, 0.15,2);
  329. //(回款金额-季度指标金额)*15%/2
  330. $e = bcdiv($e,2,2);
  331. //(分红比例/2-季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  332. $rate = bcadd($c, $e,2);
  333. // $data['data'][$key]['rate'] = $rate;
  334. //回款金额*(分红比例/2-回款金额*季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  335. $shouldPay = bcmul($value['payment_amount'], $rate,2);
  336. }
  337. $data['should_pay'] = $shouldPay;
  338. }
  339. private function makePayed($indexes, $value, &$data){
  340. $matchedIndexes_give = $indexes->filter(function ($item) use ($value) {
  341. return $item['employee_id'] == $value['employee_id_2']
  342. && $item['start_time'] <= $value['end_time']
  343. && $item['end_time'] >= $value['start_time'];
  344. });
  345. $give_out = 0;
  346. foreach ($matchedIndexes_give as $item) {
  347. $give_out = bcadd($item['give_out_amount'], $give_out,2);
  348. }
  349. $data['payed'] = $give_out;
  350. }
  351. public function statisticsEmployeeSalaryCommon($data,$user, $field = []){
  352. if(empty($field)) {
  353. $field = SalaryEmployee::$field;
  354. }
  355. $model = SalaryEmployee::Clear($user,$data);
  356. $model = $model->where('del_time',0)
  357. ->where('order_type',RevenueCost::ORDER_THREE)
  358. ->select($field)
  359. ->orderby('order_time', 'desc');
  360. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  361. $start_time = strtotime($data['order_time'][0] . "-01");
  362. $end_time = strtotime($data['order_time'][1] . "-01");
  363. $model->where('order_time', '>=', $start_time)
  364. ->where('order_time', '<=', $end_time);
  365. }
  366. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  367. return [true, $model];
  368. }
  369. public function statisticsEmployeeSalary($data,$user){
  370. list($status, $model) = $this->statisticsEmployeeSalaryCommon($data, $user);
  371. if(! $status) return [false, $model];
  372. $list = $this->limit($model,'',$data);
  373. $list = $this->statisticsEmployeeSalaryFillData($list);
  374. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  375. return [true, $list];
  376. }
  377. public function statisticsEmployeeSalaryFillData($data){
  378. if(empty($data['data'])) return $data;
  379. foreach ($data['data'] as $key => $value){
  380. $order_time = $value['order_time'] ? date('Y-m',$value['order_time']) : '';
  381. $data['data'][$key]['order_time'] = $order_time;
  382. }
  383. return $data;
  384. }
  385. public function statisticsFreightFeeCommon($data,$user, $field = []){
  386. if(empty($field)) {
  387. $field = FreightFee::$field;
  388. $field[] = DB::raw('GROUP_CONCAT(id) as result');
  389. }
  390. $model = FreightFee::Clear($user,$data);
  391. $model = $model->where('del_time',0)
  392. ->select($field)
  393. ->groupby('order_time')
  394. ->orderby('order_time', 'desc');
  395. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  396. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  397. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  398. $model->where('order_time', '>=', $start_time)
  399. ->where('order_time', '<=', $end_time);
  400. }
  401. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  402. return [true, $model];
  403. }
  404. public function statisticsFreightFee($data,$user){
  405. list($status, $model) = $this->statisticsFreightFeeCommon($data, $user);
  406. if(! $status) return [false, $model];
  407. $list = $this->limit($model,'',$data);
  408. $list = $this->statisticsFreightFeeFillData($list);
  409. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  410. return [true, $list];
  411. }
  412. public function statisticsFreightFeeFillData($data){
  413. if(empty($data['data'])) return $data;
  414. $id = implode(',', array_column($data['data'], 'result'));
  415. $idArr = explode(',', $id);
  416. $allFees = FreightFee::where('del_time', 0)
  417. ->whereIn('id', $idArr)
  418. ->get()
  419. ->toArray();
  420. $feesByDay = [];
  421. foreach ($allFees as $f) {
  422. $feesByDay[$f['order_time']][] = $f;
  423. }
  424. foreach ($data['data'] as $key => $value) {
  425. $fees = $feesByDay[$value['order_time']] ?? [];
  426. if (empty($fees)) {
  427. $data['data'][$key]['total_amount'] = 0;
  428. continue;
  429. }
  430. // 准备 time_amount(和详情逻辑一致)
  431. $time_amount = [];
  432. foreach ($fees as $f) {
  433. if ($f['business_type_id'] == FreightFee::businessTypeNormal) {
  434. $k = $f['order_time'] . $f['area_hs'];
  435. $time_amount[$k]['amount'] = isset($time_amount[$k]['amount'])
  436. ? bcadd($f['freight_amount'], $time_amount[$k]['amount'], 2)
  437. : $f['freight_amount'];
  438. $time_amount[$k]['is_use'] = $time_amount[$k]['is_use'] ?? 0;
  439. }
  440. }
  441. // 逐条算金额
  442. $valueTotal = 0;
  443. foreach ($fees as $f) {
  444. $f = $this->calculateFreightFeeRow($f, $time_amount);
  445. $valueTotal = bcadd($valueTotal, $f['total_amount'], 2);
  446. }
  447. $data['data'][$key]['total_amount'] = $valueTotal;
  448. $order_time = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  449. $data['data'][$key]['order_time_show'] = $order_time;
  450. unset($data['data'][$key]['result']);
  451. }
  452. return $data;
  453. }
  454. // public function statisticsFreightFeeDetail($data, $user){
  455. // if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  456. //
  457. // $fee = FreightFee::where('del_time',0)
  458. // ->where('order_time', $data['order_time'])
  459. // ->get()->toArray();
  460. // if(empty($fee)) return [false, '单据日期下暂无数据'];
  461. //
  462. // //同一天 同一个地区 非退货的配送费总金额
  463. // $time_amount = [];
  464. // foreach ($fee as $value){
  465. // if($value['business_type_id'] == FreightFee::businessTypeNormal){
  466. // $key = $value['order_time'] . $value['area_hs'];
  467. // if(isset($time_amount[$key])){
  468. // $freight_amount = bcadd($value['freight_amount'], $time_amount[$key]['amount'],2);
  469. // $time_amount[$key]['amount'] = $freight_amount;
  470. // }else{
  471. // $time_amount[$key] = [
  472. // 'is_use' => 0,
  473. // 'amount' => $value['freight_amount'],
  474. // ];
  475. // }
  476. // }
  477. // }
  478. //
  479. // $return = [];
  480. // foreach ($fee as $value){
  481. // //结算金额
  482. // $js_amount = 0;
  483. // $key = $value['order_time'] . $value['area_hs'];
  484. // if($value['business_type_id'] == FreightFee::businessTypeNormal){
  485. // $tmp_total_arr = $time_amount[$key];
  486. // if($tmp_total_arr['amount'] < $value['min_freight_amount']){
  487. // if(! $time_amount[$key]['is_use']){
  488. // $js_amount = $value['min_freight_amount'];
  489. // $time_amount[$key]['is_use'] = 1;
  490. // }
  491. // }else{
  492. // $js_amount = $value['js_single_amount'];
  493. // }
  494. // $value['js_amount'] = $js_amount;
  495. // //加急费
  496. // $jj_fee = 0;
  497. // if($value['delivery_mode'] == FreightFee::deliveryModeRightNow) $jj_fee = bcmul($js_amount, 0.5,2);
  498. // $value['jj_fee'] = $jj_fee;
  499. // //总金额
  500. // $total_amount = bcadd($js_amount,$value['customer_store_zx_fee'],2);
  501. // $total_amount = bcadd($total_amount,$value['sl_fee'],2);
  502. // $total_amount = bcadd($total_amount,$jj_fee,2);
  503. // $total_amount = bcadd($total_amount,$value['dh_fee'],2);
  504. // $value['total_amount'] = $total_amount;
  505. // $return[FreightFee::businessTypeNormal][$key][] = $value;
  506. // }else{
  507. // $js_amount = $value['js_single_amount'];
  508. // $value['js_amount'] = $js_amount;
  509. // $jj_fee = 0;
  510. // if($value['delivery_mode'] == FreightFee::deliveryModeRightNow) $jj_fee = bcmul($js_amount, 0.5,2);
  511. // //加急费
  512. // $value['jj_fee'] = $jj_fee;
  513. // //总金额
  514. // $total_amount = bcadd($js_amount,$value['customer_store_zx_fee'],2);
  515. // $total_amount = bcadd($total_amount,$value['sl_fee'],2);
  516. // $total_amount = bcadd($total_amount,$jj_fee,2);
  517. // $total_amount = bcadd($total_amount,$value['dh_fee'],2);
  518. // $value['total_amount'] = $total_amount;
  519. // $return[FreightFee::businessTypeReturn][$key][] = $value;
  520. // }
  521. // }
  522. //
  523. // $result = [];
  524. // foreach ($return as $value){
  525. // foreach (array_values($value) as $val){
  526. // $result[] = $val;
  527. // }
  528. // }
  529. // dd($result);
  530. // }
  531. public function statisticsFreightFeeDetail($data, $user)
  532. {
  533. if (empty($data['order_time'])) {
  534. return [false, '单据日期不能为空'];
  535. }
  536. $model = FreightFee::Clear($user,$data);
  537. $fee = $model->where('del_time', 0)
  538. ->where('order_time', $data['order_time'])
  539. ->get()
  540. ->toArray();
  541. if (empty($fee)) {
  542. return [false, '单据日期下暂无数据'];
  543. }
  544. // 按时间+地区聚合同一天、同地区的非退货配送费
  545. $time_amount = [];
  546. foreach ($fee as $value) {
  547. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  548. $key = $value['order_time'] . $value['area_hs'];
  549. $time_amount[$key]['amount'] = isset($time_amount[$key]['amount'])
  550. ? bcadd($value['freight_amount'], $time_amount[$key]['amount'], 2)
  551. : $value['freight_amount'];
  552. $time_amount[$key]['is_use'] = $time_amount[$key]['is_use'] ?? 0;
  553. }
  554. }
  555. $return = [];
  556. foreach ($fee as $value) {
  557. $value = $this->calculateFreightFeeRow($value, $time_amount);
  558. $key = $value['order_time'] . '|' . $value['area_hs'];
  559. $return[$value['business_type_id']][$key][] = $value;
  560. }
  561. $result = [];
  562. // 需要合计的字段
  563. $sumFields = ['xs', 'weight', 'freight_amount', 'js_amount', 'customer_store_zx_fee', 'jj_fee', 'dh_fee', 'total_amount'];
  564. // 业务类型 日期 地区 算一张表算运费
  565. foreach ($return as $g => $group) {
  566. $g_title = FreightFee::$business[$g] ?? "";
  567. foreach ($group as $key => $val) {
  568. $tmp_key = explode('|', $key);
  569. $title = $tmp_key[1] . "(" . $g_title . ")";
  570. // 计算合计
  571. $sumRow = [];
  572. foreach ($val as $key => $row) {
  573. $order_time = $row['order_time'] ? date('Y-m-d',$row['order_time']) : '';
  574. $val[$key]['order_time_show'] = $order_time;
  575. $val[$key]['is_present_show'] = $row['is_present'] ? '是' : '否';
  576. $delivery_mode_show = FreightFee::$delivery[$row['delivery_mode']] ?? "";
  577. $val[$key]['delivery_mode_show'] = $delivery_mode_show;
  578. $val[$key]['area_range_show'] = $row['area_range'] == 1 ? '1~5吨' : '5吨以上';
  579. foreach ($sumFields as $field) {
  580. $sumRow[$field] = isset($sumRow[$field])
  581. ? bcadd($sumRow[$field], $row[$field], 2)
  582. : $row[$field];
  583. }
  584. }
  585. // 末行合计行(非合计字段设为空字符串)
  586. $footer = [];
  587. foreach ($val[0] as $field => $v) {
  588. $footer[$field] = in_array($field, $sumFields) ? $sumRow[$field] : '';
  589. }
  590. $val[] = $footer;
  591. $result[] = [
  592. 'key' => $title,
  593. 'list' => $val
  594. ];
  595. }
  596. }
  597. return [true, $result];
  598. }
  599. protected function calculateFreightFeeRow(array $value, array &$time_amount)
  600. {
  601. $key = $value['order_time'] . $value['area_hs'];
  602. $js_amount = 0;
  603. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  604. $tmp_total_arr = $time_amount[$key];
  605. // 判断是否使用最低运费
  606. if ($tmp_total_arr['amount'] < $value['min_freight_amount']) {
  607. if (!$time_amount[$key]['is_use']) {
  608. $js_amount = $value['min_freight_amount'];
  609. $time_amount[$key]['is_use'] = 1;
  610. }
  611. } else {
  612. $js_amount = $value['js_single_amount'];
  613. }
  614. } else {
  615. $js_amount = $value['js_single_amount'];
  616. }
  617. $value['js_amount'] = $js_amount;
  618. // 加急费
  619. $jj_fee = 0;
  620. if ($value['delivery_mode'] == FreightFee::deliveryModeRightNow) {
  621. $jj_fee = bcmul($js_amount, 0.5, 2);
  622. }
  623. $value['jj_fee'] = $jj_fee;
  624. // 总金额
  625. $total_amount = bcadd($js_amount, $value['customer_store_zx_fee'], 2);
  626. $total_amount = bcadd($total_amount, $value['sl_fee'], 2);
  627. $total_amount = bcadd($total_amount, $jj_fee, 2);
  628. $total_amount = bcadd($total_amount, $value['dh_fee'], 2);
  629. $value['total_amount'] = $total_amount;
  630. return $value;
  631. }
  632. }