GluSalaryCalculationService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. $wage = floatval(number_format($salary * (float)$classResult['rate' . $i], 2, '.', ''));
  155. $wageList[] = [
  156. 'bh' => $bh,
  157. 'name' => $classResult['员工姓名' . $i] ?? '',
  158. 'rate' => $classResult['rate' . $i] ?? '',
  159. 'wage' => $wage,
  160. ];
  161. }
  162. return $wageList;
  163. }
  164. /**
  165. * 手工机台计件超产工资
  166. * @param array $report
  167. * @param array $classResult
  168. * @return array
  169. */
  170. protected function calculateManualPieceWages(array $report, array $classResult)
  171. {
  172. $employees = [];
  173. for ($i = 1; $i <= 30; $i++) {
  174. $bh = trim($classResult['bh' . $i] ?? '');
  175. if (!$this->isValidEmployeeBh($bh)) {
  176. continue;
  177. }
  178. $employees[] = [
  179. 'bh' => $bh,
  180. 'name' => $classResult['员工姓名' . $i] ?? '',
  181. 'rate' => $classResult['rate' . $i] ?? '',
  182. ];
  183. }
  184. if (empty($employees)) {
  185. return [];
  186. }
  187. $hireDates = db('人事_基本资料')
  188. ->whereIn('员工编号', array_column($employees, 'bh'))
  189. ->column('聘用日期', '员工编号');
  190. $totalOutput = (float)$report['产量'];
  191. $dailyQuota = (float)$report['日定额'];
  192. if ($dailyQuota <= 0) {
  193. $dailyQuota = (float)$report['定额代号'];
  194. }
  195. $unitPrice = (float)$report['price'];
  196. $reportDate = $report['日期'];
  197. $totalCount = count($employees);
  198. $countGt3 = 0;
  199. $count8to15 = 0;
  200. $countGt15 = 0;
  201. $allPiece = true;
  202. foreach ($employees as &$employee) {
  203. $workDays = $this->getEmployeeTenureDays($employee['bh'], $reportDate, $hireDates);
  204. $employee['work_days'] = $workDays;
  205. if ($workDays > 3) {
  206. $countGt3++;
  207. }
  208. if ($workDays >= 8 && $workDays <= 15) {
  209. $count8to15++;
  210. }
  211. if ($workDays > 15) {
  212. $countGt15++;
  213. }
  214. if ($workDays <= 7) {
  215. $allPiece = false;
  216. }
  217. }
  218. unset($employee);
  219. $wageList = [];
  220. if ($allPiece) {
  221. $overPerPerson = $totalCount > 0
  222. ? max(0, ($totalOutput - $dailyQuota * $totalCount) * $unitPrice / $totalCount)
  223. : 0;
  224. foreach ($employees as $employee) {
  225. $wage = floatval(number_format($overPerPerson, 2, '.', ''));
  226. $wageList[] = [
  227. 'bh' => $employee['bh'],
  228. 'name' => $employee['name'],
  229. 'rate' => $employee['rate'],
  230. 'wage' => $wage,
  231. ];
  232. }
  233. return $wageList;
  234. }
  235. $value1 = $countGt3 > 0
  236. ? max(0, ($totalOutput - $dailyQuota * $countGt3) * $unitPrice)
  237. : 0;
  238. $halfShare = $countGt3 > 0 ? $value1 / $countGt3 / 2 : 0;
  239. $value2 = max(0, $value1 - $halfShare * $count8to15);
  240. $gt15Share = $countGt15 > 0 ? $value2 / $countGt15 : 0;
  241. foreach ($employees as $employee) {
  242. $workDays = $employee['work_days'];
  243. if ($workDays <= 7) {
  244. $wage = 0;
  245. } elseif ($workDays >= 8 && $workDays <= 15) {
  246. $wage = $halfShare;
  247. } elseif ($workDays > 15) {
  248. $wage = $gt15Share;
  249. } else {
  250. $wage = 0;
  251. }
  252. $wageList[] = [
  253. 'bh' => $employee['bh'],
  254. 'name' => $employee['name'],
  255. 'rate' => $employee['rate'],
  256. 'wage' => floatval(number_format($wage, 2, '.', '')),
  257. ];
  258. }
  259. return $wageList;
  260. }
  261. /**
  262. * 计算员工上班天数
  263. * @param string $bh
  264. * @param string $reportDate
  265. * @param array $hireDates
  266. * @return int
  267. */
  268. protected function getEmployeeTenureDays($bh, $reportDate, array $hireDates)
  269. {
  270. if (empty($hireDates[$bh])) {
  271. return 0;
  272. }
  273. $hireTime = strtotime(date('Y-m-d', strtotime($hireDates[$bh])));
  274. $reportTime = strtotime(date('Y-m-d', strtotime($reportDate)));
  275. if ($hireTime === false || $reportTime === false || $reportTime < $hireTime) {
  276. return 0;
  277. }
  278. return (int)floor(($reportTime - $hireTime) / 86400) + 1;
  279. }
  280. /**
  281. * 班组计时工资计算
  282. * @param string $month 月份
  283. * @return array 班组计时工资数据
  284. */
  285. protected function teamTimekeepCalculation($month)
  286. {
  287. $bhFields = [];
  288. for ($i = 1; $i <= 30; $i++) {
  289. $bhFields[] = 'bh' . $i;
  290. }
  291. $list = db('糊盒班组计时')
  292. ->field(array_merge(['sczl_rq', 'type', 'duration', 'price', 'remark'], $bhFields))
  293. ->where('sczl_rq', 'like', $month . '%')
  294. ->select();
  295. if (empty($list)) {
  296. return [];
  297. }
  298. $employeeIds = [];
  299. foreach ($list as $row) {
  300. for ($i = 1; $i <= 30; $i++) {
  301. $bh = isset($row['bh' . $i]) ? trim($row['bh' . $i]) : '';
  302. if ($this->isValidEmployeeBh($bh)) {
  303. $employeeIds[$bh] = true;
  304. }
  305. }
  306. }
  307. $employeeNames = [];
  308. if (!empty($employeeIds)) {
  309. $employees = db('人事_基本资料')
  310. ->whereIn('员工编号', array_keys($employeeIds))
  311. ->field('员工编号, rtrim(员工姓名) as 姓名')
  312. ->select();
  313. foreach ($employees as $employee) {
  314. $employeeNames[$employee['员工编号']] = $employee['姓名'];
  315. }
  316. }
  317. $data = [];
  318. foreach ($list as $row) {
  319. $employees = [];
  320. for ($i = 1; $i <= 30; $i++) {
  321. $bh = isset($row['bh' . $i]) ? trim($row['bh' . $i]) : '';
  322. if ($this->isValidEmployeeBh($bh)) {
  323. $employees[] = $bh;
  324. }
  325. }
  326. if (empty($employees)) {
  327. continue;
  328. }
  329. $employeeCount = count($employees);
  330. $salaryPerEmployee = ((float)$row['duration'] * (float)$row['price']) / $employeeCount;
  331. $ymd = date('Ymd', strtotime($row['sczl_rq']));
  332. foreach ($employees as $bh) {
  333. $name = $employeeNames[$bh] ?? '';
  334. $key = $ymd . '-' . $bh . '-' . $name . '-' . $row['price'];
  335. $durationPerEmployee = (float)$row['duration'] / $employeeCount;
  336. if (isset($data[$key])) {
  337. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + $durationPerEmployee, 2, '.', ''));
  338. $data[$key]['salary'] = floatval(number_format($data[$key]['salary'] + $salaryPerEmployee, 2, '.', ''));
  339. if ($row['type'] !== '' && strpos($data[$key]['type'], $row['type']) === false) {
  340. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $row['type'], ',');
  341. }
  342. if ($row['remark'] !== '' && strpos($data[$key]['remark'], $row['remark']) === false) {
  343. $data[$key]['remark'] = trim($data[$key]['remark'] . ',' . $row['remark'], ',');
  344. }
  345. continue;
  346. }
  347. $data[$key] = [
  348. 'sczl_rq' => date('Y-m-d', strtotime($row['sczl_rq'])),
  349. 'type' => $row['type'],
  350. 'duration' => floatval(number_format($durationPerEmployee, 2, '.', '')),
  351. 'price' => $row['price'],
  352. 'remark' => $row['remark'],
  353. 'bh' => $bh,
  354. '姓名' => $name,
  355. 'salary' => floatval(number_format($salaryPerEmployee, 2, '.', '')),
  356. ];
  357. }
  358. }
  359. return $data;
  360. }
  361. /**
  362. * 计算糊盒计时工资
  363. * @param string $month 月份
  364. * @return array 糊盒计时工资数据
  365. */
  366. protected function calculateTimekeepSalary($month)
  367. {
  368. $list = db('糊盒报工机时')
  369. ->field(['wgjs_rq', 'wgjs_bh1', 'wgjs_js1', 'wgjs_yy1', 'wgjs_je1',
  370. 'wgjs_bh2', 'wgjs_js2', 'wgjs_yy2', 'wgjs_je2',
  371. 'wgjs_bh3', 'wgjs_js3', 'wgjs_yy3', 'wgjs_je3',
  372. 'wgjs_bh4', 'wgjs_js4', 'wgjs_yy4', 'wgjs_je4',
  373. 'wgjs_bh5', 'wgjs_js5', 'wgjs_yy5', 'wgjs_je5',
  374. 'wgjs_bh6', 'wgjs_js6', 'wgjs_yy6', 'wgjs_je6'])
  375. ->where('wgjs_rq', 'like', $month . '%')
  376. ->select();
  377. if (empty($list)) {
  378. return [];
  379. }
  380. $employeeIds = [];
  381. foreach ($list as $row) {
  382. for ($i = 1; $i <= 6; $i++) {
  383. $bh = isset($row['wgjs_bh' . $i]) ? trim($row['wgjs_bh' . $i]) : '';
  384. if ($this->isValidEmployeeBh($bh)) {
  385. $employeeIds[$bh] = true;
  386. }
  387. }
  388. }
  389. $employeeNames = [];
  390. if (!empty($employeeIds)) {
  391. $employees = db('人事_基本资料')
  392. ->whereIn('员工编号', array_keys($employeeIds))
  393. ->field('员工编号, rtrim(员工姓名) as 姓名')
  394. ->select();
  395. foreach ($employees as $employee) {
  396. $employeeNames[$employee['员工编号']] = $employee['姓名'];
  397. }
  398. }
  399. $data = [];
  400. foreach ($list as $row) {
  401. $ymd = date('Ymd', strtotime($row['wgjs_rq']));
  402. $sczl_rq = date('Y-m-d', strtotime($row['wgjs_rq']));
  403. for ($i = 1; $i <= 6; $i++) {
  404. $bh = isset($row['wgjs_bh' . $i]) ? trim($row['wgjs_bh' . $i]) : '';
  405. if (!$this->isValidEmployeeBh($bh)) {
  406. continue;
  407. }
  408. $duration = isset($row['wgjs_js' . $i]) ? (float)$row['wgjs_js' . $i] : 0;
  409. $type = isset($row['wgjs_yy' . $i]) ? trim($row['wgjs_yy' . $i]) : '';
  410. $price = isset($row['wgjs_je' . $i]) ? (float)$row['wgjs_je' . $i] : 0;
  411. $salary = floatval(number_format($duration * $price, 2, '.', ''));
  412. $name = $employeeNames[$bh] ?? '';
  413. $key = $ymd . '-' . $bh . '-' . $name . '-' . $price;
  414. if (isset($data[$key])) {
  415. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + $duration, 2, '.', ''));
  416. $data[$key]['salary'] = floatval(number_format((float)$data[$key]['salary'] + $salary, 2, '.', ''));
  417. if ($type !== '' && strpos($data[$key]['type'], $type) === false) {
  418. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $type, ',');
  419. }
  420. continue;
  421. }
  422. $data[$key] = [
  423. 'sczl_rq' => $sczl_rq,
  424. 'type' => $type,
  425. 'duration' => floatval(number_format($duration, 2, '.', '')),
  426. 'price' => $price,
  427. 'remark' => '',
  428. 'bh' => $bh,
  429. '姓名' => $name,
  430. 'salary' => $salary,
  431. ];
  432. }
  433. }
  434. return $data;
  435. }
  436. /**
  437. * 合并计时工资数据
  438. * @param array $data1
  439. * @param array $data2
  440. * @return array
  441. */
  442. protected function mergeTimekeepSalaryData(array $data1, array $data2)
  443. {
  444. $data = $data1;
  445. foreach ($data2 as $key => $item) {
  446. if (!isset($data[$key])) {
  447. $data[$key] = $item;
  448. continue;
  449. }
  450. $data[$key]['duration'] = floatval(number_format((float)$data[$key]['duration'] + (float)$item['duration'], 2, '.', ''));
  451. $data[$key]['salary'] = floatval(number_format((float)$data[$key]['salary'] + (float)$item['salary'], 2, '.', ''));
  452. if (!empty($item['type']) && strpos($data[$key]['type'], $item['type']) === false) {
  453. $data[$key]['type'] = trim($data[$key]['type'] . ',' . $item['type'], ',');
  454. }
  455. if (!empty($item['remark']) && strpos($data[$key]['remark'], $item['remark']) === false) {
  456. $data[$key]['remark'] = trim($data[$key]['remark'] . ',' . $item['remark'], ',');
  457. }
  458. }
  459. return $data;
  460. }
  461. /**
  462. * 构建计件工资汇总行(仅填 price、salary,计时字段为 0)
  463. * @param array $fields
  464. * @return array
  465. */
  466. protected function buildPieceSalarySummaryRow(array $fields = [])
  467. {
  468. return $this->buildSalarySummaryRow(array_merge([
  469. 'time_salary' => 0,
  470. 'time_price' => 0,
  471. 'time_duration' => 0,
  472. 'remark' => '',
  473. ], $fields));
  474. }
  475. /**
  476. * 构建计时工资汇总行(仅填 time_price、time_salary、time_duration、remark,计件字段为 0)
  477. * @param array $fields
  478. * @return array
  479. */
  480. protected function buildTimekeepSalarySummaryRow(array $fields = [])
  481. {
  482. return $this->buildSalarySummaryRow(array_merge([
  483. 'sczl_gdbh' => '',
  484. 'sczl_gxmc' => '',
  485. 'sczl_dedh' => '',
  486. 'sczl_cl' => 0,
  487. '工价系数' => '',
  488. '保养工时' => '',
  489. '装版工时' => '',
  490. '异常工时' => '',
  491. '设备运行工时' => '',
  492. 'sczl_jtbh' => '',
  493. 'cpdh' => '',
  494. 'cpmc' => '',
  495. 'rate' => '',
  496. 'salary' => 0,
  497. 'price' => 0,
  498. ], $fields));
  499. }
  500. /**
  501. * 构建工资汇总统一字段结构
  502. * @param array $fields
  503. * @return array
  504. */
  505. protected function buildSalarySummaryRow(array $fields = [])
  506. {
  507. $defaults = [
  508. 'sczl_gdbh' => '',
  509. 'sczl_gxmc' => '',
  510. 'sczl_rq' => '',
  511. 'sczl_dedh' => '',
  512. 'sczl_cl' => 0,
  513. '工价系数' => '',
  514. '保养工时' => '',
  515. '装版工时' => '',
  516. '异常工时' => '',
  517. '设备运行工时' => '',
  518. 'sczl_jtbh' => '',
  519. 'cpdh' => '',
  520. 'cpmc' => '',
  521. 'bh' => '',
  522. 'rate' => '',
  523. 'name' => '',
  524. 'salary' => 0,
  525. 'time_salary' => 0,
  526. 'price' => 0,
  527. 'time_price' => 0,
  528. 'time_duration' => 0,
  529. 'remark' => '',
  530. 'sys_id' => '',
  531. 'sys_rq' => date('Y-m-d H:i:s'),
  532. ];
  533. $row = array_merge($defaults, $fields);
  534. $decimalFields = ['sczl_cl', 'salary', 'time_salary', 'price', 'time_price', 'time_duration'];
  535. foreach ($decimalFields as $field) {
  536. if (!isset($row[$field]) || $row[$field] === '' || $row[$field] === null) {
  537. $row[$field] = 0;
  538. } else {
  539. $row[$field] = is_numeric($row[$field]) ? (float)$row[$field] : 0;
  540. }
  541. }
  542. return $row;
  543. }
  544. }