StatisticsService.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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\ItemReport;
  7. use App\Model\ItemReportMan;
  8. use App\Model\ItemReportRoad;
  9. use App\Model\RevenueCost;
  10. use App\Model\RevenueCostTotal;
  11. use App\Model\SalaryEmployee;
  12. use Illuminate\Support\Facades\DB;
  13. class StatisticsService extends Service
  14. {
  15. public function statisticsRevenueCostCommon($data,$user, $field = []){
  16. if(empty($field)) $field = RevenueCostTotal::$field;
  17. $model = RevenueCostTotal::Clear($user,$data);
  18. $model = $model->where('del_time',0)
  19. ->select($field)
  20. ->orderby('id', 'desc');
  21. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  22. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  23. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  24. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  25. $model->where('order_time', '>=', $start_time)
  26. ->where('order_time', '<', $end_time);
  27. }
  28. if(! empty($data['order_type'])) $model->where('order_type',$data['order_type']);
  29. if(! empty($data['id'])) $model->whereIn('id',$data['id']);
  30. return [true, $model];
  31. }
  32. public function statisticsRevenueCost($data,$user){
  33. list($status, $model) = $this->statisticsRevenueCostCommon($data, $user);
  34. if(! $status) return [false, $model];
  35. $list = $this->limit($model,'',$data);
  36. $list = $this->statisticsRevenueCostFillData($list);
  37. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  38. return [true, $list];
  39. }
  40. public function statisticsRevenueCostFillData($data){
  41. if(empty($data['data'])) return $data;
  42. foreach ($data['data'] as $key => $value){
  43. $time = date("Y-m", $value['order_time']);
  44. $data['data'][$key]['order_time'] = $time;
  45. $data['data'][$key]['order_type_title'] = RevenueCost::$order_type[$value['order_type']] ?? "";
  46. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  47. }
  48. return $data;
  49. }
  50. public function statisticsRevenueCostOneAndTwoCommon($data,$user, $field = []){
  51. if(empty($data['order_type']) || ! isset(RevenueCost::$order_type[$data['order_type']])) return [false, '单据类型不存在或错误'];
  52. if(empty($field)) {
  53. if($data['order_type'] == 1){
  54. $field = RevenueCost::$field_xhd;
  55. }else{
  56. $field = RevenueCost::$field_xsfp;
  57. }
  58. }
  59. $model = RevenueCost::Clear($user,$data);
  60. $model = $model->where('del_time',0)
  61. ->where('order_type',$data['order_type'])
  62. ->select($field)
  63. ->orderby('id', 'desc');
  64. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  65. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  66. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  67. $model->where('order_time', '>=', $start_time)
  68. ->where('order_time', '<=', $end_time);
  69. }
  70. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  71. if(! empty($data['customer_title'])) $model->where('customer_title', 'LIKE', '%'.$data['customer_title'].'%');
  72. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  73. if(! empty($data['id'])) $model->whereIn('id',$data['id']);
  74. return [true, $model];
  75. }
  76. public function statisticsRevenueCostOneAndTwo($data,$user){
  77. list($status, $model) = $this->statisticsRevenueCostOneAndTwoCommon($data, $user);
  78. if(! $status) return [false, $model];
  79. $list = $this->limit($model,'',$data);
  80. $list = $this->statisticsRevenueCostOneAndTwoFillData($list);
  81. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  82. return [true, $list];
  83. }
  84. public function statisticsRevenueCostOneAndTwoFillData($data){
  85. if(empty($data['data'])) return $data;
  86. foreach ($data['data'] as $key => $value){
  87. $data['data'][$key]['profit_rate'] = bcmul($value['profit_rate'], 100,2);
  88. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  89. }
  90. return $data;
  91. }
  92. public function statisticsRevenueCostThreeCommon($data,$user, $field = []){
  93. if(empty($field)) {
  94. $field = RevenueCost::$field_hkd_salary_main;
  95. $field[] = DB::raw('sum(payment_amount) as payment_amount');
  96. $field[] = DB::raw('sum(price_4_total) as price_4_total');
  97. $field[] = DB::raw('sum(profit) as profit');
  98. $field[] = DB::raw('max(employee_id_2) as employee_id_2');
  99. $field[] = DB::raw("MAX(COALESCE(employee_id_2_title, '')) as employee_id_2_title");
  100. }
  101. $model = RevenueCost::Clear($user,$data);
  102. $model = $model->where('del_time',0)
  103. ->where('order_type',RevenueCost::ORDER_THREE)
  104. ->select($field)
  105. ->groupby('order_id')
  106. ->orderby('id', 'desc');
  107. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  108. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  109. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  110. $model->where('order_time', '>=', $start_time)
  111. ->where('order_time', '<=', $end_time);
  112. }
  113. if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');
  114. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  115. if(! empty($data['employee_id_1'])) $model->where('employee_id_1', 'LIKE', $data['employee_id_1']);
  116. if(! empty($data['employee_id_2'])) $model->where('employee_id_2', 'LIKE', $data['employee_id_2']);
  117. if(! empty($data['employee_id_2_title'])) $model->where('employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  118. if(! empty($data['channel_finance_array'])) {
  119. $array = explode("\n", str_replace(["\r\n", "\r"], "\n", $data['channel_finance_array']));
  120. $model->whereIn('channel_finance', $array);
  121. }
  122. if(! empty($data['id'])) $model->whereIn('order_id',$data['id']);
  123. return [true, $model];
  124. }
  125. public function statisticsRevenueCostThree($data,$user){
  126. list($status, $model) = $this->statisticsRevenueCostThreeCommon($data, $user);
  127. if(! $status) return [false, $model];
  128. $list = $this->limit($model,'',$data);
  129. $list = $this->statisticsRevenueCostThreeFillData($list);
  130. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  131. return [true, $list];
  132. }
  133. public function statisticsRevenueCostThreeFillData($data){
  134. if(empty($data['data'])) return $data;
  135. foreach ($data['data'] as $key => $value){
  136. $profit_rate = $value['payment_amount'] > 0 ? bcdiv($value['profit'], $value['payment_amount'],8) : 0;
  137. $data['data'][$key]['profit_rate'] = bcmul($profit_rate, 100,2);
  138. $data['data'][$key]['order_time'] = $value['order_time'] ? date("Y-m-d", $value['order_time']) : "";
  139. }
  140. return $data;
  141. }
  142. public function statisticsRevenueCostThreeDetail($data,$user){
  143. if(empty($data['order_number'])) return [false, '回款单号不能为空'];
  144. $result = RevenueCost::where('del_time',0)
  145. ->where('order_type',RevenueCost::ORDER_THREE)
  146. ->where('order_number',$data['order_number'])
  147. ->select(RevenueCost::$field_hkd_detail)
  148. ->get()->toArray();
  149. if(empty($result)) return [false, "回款单不存在或已被删除"];
  150. $detail = [];
  151. foreach ($result as $value){
  152. $detail[] = [
  153. 'order_number' => $value['order_number_upstream'],
  154. 'customer_code' => $value['customer_code'],
  155. 'customer_title' => $value['customer_title'],
  156. 'channel_finance' => $value['channel_finance'],
  157. 'product_code' => $value['product_code'],
  158. 'product_title' => $value['product_title'],
  159. 'product_size' => $value['product_size'],
  160. 'unit' => $value['unit'],
  161. 'quantity' => $value['quantity'],
  162. 'payment_amount' => $value['payment_amount'],
  163. 'price_1' => $value['price_1'],
  164. 'price_1_total' => $value['price_1_total'],
  165. 'price_4' => $value['price_4'],
  166. 'price_4_total' => $value['price_4_total'],
  167. 'profit' => $value['profit'],
  168. 'profit_rate' => bcmul($value['profit_rate'],100,2) . '%',
  169. 'customer_profit_rate' => bcmul($value['customer_profit_rate'],100,2) . '%',
  170. 'voucher_type_title' => RevenueCost::$voucher_type[$value['voucher_type']] ?? "",
  171. ];
  172. }
  173. $footer = $this->countTotal($result, $user['header_default']);
  174. $footer['profit_rate'] = $footer['profit_rate'] . "%";
  175. $footer = array_merge( [
  176. 'order_number' => '',
  177. 'customer_code' => '',
  178. 'customer_title' => '',
  179. 'channel_finance' => '',
  180. 'product_code' => '',
  181. 'product_title' => '',
  182. 'product_size' => '',
  183. 'unit' => '',
  184. 'quantity' => '',
  185. 'payment_amount' => '',
  186. 'price_1' => '',
  187. 'price_1_total' => '',
  188. 'price_4' => '',
  189. 'price_4_total' => '',
  190. 'profit' => '',
  191. 'profit_rate' => '',
  192. 'customer_profit_rate'=> '',
  193. 'voucher_type_title' => '',
  194. ], $footer);
  195. $detail[] = $footer;
  196. $first = $result[0];
  197. $order = [
  198. 'order_number' => $data['order_number'],
  199. 'order_time' => date("Y-m-d",$first['order_time']),
  200. 'employee_id_1_title' => $first['employee_id_1_title'],
  201. 'detail' => $detail
  202. ];
  203. return [true, $order];
  204. }
  205. public function statisticsProfitCommon($data,$user, $field = []){
  206. if(empty($field)) {
  207. $field = RevenueCost::$field_hkd_profit_main;
  208. $field[] = DB::raw('COALESCE(SUM(rc.payment_amount), 0) AS payment_amount');
  209. }
  210. $type = RevenueCost::ORDER_THREE;
  211. $model = EmployeeIndex::Clear($user, $data)
  212. ->where('employee_index.del_time', 0)
  213. ->where('employee_index.type', EmployeeIndex::TYPE_THREE)
  214. ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  215. $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  216. ->where('rc.del_time', 0)
  217. ->where('rc.order_type', $type)
  218. ->whereNotNull('rc.employee_id_2')
  219. ->where('rc.employee_id_2', '<>', '')
  220. ->whereRaw('rc.order_time >= employee_index.start_time')
  221. ->whereRaw('rc.order_time <= employee_index.end_time');
  222. })
  223. ->select($field)
  224. ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  225. ->orderBy('employee_index.end_time', 'desc');
  226. // $type = RevenueCost::ORDER_THREE;
  227. // $model = EmployeeIndex::where('employee_index.del_time',0)
  228. // ->where('employee_index.type',EmployeeIndex::TYPE_THREE)
  229. // ->leftJoin(DB::raw('revenue_cost as rc'), function ($join) use ($type) {
  230. // $join->on('rc.employee_id_2', '=', 'employee_index.employee_id')
  231. // ->where('rc.del_time', 0)
  232. // ->where('rc.order_type', $type)
  233. // ->whereRaw('rc.order_time >= employee_index.start_time')
  234. // ->whereRaw('rc.order_time <= employee_index.end_time');
  235. // })
  236. // ->select($field)
  237. // ->groupBy('employee_index.employee_id', 'employee_index.start_time', 'employee_index.end_time')
  238. // ->orderBy('employee_index.end_time','desc');
  239. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){;
  240. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  241. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  242. $model->where('employee_index.start_time', '<=', $end_time)
  243. ->where('employee_index.end_time', '>=', $start_time);
  244. }
  245. if(! empty($data['employee_id_2_title'])) $model->where('rc.employee_id_2_title', 'LIKE', '%'.$data['employee_id_2_title'].'%');
  246. if(! empty($data['id'])) $model->whereIn('employee_index.id', $data['id']);
  247. return [true, $model];
  248. }
  249. public function statisticsProfit($data,$user){
  250. list($status, $model) = $this->statisticsProfitCommon($data, $user);
  251. if(! $status) return [false, $model];
  252. $list = $this->limit($model,'',$data);
  253. $list = $this->statisticsProfitFillData($list);
  254. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  255. return [true, $list];
  256. }
  257. public function statisticsProfitFillData($data){
  258. if(empty($data['data'])) return $data;
  259. //获取应发放金额需要的指标
  260. $indexes = $this->getEmployeeIndex($data['data']);
  261. //已发
  262. $indexes_give = $this->getEmployeeGiveOut($data['data']);
  263. foreach ($data['data'] as $key => $value){
  264. $start = $value['start_time'] ? date('Y-m-d',$value['start_time']) : '';
  265. $end = $value['end_time'] ? date('Y-m-d',$value['end_time']) : '';
  266. $string = "";
  267. if(! empty($start) && ! empty($end)) $string = $start . "-" . $end;
  268. $value['check_time'] = $string;
  269. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  270. $value['index_' . EmployeeIndex::TYPE_FIVE] = 0;
  271. //指标
  272. $this->makeIndex($indexes, $value, $data['data'][$key]);
  273. //应付
  274. $this->makeShouldPay($value,$data['data'][$key]);
  275. //已付
  276. $this->makePayed($indexes_give, $value,$data['data'][$key]);
  277. //未付
  278. $not_pay = bcsub($data['data'][$key]['should_pay'], $data['data'][$key]['payed'],2);
  279. $data['data'][$key]['not_pay'] = $not_pay;
  280. }
  281. return $data;
  282. }
  283. private function getEmployeeIndex($existingData)
  284. {
  285. if (empty($existingData)) {
  286. return collect();
  287. }
  288. // 取出所有涉及的 employee_id 和时间区间
  289. $employeeIds = array_column($existingData, 'employee_id_2');
  290. $start_time = array_column($existingData, 'start_time');
  291. $minStart = ! empty($start_time) ? min($start_time) : 0;
  292. $end_time = array_column($existingData, 'end_time');
  293. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  294. // 一次性查出这些员工在最大区间范围内的所有指标
  295. $results = EmployeeIndex::where('del_time', 0)
  296. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_FIVE])
  297. ->whereIn('employee_id', $employeeIds)
  298. ->where('start_time', '<=', $maxEnd)
  299. ->where('end_time', '>=', $minStart)
  300. ->select('start_time','end_time','employee_id','index','type')
  301. ->get();
  302. return $results;
  303. }
  304. private function getEmployeeGiveOut($existingData)
  305. {
  306. if (empty($existingData)) {
  307. return collect();
  308. }
  309. // 取出所有涉及的 employee_id 和时间区间
  310. $employeeIds = array_column($existingData, 'employee_id_2');
  311. $start_time = array_column($existingData, 'start_time');
  312. $minStart = ! empty($start_time) ? min($start_time) : 0;
  313. $end_time = array_column($existingData, 'end_time');
  314. $maxEnd = ! empty($end_time) ? max($end_time) : 0;
  315. // 一次性查出这些员工在最大区间范围内的所有指标
  316. $results = GiveOut::where('del_time', 0)
  317. ->whereIn('employee_id_1', $employeeIds)
  318. ->where('start_time', '<=', $maxEnd)
  319. ->where('end_time', '>=', $minStart)
  320. ->select('start_time','end_time','employee_id_1 as employee_id','give_out_amount')
  321. ->get();
  322. return $results;
  323. }
  324. private function makeIndex($indexes, $value, &$data){
  325. // 找到所有符合条件的 index(可能多个 type)
  326. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  327. return $item['employee_id'] == $value['employee_id_2']
  328. && $item['start_time'] <= $value['end_time']
  329. && $item['end_time'] >= $value['start_time'];
  330. });
  331. // 按 type 去重,只保留第一次出现的
  332. $uniqueByType = [];
  333. foreach ($matchedIndexes as $item) {
  334. $index = "index_" . $item['type'];
  335. if (! isset($uniqueByType[$index])) {
  336. $uniqueByType[$index] = $item['index'];
  337. }
  338. }
  339. $data = array_merge($value, $uniqueByType);
  340. }
  341. private function makeShouldPay($value, &$data){
  342. $index_1 = bcdiv($data['index_1'],100,2);
  343. $index_5 = bcdiv($data['index_5'],100,2);
  344. // 分红比例/2
  345. $a = bcdiv($index_5,2,2);
  346. // 季度预支分红比例/2
  347. $b = bcdiv($index_1,2,2);
  348. //(分红比例/2-季度预支分红比例/2)
  349. $c = bcsub($a, $b,2);
  350. $data['part_left'] = $c;
  351. if($value['payment_amount'] < $value['index']){
  352. //回款金额*(分红比例/2-季度预支分红比例/2);
  353. $shouldPay = bcmul($value['payment_amount'], $c,2);
  354. }else{
  355. //回款金额-季度指标金额
  356. $d = bcsub($value['payment_amount'], $value['index'],2);
  357. //(回款金额-季度指标金额)*15%
  358. $e = bcmul($d, 0.15,2);
  359. //(回款金额-季度指标金额)*15%/2
  360. $e = bcdiv($e,2,2);
  361. //(分红比例/2-季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  362. $rate = bcadd($c, $e,2);
  363. // $data['data'][$key]['rate'] = $rate;
  364. //回款金额*(分红比例/2-回款金额*季度预支分红比例/2+(回款金额-季度指标金额)*15%/2)
  365. $shouldPay = bcmul($value['payment_amount'], $rate,2);
  366. }
  367. $data['should_pay'] = $shouldPay;
  368. }
  369. private function makePayed($indexes, $value, &$data){
  370. $matchedIndexes_give = $indexes->filter(function ($item) use ($value) {
  371. return $item['employee_id'] == $value['employee_id_2']
  372. && $item['start_time'] <= $value['end_time']
  373. && $item['end_time'] >= $value['start_time'];
  374. });
  375. $give_out = 0;
  376. foreach ($matchedIndexes_give as $item) {
  377. $give_out = bcadd($item['give_out_amount'], $give_out,2);
  378. }
  379. $data['payed'] = $give_out;
  380. }
  381. public function statisticsEmployeeSalaryCommon($data,$user, $field = []){
  382. if(empty($field)) {
  383. $field = SalaryEmployee::$field;
  384. }
  385. $model = SalaryEmployee::Clear($user,$data);
  386. $model = $model->where('del_time',0)
  387. ->where('order_type',RevenueCost::ORDER_THREE)
  388. ->select($field)
  389. ->orderby('order_time', 'desc');
  390. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  391. $start_time = strtotime($data['order_time'][0] . "-01");
  392. $end_time = strtotime($data['order_time'][1] . "-01");
  393. $model->where('order_time', '>=', $start_time)
  394. ->where('order_time', '<=', $end_time);
  395. }
  396. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  397. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  398. return [true, $model];
  399. }
  400. public function statisticsEmployeeSalary($data,$user){
  401. list($status, $model) = $this->statisticsEmployeeSalaryCommon($data, $user);
  402. if(! $status) return [false, $model];
  403. $list = $this->limit($model,'',$data);
  404. $list = $this->statisticsEmployeeSalaryFillData($list);
  405. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  406. return [true, $list];
  407. }
  408. public function statisticsEmployeeSalaryFillData($data){
  409. if(empty($data['data'])) return $data;
  410. foreach ($data['data'] as $key => $value){
  411. $order_time = $value['order_time'] ? date('Y-m',$value['order_time']) : '';
  412. $data['data'][$key]['order_time'] = $order_time;
  413. }
  414. return $data;
  415. }
  416. public function statisticsFreightFeeCommon($data,$user, $field = []){
  417. if(empty($field)) {
  418. $field = FreightFee::$field;
  419. }
  420. $model = FreightFee::Clear($user,$data);
  421. $model = $model->where('del_time',0)
  422. ->select($field)
  423. ->groupby('order_time')
  424. ->orderby('order_time', 'desc');
  425. if(! empty($data['order_time'][0]) && ! empty($data['order_time'][1])){
  426. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['order_time'],false);
  427. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "单据日期的区间无效"];
  428. $model->where('order_time', '>=', $start_time)
  429. ->where('order_time', '<=', $end_time);
  430. }
  431. if(! empty($data['employee_id_1_title'])) $model->where('employee_id_1_title', 'LIKE', '%'.$data['employee_id_1_title'].'%');
  432. if(! empty($data['id'])) $model->whereIn('order_time', $data['id']);
  433. return [true, $model];
  434. }
  435. public function statisticsFreightFee($data,$user){
  436. list($status, $model) = $this->statisticsFreightFeeCommon($data, $user);
  437. if(! $status) return [false, $model];
  438. $list = $this->limit($model,'',$data);
  439. $list = $this->statisticsFreightFeeFillData($list, $user,$data);
  440. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  441. return [true, $list];
  442. }
  443. public function statisticsFreightFeeFillData($data, $user, $ergs){
  444. if(empty($data['data'])) return $data;
  445. $order_time = array_column($data['data'], 'order_time');
  446. $model = FreightFee::Clear($user,$ergs);
  447. $allFees = $model->where('del_time', 0)
  448. ->whereIn('order_time', $order_time)
  449. ->get()
  450. ->toArray();
  451. $feesByDay = [];
  452. foreach ($allFees as $f) {
  453. $feesByDay[$f['order_time']][] = $f;
  454. }
  455. foreach ($data['data'] as $key => $value) {
  456. $fees = $feesByDay[$value['order_time']] ?? [];
  457. if (empty($fees)) {
  458. $data['data'][$key]['total_amount'] = 0;
  459. continue;
  460. }
  461. // 准备 time_amount(和详情逻辑一致)
  462. $time_amount = [];
  463. foreach ($fees as $f) {
  464. if ($f['business_type_id'] == FreightFee::businessTypeNormal) {
  465. $k = $f['order_time'] . $f['area_hs'];
  466. $time_amount[$k]['amount'] = isset($time_amount[$k]['amount'])
  467. ? bcadd($f['freight_amount'], $time_amount[$k]['amount'], 4)
  468. : $f['freight_amount'];
  469. $time_amount[$k]['is_use'] = $time_amount[$k]['is_use'] ?? 0;
  470. }
  471. }
  472. // 逐条算金额
  473. $valueTotal = 0;
  474. foreach ($fees as $f) {
  475. $f = $this->calculateFreightFeeRow($f, $time_amount);
  476. $valueTotal = bcadd($valueTotal, $f['total_amount'], 4);
  477. }
  478. $data['data'][$key]['total_amount'] = $valueTotal;
  479. $order_time = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  480. $data['data'][$key]['order_time_show'] = $order_time;
  481. $data['data'][$key]['id'] = $value['order_time'];
  482. }
  483. return $data;
  484. }
  485. public function statisticsFreightFeeDetail($data, $user)
  486. {
  487. if (empty($data['order_time'])) {
  488. return [false, '单据日期不能为空'];
  489. }
  490. $model = FreightFee::Clear($user,$data);
  491. $fee = $model->where('del_time', 0)
  492. ->where('order_time', $data['order_time'])
  493. ->get()
  494. ->toArray();
  495. if (empty($fee)) {
  496. return [false, '单据日期下暂无数据'];
  497. }
  498. // 按时间+地区聚合同一天、同地区的非退货配送费
  499. $time_amount = [];
  500. foreach ($fee as $value) {
  501. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  502. $key = $value['order_time'] . $value['area_hs'];
  503. $time_amount[$key]['amount'] = isset($time_amount[$key]['amount'])
  504. ? bcadd($value['freight_amount'], $time_amount[$key]['amount'], 4)
  505. : $value['freight_amount'];
  506. $time_amount[$key]['is_use'] = $time_amount[$key]['is_use'] ?? 0;
  507. }
  508. }
  509. $return = [];
  510. foreach ($fee as $value) {
  511. $value = $this->calculateFreightFeeRow($value, $time_amount);
  512. $key = $value['order_time'] . '|' . $value['area_hs'];
  513. $return[$value['business_type_id']][$key][] = $value;
  514. }
  515. $result = [];
  516. // 需要合计的字段
  517. $sumFields = ['xs', 'weight', 'freight_amount', 'js_amount', 'customer_store_zx_fee', 'jj_fee', 'dh_fee', 'total_amount'];
  518. $sumFields_map = ['weight' => 4,'freight_amount' => 4, 'js_amount' => 4,'customer_store_zx_fee' => 4, 'jj_fee' => 4, 'dh_fee' => 4, 'total_amount' => 4];
  519. // 业务类型 日期 地区 算一张表算运费
  520. foreach ($return as $g => $group) {
  521. $g_title = FreightFee::$business[$g] ?? "";
  522. foreach ($group as $key => $val) {
  523. $tmp_key = explode('|', $key);
  524. $title = $tmp_key[1] . "(" . $g_title . ")";
  525. // 计算合计
  526. $sumRow = [];
  527. foreach ($val as $key => $row) {
  528. $order_time = $row['order_time'] ? date('Y-m-d',$row['order_time']) : '';
  529. $val[$key]['order_time_show'] = $order_time;
  530. $val[$key]['is_present_show'] = $row['is_present'] ? '是' : '否';
  531. $delivery_mode_show = FreightFee::$delivery[$row['delivery_mode']] ?? "";
  532. $val[$key]['delivery_mode_show'] = $delivery_mode_show;
  533. $val[$key]['area_range_show'] = $row['area_range'] == 1 ? '1~5吨' : '5吨以上';
  534. foreach ($sumFields as $field) {
  535. $decimals = $sumFields_map[$field] ?? 2;
  536. $sumRow[$field] = isset($sumRow[$field])
  537. ? bcadd($sumRow[$field], $row[$field], $decimals)
  538. : $row[$field];
  539. }
  540. }
  541. // 末行合计行(非合计字段设为空字符串)
  542. $footer = [];
  543. foreach ($val[0] as $field => $v) {
  544. $footer[$field] = in_array($field, $sumFields) ? $sumRow[$field] : '';
  545. }
  546. $val[] = $footer;
  547. $result[] = [
  548. 'key' => $title,
  549. 'list' => $val
  550. ];
  551. }
  552. }
  553. return [true, $result];
  554. }
  555. public function statisticsFreightFeeDetailsForExport($data, $user)
  556. {
  557. if (empty($data['order_time'])) return [];
  558. $model = FreightFee::Clear($user, $data);
  559. $orderTimes = is_array($data['order_time']) ? $data['order_time'] : [$data['order_time']];
  560. $fee = $model->where('del_time', 0)
  561. ->whereIn('order_time', $orderTimes)
  562. ->get()
  563. ->toArray();
  564. // 表头定义(所有 sheet 通用)
  565. $header = [
  566. "仓库", "销货单备注", "业务类型", "销货单号", "销货日期", "客户",
  567. "客户门店装车费单价", "业务员", "送货地址", "地区华商", "存货编码", "存货名称", "箱规",
  568. "华商重量", "门店卸货费单价(华商)", "门店卸货费单价(华商)", "赠品", "货类(华商)", "运输方式",
  569. "数量", "含税单价", "含税金额", "箱数", "总重量", "运价区间", "配送费单价", "配送费金额", "结算金额",
  570. "门店卸货费", "上楼费", "加急费", "到货装卸费", "总金额"
  571. ];
  572. if (empty($fee)) {
  573. // 返回每个请求的日期都带表头(只有表头),以便导出时每个 sheet 至少有表头
  574. $resultEmpty = [];
  575. foreach ($orderTimes as $ot) {
  576. $dateKey = date('Y-m-d', $ot);
  577. $resultEmpty[$dateKey] = [
  578. 0 => $header
  579. ];
  580. }
  581. return $resultEmpty;
  582. }
  583. // 按时间+地区聚合同一天、同地区的非退货配送费(用于 calculate 逻辑)
  584. $time_amount = [];
  585. foreach ($fee as $value) {
  586. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  587. $key = $value['order_time'] . $value['area_hs'];
  588. $time_amount[$key]['amount'] = isset($time_amount[$key]['amount'])
  589. ? bcadd($value['freight_amount'], $time_amount[$key]['amount'], 4)
  590. : $value['freight_amount'];
  591. $time_amount[$key]['is_use'] = $time_amount[$key]['is_use'] ?? 0;
  592. }
  593. }
  594. // 先按 order_time -> business_type_id -> (order_time|area_hs) 分组收集数据行
  595. $grouped = [];
  596. foreach ($fee as $value) {
  597. $value = $this->calculateFreightFeeRow($value, $time_amount);
  598. $key = $value['order_time'] . '|' . $value['area_hs'];
  599. $grouped[$value['order_time']][$value['business_type_id']][$key][] = $value;
  600. }
  601. // 构造返回:每个日期一个 sheet(键为 YYYY-MM-DD),值为数值下标数组,0 为表头
  602. $result = [];
  603. // 需要合计的字段及小数位
  604. $sumFields = ['xs','weight', 'freight_amount', 'js_amount', 'customer_store_zx_fee', 'jj_fee', 'dh_fee', 'total_amount'];
  605. $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];
  606. // 初始化每个传入日期,确保即使某个日期无数据也有表头
  607. foreach ($orderTimes as $ot) {
  608. $dateKey = date('Y-m-d', $ot);
  609. $result[$dateKey] = [];
  610. $result[$dateKey][] = $header; // index 0 为表头
  611. }
  612. // 填充数据
  613. foreach ($grouped as $order_time => $types) {
  614. $dateKey = date('Y-m-d', $order_time);
  615. // 若该日期未初始化(理论上不会),先初始化表头
  616. if (!isset($result[$dateKey])) {
  617. $result[$dateKey] = [];
  618. $result[$dateKey][] = $header;
  619. }
  620. foreach ($types as $business_type_id => $group) {
  621. $businessTitle = FreightFee::$business[$business_type_id] ?? '';
  622. foreach ($group as $key => $rows) {
  623. // 每个 key 对应一组明细(按 area_hs 分组)
  624. $sumRow = []; // 用于该分组的合计
  625. foreach ($rows as $row) {
  626. $date_show = $row['order_time'] ? date('Y-m-d', $row['order_time']) : "";
  627. $is_present_show = !empty($row['is_present']) ? '是' : '否';
  628. $delivery_mode_show = FreightFee::$delivery[$row['delivery_mode']] ?? "";
  629. $area_range_show = isset($row['area_range']) && $row['area_range'] == 1 ? '1~5吨' : '5吨以上';
  630. // 单行数据(按你指定的字段顺序)
  631. $line = [
  632. $row['warehouse_name'] ?? '', // 仓库
  633. $row['mark'] ?? '', // 销货单备注
  634. $row['business_type_title'] ?? '', // 业务类型
  635. $row['order_number'] ?? '', // 销货单号
  636. $date_show, // 销货日期
  637. $row['customer_title'] ?? '', // 客户
  638. $row['customer_store_price'] ?? 0, // 客户门店装车费单价
  639. $row['employee_id_1_title'] ?? '', // 业务员
  640. $row['address'] ?? '', // 送货地址
  641. $row['area_hs'] ?? '', // 地区华商
  642. $row['product_code'] ?? '', // 存货编码
  643. $row['product_title'] ?? '', // 存货名称
  644. $row['product_box_size'] ?? '', // 箱规
  645. $row['product_weight'] ?? 0, // 华商重量
  646. $row['product_store_price'] ?? 0, // 门店卸货费单价(华商)
  647. $row['product_store_price2'] ?? 0, // 到货装卸费单价(华商)
  648. $is_present_show, // 赠品
  649. $row['product_category'] ?? '', // 货类(华商)
  650. $delivery_mode_show, // 运输方式
  651. $row['quantity'] ?? 0, // 数量
  652. $row['price_3'] ?? 0, // 含税单价
  653. $row['price_3_total'] ?? 0, // 含税金额
  654. number_format($row['xs'] ?? 0), // 箱数
  655. $row['weight'] ?? 0, // 总重量
  656. $area_range_show, // 运价区间
  657. $row['freight_unit_price'] ?? 0, // 配送费单价
  658. $row['freight_amount'] ?? 0, // 配送费金额
  659. $row['js_amount'] ?? 0, // 结算金额
  660. $row['customer_store_zx_fee'] ?? 0, // 门店卸货费
  661. $row['sl_fee'] ?? 0, // 上楼费
  662. number_format($row['jj_fee'] ?? 0, 2), // 加急费
  663. $row['dh_fee'] ?? 0, // 到货装卸费
  664. $row['total_amount'] ?? 0, // 总金额
  665. ];
  666. $result[$dateKey][] = $line;
  667. // 累加合计
  668. foreach ($sumFields as $field) {
  669. $decimals = $sumFields_map[$field] ?? 2;
  670. $sumRow[$field] = isset($sumRow[$field])
  671. ? bcadd($sumRow[$field], $row[$field], $decimals)
  672. : ($row[$field] ?? 0);
  673. }
  674. }
  675. // 添加本分组合计行(合计位置与表头列对齐,其它非合计字段留空)
  676. $totalLine = [
  677. '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  678. $sumRow['xs'] ?? 0,
  679. $sumRow['weight'] ?? 0,
  680. '', '',
  681. $sumRow['freight_amount'] ?? 0, // 配送费金额合计
  682. $sumRow['js_amount'] ?? 0, // 结算金额合计
  683. $sumRow['customer_store_zx_fee'] ?? 0, // 门店卸货费合计
  684. $sumRow['sl_fee'] ?? 0, // 上楼费合计
  685. $sumRow['jj_fee'] ?? 0, // 加急费合计
  686. $sumRow['dh_fee'] ?? 0, // 到货装卸费合计
  687. $sumRow['total_amount'] ?? 0, // 总金额合计
  688. ];
  689. $result[$dateKey][] = $totalLine;
  690. }
  691. }
  692. }
  693. // 确保每个日期的数组是从 0 开始的连续下标(虽然我们已经按顺序 push,但为了保险)
  694. return $result;
  695. }
  696. protected function calculateFreightFeeRow(array $value, array &$time_amount)
  697. {
  698. $key = $value['order_time'] . $value['area_hs'];
  699. $js_amount = 0;
  700. if ($value['business_type_id'] == FreightFee::businessTypeNormal) {
  701. $tmp_total_arr = $time_amount[$key];
  702. // 判断是否使用最低运费
  703. if ($tmp_total_arr['amount'] < $value['min_freight_amount']) {
  704. if (!$time_amount[$key]['is_use']) {
  705. $js_amount = $value['min_freight_amount'];
  706. $time_amount[$key]['is_use'] = 1;
  707. }
  708. } else {
  709. $js_amount = $value['js_single_amount'];
  710. }
  711. } else {
  712. $js_amount = $value['js_single_amount'];
  713. }
  714. $value['js_amount'] = $js_amount;
  715. // 加急费
  716. $jj_fee = 0;
  717. if ($value['delivery_mode'] == FreightFee::deliveryModeRightNow) {
  718. $jj_fee = bcmul($js_amount, 0.5, 4);
  719. }
  720. $value['jj_fee'] = $jj_fee;
  721. // 总金额
  722. $total_amount = bcadd($js_amount, $value['customer_store_zx_fee'], 4);
  723. $total_amount = bcadd($total_amount, $value['sl_fee'], 4);
  724. $total_amount = bcadd($total_amount, $jj_fee, 4);
  725. $total_amount = bcadd($total_amount, $value['dh_fee'], 4);
  726. $value['total_amount'] = $total_amount;
  727. return $value;
  728. }
  729. public function statisticsItem($data, $user)
  730. {
  731. $model = $this->statisticsItemCommon($data, $user);
  732. $list = $this->limit($model,'',$data);
  733. $list = $this->statisticsItemFillData($list, $user,$data);
  734. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  735. return [true, $list];
  736. }
  737. public function statisticsItemCommon($data,$user, $field = []){
  738. $model = ItemReport::select('*')
  739. ->orderby('id', 'desc');
  740. if(! empty($data['order_time'])){
  741. $time = strtotime($data['order_time'] . "-01");
  742. $model->where('time', $time);
  743. }
  744. return $model;
  745. }
  746. public function statisticsItemFillData($data, $user, $ergs){
  747. if(empty($data['data'])) return $data;
  748. foreach ($data['data'] as $key => $value) {
  749. $time = $value['time'] ? date('Y-m',$value['time']) : '';
  750. $data['data'][$key]['time'] = $time;
  751. }
  752. return $data;
  753. }
  754. public function statisticsRoad($data, $user)
  755. {
  756. $model = $this->statisticsRoadCommon($data, $user);
  757. $list = $this->limit($model,'',$data);
  758. $list = $this->statisticsRoadFillData($list, $user,$data);
  759. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  760. return [true, $list];
  761. }
  762. public function statisticsRoadCommon($data,$user, $field = []){
  763. $model = ItemReportRoad::select('*')
  764. ->orderby('id', 'desc');
  765. if(! empty($data['order_time'])){
  766. $time = strtotime($data['order_time'] . "-01");
  767. $model->where('time', $time);
  768. }
  769. return $model;
  770. }
  771. public function statisticsRoadFillData($data, $user, $ergs){
  772. if(empty($data['data'])) return $data;
  773. foreach ($data['data'] as $key => $value) {
  774. $time = $value['time'] ? date('Y-m',$value['time']) : '';
  775. $data['data'][$key]['time'] = $time;
  776. $data['data'][$key]['employee_title_type_title'] = ItemReportRoad::$order_type[$value['employee_title_type']] ?? '';
  777. }
  778. return $data;
  779. }
  780. public function statisticsMan($data, $user)
  781. {
  782. $model = $this->statisticsManCommon($data, $user);
  783. $list = $this->limit($model,'',$data);
  784. $list = $this->statisticsManFillData($list, $user,$data);
  785. $list['count'] = $this->countTotal($list['data'], $user['header_default']);
  786. return [true, $list];
  787. }
  788. public function statisticsManCommon($data,$user, $field = []){
  789. $model = ItemReportMan::select('*')
  790. ->orderby('id', 'desc');
  791. if(! empty($data['order_time'])){
  792. $time = strtotime($data['order_time'] . "-01");
  793. $model->where('time', $time);
  794. }
  795. return $model;
  796. }
  797. public function statisticsManFillData($data, $user, $ergs){
  798. if(empty($data['data'])) return $data;
  799. foreach ($data['data'] as $key => $value) {
  800. $time = $value['time'] ? date('Y-m',$value['time']) : '';
  801. $data['data'][$key]['time'] = $time;
  802. }
  803. return $data;
  804. }
  805. public function getChannelReport($data)
  806. {
  807. if(empty($data['order_time'])) return [false, '年月不能为空'];
  808. $yearMonth = $data['order_time'];
  809. // 1. 解析输入
  810. [$year, $month] = explode('-', $yearMonth);
  811. $year = (int)$year;
  812. $month = (int)$month;
  813. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  814. $yearStartTs = mktime(0, 0, 0, 1, 1, $year);
  815. // 2. 获取所有相关数据
  816. $records = DB::table('item_report')
  817. ->whereBetween('time', [$yearStartTs, $currentMonthTs])
  818. ->whereNotNull('channel_details') // 可选:排除空渠道
  819. ->get();
  820. // 3. 初始化结果容器
  821. $channels = [];
  822. foreach ($records as $record) {
  823. $channel = $record->channel_details;
  824. if (!isset($channels[$channel])) {
  825. // 初始化当月和累计
  826. $channels[$channel] = [
  827. 'monthly' => array_fill_keys($this->getAmountFieldNames(), 0),
  828. 'cumulative' => array_fill_keys($this->getAmountFieldNames(), 0),
  829. ];
  830. }
  831. // 判断是否是当月
  832. $isCurrentMonth = ($record->time == $currentMonthTs);
  833. // 累加所有字段(包括 NULL 处理)
  834. foreach ($this->getAmountFieldNames() as $field) {
  835. $value = $record->$field ?? 0;
  836. $channels[$channel]['cumulative'][$field] += $value;
  837. if ($isCurrentMonth) {
  838. $channels[$channel]['monthly'][$field] += $value;
  839. }
  840. }
  841. }
  842. // 4. 插入 amount1 和 amount2,并格式化输出
  843. $finalResult = [];
  844. foreach ($channels as $channel => $data) {
  845. $finalResult[] = [
  846. 'channel' => $channel,
  847. 'monthly' => $this->injectAmount1And2($data['monthly']),
  848. 'cumulative' => $this->injectAmount1And2($data['cumulative']),
  849. ];
  850. }
  851. return $finalResult;
  852. }
  853. private function getAmountFieldNames()
  854. {
  855. return [
  856. 'receipt_amount',
  857. 'cost',
  858. 'profit',
  859. 'settle_amount',
  860. 'gl_amount',
  861. 'wl_amount',
  862. 'ht_amount',
  863. 'zk_amount',
  864. 'cx_amount',
  865. 'tg_amount',
  866. 'cl_amount',
  867. 'kq_amount',
  868. 'zp_amount',
  869. 'gg_amount',
  870. 'kd_amount',
  871. 'xsqt_amount',
  872. 'ry_amount',
  873. 'sb_amount',
  874. 'sj_amount', // 注意:包含 sj_amount
  875. ];
  876. }
  877. private function injectAmount1And2($data)
  878. {
  879. $result = [];
  880. $expenseFields = [
  881. 'settle_amount',
  882. 'gl_amount',
  883. 'wl_amount',
  884. 'ht_amount',
  885. 'zk_amount',
  886. 'cx_amount',
  887. 'tg_amount',
  888. 'cl_amount',
  889. 'kq_amount',
  890. 'zp_amount',
  891. 'gg_amount',
  892. 'kd_amount',
  893. 'xsqt_amount',
  894. 'ry_amount',
  895. 'sb_amount',
  896. 'sj_amount', // 注意:sj_amount 要包含
  897. ];
  898. // 第一步:按顺序构建带 amount1/2 的数组
  899. foreach ($data as $key => $value) {
  900. if ($key === 'sj_amount') {
  901. $result['amount1'] = '0.00';
  902. $result['sj_amount'] = number_format($value, 2, '.', '');
  903. $result['amount2'] = '0.00';
  904. } else {
  905. $result[$key] = number_format($value, 2, '.', '');
  906. }
  907. }
  908. // 第二步:计算 total(仅 expenseFields 中的字段,从 $data 原始值取,避免字符串运算)
  909. $total = 0;
  910. foreach ($expenseFields as $field) {
  911. $val = $data[$field] ?? 0;
  912. $total += is_numeric($val) ? (float)$val : 0;
  913. }
  914. $result['total'] = number_format($total, 2, '.', '');
  915. return $result;
  916. }
  917. public function getChannelReportRoad($data)
  918. {
  919. if(empty($data['order_time'])) return [false, '年月不能为空'];
  920. $yearMonth = $data['order_time'];
  921. // 1. 解析输入
  922. [$year, $month] = explode('-', $yearMonth);
  923. $year = (int)$year;
  924. $month = (int)$month;
  925. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  926. $yearStartTs = mktime(0, 0, 0, 1, 1, $year);
  927. // 2. 获取所有相关数据
  928. $records = DB::table('item_report_road')
  929. ->whereBetween('time', [$yearStartTs, $currentMonthTs])
  930. ->whereNotNull('employee_title_type') //
  931. ->get();
  932. // 3. 初始化结果容器
  933. $channels = [];
  934. foreach ($records as $record) {
  935. $channel = $record->employee_title_type;
  936. if (!isset($channels[$channel])) {
  937. // 初始化当月和累计
  938. $channels[$channel] = [
  939. 'monthly' => array_fill_keys($this->getAmountFieldNames(), 0),
  940. 'cumulative' => array_fill_keys($this->getAmountFieldNames(), 0),
  941. ];
  942. }
  943. // 判断是否是当月
  944. $isCurrentMonth = ($record->time == $currentMonthTs);
  945. // 累加所有字段(包括 NULL 处理)
  946. foreach ($this->getAmountFieldNames() as $field) {
  947. $value = $record->$field ?? 0;
  948. $channels[$channel]['cumulative'][$field] += $value;
  949. if ($isCurrentMonth) {
  950. $channels[$channel]['monthly'][$field] += $value;
  951. }
  952. }
  953. }
  954. // 4. 插入 amount1 和 amount2,并格式化输出
  955. $finalResult = [];
  956. foreach ($channels as $channel => $data) {
  957. $finalResult[] = [
  958. 'channel' => $channel,
  959. 'monthly' => $this->injectAmount1And2($data['monthly']),
  960. 'cumulative' => $this->injectAmount1And2($data['cumulative']),
  961. ];
  962. }
  963. return $finalResult;
  964. }
  965. private function getAmountFieldManNames()
  966. {
  967. return [
  968. 'receipt_amount', 'receipt_not_amount', 'cost', 'profit', 'profit_not',
  969. 'settle_amount', 'gl_amount', 'gl_not_amount', 'wl_amount', 'wl_not_amount',
  970. 'ht_amount', 'zk_amount', 'cx_amount', 'tg_amount', 'cl_amount',
  971. 'kq_amount', 'zp_amount', 'gg_amount', 'kd_amount', 'xsqt_amount',
  972. 'ry_amount', 'sb_amount', 'sj_amount', 'sj_not_amount', 'sx_amount',
  973. 'sx_not_amount', 'other_ck_amount', 'cg_amount'
  974. ];
  975. }
  976. private function injectAmountMan($data)
  977. {
  978. $result = [];
  979. // 参与 total 计算的费用字段 (排除收入、成本和利润)
  980. $expenseFields = [
  981. 'settle_amount', 'gl_amount', 'gl_not_amount', 'wl_amount', 'wl_not_amount',
  982. 'ht_amount', 'zk_amount', 'cx_amount', 'tg_amount', 'cl_amount',
  983. 'kq_amount', 'zp_amount', 'gg_amount', 'kd_amount', 'xsqt_amount',
  984. 'ry_amount', 'sb_amount', 'sj_amount', 'sj_not_amount', 'sx_amount',
  985. 'sx_not_amount', 'other_ck_amount', 'cg_amount'
  986. ];
  987. // 第一步:格式化并插入占位符
  988. foreach ($this->getAmountFieldManNames() as $key) {
  989. $val = $data[$key] ?? 0;
  990. if ($key === 'sj_amount') {
  991. $result['amount1'] = '0.00'; // 占位
  992. $result['sj_amount'] = number_format((float)$val, 2, '.', '');
  993. $result['amount2'] = '0.00'; // 占位
  994. } else {
  995. $result[$key] = number_format((float)$val, 2, '.', '');
  996. }
  997. }
  998. // 第二步:计算费用总额
  999. $total = 0;
  1000. foreach ($expenseFields as $field) {
  1001. $total += (float)($data[$field] ?? 0);
  1002. }
  1003. $result['total'] = number_format($total, 2, '.', '');
  1004. return $result;
  1005. }
  1006. public function getChannelReportMan1($data)
  1007. {
  1008. if(empty($data['order_time'])) return [false, '年月不能为空'];
  1009. $yearMonth = $data['order_time']; // 格式如 2026-02
  1010. [$year, $month] = explode('-', $yearMonth);
  1011. $year = (int)$year;
  1012. $month = (int)$month;
  1013. // 当前选择月的第一天戳
  1014. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  1015. // 去年7月1日的时间戳 (例如输入2026-02,则起始为2025-07-01)
  1016. $startTs = mktime(0, 0, 0, 7, 1, $year - 1);
  1017. // 从业务员报表获取数据
  1018. $records = DB::table('item_report_man')
  1019. ->whereBetween('time', [$startTs, $currentMonthTs])
  1020. ->get();
  1021. $channels = [];
  1022. $allFields = $this->getAmountFieldManNames();
  1023. foreach ($records as $record) {
  1024. // 以渠道财务分组
  1025. $channel = $record->channel_finance ?: '未知渠道';
  1026. if (!isset($channels[$channel])) {
  1027. $channels[$channel] = [
  1028. 'monthly' => array_fill_keys($allFields, 0),
  1029. 'cumulative' => array_fill_keys($allFields, 0),
  1030. ];
  1031. }
  1032. $isCurrentMonth = ((int)$record->time === $currentMonthTs);
  1033. foreach ($allFields as $field) {
  1034. $val = (float)($record->$field ?? 0);
  1035. // 累计去年7月至今
  1036. $channels[$channel]['cumulative'][$field] += $val;
  1037. // 仅当月
  1038. if ($isCurrentMonth) {
  1039. $channels[$channel]['monthly'][$field] += $val;
  1040. }
  1041. }
  1042. }
  1043. $finalResult = [];
  1044. foreach ($channels as $channelName => $values) {
  1045. $finalResult[] = [
  1046. 'channel' => $channelName,
  1047. 'monthly' => $this->injectAmountMan($values['monthly']),
  1048. 'cumulative' => $this->injectAmountMan($values['cumulative']),
  1049. ];
  1050. }
  1051. return $finalResult;
  1052. }
  1053. public function getChannelReportMan2($data)
  1054. {
  1055. if (empty($data['order_time'])) return [false, '年月不能为空'];
  1056. $yearMonth = $data['order_time'];
  1057. [$year, $month] = explode('-', $yearMonth);
  1058. $year = (int)$year;
  1059. $month = (int)$month;
  1060. // 1. 计算时间范围
  1061. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  1062. // 财年规则:如果当前月 >= 7月,起始是当年7月;否则是去年7月
  1063. $startYear = ($month >= 7) ? $year : $year - 1;
  1064. $startTs = mktime(0, 0, 0, 7, 1, $startYear);
  1065. // 2. 一次性获取所有相关记录
  1066. $records = DB::table('item_report_man')
  1067. ->whereBetween('time', [$startTs, $currentMonthTs])
  1068. ->get();
  1069. // 3. 定义金额字段(按 B5-B27 的顺序排列,方便后面直接填充 row)
  1070. $rowFieldMapping = [
  1071. 5 => 'receipt_amount', 6 => 'cost', 7 => 'profit',
  1072. 8 => 'settle_amount', 9 => 'gl_amount', 10 => 'wl_amount',
  1073. 11 => 'ht_amount', 12 => 'zk_amount', 13 => 'cx_amount',
  1074. 14 => 'tg_amount', 15 => 'cl_amount', 16 => 'kq_amount',
  1075. 17 => 'zp_amount', 18 => 'gg_amount', 19 => 'kd_amount',
  1076. 20 => 'xsqt_amount', 21 => 'ry_amount', 22 => 'sb_amount',
  1077. 23 => '退货亏损', 24 => 'cg_amount', 25 => 'sj_amount',
  1078. 26 => 'sx_amount', 27 => 'other_ck_amount'
  1079. ];
  1080. // 4. 初始化列容器(C到Z)
  1081. $columns = [];
  1082. $columnKeys = range('C', 'Z');
  1083. foreach ($columnKeys as $col) {
  1084. $columns[$col] = array_fill(5, 28, 0); // 5-32行,初始化为0
  1085. }
  1086. // 5. 遍历分拣数据
  1087. foreach ($records as $record) {
  1088. $empId = (int)$record->employee_id_1;
  1089. $finance = $record->channel_finance;
  1090. $isCurrent = ((int)$record->time === $currentMonthTs);
  1091. foreach ($rowFieldMapping as $rowIdx => $field) {
  1092. $val = (float)($record->$field ?? 0);
  1093. // 规则分拣 (C, D, G, H, K, L, O, Q, R, U, W)
  1094. // C: 2+社区
  1095. if ($empId === 2 && $finance === '社区') {
  1096. if ($isCurrent) $columns['C'][$rowIdx] += $val;
  1097. $columns['F'][$rowIdx] += $val; // 累计
  1098. }
  1099. // D: (2+通路) + (5+通路)
  1100. if (($empId === 2 || $empId === 5) && $finance === '通路') {
  1101. if ($isCurrent) $columns['D'][$rowIdx] += $val;
  1102. $columns['F'][$rowIdx] += $val; // 累计到F
  1103. }
  1104. // G: 3+通路
  1105. if ($empId === 3 && $finance === '通路') {
  1106. if ($isCurrent) $columns['G'][$rowIdx] += $val;
  1107. $columns['J'][$rowIdx] += $val;
  1108. }
  1109. // H: 3+联华加盟
  1110. if ($empId === 3 && $finance === '联华加盟') {
  1111. if ($isCurrent) $columns['H'][$rowIdx] += $val;
  1112. $columns['J'][$rowIdx] += $val;
  1113. }
  1114. // K: 23+通路
  1115. if ($empId === 23 && $finance === '通路') {
  1116. if ($isCurrent) $columns['K'][$rowIdx] += $val;
  1117. $columns['N'][$rowIdx] += $val;
  1118. }
  1119. // L: 23+智鲸
  1120. if ($empId === 23 && $finance === '智鲸') {
  1121. if ($isCurrent) $columns['L'][$rowIdx] += $val;
  1122. $columns['N'][$rowIdx] += $val;
  1123. }
  1124. // O: (7,8,54) + (通路,大卖场)
  1125. if (in_array($empId, [7, 8, 54]) && in_array($finance, ['通路', '大卖场'])) {
  1126. if ($isCurrent) $columns['O'][$rowIdx] += $val;
  1127. $columns['P'][$rowIdx] += $val;
  1128. }
  1129. // Q: 48+通路
  1130. if ($empId === 48 && $finance === '通路') {
  1131. if ($isCurrent) $columns['Q'][$rowIdx] += $val;
  1132. $columns['T'][$rowIdx] += $val;
  1133. }
  1134. // R: 48+大卖场
  1135. if ($empId === 48 && $finance === '大卖场') {
  1136. if ($isCurrent) $columns['R'][$rowIdx] += $val;
  1137. $columns['T'][$rowIdx] += $val;
  1138. }
  1139. // U: 行政
  1140. if ($finance === '行政') {
  1141. if ($isCurrent) $columns['U'][$rowIdx] += $val;
  1142. $columns['V'][$rowIdx] += $val;
  1143. }
  1144. // W: 鲍总
  1145. if ($finance === '鲍总') {
  1146. if ($isCurrent) $columns['W'][$rowIdx] += $val;
  1147. $columns['X'][$rowIdx] += $val;
  1148. }
  1149. }
  1150. }
  1151. // 6. 计算横向合计列
  1152. for ($i = 5; $i <= 27; $i++) {
  1153. $columns['E'][$i] = $columns['C'][$i] + $columns['D'][$i]; // 张+霍当月合计
  1154. $columns['I'][$i] = $columns['G'][$i] + $columns['H'][$i]; // 金小勇当月合计
  1155. $columns['M'][$i] = $columns['K'][$i] + $columns['L'][$i]; // 沈强当月合计
  1156. $columns['S'][$i] = $columns['Q'][$i] + $columns['R'][$i]; // 叶南汝当月合计
  1157. // Y: 当月总计 (所有当月列累加)
  1158. $columns['Y'][$i] = $columns['C'][$i] + $columns['D'][$i] + $columns['G'][$i] +
  1159. $columns['H'][$i] + $columns['K'][$i] + $columns['L'][$i] +
  1160. $columns['O'][$i] + $columns['Q'][$i] + $columns['R'][$i] +
  1161. $columns['U'][$i] + $columns['W'][$i];
  1162. // Z: 年累计总计 (所有累计列累加)
  1163. $columns['Z'][$i] = $columns['F'][$i] + $columns['J'][$i] + $columns['N'][$i] +
  1164. $columns['P'][$i] + $columns['T'][$i] + $columns['V'][$i] + $columns['X'][$i];
  1165. }
  1166. // 7. 组装最终供 Excel 填充的数组 (5行到32行)
  1167. $finalData = [];
  1168. for ($row = 5; $row <= 32; $row++) {
  1169. $rowData = [];
  1170. // 从 C 到 Z 循环取数据
  1171. foreach (range('C', 'Z') as $colLetter) {
  1172. $val = $columns[$colLetter][$row] ?? 0;
  1173. // 28-32行填空字符串,其他格式化
  1174. if ($row > 27 && $row < 32) {
  1175. $rowData[] = '';
  1176. } elseif ($row == 32) {
  1177. // 如果需要算小计可以在这里加,目前先填空字符串
  1178. $rowData[] = '';
  1179. } else {
  1180. $rowData[] = $val == 0 ? '0.00' : number_format($val, 2, '.', '');
  1181. }
  1182. }
  1183. $finalData[] = $rowData;
  1184. }
  1185. return $finalData;
  1186. }
  1187. public function getChannelReportMan($data)
  1188. {
  1189. if (empty($data['order_time'])) return [false, '年月不能为空'];
  1190. $yearMonth = $data['order_time'];
  1191. [$year, $month] = explode('-', $yearMonth);
  1192. $year = (int)$year;
  1193. $month = (int)$month;
  1194. // 1. 计算时间范围:7月财年规则
  1195. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  1196. $startYear = ($month >= 7) ? $year : $year - 1;
  1197. $startTs = mktime(0, 0, 0, 7, 1, $startYear);
  1198. // 2. 一次性获取数据
  1199. $records = DB::table('item_report_man')
  1200. ->whereBetween('time', [$startTs, $currentMonthTs])
  1201. ->get();
  1202. // 3. 字段映射 (注意 23 行,若数据库无字段则设为 null 会自动补 0)
  1203. $rowFieldMapping = [
  1204. 5 => 'receipt_amount', 6 => 'cost', 7 => 'profit',
  1205. 8 => 'settle_amount', 9 => 'gl_amount', 10 => 'wl_amount',
  1206. 11 => 'ht_amount', 12 => 'zk_amount', 13 => 'cx_amount',
  1207. 14 => 'tg_amount', 15 => 'cl_amount', 16 => 'kq_amount',
  1208. 17 => 'zp_amount', 18 => 'gg_amount', 19 => 'kd_amount',
  1209. 20 => 'xsqt_amount', 21 => 'ry_amount', 22 => 'sb_amount',
  1210. 23 => null, // 退货亏损 (不良仓),暂无字段映射,填充0
  1211. 24 => 'cg_amount', 25 => 'sj_amount',
  1212. 26 => 'sx_amount', 27 => 'other_ck_amount'
  1213. ];
  1214. // 4. 初始化列容器 (C 到 Z)
  1215. $columns = [];
  1216. $columnKeys = range('C', 'Z');
  1217. foreach ($columnKeys as $col) {
  1218. $columns[$col] = array_fill(5, 28, 0); // 覆盖 5-32 行
  1219. }
  1220. // 5. 数据分拣累加
  1221. foreach ($records as $record) {
  1222. $empId = (int)$record->employee_id_1;
  1223. $finance = $record->channel_finance;
  1224. $isCurrent = ((int)$record->time === $currentMonthTs);
  1225. foreach ($rowFieldMapping as $rowIdx => $field) {
  1226. $val = $field ? (float)($record->$field ?? 0) : 0;
  1227. // 分拣规则
  1228. // 张春勇、霍尚琳
  1229. if ($empId === 2 && $finance === '社区') {
  1230. if ($isCurrent) $columns['C'][$rowIdx] += $val;
  1231. $columns['F'][$rowIdx] += $val;
  1232. }
  1233. if (($empId === 2 || $empId === 5) && $finance === '通路') {
  1234. if ($isCurrent) $columns['D'][$rowIdx] += $val;
  1235. $columns['F'][$rowIdx] += $val;
  1236. }
  1237. // 金小勇
  1238. if ($empId === 3 && $finance === '通路') {
  1239. if ($isCurrent) $columns['G'][$rowIdx] += $val;
  1240. $columns['J'][$rowIdx] += $val;
  1241. }
  1242. if ($empId === 3 && $finance === '联华加盟') {
  1243. if ($isCurrent) $columns['H'][$rowIdx] += $val;
  1244. $columns['J'][$rowIdx] += $val;
  1245. }
  1246. // 沈强
  1247. if ($empId === 23 && $finance === '通路') {
  1248. if ($isCurrent) $columns['K'][$rowIdx] += $val;
  1249. $columns['N'][$rowIdx] += $val;
  1250. }
  1251. if ($empId === 23 && $finance === '智鲸') {
  1252. if ($isCurrent) $columns['L'][$rowIdx] += $val;
  1253. $columns['N'][$rowIdx] += $val;
  1254. }
  1255. // 王利英等组合 (O/P列)
  1256. if (in_array($empId, [7, 8, 54]) && in_array($finance, ['通路', '大卖场'])) {
  1257. if ($isCurrent) $columns['O'][$rowIdx] += $val;
  1258. $columns['P'][$rowIdx] += $val;
  1259. }
  1260. // 叶南汝
  1261. if ($empId === 48 && $finance === '通路') {
  1262. if ($isCurrent) $columns['Q'][$rowIdx] += $val;
  1263. $columns['T'][$rowIdx] += $val;
  1264. }
  1265. if ($empId === 48 && $finance === '大卖场') {
  1266. if ($isCurrent) $columns['R'][$rowIdx] += $val;
  1267. $columns['T'][$rowIdx] += $val;
  1268. }
  1269. // 行政
  1270. if ($finance === '行政') {
  1271. if ($isCurrent) $columns['U'][$rowIdx] += $val;
  1272. $columns['V'][$rowIdx] += $val;
  1273. }
  1274. // 鲍总
  1275. if ($finance === '鲍总') {
  1276. if ($isCurrent) $columns['W'][$rowIdx] += $val;
  1277. $columns['X'][$rowIdx] += $val;
  1278. }
  1279. }
  1280. }
  1281. // 6. 计算合计列与纵向小计
  1282. for ($i = 5; $i <= 27; $i++) {
  1283. // 合计列
  1284. $columns['E'][$i] = $columns['C'][$i] + $columns['D'][$i];
  1285. $columns['I'][$i] = $columns['G'][$i] + $columns['H'][$i];
  1286. $columns['M'][$i] = $columns['K'][$i] + $columns['L'][$i];
  1287. $columns['S'][$i] = $columns['Q'][$i] + $columns['R'][$i];
  1288. // Y/Z 总计
  1289. $columns['Y'][$i] = $columns['C'][$i] + $columns['D'][$i] + $columns['G'][$i] + $columns['H'][$i] +
  1290. $columns['K'][$i] + $columns['L'][$i] + $columns['O'][$i] + $columns['Q'][$i] +
  1291. $columns['R'][$i] + $columns['U'][$i] + $columns['W'][$i];
  1292. $columns['Z'][$i] = $columns['F'][$i] + $columns['J'][$i] + $columns['N'][$i] + $columns['P'][$i] +
  1293. $columns['T'][$i] + $columns['V'][$i] + $columns['X'][$i];
  1294. }
  1295. // 纵向小计 (第 32 行 = 8 到 31 行累加)
  1296. foreach ($columnKeys as $col) {
  1297. $subTotal = 0;
  1298. for ($r = 8; $r <= 31; $r++) {
  1299. $subTotal += (float)($columns[$col][$r] ?? 0);
  1300. }
  1301. $columns[$col][32] = $subTotal;
  1302. }
  1303. // 7. 最终格式化
  1304. $finalData = [];
  1305. for ($row = 5; $row <= 32; $row++) {
  1306. $rowData = [];
  1307. foreach ($columnKeys as $colLetter) {
  1308. $val = $columns[$colLetter][$row] ?? 0;
  1309. if ($row >= 28 && $row <= 31) {
  1310. $rowData[] = ''; // 预留行填空
  1311. } else {
  1312. $rowData[] = ($val == 0) ? '0.00' : number_format($val, 2, '.', '');
  1313. }
  1314. }
  1315. $finalData[] = $rowData;
  1316. }
  1317. return $finalData;
  1318. }
  1319. }