BIService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace App\Service;
  3. use App\Model\DailyDwOrder;
  4. use App\Model\DailyDwOrderDetails;
  5. use App\Model\DailyPwOrder;
  6. use App\Model\DailyPwOrderDetails;
  7. use App\Model\ExpenseClaims;
  8. use App\Model\ExpenseClaimsDetails;
  9. use App\Model\Fee;
  10. use App\Model\Item;
  11. use App\Model\MonthlyDdOrder;
  12. use App\Model\MonthlyDdOrderDetails;
  13. use App\Model\MonthlyPsOrder;
  14. use App\Model\MonthlyPsOrderDetails;
  15. use App\Model\PLeaveOverOrder;
  16. use App\Model\PLeaveOverOrderDetails;
  17. use Illuminate\Support\Facades\DB;
  18. class BIService extends Service
  19. {
  20. private function commonRule($data)
  21. {
  22. if (isset($data['time']) && !empty($data['time'])) {
  23. $start = $this->changeDateToDate($data['time'][0]);
  24. $end = $this->changeDateToDate($data['time'][1], true);
  25. $data['month_start'] = date("Y-m-d", $start);
  26. $data['month_end'] = date("Y-m-d", $end);
  27. }
  28. if (!isset($data['month_start'])) $month_start = date('Y-01-01', strtotime('-1 year'));
  29. else $month_start = date('Y-m-01', strtotime($data['month_start']));
  30. if (!isset($data['month_end'])) $month_end = date('Y-01-01', strtotime('+1 year', strtotime($month_start)));
  31. else {
  32. $start_year = date('Y', strtotime($month_start));
  33. $end_year = date('Y', strtotime($data['month_end']));
  34. if ($start_year != $end_year) return [false, "查询不得跨年!", ""];
  35. $month_end = date('Y-m-01', strtotime($data['month_end'] . ' +1 month'));
  36. }
  37. return [true, strtotime($month_start), strtotime($month_end)];
  38. }
  39. public function homePageData($data, $user)
  40. {
  41. $model = Item::TopClear($user,$data);
  42. $start_time = $model->where('del_time',0)
  43. ->orderby('id', 'desc')->value("start_time");
  44. $year = date('Y-01-01',$start_time);
  45. $data['month_start'] = $year;
  46. // $data['month_start'] = "2024-01-01";
  47. list($status, $month_start, $month_end) = $this->commonRule($data);
  48. if (!$status) return [false, $month_start];
  49. //当年项目总数
  50. $intersectCount = $model->where('start_time', '<=', $month_end) // 项目开始时间 <= 区间结束时间
  51. ->where('end_time', '>=', $month_start) // 项目结束时间 >= 区间开始时间
  52. ->count();
  53. //人员费用
  54. list($total_man, $salary_map) = $this->getEmployeeSalary($month_start, $month_end, $data, $user);
  55. //折旧费用
  56. list($total_zj, $zj_map) = $this->getDeviceSalary($month_start, $month_end, $data, $user);
  57. //费用报销
  58. list($total_other, $other_map, $return_fee) = $this->getFeeItemSalary($month_start, $month_end, $data, $user);
  59. //研发费用总额
  60. $total = bcadd(bcadd($total_man, $total_zj,3), $total_other,3);
  61. //研发费用结构
  62. $rd = [
  63. 0 => [
  64. 'title' => '人工费用',
  65. 'rate' => $total == 0 ? 0 : bcmul(bcdiv($total_man,$total,4),100,2),
  66. 'rate_unit' => '%',
  67. 'total' => $total_man,
  68. 'total_unit' => '¥',
  69. ],
  70. 1 => [
  71. 'title' => '折旧费用',
  72. 'rate' => $total == 0 ? 0 :bcmul(bcdiv($total_zj,$total,4),100,2),
  73. 'rate_unit' => '%',
  74. 'total' => $total_zj,
  75. 'total_unit' => '¥',
  76. ],
  77. 2 => [
  78. 'title' => '费用报销',
  79. 'rate' => $total == 0 ? 0 :bcmul(bcdiv($total_other,$total,4),100,2),
  80. 'rate_unit' => '%',
  81. 'total' => $total_other,
  82. 'total_unit' => '¥',
  83. ],
  84. ];
  85. //研发费用趋势
  86. $rd_trend = $this->makeTrend($month_start, $salary_map, $zj_map, $other_map);
  87. //研发费用报销占比
  88. $rd_rate = $return_fee;
  89. //加班 请假 总时长
  90. list($over_time, $leave_time) = $this->overLeave($month_start, $month_end, $data, $user);
  91. // 项目人员工时汇总
  92. $man_work = $this->manWork($month_start, $month_end, $data, $user);
  93. //加计扣除金额
  94. $statisticService = new StatisticService();
  95. $attendance = $statisticService->employeeAttendanceMonthStatistic(["year"=>$year, "s" => "/api/employeeAttendanceMonthStatistic"],$user);
  96. $discount = 0;
  97. foreach ($attendance[1]['list'] as $v){
  98. $discount += $v['jj_total_amount']*100;
  99. }
  100. return [true, [
  101. 'rd_total' => $total,
  102. 'rd_unit' => '¥',
  103. 'rd_title' => '研发费用总额', //-----
  104. 'discount_total' => round($discount/100,2),
  105. 'discount_unit' => '¥',
  106. 'discount_title' => '加计扣除金额', //------
  107. 'over_time' => $over_time, // 加班
  108. 'leave_time' => $leave_time, // 请假
  109. 'rd' => $rd, //研发费用结构
  110. 'rd_trend' => $rd_trend, //研发费用趋势
  111. 'rd_rate' => $rd_rate, // 研发费用报销占比
  112. 'man_work' => $man_work, //项目人员工时汇总
  113. 'year' => date('Y',strtotime($year)),
  114. 'item_num' => $intersectCount
  115. ]];
  116. }
  117. private function getEmployeeSalary($month_start, $month_end, $data, $user)
  118. {
  119. $monthly_ps_order = MonthlyPsOrder::Clear($user, $data)
  120. ->where('del_time', 0)
  121. ->where("month", ">=", $month_start)
  122. ->where("month", "<", $month_end)
  123. ->pluck('month','id')
  124. ->toArray();
  125. $monthly_ps_order_ids = array_keys($monthly_ps_order);
  126. $month_employee_salary = MonthlyPsOrderDetails::whereIn('main_id', $monthly_ps_order_ids)
  127. ->select("base_salary","performance_salary","other","bonus", "main_id")
  128. ->get()
  129. ->toArray();
  130. $total = 0;
  131. $salary_map = [];
  132. foreach ($month_employee_salary as $value) {
  133. $currentAmount = bcadd($value['base_salary'], $value['performance_salary'],3);
  134. $currentAmount = bcadd($currentAmount, $value['other'],3);
  135. $currentAmount = bcadd($currentAmount, $value['bonus'],3);
  136. if(isset($monthly_ps_order[$value['main_id']])){
  137. $month = $monthly_ps_order[$value['main_id']];
  138. if(isset($salary_map[$month])){
  139. $salary_map[$month] = bcadd($salary_map[$month], $currentAmount,3);
  140. }else{
  141. $salary_map[$month] = $currentAmount;
  142. }
  143. }
  144. $total = bcadd($total, $currentAmount,3);
  145. }
  146. return [$total, $salary_map];
  147. }
  148. private function getDeviceSalary($month_start, $month_end, $data, $user)
  149. {
  150. $monthly_dd_order= MonthlyDdOrder::Clear($user, $data)
  151. ->where('del_time', 0)
  152. ->where("month", ">=", $month_start)
  153. ->where("month", "<", $month_end)
  154. ->pluck('month','id')
  155. ->toArray();
  156. $monthly_dd_order_ids = array_keys($monthly_dd_order);
  157. $month_device_salary = MonthlyDdOrderDetails::whereIn('main_id', $monthly_dd_order_ids)
  158. ->select("depreciation_amount as amount", "main_id")
  159. ->get()
  160. ->toArray();
  161. $total = 0;
  162. $amount_map = [];
  163. foreach ($month_device_salary as $value) {
  164. $currentAmount = (string)$value['amount'];
  165. if(isset($monthly_dd_order[$value['main_id']])){
  166. $month = $monthly_dd_order[$value['main_id']];
  167. if(isset($amount_map[$month])){
  168. $amount_map[$month] = bcadd($amount_map[$month], $currentAmount,3);
  169. }else{
  170. $amount_map[$month] = $currentAmount;
  171. }
  172. }
  173. $total = bcadd($total, $currentAmount,3);
  174. }
  175. return [$total, $amount_map];
  176. }
  177. private function getFeeItemSalary($month_start, $month_end, $data, $user)
  178. {
  179. $e_order = ExpenseClaims::Clear($user, $data)
  180. ->where('del_time', 0)
  181. ->where("month", ">=", $month_start)
  182. ->where("month", "<", $month_end)
  183. ->pluck('month','id')
  184. ->toArray();
  185. $e_order_ids = array_keys($e_order);
  186. $e_order_detail = ExpenseClaimsDetails::whereIn('expense_claims_id', $e_order_ids)
  187. ->select("amount", "expense_claims_id as main_id", "fee_id")
  188. ->get()
  189. ->toArray();
  190. $fee = Fee::TopClear($user, $data);
  191. $fee_map = $fee->whereIn('id', array_unique(array_column($e_order_detail,'fee_id')))->pluck('title','id')->toArray();
  192. $total = 0;
  193. $amount_map = [];
  194. $fee_amount_map = [];
  195. foreach ($e_order_detail as $value) {
  196. $currentAmount = (string)$value['amount'];
  197. if(isset($e_order[$value['main_id']])){
  198. $month = $e_order[$value['main_id']];
  199. if(isset($amount_map[$month])){
  200. $amount_map[$month] = bcadd($amount_map[$month], $currentAmount,3);
  201. }else{
  202. $amount_map[$month] = $currentAmount;
  203. }
  204. }
  205. $fee_tmp = $fee_map[$value['fee_id']] ?? "";
  206. if(! empty($fee_tmp)){
  207. if(isset($fee_amount_map[$fee_tmp])){
  208. $fee_amount_map[$fee_tmp] = bcadd($fee_amount_map[$fee_tmp], $currentAmount,3);
  209. }else{
  210. $fee_amount_map[$fee_tmp] = $currentAmount;
  211. }
  212. }
  213. $total = bcadd($total, $currentAmount,3);
  214. }
  215. $return_fee = [];
  216. foreach ($fee_amount_map as $key => $value){
  217. $amount = (string)$value;
  218. $return_fee[] = [
  219. "title" => $key,
  220. "total" => $amount,
  221. "total_unit" => "元",
  222. "rate" => bcmul(bcdiv($amount,$total,4),100,2),
  223. "rate_unit" => "%"
  224. ];
  225. }unset($fee_amount_map);
  226. return [$total, $amount_map, $return_fee];
  227. }
  228. private function makeTrend($month_start, $salary_map, $zj_map, $other_map)
  229. {
  230. $trend = [];
  231. for ($i = 0; $i < 12; $i++) {
  232. // 计算每个月第一天的时间戳作为 Key
  233. $timestamp = strtotime("+$i month", $month_start);
  234. $monthName = ($i + 1) . '月';
  235. $trend[$timestamp] = [
  236. 'month' => $monthName,
  237. // 'salary' => "0.000",
  238. // 'zj' => "0.000",
  239. // 'other' => "0.000",
  240. 'total' => "0.000",
  241. ];
  242. }
  243. // 2. 将传入的 Map 数据填充进去
  244. foreach ($trend as $timestamp => &$item) {
  245. // 使用 ?? "0" 容错,并强制转为 string 保证 bcadd 精度
  246. $s = $salary_map[$timestamp] ?? "0";
  247. $z = $zj_map[$timestamp] ?? "0";
  248. $o = $other_map[$timestamp] ?? "0";
  249. // $item['salary'] = bcadd($s, "0", 3);
  250. // $item['zj'] = bcadd($z, "0", 3);
  251. // $item['other'] = bcadd($o, "0", 3);
  252. // 计算该月总计
  253. $item['total'] = bcadd(bcadd($s, $z, 3), $o, 3);
  254. }
  255. return array_values($trend);
  256. }
  257. private function overLeave($month_start, $month_end, $data, $user)
  258. {
  259. $id = PLeaveOverOrder::Clear($user, $data)
  260. ->where('del_time', 0)
  261. ->where("order_time", ">=", $month_start)
  262. ->where("order_time", "<", $month_end)
  263. ->pluck('id')
  264. ->toArray();
  265. $p = PLeaveOverOrderDetails::whereIn('main_id', $id)
  266. ->select("type", "total_min")
  267. ->get()
  268. ->toArray();
  269. $total = $total_1 = 0;
  270. foreach ($p as $value) {
  271. $total_min = (string)$value['total_min'];
  272. if($value['type'] == PLeaveOverOrderDetails::TYPE_ONE){
  273. $total = bcadd($total, $total_min,2);
  274. }else{
  275. $total_1 = bcadd($total_1, $total_min,2);
  276. }
  277. }
  278. // 最终返回或输出前转换
  279. $total_hours = bcdiv($total, 60, 2);
  280. $total_1_hours = bcdiv($total_1, 60, 2);
  281. return [$total_1_hours, $total_hours];
  282. }
  283. private function manWork($month_start, $month_end, $data, $user)
  284. {
  285. $daily_pw = DailyPwOrder::Clear($user, $data)
  286. ->where('del_time', 0)
  287. ->where("order_time", ">=", $month_start)
  288. ->where("order_time", "<", $month_end)
  289. ->select('id','item_id')
  290. ->get()->toArray();
  291. $item_map = Item::whereIn('id',array_unique(array_column($daily_pw,'item_id')))
  292. ->pluck('title','id')
  293. ->toArray();
  294. $p = DailyPwOrderDetails::whereIn('main_id', array_column($daily_pw,'id'))
  295. ->select("item_id", "total_work_min")
  296. ->get()
  297. ->toArray();
  298. $total = 0;
  299. $map = [];
  300. foreach ($p as $value) {
  301. $total_min = (string)$value['total_work_min'];
  302. if(isset($map[$value['item_id']])){
  303. $map[$value['item_id']] = bcadd($map[$value['item_id']], $total_min,2);
  304. }else{
  305. $map[$value['item_id']] = $total_min;
  306. }
  307. $total = bcadd($total, $total_min,2);
  308. }
  309. $return = [];
  310. foreach ($map as $key => $value){
  311. $rate = bcmul(bcdiv($value, $total,4),100,2);
  312. $total_hours = bcdiv($value, 60, 2);
  313. $return[] = [
  314. 'title' => $item_map[$key] ?? "",
  315. 'total_work_hour' => $total_hours,
  316. 'total_work_hour_unit' => "小时",
  317. "rate" => $rate,
  318. "rate_unit" => "%",
  319. ];
  320. }
  321. return $return;
  322. }
  323. public function cockpit($data, $user)
  324. {
  325. // 1. 声明时区对象
  326. $utcZone = new \DateTimeZone('UTC');
  327. $localZone = new \DateTimeZone('Asia/Shanghai'); // 你的数据库/服务器本地时区(北京时间)
  328. if (!empty($data['time'][0]) && !empty($data['time'][1])) {
  329. // 【A. 满足 employeeSalarySummary 的 UTC 干净时间】
  330. // 提取前端 ISO 串中的纯日期,强制转为 UTC 视角的开始和结束
  331. $rawStartUtc = new \DateTime($data['time'][0], $utcZone);
  332. $rawEndUtc = new \DateTime($data['time'][1], $utcZone);
  333. $startDateTimeUtc = new \DateTime($rawStartUtc->format('Y-m-d') . ' 00:00:00', $utcZone);
  334. $endDateTimeUtc = new \DateTime($rawEndUtc->format('Y-m-d') . ' 23:59:59', $utcZone);
  335. // 【B. 满足 getManWork 的本地 00点和23点 时间戳】
  336. $startTimestampLocal = (new \DateTime($rawStartUtc->format('Y-m-d') . ' 00:00:00', $localZone))->getTimestamp();
  337. $endTimestampLocal = (new \DateTime($rawEndUtc->format('Y-m-d') . ' 23:59:59', $localZone))->getTimestamp();
  338. } else {
  339. // 【没传参时的默认兜底逻辑】
  340. // UTC 视角的当月起止
  341. $startDateTimeUtc = new \DateTime('first day of this month 00:00:00', $utcZone);
  342. $endDateTimeUtc = new \DateTime('last day of this month 23:59:59', $utcZone);
  343. // 本地视角的当月起止时间戳
  344. $startTimestampLocal = (new \DateTime('first day of this month 00:00:00', $localZone))->getTimestamp();
  345. $endTimestampLocal = (new \DateTime('last day of this month 23:59:59', $localZone))->getTimestamp();
  346. }
  347. $data['start_time'] = $startTimestampLocal;
  348. $data['end_time'] = $endTimestampLocal;
  349. $array = $this->getManWork($data, $user);
  350. // 当月设备工时信息
  351. $array2 = $this->getDeviceWork($data, $user);
  352. $array = array_merge_recursive($array, $array2);
  353. $array3 = $this->getDeviceOldWork($data, $user);
  354. $array = array_merge_recursive($array, $array3);
  355. $array3 = $this->getFeeOrder($data, $user);
  356. $array = array_merge_recursive($array, $array3);
  357. $passTime = [
  358. $startDateTimeUtc->format('Y-m-d'),
  359. $endDateTimeUtc->format('Y-m-d')
  360. ];
  361. list($status, $return) = (new StatisticService())->employeeSalarySummary(['time' => $passTime], $user);
  362. if(! $status) return [false, $return];
  363. $total = array_sum(array_column($return,'money'));
  364. $array['rd_total_money'] = $total;
  365. return [true, $array];
  366. }
  367. private function getManWork($data, $user){
  368. $model = DailyPwOrder::Clear($user, $data);
  369. $id = $model->where('del_time', 0)
  370. ->where('order_time', '>=', $data['start_time'])
  371. ->where('order_time', '<=', $data['end_time'])
  372. ->pluck('id')
  373. ->toArray();
  374. $details = DailyPwOrderDetails::where('del_time', 0)
  375. ->whereIn('main_id', $id) // 💡 避坑提示:原代码如果是数组 $id,这里建议用 whereIn
  376. ->select('employee_id', 'total_work_min')
  377. ->get()->toArray();
  378. // 1. 计算当月总工时(将二维数组中所有 'total_work_min' 字段求和)
  379. $totalWorkMin = array_sum(array_column($details, 'total_work_min'));
  380. // 2. 如果你需要把分钟数转换为“小时”,可以除以 60(保留两位小数,根据业务需要决定是否转换)
  381. $totalWorkHours = round($totalWorkMin / 60, 2);
  382. // 3. 计算参与人员总数(先提取所有员工ID,再通过 array_unique 去重,最后 count 计算数量)
  383. $employeeIds = array_column($details, 'employee_id');
  384. $uniqueEmployeeIds = array_unique($employeeIds);
  385. $totalEmployees = count($uniqueEmployeeIds);
  386. return [
  387. 'man_total_work_hours' => $totalWorkHours, // 当月总工时
  388. 'man_total_employees' => $totalEmployees, // 参与人员总数
  389. ];
  390. }
  391. private function getDeviceWork($data, $user){
  392. $model = DailyDwOrder::Clear($user, $data);
  393. $id = $model->where('del_time', 0)
  394. ->where('order_time', '>=', $data['start_time'])
  395. ->where('order_time', '<=', $data['end_time'])
  396. ->pluck('id')
  397. ->toArray();
  398. $details = DailyDwOrderDetails::where('del_time', 0)
  399. ->whereIn('main_id', $id) // 💡 避坑提示:原代码如果是数组 $id,这里建议用 whereIn
  400. ->select('device_id', 'total_work_min')
  401. ->get()->toArray();
  402. // 1. 计算当月总工时(将二维数组中所有 'total_work_min' 字段求和)
  403. $totalWorkMin = array_sum(array_column($details, 'total_work_min'));
  404. // 2. 如果你需要把分钟数转换为“小时”,可以除以 60(保留两位小数,根据业务需要决定是否转换)
  405. $totalWorkHours = round($totalWorkMin / 60, 2);
  406. $employeeIds = array_column($details, 'device_id');
  407. $uniqueEmployeeIds = array_unique($employeeIds);
  408. $totalEmployees = count($uniqueEmployeeIds);
  409. return [
  410. 'device_total_work_hours' => $totalWorkHours, // 当月总工时
  411. 'device_total_num' => $totalEmployees, // 参与人员总数
  412. ];
  413. }
  414. private function getDeviceOldWork($data, $user){
  415. $model = MonthlyDdOrder::Clear($user, $data);
  416. $id = $model->where('del_time', 0)
  417. ->where('month', '>=', $data['start_time'])
  418. ->where('month', '<=', $data['end_time'])
  419. ->pluck('id')
  420. ->toArray();
  421. $details = MonthlyDdOrderDetails::where('del_time', 0)
  422. ->whereIn('main_id', $id)
  423. ->select('device_id', 'depreciation_amount')
  424. ->get()->toArray();
  425. $totalWorkMin = array_sum(array_column($details, 'depreciation_amount'));
  426. return [
  427. 'device_total_money' => $totalWorkMin,
  428. ];
  429. }
  430. private function getFeeOrder($data, $user){
  431. $model = ExpenseClaims::Clear($user, $data);
  432. $id = $model->where('del_time', 0)
  433. ->where('month', '>=', $data['start_time'])
  434. ->where('month', '<=', $data['end_time'])
  435. ->pluck('id')
  436. ->toArray();
  437. $details = ExpenseClaimsDetails::where('del_time', 0)
  438. ->whereIn('expense_claims_id', $id)
  439. ->select('item_id', 'amount')
  440. ->get()->toArray();
  441. $totalWorkMin = array_sum(array_column($details, 'amount'));
  442. $employeeIds = array_column($details, 'item_id');
  443. $uniqueEmployeeIds = array_unique($employeeIds);
  444. $totalEmployees = count($uniqueEmployeeIds);
  445. return [
  446. 'fee_total_money' => $totalWorkMin,
  447. 'fee_total_num' => $totalEmployees,
  448. ];
  449. }
  450. }