StatisticsService.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  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. public function getChannelReportItem1($data)
  1320. {
  1321. if (empty($data['order_time'])) return [false, '年月不能为空'];
  1322. $yearMonth = $data['order_time'];
  1323. [$year, $month] = explode('-', $yearMonth);
  1324. $year = (int)$year;
  1325. $month = (int)$month;
  1326. // 1. 计算时间范围:7月财年规则
  1327. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  1328. $startYear = ($month >= 7) ? $year : $year - 1;
  1329. $startTs = mktime(0, 0, 0, 7, 1, $startYear);
  1330. // 2. 一次性获取数据
  1331. $records = DB::table('item_report')
  1332. ->whereBetween('time', [$startTs, $currentMonthTs])
  1333. ->get();
  1334. // 3. 字段映射 (注意 24 行,若数据库无字段则设为 null 会自动补 0)
  1335. $rowFieldMapping = [
  1336. 5 => 'receipt_amount', 6 => 'pk_amount', 7 => 'cost', 8 => 'profit',
  1337. 9 => 'settle_amount', 10 => 'gl_amount', 11 => 'wl_amount',
  1338. 12 => 'ht_amount', 13 => 'zk_amount', 14 => 'cx_amount',
  1339. 15 => 'tg_amount', 16 => 'cl_amount', 17 => 'kq_amount',
  1340. 18 => 'zp_amount', 19 => 'gg_amount', 20 => 'kd_amount',
  1341. 21 => 'xsqt_amount', 22 => 'ry_amount', 23 => 'sb_amount',
  1342. 24 => null, // 退货亏损 (不良仓),暂无字段映射,填充0
  1343. 25 => 'cg_amount', 26 => 'sj_amount',
  1344. 27 => 'sx_amount', 28 => 'other_ck_amount'
  1345. ];
  1346. // 4. 初始化列容器 (C 到 Z)
  1347. $columns = [];
  1348. $columnKeys = range('C', 'AB');
  1349. foreach ($columnKeys as $col) {
  1350. $columns[$col] = array_fill(5, 33, 0); // 覆盖 5-33 行
  1351. }
  1352. // 5. 数据分拣累加
  1353. foreach ($records as $record) {
  1354. $channel_details = $record->channel_details;
  1355. $isCurrent = ((int)$record->time === $currentMonthTs);
  1356. foreach ($rowFieldMapping as $rowIdx => $field) {
  1357. $val = $field ? (float)($record->$field ?? 0) : 0;
  1358. if ($channel_details === '大卖场') {
  1359. if ($isCurrent) $columns['C'][$rowIdx] += $val;
  1360. $columns['F'][$rowIdx] += $val;
  1361. }
  1362. if (($empId === 2 || $empId === 5) && $finance === '通路') {
  1363. if ($isCurrent) $columns['D'][$rowIdx] += $val;
  1364. $columns['F'][$rowIdx] += $val;
  1365. }
  1366. // 金小勇
  1367. if ($empId === 3 && $finance === '通路') {
  1368. if ($isCurrent) $columns['G'][$rowIdx] += $val;
  1369. $columns['J'][$rowIdx] += $val;
  1370. }
  1371. if ($empId === 3 && $finance === '联华加盟') {
  1372. if ($isCurrent) $columns['H'][$rowIdx] += $val;
  1373. $columns['J'][$rowIdx] += $val;
  1374. }
  1375. // 沈强
  1376. if ($empId === 23 && $finance === '通路') {
  1377. if ($isCurrent) $columns['K'][$rowIdx] += $val;
  1378. $columns['N'][$rowIdx] += $val;
  1379. }
  1380. if ($empId === 23 && $finance === '智鲸') {
  1381. if ($isCurrent) $columns['L'][$rowIdx] += $val;
  1382. $columns['N'][$rowIdx] += $val;
  1383. }
  1384. // 王利英等组合 (O/P列)
  1385. if (in_array($empId, [7, 8, 54]) && in_array($finance, ['通路', '大卖场'])) {
  1386. if ($isCurrent) $columns['O'][$rowIdx] += $val;
  1387. $columns['P'][$rowIdx] += $val;
  1388. }
  1389. // 叶南汝
  1390. if ($empId === 48 && $finance === '通路') {
  1391. if ($isCurrent) $columns['Q'][$rowIdx] += $val;
  1392. $columns['T'][$rowIdx] += $val;
  1393. }
  1394. if ($empId === 48 && $finance === '大卖场') {
  1395. if ($isCurrent) $columns['R'][$rowIdx] += $val;
  1396. $columns['T'][$rowIdx] += $val;
  1397. }
  1398. // 行政
  1399. if ($finance === '行政') {
  1400. if ($isCurrent) $columns['U'][$rowIdx] += $val;
  1401. $columns['V'][$rowIdx] += $val;
  1402. }
  1403. // 鲍总
  1404. if ($finance === '鲍总') {
  1405. if ($isCurrent) $columns['W'][$rowIdx] += $val;
  1406. $columns['X'][$rowIdx] += $val;
  1407. }
  1408. }
  1409. }
  1410. // 6. 计算合计列与纵向小计
  1411. for ($i = 5; $i <= 27; $i++) {
  1412. // 合计列
  1413. $columns['E'][$i] = $columns['C'][$i] + $columns['D'][$i];
  1414. $columns['I'][$i] = $columns['G'][$i] + $columns['H'][$i];
  1415. $columns['M'][$i] = $columns['K'][$i] + $columns['L'][$i];
  1416. $columns['S'][$i] = $columns['Q'][$i] + $columns['R'][$i];
  1417. // Y/Z 总计
  1418. $columns['Y'][$i] = $columns['C'][$i] + $columns['D'][$i] + $columns['G'][$i] + $columns['H'][$i] +
  1419. $columns['K'][$i] + $columns['L'][$i] + $columns['O'][$i] + $columns['Q'][$i] +
  1420. $columns['R'][$i] + $columns['U'][$i] + $columns['W'][$i];
  1421. $columns['Z'][$i] = $columns['F'][$i] + $columns['J'][$i] + $columns['N'][$i] + $columns['P'][$i] +
  1422. $columns['T'][$i] + $columns['V'][$i] + $columns['X'][$i];
  1423. }
  1424. // 纵向小计 (第 32 行 = 8 到 31 行累加)
  1425. foreach ($columnKeys as $col) {
  1426. $subTotal = 0;
  1427. for ($r = 8; $r <= 31; $r++) {
  1428. $subTotal += (float)($columns[$col][$r] ?? 0);
  1429. }
  1430. $columns[$col][32] = $subTotal;
  1431. }
  1432. // 7. 最终格式化
  1433. $finalData = [];
  1434. for ($row = 5; $row <= 32; $row++) {
  1435. $rowData = [];
  1436. foreach ($columnKeys as $colLetter) {
  1437. $val = $columns[$colLetter][$row] ?? 0;
  1438. if ($row >= 28 && $row <= 31) {
  1439. $rowData[] = ''; // 预留行填空
  1440. } else {
  1441. $rowData[] = ($val == 0) ? '0.00' : number_format($val, 2, '.', '');
  1442. }
  1443. }
  1444. $finalData[] = $rowData;
  1445. }
  1446. return $finalData;
  1447. }
  1448. public function getChannelReportItem($data)
  1449. {
  1450. if (empty($data['order_time'])) return [false, '年月不能为空'];
  1451. $yearMonth = $data['order_time'];
  1452. [$year, $month] = explode('-', $yearMonth);
  1453. $year = (int)$year;
  1454. $month = (int)$month;
  1455. // 1. 财年计算 (7月起算)
  1456. $currentMonthTs = mktime(0, 0, 0, $month, 1, $year);
  1457. $startYear = ($month >= 7) ? $year : $year - 1;
  1458. $startTs = mktime(0, 0, 0, 7, 1, $startYear);
  1459. // 2. 获取数据
  1460. $records = DB::table('item_report')
  1461. ->whereBetween('time', [$startTs, $currentMonthTs])
  1462. ->get();
  1463. // 3. 字段映射 (严格对应 B 列 5-28 行项目)
  1464. $rowFieldMapping = [
  1465. 5 => 'receipt_amount', 6 => 'pk_amount', 7 => 'cost', 8 => 'profit',
  1466. 9 => 'settle_amount', 10 => 'gl_amount', 11 => 'wl_amount', 12 => 'ht_amount',
  1467. 13 => 'zk_amount', 14 => 'cx_amount', 15 => 'tg_amount', 16 => 'cl_amount',
  1468. 17 => 'kq_amount', 18 => 'zp_amount', 19 => 'gg_amount', 20 => 'kd_amount',
  1469. 21 => 'xsqt_amount', 22 => 'ry_amount', 23 => 'sb_amount',
  1470. 24 => null, // 退货亏损 (不良仓) 预留映射位
  1471. 25 => 'cg_amount', 26 => 'sj_amount', 27 => 'sx_amount', 28 => 'other_ck_amount'
  1472. ];
  1473. // 4. 初始化列容器 (C 到 AB, 即第 3 列到第 28 列)
  1474. $columnKeys = [];
  1475. for ($i = 3; $i <= 28; $i++) {
  1476. $columnKeys[] = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i);
  1477. }
  1478. $columns = [];
  1479. foreach ($columnKeys as $col) {
  1480. $columns[$col] = array_fill(5, 29, 0); // 初始化 5-33 行
  1481. }
  1482. // 渠道名称与其起始列(当月列)的映射
  1483. $channelMap = [
  1484. '大卖场' => 'C',
  1485. '杭州大红鹰超市有限公司' => 'E',
  1486. '杭州宏祐贸易有限公司' => 'G',
  1487. '联华加盟' => 'I',
  1488. '社区' => 'K',
  1489. '通路' => 'M',
  1490. '浙江汇德隆食品有限公司' => 'O',
  1491. '浙江灵峰教育后勤管理有限公司' => 'Q',
  1492. '浙江物联电子商务有限公司' => 'S',
  1493. '浙江新宇贸易有限公司' => 'U',
  1494. '智鲸' => 'W',
  1495. '行政' => 'Y',
  1496. ];
  1497. // 5. 分拣累加
  1498. foreach ($records as $record) {
  1499. $channel = $record->channel_details;
  1500. $isCurrent = ((int)$record->time === $currentMonthTs);
  1501. if (isset($channelMap[$channel])) {
  1502. $curCol = $channelMap[$channel]; // 当月列
  1503. // 安全获取下一列(累计列)字母,避免 chr() 处理双字母失败
  1504. $accCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(
  1505. \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($curCol) + 1
  1506. );
  1507. foreach ($rowFieldMapping as $rowIdx => $field) {
  1508. $val = $field ? (float)($record->$field ?? 0) : 0;
  1509. if ($isCurrent) $columns[$curCol][$rowIdx] += $val;
  1510. $columns[$accCol][$rowIdx] += $val;
  1511. }
  1512. }
  1513. }
  1514. // 6. 计算横向合计 (AA, AB) 与 纵向小计 (第 33 行)
  1515. $channelStartCols = array_values($channelMap);
  1516. for ($row = 5; $row <= 28; $row++) {
  1517. foreach ($channelStartCols as $sCol) {
  1518. $aCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(
  1519. \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($sCol) + 1
  1520. );
  1521. $columns['AA'][$row] += $columns[$sCol][$row];
  1522. $columns['AB'][$row] += $columns[$aCol][$row];
  1523. }
  1524. }
  1525. // 计算纵向小计 (第 33 行 = 9 到 28 行的累加,跳过预留行)
  1526. foreach ($columnKeys as $col) {
  1527. $subTotal = 0;
  1528. for ($r = 9; $r <= 28; $r++) {
  1529. $subTotal += (float)($columns[$col][$r] ?? 0);
  1530. }
  1531. $columns[$col][33] = $subTotal;
  1532. }
  1533. // 7. 最终格式化输出
  1534. $finalData = [];
  1535. for ($row = 5; $row <= 33; $row++) {
  1536. // 关键:29-32行我们直接不生成数据,或者生成空
  1537. if ($row >= 29 && $row <= 32) continue;
  1538. $rowData = [];
  1539. foreach ($columnKeys as $colLetter) {
  1540. $val = $columns[$colLetter][$row] ?? 0;
  1541. $rowData[] = ($val == 0) ? '0.00' : number_format($val, 2, '.', '');
  1542. }
  1543. // 使用行号作为 Key
  1544. $finalData[$row] = $rowData;
  1545. }
  1546. return $finalData;
  1547. }
  1548. }