GluSalaryCalculationService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. <?php
  2. namespace app\service;
  3. /**
  4. * 糊盒工资计算服务
  5. */
  6. class GluSalaryCalculationService
  7. {
  8. /**
  9. * 执行糊盒工资计算
  10. * @param array $params
  11. * @return array
  12. */
  13. public function execute(array $params)
  14. {
  15. try {
  16. if (empty($params['month']) || empty($params['startDay']) || empty($params['endDay'])) {
  17. return ['success' => false, 'message' => '参数错误'];
  18. }
  19. $where = ['a.sczl_rq' => ['between', [$params['startDay'] . ' 00:00:00', $params['endDay'] . ' 23:59:59']]];
  20. $filds = "a.sczl_gdbh as 工单编号,a.sczl_gxmc as 工序名称,a.sczl_cl as 产量,a.sczl_rq as 日期,
  21. a.sczl_dedh as 定额代号,d.日定额 as 日定额,a.工价系数,a.保养工时,a.装版工时,a.异常工时,a.设备运行工时,a.role,a.sczl_jtbh,b.Gd_cpdh,b.Gd_cpmc,a.price";
  22. $list = db('设备_糊盒报工资料')
  23. ->alias('a')
  24. ->join('工单_基本资料 b', 'a.sczl_gdbh = b.Gd_gdbh ', 'left')
  25. ->join('dic_lzde d', 'a.sczl_dedh = d.sys_bh', 'left')
  26. ->field($filds)
  27. ->where($where)
  28. ->group('a.Uid')
  29. ->select();
  30. $pieceData = [];
  31. foreach ($list as $v) {
  32. $result = $this->salaryCalculationClass($v['role']);
  33. if ($this->isManualMachine($v['sczl_jtbh'])) {
  34. $wageList = $this->calculateManualPieceWages($v, $result);
  35. } else {
  36. $wageList = $this->calculateRegularPieceWages($v, $result);
  37. }
  38. foreach ($wageList as $wageItem) {
  39. $pieceData[] = $this->buildPieceSalarySummaryRow([
  40. 'sczl_gdbh' => $v['工单编号'],
  41. 'sczl_gxmc' => $v['工序名称'],
  42. 'sczl_rq' => $v['日期'],
  43. 'sczl_cl' => $v['产量'],
  44. 'sczl_dedh' => $v['定额代号'],
  45. '工价系数' => $v['工价系数'],
  46. '保养工时' => $v['保养工时'],
  47. '装版工时' => $v['装版工时'],
  48. '异常工时' => $v['异常工时'],
  49. '设备运行工时' => $v['设备运行工时'],
  50. 'sczl_jtbh' => $v['sczl_jtbh'],
  51. 'cpdh' => $v['Gd_cpdh'],
  52. 'cpmc' => $v['Gd_cpmc'],
  53. 'bh' => $wageItem['bh'],
  54. 'rate' => $wageItem['rate'],
  55. 'name' => $wageItem['name'],
  56. 'salary' => $wageItem['wage'],
  57. 'price' => $v['price'],
  58. 'sys_id' => $params['sys_id'] ?? '',
  59. ]);
  60. }
  61. }
  62. $teamres = $this->teamTimekeepCalculation($params['month']);
  63. $timekeepres = $this->calculateTimekeepSalary($params['month']);
  64. $timekeepData = $this->mergeTimekeepSalaryData($teamres, $timekeepres);
  65. $timekeepInsert = [];
  66. foreach ($timekeepData as $item) {
  67. $timekeepInsert[] = $this->buildTimekeepSalarySummaryRow([
  68. 'sczl_rq' => $item['sczl_rq'] . ' 00:00:00',
  69. 'bh' => $item['bh'],
  70. 'name' => $item['姓名'],
  71. 'time_salary' => $item['salary'],
  72. 'time_price' => $item['price'],
  73. 'time_duration' => $item['duration'],
  74. 'remark' => $item['remark'] ?? '',
  75. 'sys_id' => $params['sys_id'] ?? '',
  76. ]);
  77. }
  78. $insertData = array_merge($pieceData, $timekeepInsert);
  79. if (empty($insertData)) {
  80. return ['success' => false, 'message' => '无可保存的工资数据'];
  81. }
  82. db('糊盒工资汇总')->where('sczl_rq', 'like', $params['month'] . '%')->delete();
  83. $sql = db('糊盒工资汇总')->fetchSql(true)->insertAll($insertData);
  84. $res = db()->query($sql);
  85. if ($res === false) {
  86. return ['success' => false, 'message' => '工资数据保存失败'];
  87. }
  88. return [
  89. 'success' => true,
  90. 'message' => '成功',
  91. 'piece_count' => count($pieceData),
  92. 'timekeep_count' => count($timekeepInsert),
  93. 'total_count' => count($insertData),
  94. ];
  95. } catch (\Exception $e) {
  96. return ['success' => false, 'message' => '糊盒工资计算失败: ' . $e->getMessage()];
  97. }
  98. }
  99. protected function salaryCalculationClass($role)
  100. {
  101. // 构建查询对象
  102. $query = db('糊盒报工班组')->alias('a')->where('a.id', $role);
  103. // 构建字段列表
  104. $fieldParts = [];
  105. // 添加 bh 和 rate 字段
  106. for ($i = 1; $i <= 30; $i++) {
  107. $fieldParts[] = "a.bh{$i}";
  108. $fieldParts[] = "a.rate{$i}";
  109. }
  110. // 添加 JOIN 和员工姓名字段
  111. for ($i = 1; $i <= 30; $i++) {
  112. $table = 'b' . $i;
  113. $fieldParts[] = "{$table}.员工姓名 as 员工姓名{$i}";
  114. $query->join("人事_基本资料 {$table}", "a.bh{$i} = {$table}.员工编号", 'left');
  115. }
  116. // 设置字段
  117. $query->field(implode(',', $fieldParts));
  118. return $query->find();
  119. }
  120. /**
  121. * 判断是否手工机台
  122. * @param string $jtbh
  123. * @return bool
  124. */
  125. protected function isManualMachine($jtbh)
  126. {
  127. return stripos((string)$jtbh, 'SG') !== false;
  128. }
  129. /**
  130. * 员工编号是否参与工资计算(仅纯数字编号)
  131. * @param mixed $bh
  132. * @return bool
  133. */
  134. protected function isValidEmployeeBh($bh)
  135. {
  136. $bh = trim((string)$bh);
  137. return $bh !== '' && $bh !== '0000' && ctype_digit($bh);
  138. }
  139. /**
  140. * 普通机台计件工资
  141. * @param array $report
  142. * @param array $classResult
  143. * @return array
  144. */
  145. protected function calculateRegularPieceWages(array $report, array $classResult)
  146. {
  147. $wageList = [];
  148. $salary = (float)$report['产量'] * (float)$report['price'];
  149. for ($i = 1; $i <= 30; $i++) {
  150. $bh = trim($classResult['bh' . $i] ?? '');
  151. if (!$this->isValidEmployeeBh($bh)) {
  152. continue;
  153. }
  154. $wageList[] = [
  155. 'bh' => $bh,
  156. 'name' => $classResult['员工姓名' . $i] ?? '',
  157. 'rate' => $classResult['rate' . $i] ?? '',
  158. 'wage' => floatval(number_format($salary * (float)$classResult['rate' . $i], 2, '.', '')),
  159. ];
  160. }
  161. return $wageList;
  162. }
  163. /**
  164. * 手工机台计件超产工资
  165. * @param array $report
  166. * @param array $classResult
  167. * @return array
  168. */
  169. protected function calculateManualPieceWages(array $report, array $classResult)
  170. {
  171. $employees = [];
  172. for ($i = 1; $i <= 30; $i++) {
  173. $bh = trim($classResult['bh' . $i] ?? '');
  174. if (!$this->isValidEmployeeBh($bh)) {
  175. continue;
  176. }
  177. $employees[] = [
  178. 'bh' => $bh,
  179. 'name' => $classResult['员工姓名' . $i] ?? '',
  180. 'rate' => $classResult['rate' . $i] ?? '',
  181. ];
  182. }
  183. if (empty($employees)) {
  184. return [];
  185. }
  186. $hireDates = db('人事_基本资料')
  187. ->whereIn('员工编号', array_column($employees, 'bh'))
  188. ->column('聘用日期', '员工编号');
  189. $totalOutput = (float)$report['产量'];
  190. $dailyQuota = (float)$report['日定额'];
  191. if ($dailyQuota <= 0) {
  192. $dailyQuota = (float)$report['定额代号'];
  193. }
  194. $unitPrice = (float)$report['price'];
  195. $reportDate = $report['日期'];
  196. $totalCount = count($employees);
  197. $countGt3 = 0;
  198. $count8to15 = 0;
  199. $countGt15 = 0;
  200. $allPiece = true;
  201. foreach ($employees as &$employee) {
  202. $workDays = $this->getEmployeeTenureDays($employee['bh'], $reportDate, $hireDates);
  203. $employee['work_days'] = $workDays;
  204. if ($workDays > 3) {
  205. $countGt3++;
  206. }
  207. if ($workDays >= 8 && $workDays <= 15) {
  208. $count8to15++;
  209. }
  210. if ($workDays > 15) {
  211. $countGt15++;
  212. }
  213. if ($workDays <= 7) {
  214. $allPiece = false;
  215. }
  216. }
  217. unset($employee);
  218. $wageList = [];
  219. if ($allPiece) {
  220. $overPerPerson = $totalCount > 0
  221. ? max(0, ($totalOutput - $dailyQuota * $totalCount) * $unitPrice / $totalCount)
  222. : 0;
  223. foreach ($employees as $employee) {
  224. $wageList[] = [
  225. 'bh' => $employee['bh'],
  226. 'name' => $employee['name'],
  227. 'rate' => $employee['rate'],
  228. 'wage' => floatval(number_format($overPerPerson, 2, '.', '')),
  229. ];
  230. }
  231. return $wageList;
  232. }
  233. $value1 = $countGt3 > 0
  234. ? max(0, ($totalOutput - $dailyQuota * $countGt3) * $unitPrice)
  235. : 0;
  236. $halfShare = $countGt3 > 0 ? $value1 / $countGt3 / 2 : 0;
  237. $value2 = max(0, $value1 - $halfShare * $count8to15);
  238. $gt15Share = $countGt15 > 0 ? $value2 / $countGt15 : 0;
  239. foreach ($employees as $employee) {
  240. $workDays = $employee['work_days'];
  241. if ($workDays <= 7) {
  242. $wage = 0;
  243. } elseif ($workDays >= 8 && $workDays <= 15) {
  244. $wage = $halfShare;
  245. } elseif ($workDays > 15) {
  246. $wage = $gt15Share;
  247. } else {
  248. $wage = 0;
  249. }
  250. $wageList[] = [
  251. 'bh' => $employee['bh'],
  252. 'name' => $employee['name'],
  253. 'rate' => $employee['rate'],
  254. 'wage' => floatval(number_format($wage, 2, '.', '')),
  255. ];
  256. }
  257. return $wageList;
  258. }
  259. /**
  260. * 计算员工上班天数
  261. * @param string $bh
  262. * @param string $reportDate
  263. * @param array $hireDates
  264. * @return int
  265. */
  266. protected function getEmployeeTenureDays($bh, $reportDate, array $hireDates)
  267. {
  268. if (empty($hireDates[$bh])) {
  269. return 0;
  270. }
  271. $hireTime = strtotime(date('Y-m-d', strtotime($hireDates[$bh])));
  272. $reportTime = strtotime(date('Y-m-d', strtotime($reportDate)));
  273. if ($hireTime === false || $reportTime === false || $reportTime < $hireTime) {
  274. return 0;
  275. }
  276. return (int)floor(($reportTime - $hireTime) / 86400) + 1;
  277. }
  278. /**
  279. * 班组计时工资计算
  280. * @param string $month 月份
  281. * @return array 班组计时工资数据
  282. */
  283. protected function teamTimekeepCalculation($month)
  284. {
  285. $bhFields = [];
  286. for ($i = 1; $i <= 30; $i++) {
  287. $bhFields[] = 'bh' . $i;
  288. }
  289. $list = db('糊盒班组计时')
  290. ->field(array_merge(['sczl_rq', 'type', 'duration', 'price', 'remark'], $bhFields))
  291. ->where('sczl_rq', 'like', $month . '%')
  292. ->select();
  293. if (empty($list)) {
  294. return [];
  295. }
  296. $employeeIds = [];
  297. foreach ($list as $row) {
  298. for ($i = 1; $i <= 30; $i++) {
  299. $bh = isset($row['bh' . $i]) ? trim($row['bh' . $i]) : '';
  300. if ($this->isValidEmployeeBh($bh)) {
  301. $employeeIds[$bh] = true;
  302. }
  303. }
  304. }
  305. $employeeNames = [];
  306. if (!empty($employeeIds)) {
  307. $employees = db('人事_基本资料')
  308. ->whereIn('员工编号', array_keys($employeeIds))
  309. ->field('员工编号, rtrim(员工姓名) as 姓名')
  310. ->select();
  311. foreach ($employees as $employee) {
  312. $employeeNames[$employee['员工编号']] = $employee['姓名'];
  313. }
  314. }
  315. $data = [];
  316. foreach ($list as $row) {
  317. $employees = [];
  318. for ($i = 1; $i <= 30; $i++) {
  319. $bh = isset($row['bh' . $i]) ? trim($row['bh' . $i]) : '';
  320. if ($this->isValidEmployeeBh($bh)) {
  321. $employees[] = $bh;
  322. }
  323. }
  324. if (empty($employees)) {
  325. continue;
  326. }
  327. $employeeCount = count($employees);
  328. $salaryPerEmployee = ((float)$row['duration'] * (float)$row['price']) / $employeeCount;
  329. $ymd = date('Ymd', strtotime($row['sczl_rq']));
  330. foreach ($employees as $bh) {
  331. $name = $employeeNames[$bh] ?? '';
  332. $key = $ymd . '-' . $bh . '-' . $name . '-' . $row['price'];
  333. $durationPerEmployee = (float)$row['duration'] / $employeeCount;
  334. if (isset($data[$key])) {
  335. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + $durationPerEmployee, 2, '.', ''));
  336. $data[$key]['salary'] = floatval(number_format($data[$key]['salary'] + $salaryPerEmployee, 2, '.', ''));
  337. if ($row['type'] !== '' && strpos($data[$key]['type'], $row['type']) === false) {
  338. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $row['type'], ',');
  339. }
  340. if ($row['remark'] !== '' && strpos($data[$key]['remark'], $row['remark']) === false) {
  341. $data[$key]['remark'] = trim($data[$key]['remark'] . ',' . $row['remark'], ',');
  342. }
  343. continue;
  344. }
  345. $data[$key] = [
  346. 'sczl_rq' => date('Y-m-d', strtotime($row['sczl_rq'])),
  347. 'type' => $row['type'],
  348. 'duration' => floatval(number_format($durationPerEmployee, 2, '.', '')),
  349. 'price' => $row['price'],
  350. 'remark' => $row['remark'],
  351. 'bh' => $bh,
  352. '姓名' => $name,
  353. 'salary' => floatval(number_format($salaryPerEmployee, 2, '.', '')),
  354. ];
  355. }
  356. }
  357. return $data;
  358. }
  359. /**
  360. * 计算糊盒计时工资
  361. * @param string $month 月份
  362. * @return array 糊盒计时工资数据
  363. */
  364. protected function calculateTimekeepSalary($month)
  365. {
  366. $list = db('糊盒报工机时')
  367. ->field(['wgjs_rq', 'wgjs_bh1', 'wgjs_js1', 'wgjs_yy1', 'wgjs_je1',
  368. 'wgjs_bh2', 'wgjs_js2', 'wgjs_yy2', 'wgjs_je2',
  369. 'wgjs_bh3', 'wgjs_js3', 'wgjs_yy3', 'wgjs_je3',
  370. 'wgjs_bh4', 'wgjs_js4', 'wgjs_yy4', 'wgjs_je4',
  371. 'wgjs_bh5', 'wgjs_js5', 'wgjs_yy5', 'wgjs_je5',
  372. 'wgjs_bh6', 'wgjs_js6', 'wgjs_yy6', 'wgjs_je6'])
  373. ->where('wgjs_rq', 'like', $month . '%')
  374. ->select();
  375. if (empty($list)) {
  376. return [];
  377. }
  378. $employeeIds = [];
  379. foreach ($list as $row) {
  380. for ($i = 1; $i <= 6; $i++) {
  381. $bh = isset($row['wgjs_bh' . $i]) ? trim($row['wgjs_bh' . $i]) : '';
  382. if ($this->isValidEmployeeBh($bh)) {
  383. $employeeIds[$bh] = true;
  384. }
  385. }
  386. }
  387. $employeeNames = [];
  388. if (!empty($employeeIds)) {
  389. $employees = db('人事_基本资料')
  390. ->whereIn('员工编号', array_keys($employeeIds))
  391. ->field('员工编号, rtrim(员工姓名) as 姓名')
  392. ->select();
  393. foreach ($employees as $employee) {
  394. $employeeNames[$employee['员工编号']] = $employee['姓名'];
  395. }
  396. }
  397. $data = [];
  398. foreach ($list as $row) {
  399. $ymd = date('Ymd', strtotime($row['wgjs_rq']));
  400. $sczl_rq = date('Y-m-d', strtotime($row['wgjs_rq']));
  401. for ($i = 1; $i <= 6; $i++) {
  402. $bh = isset($row['wgjs_bh' . $i]) ? trim($row['wgjs_bh' . $i]) : '';
  403. if (!$this->isValidEmployeeBh($bh)) {
  404. continue;
  405. }
  406. $duration = isset($row['wgjs_js' . $i]) ? (float)$row['wgjs_js' . $i] : 0;
  407. $type = isset($row['wgjs_yy' . $i]) ? trim($row['wgjs_yy' . $i]) : '';
  408. $salary = isset($row['wgjs_je' . $i]) ? (float)$row['wgjs_je' . $i] : 0;
  409. $price = '';
  410. $name = $employeeNames[$bh] ?? '';
  411. $key = $ymd . '-' . $bh . '-' . $name . '-' . $price;
  412. if (isset($data[$key])) {
  413. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + $duration, 2, '.', ''));
  414. $data[$key]['salary'] = floatval(number_format((float)$data[$key]['salary'] + $salary, 2, '.', ''));
  415. if ($type !== '' && strpos($data[$key]['type'], $type) === false) {
  416. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $type, ',');
  417. }
  418. continue;
  419. }
  420. $data[$key] = [
  421. 'sczl_rq' => $sczl_rq,
  422. 'type' => $type,
  423. 'duration' => floatval(number_format($duration, 2, '.', '')),
  424. 'price' => '',
  425. 'remark' => '',
  426. 'bh' => $bh,
  427. '姓名' => $name,
  428. 'salary' => floatval(number_format($salary, 2, '.', '')),
  429. ];
  430. }
  431. }
  432. return $data;
  433. }
  434. /**
  435. * 合并计时工资数据
  436. * @param array $data1
  437. * @param array $data2
  438. * @return array
  439. */
  440. protected function mergeTimekeepSalaryData(array $data1, array $data2)
  441. {
  442. $data = $data1;
  443. foreach ($data2 as $key => $item) {
  444. if (!isset($data[$key])) {
  445. $data[$key] = $item;
  446. continue;
  447. }
  448. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + (float)$item['duration'], 2, '.', ''));
  449. $data[$key]['salary'] = floatval(number_format((float)$data[$key]['salary'] + (float)$item['salary'], 2, '.', ''));
  450. if (!empty($item['type']) && strpos($data[$key]['type'], $item['type']) === false) {
  451. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $item['type'], ',');
  452. }
  453. if (!empty($item['remark']) && strpos($data[$key]['remark'], $item['remark']) === false) {
  454. $data[$key]['remark'] = trim($data[$key]['remark'] . ',' . $item['remark'], ',');
  455. }
  456. }
  457. return $data;
  458. }
  459. /**
  460. * 构建计件工资汇总行(仅填 price、salary,计时字段为 0)
  461. * @param array $fields
  462. * @return array
  463. */
  464. protected function buildPieceSalarySummaryRow(array $fields = [])
  465. {
  466. return $this->buildSalarySummaryRow(array_merge([
  467. 'time_salary' => 0,
  468. 'time_price' => 0,
  469. 'time_duration' => 0,
  470. 'remark' => '',
  471. ], $fields));
  472. }
  473. /**
  474. * 构建计时工资汇总行(仅填 time_price、time_salary、time_duration、remark,计件字段为 0)
  475. * @param array $fields
  476. * @return array
  477. */
  478. protected function buildTimekeepSalarySummaryRow(array $fields = [])
  479. {
  480. return $this->buildSalarySummaryRow(array_merge([
  481. 'sczl_gdbh' => '',
  482. 'sczl_gxmc' => '',
  483. 'sczl_dedh' => '',
  484. 'sczl_cl' => 0,
  485. '工价系数' => '',
  486. '保养工时' => '',
  487. '装版工时' => '',
  488. '异常工时' => '',
  489. '设备运行工时' => '',
  490. 'sczl_jtbh' => '',
  491. 'cpdh' => '',
  492. 'cpmc' => '',
  493. 'rate' => '',
  494. 'salary' => 0,
  495. 'price' => 0,
  496. ], $fields));
  497. }
  498. /**
  499. * 构建工资汇总统一字段结构
  500. * @param array $fields
  501. * @return array
  502. */
  503. protected function buildSalarySummaryRow(array $fields = [])
  504. {
  505. $defaults = [
  506. 'sczl_gdbh' => '',
  507. 'sczl_gxmc' => '',
  508. 'sczl_rq' => '',
  509. 'sczl_dedh' => '',
  510. 'sczl_cl' => 0,
  511. '工价系数' => '',
  512. '保养工时' => '',
  513. '装版工时' => '',
  514. '异常工时' => '',
  515. '设备运行工时' => '',
  516. 'sczl_jtbh' => '',
  517. 'cpdh' => '',
  518. 'cpmc' => '',
  519. 'bh' => '',
  520. 'rate' => '',
  521. 'name' => '',
  522. 'salary' => 0,
  523. 'time_salary' => 0,
  524. 'price' => 0,
  525. 'time_price' => 0,
  526. 'time_duration' => 0,
  527. 'remark' => '',
  528. 'sys_id' => '',
  529. 'sys_rq' => date('Y-m-d H:i:s'),
  530. ];
  531. $row = array_merge($defaults, $fields);
  532. $decimalFields = ['sczl_cl', 'salary', 'time_salary', 'price', 'time_price', 'time_duration'];
  533. foreach ($decimalFields as $field) {
  534. if (!isset($row[$field]) || $row[$field] === '' || $row[$field] === null) {
  535. $row[$field] = 0;
  536. } else {
  537. $row[$field] = is_numeric($row[$field]) ? (float)$row[$field] : 0;
  538. }
  539. }
  540. return $row;
  541. }
  542. }