StatisticsService.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. if(! empty($data['id'])) $model->whereIn('id',$data['id']);
  27. return [true, $model];
  28. }
  29. public function statisticsRevenueCost($data,$user){
  30. list($status, $model) = $this->statisticsRevenueCostCommon($data, $user);
  31. if(! $status) return [false, $model];
  32. $list = $this->limit($model,'',$data);
  33. $list = $this->statisticsRevenueCostFillData($list);
  34. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  35. return [true, $list];
  36. }
  37. public function statisticsRevenueCostFillData($data){
  38. if(empty($data['data'])) return $data;
  39. foreach ($data['data'] as $key => $value){
  40. $time = date("Y-m", $value['order_time']);
  41. $data['data'][$key]['order_time'] = $time;
  42. $data['data'][$key]['order_type_title'] = RevenueCost::$order_type[$value['order_type']] ?? "";
  43. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  44. }
  45. return $data;
  46. }
  47. public function statisticsRevenueCostOneAndTwoCommon($data,$user, $field = []){
  48. if(empty($data['order_type']) || ! isset(RevenueCost::$order_type[$data['order_type']])) return [false, '单据类型不存在或错误'];
  49. if(empty($field)) {
  50. if($data['order_type'] == 1){
  51. $field = RevenueCost::$field_xhd;
  52. }else{
  53. $field = RevenueCost::$field_xsfp;
  54. }
  55. }
  56. $model = RevenueCost::Clear($user,$data);
  57. $model = $model->where('del_time',0)
  58. ->where('order_type',$data['order_type'])
  59. ->select($field)
  60. ->orderby('id', 'desc');
  61. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  62. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  63. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  64. $model->where('order_time', '>=', $start_time)
  65. ->where('order_time', '<=', $end_time);
  66. }
  67. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  68. if(! empty($data['customer_title'])) $model->where('customer_title', 'LIKE', '%'.$data['customer_title'].'%');
  69. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  70. if(! empty($data['id'])) $model->whereIn('id',$data['id']);
  71. return [true, $model];
  72. }
  73. public function statisticsRevenueCostOneAndTwo($data,$user){
  74. list($status, $model) = $this->statisticsRevenueCostOneAndTwoCommon($data, $user);
  75. if(! $status) return [false, $model];
  76. $list = $this->limit($model,'',$data);
  77. $list = $this->statisticsRevenueCostOneAndTwoFillData($list);
  78. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  79. return [true, $list];
  80. }
  81. public function statisticsRevenueCostOneAndTwoFillData($data){
  82. if(empty($data['data'])) return $data;
  83. foreach ($data['data'] as $key => $value){
  84. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  85. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  86. }
  87. return $data;
  88. }
  89. public function statisticsRevenueCostThreeCommon($data,$user, $field = []){
  90. if(empty($field)) {
  91. $field = RevenueCost::$field_hkd_salary_main;
  92. $field[] = DB::raw('sum(payment_amount) as payment_amount');
  93. $field[] = DB::raw('sum(price_4_total) as price_4_total');
  94. $field[] = DB::raw('sum(profit) as profit');
  95. $field[] = DB::raw('max(employee_id_2) as employee_id_2');
  96. $field[] = DB::raw("MAX(COALESCE(employee_id_2_title, '')) as employee_id_2_title");
  97. }
  98. $model = RevenueCost::Clear($user,$data);
  99. $model = $model->where('del_time',0)
  100. ->where('order_type',RevenueCost::ORDER_THREE)
  101. ->select($field)
  102. ->groupby('order_id')
  103. ->orderby('id', 'desc');
  104. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  105. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  106. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  107. $model->where('order_time', '>=', $start_time)
  108. ->where('order_time', '<=', $end_time);
  109. }
  110. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  111. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  112. if(! empty($data['employee_id_1'])) $model->where('employee_id_1', 'LIKE', $data['employee_id_1']);
  113. if(! empty($data['employee_id_2'])) $model->where('employee_id_2', 'LIKE', $data['employee_id_2']);
  114. if(! empty($data['employee_id_2_title'])) $model->where('employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  115. if(! empty($data['channel_finance_array'])) {
  116. $array = explode("\n", str_replace(["\r\n", "\r"], "\n", $data['channel_finance_array']));
  117. $model->whereIn('channel_finance', $array);
  118. }
  119. if(! empty($data['id'])) $model->whereIn('order_id',$data['id']);
  120. return [true, $model];
  121. }
  122. public function statisticsRevenueCostThree($data,$user){
  123. list($status, $model) = $this->statisticsRevenueCostThreeCommon($data, $user);
  124. if(! $status) return [false, $model];
  125. $list = $this->limit($model,'',$data);
  126. $list = $this->statisticsRevenueCostThreeFillData($list);
  127. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  128. return [true, $list];
  129. }
  130. public function statisticsRevenueCostThreeFillData($data){
  131. if(empty($data['data'])) return $data;
  132. foreach ($data['data'] as $key => $value){
  133. $profit_rate = $value['payment_amount'] > 0 ? bcdiv($value['profit'], $value['payment_amount'],8) : 0;
  134. $data['data'][$key]['profit_rate'] = bcmul($profit_rate, 100,2);
  135. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  136. }
  137. return $data;
  138. }
  139. public function statisticsRevenueCostThreeDetail($data,$user){
  140. if(empty($data['order_number'])) return [false, '回款单号不能为空'];
  141. $result = RevenueCost::where('del_time',0)
  142. ->where('order_type',RevenueCost::ORDER_THREE)
  143. ->where('order_number',$data['order_number'])
  144. ->select(RevenueCost::$field_hkd_detail)
  145. ->get()->toArray();
  146. if(empty($result)) return [false, "回款单不存在或已被删除"];
  147. $detail = [];
  148. foreach ($result as $value){
  149. $detail[] = [
  150. 'order_number' => $value['order_number_upstream'],
  151. 'customer_code' => $value['customer_code'],
  152. 'customer_title' => $value['customer_title'],
  153. 'channel_finance' => $value['channel_finance'],
  154. 'product_code' => $value['product_code'],
  155. 'product_title' => $value['product_title'],
  156. 'product_size' => $value['product_size'],
  157. 'unit' => $value['unit'],
  158. 'quantity' => $value['quantity'],
  159. 'payment_amount' => $value['payment_amount'],
  160. 'price_1' => $value['price_1'],
  161. 'price_1_total' => $value['price_1_total'],
  162. 'price_4' => $value['price_4'],
  163. 'price_4_total' => $value['price_4_total'],
  164. 'profit' => $value['profit'],
  165. 'profit_rate' => bcmul($value['profit_rate'],100,2) . '%',
  166. 'customer_profit_rate' => bcmul($value['customer_profit_rate'],100,2) . '%',
  167. 'voucher_type_title' => RevenueCost::$voucher_type[$value['voucher_type']] ?? "",
  168. ];
  169. }
  170. $footer = $this->countTotal($result, $user['header_default']);
  171. $footer['profit_rate'] = $footer['profit_rate'] . "%";
  172. $footer = array_merge( [
  173. 'order_number' => '',
  174. 'customer_code' => '',
  175. 'customer_title' => '',
  176. 'channel_finance' => '',
  177. 'product_code' => '',
  178. 'product_title' => '',
  179. 'product_size' => '',
  180. 'unit' => '',
  181. 'quantity' => '',
  182. 'payment_amount' => '',
  183. 'price_1' => '',
  184. 'price_1_total' => '',
  185. 'price_4' => '',
  186. 'price_4_total' => '',
  187. 'profit' => '',
  188. 'profit_rate' => '',
  189. 'customer_profit_rate'=> '',
  190. 'voucher_type_title' => '',
  191. ], $footer);
  192. $detail[] = $footer;
  193. $first = $result[0];
  194. $order = [
  195. 'order_number' => $data['order_number'],
  196. 'order_time' => date("Y-m-d",$first['order_time']),
  197. 'employee_id_1_title' => $first['employee_id_1_title'],
  198. 'detail' => $detail
  199. ];
  200. return [true, $order];
  201. }
  202. public function statisticsProfitCommon($data,$user, $field = []){
  203. if(empty($field)) {
  204. $field = RevenueCost::$field_hkd_profit_main;
  205. $field[] = DB::raw('COALESCE(SUM(rc.payment_amount), 0) AS payment_amount');
  206. }
  207. $type = RevenueCost::ORDER_THREE;
  208. $model = EmployeeIndex::Clear($user, $data)
  209. ->where('employee_index.del_time', 0)
  210. ->where('employee_index.type', EmployeeIndex::TYPE_THREE)
  211. ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  212. $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  213. ->where('rc.del_time', 0)
  214. ->where('rc.order_type', $type)
  215. ->whereNotNull('rc.employee_id_2')
  216. ->where('rc.employee_id_2', '<>', '')
  217. ->whereRaw('rc.order_time >= employee_index.start_time')
  218. ->whereRaw('rc.order_time <= employee_index.end_time');
  219. })
  220. ->select($field)
  221. ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  222. ->orderBy('employee_index.end_time', 'desc');
  223. // $type = RevenueCost::ORDER_THREE;
  224. // $model = EmployeeIndex::where('employee_index.del_time',0)
  225. // ->where('employee_index.type',EmployeeIndex::TYPE_THREE)
  226. // ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  227. // $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  228. // ->where('rc.del_time', 0)
  229. // ->where('rc.order_type', $type)
  230. // ->whereRaw('rc.order_time >= employee_index.start_time')
  231. // ->whereRaw('rc.order_time <= employee_index.end_time');
  232. // })
  233. // ->select($field)
  234. // ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  235. // ->orderBy('employee_index.end_time','desc');
  236. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){;
  237. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  238. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  239. $model->where('employee_index.start_time', '<=', $end_time)
  240. ->where('employee_index.end_time', '>=', $start_time);
  241. }
  242. if(! empty($data['employee_id_2_title'])) $model->where('rc.employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  243. if(! empty($data['id'])) $model->whereIn('employee_index.id', $data['id']);
  244. return [true, $model];
  245. }
  246. public function statisticsProfit($data,$user){
  247. list($status, $model) = $this->statisticsProfitCommon($data, $user);
  248. if(! $status) return [false, $model];
  249. $list = $this->limit($model,'',$data);
  250. $list = $this->statisticsProfitFillData($list);
  251. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  252. return [true, $list];
  253. }
  254. public function statisticsProfitFillData($data){
  255. if(empty($data['data'])) return $data;
  256. //获取应发放金额需要的指标
  257. $indexes = $this->getEmployeeIndex($data['data']);
  258. //已发
  259. $indexes_give = $this->getEmployeeGiveOut($data['data']);
  260. foreach ($data['data'] as $key => $value){
  261. $start = $value['start_time'] ? date('Y-m-d',$value['start_time']) : '';
  262. $end = $value['end_time'] ? date('Y-m-d',$value['end_time']) : '';
  263. $string = "";
  264. if(! empty($start) && ! empty($end)) $string = $start . "-" . $end;
  265. $value['check_time'] = $string;
  266. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  267. $value['index_' . EmployeeIndex::TYPE_FIVE] = 0;
  268. //指标
  269. $this->makeIndex($indexes, $value, $data['data'][$key]);
  270. //应付
  271. $this->makeShouldPay($value,$data['data'][$key]);
  272. //已付
  273. $this->makePayed($indexes_give, $value,$data['data'][$key]);
  274. //未付
  275. $not_pay = bcsub($data['data'][$key]['should_pay'], $data['data'][$key]['payed'],2);
  276. $data['data'][$key]['not_pay'] = $not_pay;
  277. }
  278. return $data;
  279. }
  280. private function getEmployeeIndex($existingData)
  281. {
  282. if (empty($existingData)) {
  283. return collect();
  284. }
  285. // 取出所有涉及的 employee_id 和时间区间
  286. $employeeIds = array_column($existingData, 'employee_id_2');
  287. $start_time = array_column($existingData, 'start_time');
  288. $minStart = ! empty($start_time) ? min($start_time) : 0;
  289. $end_time = array_column($existingData, 'end_time');
  290. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  291. // 一次性查出这些员工在最大区间范围内的所有指标
  292. $results = EmployeeIndex::where('del_time', 0)
  293. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_FIVE])
  294. ->whereIn('employee_id', $employeeIds)
  295. ->where('start_time', '<=', $maxEnd)
  296. ->where('end_time', '>=', $minStart)
  297. ->select('start_time','end_time','employee_id','index','type')
  298. ->get();
  299. return $results;
  300. }
  301. private function getEmployeeGiveOut($existingData)
  302. {
  303. if (empty($existingData)) {
  304. return collect();
  305. }
  306. // 取出所有涉及的 employee_id 和时间区间
  307. $employeeIds = array_column($existingData, 'employee_id_2');
  308. $start_time = array_column($existingData, 'start_time');
  309. $minStart = ! empty($start_time) ? min($start_time) : 0;
  310. $end_time = array_column($existingData, 'end_time');
  311. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  312. // 一次性查出这些员工在最大区间范围内的所有指标
  313. $results = GiveOut::where('del_time', 0)
  314. ->whereIn('employee_id_1', $employeeIds)
  315. ->where('start_time', '<=', $maxEnd)
  316. ->where('end_time', '>=', $minStart)
  317. ->select('start_time','end_time','employee_id_1 as employee_id','give_out_amount')
  318. ->get();
  319. return $results;
  320. }
  321. private function makeIndex($indexes, $value, &$data){
  322. // 找到所有符合条件的 index(可能多个 type)
  323. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  324. return $item['employee_id'] == $value['employee_id_2']
  325. && $item['start_time'] <= $value['end_time']
  326. && $item['end_time'] >= $value['start_time'];
  327. });
  328. // 按 type 去重,只保留第一次出现的
  329. $uniqueByType = [];
  330. foreach ($matchedIndexes as $item) {
  331. $index = "index_" . $item['type'];
  332. if (! isset($uniqueByType[$index])) {
  333. $uniqueByType[$index] = $item['index'];
  334. }
  335. }
  336. $data = array_merge($value, $uniqueByType);
  337. }
  338. private function makeShouldPay($value, &$data){
  339. $index_1 = bcdiv($data['index_1'],100,2);
  340. $index_5 = bcdiv($data['index_5'],100,2);
  341. // 分红比例/2
  342. $a = bcdiv($index_5,2,2);
  343. // 季度预支分红比例/2
  344. $b = bcdiv($index_1,2,2);
  345. //(分红比例/2-季度预支分红比例/2)
  346. $c = bcsub($a, $b,2);
  347. $data['part_left'] = $c;
  348. if($value['payment_amount'] < $value['index']){
  349. //回款金额*(分红比例/2-季度预支分红比例/2);
  350. $shouldPay = bcmul($value['payment_amount'], $c,2);
  351. }else{
  352. //回款金额-季度指标金额
  353. $d = bcsub($value['payment_amount'], $value['index'],2);
  354. //(回款金额-季度指标金额)*15%
  355. $e = bcmul($d, 0.15,2);
  356. //(回款金额-季度指标金额)*15%/2
  357. $e = bcdiv($e,2,2);
  358. //(分红比例/2-季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  359. $rate = bcadd($c, $e,2);
  360. // $data['data'][$key]['rate'] = $rate;
  361. //回款金额*(分红比例/2-回款金额*季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  362. $shouldPay = bcmul($value['payment_amount'], $rate,2);
  363. }
  364. $data['should_pay'] = $shouldPay;
  365. }
  366. private function makePayed($indexes, $value, &$data){
  367. $matchedIndexes_give = $indexes->filter(function ($item) use ($value) {
  368. return $item['employee_id'] == $value['employee_id_2']
  369. && $item['start_time'] <= $value['end_time']
  370. && $item['end_time'] >= $value['start_time'];
  371. });
  372. $give_out = 0;
  373. foreach ($matchedIndexes_give as $item) {
  374. $give_out = bcadd($item['give_out_amount'], $give_out,2);
  375. }
  376. $data['payed'] = $give_out;
  377. }
  378. public function statisticsEmployeeSalaryCommon($data,$user, $field = []){
  379. if(empty($field)) {
  380. $field = SalaryEmployee::$field;
  381. }
  382. $model = SalaryEmployee::Clear($user,$data);
  383. $model = $model->where('del_time',0)
  384. ->where('order_type',RevenueCost::ORDER_THREE)
  385. ->select($field)
  386. ->orderby('order_time', 'desc');
  387. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  388. $start_time = strtotime($data['order_time'][0] . "-01");
  389. $end_time = strtotime($data['order_time'][1] . "-01");
  390. $model->where('order_time', '>=', $start_time)
  391. ->where('order_time', '<=', $end_time);
  392. }
  393. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  394. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  395. return [true, $model];
  396. }
  397. public function statisticsEmployeeSalary($data,$user){
  398. list($status, $model) = $this->statisticsEmployeeSalaryCommon($data, $user);
  399. if(! $status) return [false, $model];
  400. $list = $this->limit($model,'',$data);
  401. $list = $this->statisticsEmployeeSalaryFillData($list);
  402. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  403. return [true, $list];
  404. }
  405. public function statisticsEmployeeSalaryFillData($data){
  406. if(empty($data['data'])) return $data;
  407. foreach ($data['data'] as $key => $value){
  408. $order_time = $value['order_time'] ? date('Y-m',$value['order_time']) : '';
  409. $data['data'][$key]['order_time'] = $order_time;
  410. }
  411. return $data;
  412. }
  413. public function statisticsFreightFeeCommon($data,$user, $field = []){
  414. if(empty($field)) {
  415. $field = FreightFee::$field;
  416. }
  417. $model = FreightFee::Clear($user,$data);
  418. $model = $model->where('del_time',0)
  419. ->select($field)
  420. ->groupby('order_time')
  421. ->orderby('order_time', 'desc');
  422. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  423. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  424. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  425. $model->where('order_time', '>=', $start_time)
  426. ->where('order_time', '<=', $end_time);
  427. }
  428. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  429. if(! empty($data['id'])) $model->whereIn('order_time', $data['id']);
  430. return [true, $model];
  431. }
  432. public function statisticsFreightFee($data,$user){
  433. list($status, $model) = $this->statisticsFreightFeeCommon($data, $user);
  434. if(! $status) return [false, $model];
  435. $list = $this->limit($model,'',$data);
  436. $list = $this->statisticsFreightFeeFillData($list, $user,$data);
  437. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  438. return [true, $list];
  439. }
  440. public function statisticsFreightFeeFillData($data, $user, $ergs){
  441. if(empty($data['data'])) return $data;
  442. $order_time = array_column($data['data'], 'order_time');
  443. $model = FreightFee::Clear($user,$ergs);
  444. $allFees = $model->where('del_time', 0)
  445. ->whereIn('order_time', $order_time)
  446. ->get()
  447. ->toArray();
  448. $feesByDay = [];
  449. foreach ($allFees as $f) {
  450. $feesByDay[$f['order_time']][] = $f;
  451. }
  452. foreach ($data['data'] as $key => $value) {
  453. $fees = $feesByDay[$value['order_time']] ?? [];
  454. if (empty($fees)) {
  455. $data['data'][$key]['total_amount'] = 0;
  456. continue;
  457. }
  458. // 准备 time_amount(和详情逻辑一致)
  459. $time_amount = [];
  460. foreach ($fees as $f) {
  461. if ($f['business_type_id'] == FreightFee::businessTypeNormal) {
  462. $k = $f['order_time'] . $f['area_hs'];
  463. $time_amount[$k]['amount'] = isset($time_amount[$k]['amount'])
  464. ? bcadd($f['freight_amount'], $time_amount[$k]['amount'], 4)
  465. : $f['freight_amount'];
  466. $time_amount[$k]['is_use'] = $time_amount[$k]['is_use'] ?? 0;
  467. }
  468. }
  469. // 逐条算金额
  470. $valueTotal = 0;
  471. foreach ($fees as $f) {
  472. $f = $this->calculateFreightFeeRow($f, $time_amount);
  473. $valueTotal = bcadd($valueTotal, $f['total_amount'], 4);
  474. }
  475. $data['data'][$key]['total_amount'] = $valueTotal;
  476. $order_time = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  477. $data['data'][$key]['order_time_show'] = $order_time;
  478. $data['data'][$key]['id'] = $value['order_time'];
  479. }
  480. return $data;
  481. }
  482. public function statisticsFreightFeeDetail($data, $user)
  483. {
  484. if (empty($data['order_time'])) {
  485. return [false, '单据日期不能为空'];
  486. }
  487. $model = FreightFee::Clear($user,$data);
  488. $fee = $model->where('del_time', 0)
  489. ->where('order_time', $data['order_time'])
  490. ->get()
  491. ->toArray();
  492. if (empty($fee)) {
  493. return [false, '单据日期下暂无数据'];
  494. }
  495. // 按时间+地区聚合同一天、同地区的非退货配送费
  496. $time_amount = [];
  497. foreach ($fee as $value) {
  498. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  499. $key = $value['order_time'] . $value['area_hs'];
  500. $time_amount[$key]['amount'] = isset($time_amount[$key]['amount'])
  501. ? bcadd($value['freight_amount'], $time_amount[$key]['amount'], 4)
  502. : $value['freight_amount'];
  503. $time_amount[$key]['is_use'] = $time_amount[$key]['is_use'] ?? 0;
  504. }
  505. }
  506. $return = [];
  507. foreach ($fee as $value) {
  508. $value = $this->calculateFreightFeeRow($value, $time_amount);
  509. $key = $value['order_time'] . '|' . $value['area_hs'];
  510. $return[$value['business_type_id']][$key][] = $value;
  511. }
  512. $result = [];
  513. // 需要合计的字段
  514. $sumFields = ['xs', 'weight', 'freight_amount', 'js_amount', 'customer_store_zx_fee', 'jj_fee', 'dh_fee', 'total_amount'];
  515. $sumFields_map = ['weight' => 4,'freight_amount' => 4, 'js_amount' => 4,'customer_store_zx_fee' => 4, 'jj_fee' => 4, 'dh_fee' => 4, 'total_amount' => 4];
  516. // 业务类型 日期 地区 算一张表算运费
  517. foreach ($return as $g => $group) {
  518. $g_title = FreightFee::$business[$g] ?? "";
  519. foreach ($group as $key => $val) {
  520. $tmp_key = explode('|', $key);
  521. $title = $tmp_key[1] . "(" . $g_title . ")";
  522. // 计算合计
  523. $sumRow = [];
  524. foreach ($val as $key => $row) {
  525. $order_time = $row['order_time'] ? date('Y-m-d',$row['order_time']) : '';
  526. $val[$key]['order_time_show'] = $order_time;
  527. $val[$key]['is_present_show'] = $row['is_present'] ? '是' : '否';
  528. $delivery_mode_show = FreightFee::$delivery[$row['delivery_mode']] ?? "";
  529. $val[$key]['delivery_mode_show'] = $delivery_mode_show;
  530. $val[$key]['area_range_show'] = $row['area_range'] == 1 ? '1~5吨' : '5吨以上';
  531. foreach ($sumFields as $field) {
  532. $decimals = $sumFields_map[$field] ?? 2;
  533. $sumRow[$field] = isset($sumRow[$field])
  534. ? bcadd($sumRow[$field], $row[$field], $decimals)
  535. : $row[$field];
  536. }
  537. }
  538. // 末行合计行(非合计字段设为空字符串)
  539. $footer = [];
  540. foreach ($val[0] as $field => $v) {
  541. $footer[$field] = in_array($field, $sumFields) ? $sumRow[$field] : '';
  542. }
  543. $val[] = $footer;
  544. $result[] = [
  545. 'key' => $title,
  546. 'list' => $val
  547. ];
  548. }
  549. }
  550. return [true, $result];
  551. }
  552. public function statisticsFreightFeeDetailsForExport($data, $user)
  553. {
  554. if (empty($data['order_time'])) return [];
  555. $model = FreightFee::Clear($user, $data);
  556. $orderTimes = is_array($data['order_time']) ? $data['order_time'] : [$data['order_time']];
  557. $fee = $model->where('del_time', 0)
  558. ->whereIn('order_time', $orderTimes)
  559. ->get()
  560. ->toArray();
  561. // 表头定义(所有 sheet 通用)
  562. $header = [
  563. "仓库", "销货单备注", "业务类型", "销货单号", "销货日期", "客户",
  564. "客户门店装车费单价", "业务员", "送货地址", "地区华商", "存货编码", "存货名称", "箱规",
  565. "华商重量", "门店卸货费单价(华商)", "门店卸货费单价(华商)", "赠品", "货类(华商)", "运输方式",
  566. "数量", "含税单价", "含税金额", "箱数", "总重量", "运价区间", "配送费单价", "配送费金额", "结算金额",
  567. "门店卸货费", "上楼费", "加急费", "到货装卸费", "总金额"
  568. ];
  569. if (empty($fee)) {
  570. // 返回每个请求的日期都带表头(只有表头),以便导出时每个 sheet 至少有表头
  571. $resultEmpty = [];
  572. foreach ($orderTimes as $ot) {
  573. $dateKey = date('Y-m-d', $ot);
  574. $resultEmpty[$dateKey] = [
  575. 0 => $header
  576. ];
  577. }
  578. return $resultEmpty;
  579. }
  580. // 按时间+地区聚合同一天、同地区的非退货配送费(用于 calculate 逻辑)
  581. $time_amount = [];
  582. foreach ($fee as $value) {
  583. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  584. $key = $value['order_time'] . $value['area_hs'];
  585. $time_amount[$key]['amount'] = isset($time_amount[$key]['amount'])
  586. ? bcadd($value['freight_amount'], $time_amount[$key]['amount'], 4)
  587. : $value['freight_amount'];
  588. $time_amount[$key]['is_use'] = $time_amount[$key]['is_use'] ?? 0;
  589. }
  590. }
  591. // 先按 order_time -> business_type_id -> (order_time|area_hs) 分组收集数据行
  592. $grouped = [];
  593. foreach ($fee as $value) {
  594. $value = $this->calculateFreightFeeRow($value, $time_amount);
  595. $key = $value['order_time'] . '|' . $value['area_hs'];
  596. $grouped[$value['order_time']][$value['business_type_id']][$key][] = $value;
  597. }
  598. // 构造返回:每个日期一个 sheet(键为 YYYY-MM-DD),值为数值下标数组,0 为表头
  599. $result = [];
  600. // 需要合计的字段及小数位
  601. $sumFields = ['xs','weight', 'freight_amount', 'js_amount', 'customer_store_zx_fee', 'jj_fee', 'dh_fee', 'total_amount'];
  602. $sumFields_map = ['xs' => 0,'weight' => 4, 'freight_amount' => 4, 'js_amount' => 4, 'customer_store_zx_fee' => 4, 'jj_fee' => 4, 'dh_fee' => 4, 'total_amount' => 4];
  603. // 初始化每个传入日期,确保即使某个日期无数据也有表头
  604. foreach ($orderTimes as $ot) {
  605. $dateKey = date('Y-m-d', $ot);
  606. $result[$dateKey] = [];
  607. $result[$dateKey][] = $header; // index 0 为表头
  608. }
  609. // 填充数据
  610. foreach ($grouped as $order_time => $types) {
  611. $dateKey = date('Y-m-d', $order_time);
  612. // 若该日期未初始化(理论上不会),先初始化表头
  613. if (!isset($result[$dateKey])) {
  614. $result[$dateKey] = [];
  615. $result[$dateKey][] = $header;
  616. }
  617. foreach ($types as $business_type_id => $group) {
  618. $businessTitle = FreightFee::$business[$business_type_id] ?? '';
  619. foreach ($group as $key => $rows) {
  620. // 每个 key 对应一组明细(按 area_hs 分组)
  621. $sumRow = []; // 用于该分组的合计
  622. foreach ($rows as $row) {
  623. $date_show = $row['order_time'] ? date('Y-m-d', $row['order_time']) : "";
  624. $is_present_show = !empty($row['is_present']) ? '是' : '否';
  625. $delivery_mode_show = FreightFee::$delivery[$row['delivery_mode']] ?? "";
  626. $area_range_show = isset($row['area_range']) && $row['area_range'] == 1 ? '1~5吨' : '5吨以上';
  627. // 单行数据(按你指定的字段顺序)
  628. $line = [
  629. $row['warehouse_name'] ?? '', // 仓库
  630. $row['mark'] ?? '', // 销货单备注
  631. $row['business_type_title'] ?? '', // 业务类型
  632. $row['order_number'] ?? '', // 销货单号
  633. $date_show, // 销货日期
  634. $row['customer_title'] ?? '', // 客户
  635. $row['customer_store_price'] ?? 0, // 客户门店装车费单价
  636. $row['employee_id_1_title'] ?? '', // 业务员
  637. $row['address'] ?? '', // 送货地址
  638. $row['area_hs'] ?? '', // 地区华商
  639. $row['product_code'] ?? '', // 存货编码
  640. $row['product_title'] ?? '', // 存货名称
  641. $row['product_box_size'] ?? '', // 箱规
  642. $row['product_weight'] ?? 0, // 华商重量
  643. $row['product_store_price'] ?? 0, // 门店卸货费单价(华商)
  644. $row['product_store_price2'] ?? 0, // 到货装卸费单价(华商)
  645. $is_present_show, // 赠品
  646. $row['product_category'] ?? '', // 货类(华商)
  647. $delivery_mode_show, // 运输方式
  648. $row['quantity'] ?? 0, // 数量
  649. $row['price_3'] ?? 0, // 含税单价
  650. $row['price_3_total'] ?? 0, // 含税金额
  651. number_format($row['xs'] ?? 0), // 箱数
  652. $row['weight'] ?? 0, // 总重量
  653. $area_range_show, // 运价区间
  654. $row['freight_unit_price'] ?? 0, // 配送费单价
  655. $row['freight_amount'] ?? 0, // 配送费金额
  656. $row['js_amount'] ?? 0, // 结算金额
  657. $row['customer_store_zx_fee'] ?? 0, // 门店卸货费
  658. $row['sl_fee'] ?? 0, // 上楼费
  659. number_format($row['jj_fee'] ?? 0, 2), // 加急费
  660. $row['dh_fee'] ?? 0, // 到货装卸费
  661. $row['total_amount'] ?? 0, // 总金额
  662. ];
  663. $result[$dateKey][] = $line;
  664. // 累加合计
  665. foreach ($sumFields as $field) {
  666. $decimals = $sumFields_map[$field] ?? 2;
  667. $sumRow[$field] = isset($sumRow[$field])
  668. ? bcadd($sumRow[$field], $row[$field], $decimals)
  669. : ($row[$field] ?? 0);
  670. }
  671. }
  672. // 添加本分组合计行(合计位置与表头列对齐,其它非合计字段留空)
  673. $totalLine = [
  674. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  675. $sumRow['xs'] ?? 0,
  676. $sumRow['weight'] ?? 0,
  677. '', '',
  678. $sumRow['freight_amount'] ?? 0, // 配送费金额合计
  679. $sumRow['js_amount'] ?? 0, // 结算金额合计
  680. $sumRow['customer_store_zx_fee'] ?? 0, // 门店卸货费合计
  681. $sumRow['sl_fee'] ?? 0, // 上楼费合计
  682. $sumRow['jj_fee'] ?? 0, // 加急费合计
  683. $sumRow['dh_fee'] ?? 0, // 到货装卸费合计
  684. $sumRow['total_amount'] ?? 0, // 总金额合计
  685. ];
  686. $result[$dateKey][] = $totalLine;
  687. }
  688. }
  689. }
  690. // 确保每个日期的数组是从 0 开始的连续下标(虽然我们已经按顺序 push,但为了保险)
  691. return $result;
  692. }
  693. protected function calculateFreightFeeRow(array $value, array &$time_amount)
  694. {
  695. $key = $value['order_time'] . $value['area_hs'];
  696. $js_amount = 0;
  697. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  698. $tmp_total_arr = $time_amount[$key];
  699. // 判断是否使用最低运费
  700. if ($tmp_total_arr['amount'] < $value['min_freight_amount']) {
  701. if (!$time_amount[$key]['is_use']) {
  702. $js_amount = $value['min_freight_amount'];
  703. $time_amount[$key]['is_use'] = 1;
  704. }
  705. } else {
  706. $js_amount = $value['js_single_amount'];
  707. }
  708. } else {
  709. $js_amount = $value['js_single_amount'];
  710. }
  711. $value['js_amount'] = $js_amount;
  712. // 加急费
  713. $jj_fee = 0;
  714. if ($value['delivery_mode'] == FreightFee::deliveryModeRightNow) {
  715. $jj_fee = bcmul($js_amount, 0.5, 4);
  716. }
  717. $value['jj_fee'] = $jj_fee;
  718. // 总金额
  719. $total_amount = bcadd($js_amount, $value['customer_store_zx_fee'], 4);
  720. $total_amount = bcadd($total_amount, $value['sl_fee'], 4);
  721. $total_amount = bcadd($total_amount, $jj_fee, 4);
  722. $total_amount = bcadd($total_amount, $value['dh_fee'], 4);
  723. $value['total_amount'] = $total_amount;
  724. return $value;
  725. }
  726. }