| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use \think\Request;
- use \think\Db;
- /**
- * 车间工分报工
- */
- class ReportingWork extends Api
- {
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- /** @var bool */
- private static $reportingWorkLogTableReady = false;
- /**
- * 根据机台编号获取大工序和人员信息
- * @ApiMethod (GET)
- * @param string $machine 机台编号
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function getMajorprocessAndPerson()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- if (empty($params['machine'])) {
- $this->error('机台编号不能为空');
- }
- //获取大工序
- $majorprocess = db('设备_基本资料')
- ->where('设备编号', $params['machine'])
- ->field('生产工序,设备编组')
- ->find();
- if (empty($majorprocess)) {
- $this->error('设备信息');
- }
- //小组信息
- // $person = db('人员_小组资料')
- // ->where('team_name', $majorprocess['设备编组'])
- // ->where('status', 1)
- // ->field('team_name as 小组名称,staff_no as 员工编号,staff_name as 员工姓名')
- // ->select();
- $person = Db::name('人员_小组资料')->alias('a')
- ->field('
- b.staff_no as 员工编号,
- b.staff_name as 员工姓名,
- a.team_name as 小组名称
- ')
- ->join('人员_基本资料 b', 'a.staff_no = b.staff_no')
- ->where('a.team_name', $majorprocess['设备编组'])
- ->whereNull('a.mod_rq')
- ->whereNull('b.mod_rq')
- ->order('a.id asc')
- ->select();
- if (empty($person)) {
- $this->error('未找到人员信息');
- }
- $data['majorprocess'] = $majorprocess;
- $data['person'] = $person;
- $this->success('成功', $data);
- }
- /**
- * 获取订单工艺数据
- * @ApiMethod (GET)
- * @param string $workorder 工单编号
- * @param string $majorprocess 大工序
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- *
- */
- public function GetOrderProcess()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- if (empty($params['workorder'])) {
- $this->error('工单编号不能为空');
- }
- if (empty($params['majorprocess'])) {
- $this->error('大工序不能为空');
- }
- $data = db('工单_基础工艺资料')
- ->where('work_order', $params['workorder'])
- ->where('big_process', $params['majorprocess'])
- ->whereNull('del_rq')
- // ->where('status', 1)
- ->field('part_code as 部件编号,part_name as 部件名称')
- ->group('part_code')
- ->select();
- usort($data, function ($a, $b) {
- return strnatcmp((string)$a['部件编号'], (string)$b['部件编号']);
- });
- $this->success('成功', $data);
- }
- /**
- * 获取车缝部件的工艺资料
- * @ApiMethod (GET)
- * @param string $part_code 部件编号
- * @param string $workorder 工单编号
- * @param string $sys_id 小组名称(可选,传了则返回本组完成数)
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function GetCarProcess()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- if (empty($params['workorder'])) {
- $this->error('工单编号不能为空');
- }
- if (empty($params['part_code'])) {
- $this->error('部件编号不能为空');
- }
- $sysId = isset($params['sys_id']) ? trim((string)$params['sys_id']) : '';
- $orderInfo = db('工单_基本资料')
- ->where('订单编号', $params['workorder'])
- ->whereNull('Mod_rq')
- ->field('订单数量')
- ->find();
- $manufactureQty = !empty($orderInfo) ? $orderInfo['订单数量'] : 0;
- $data = db('工单_基础工艺资料')
- ->where('work_order', $params['workorder'])
- ->where('part_code', $params['part_code'])
- ->whereNull('del_rq')
- // 已拆分母工序 status=1 不展示,仅返回可报工工序 status=0
- ->where('status', 0)
- ->field('process_code as 工艺编号,process_name as 工艺名称,standard_hour as 标准工时,standard_minutes as 标准分钟,
- standard_score as 标准工分,coefficient as 系数,remark as 备注,money as 金额,status')
- ->select();
- usort($data, function ($a, $b) {
- return strnatcmp((string)$a['工艺编号'], (string)$b['工艺编号']);
- });
- // 累计完成数:全部小组
- $reportList = db('设备_工分计酬')
- ->where('work_order', $params['workorder'])
- ->where('part_code', $params['part_code'])
- ->whereNull('del_rq')
- ->field('process_code, SUM(number) as completed_qty')
- ->group('process_code')
- ->select();
- $completedMap = [];
- foreach ($reportList as $report) {
- $completedMap[trim((string)$report['process_code'])] = floatval($report['completed_qty']);
- }
- // 本组完成数:按 sys_id(小组名称)过滤
- $groupCompletedMap = [];
- if ($sysId !== '') {
- $groupReportList = db('设备_工分计酬')
- ->where('work_order', $params['workorder'])
- ->where('part_code', $params['part_code'])
- ->where('sys_id', $sysId)
- ->whereNull('del_rq')
- ->field('process_code, SUM(number) as completed_qty')
- ->group('process_code')
- ->select();
- foreach ($groupReportList as $report) {
- $groupCompletedMap[trim((string)$report['process_code'])] = floatval($report['completed_qty']);
- }
- }
- foreach ($data as $key => $row) {
- $processCode = trim((string)$row['工艺编号']);
- $completedQty = $completedMap[$processCode] ?? 0;
- $groupCompletedQty = $groupCompletedMap[$processCode] ?? 0;
- $data[$key]['制造数量'] = $manufactureQty;
- $data[$key]['累计完成数'] = $completedQty;
- $data[$key]['本组完成数'] = $groupCompletedQty;
- $data[$key]['未完成数'] = floatval($manufactureQty) - $completedQty;
- }
- $this->success('成功', $data);
- }
- /**
- * 工分报工接口
- * @ApiMethod (POST)
- * @param array $list 报工数据
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function ReportingWork()
- {
- if (!$this->request->isPost()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->post();
- $reportList = [];
- if (isset($params[0]) && is_array($params[0])) {
- $reportList = $params;
- } elseif (!empty($params['list']) && is_array($params['list'])) {
- $reportList = $params['list'];
- } elseif (!empty($params['data']) && is_array($params['data'])) {
- $reportList = $params['data'];
- } else {
- $rawBody = file_get_contents('php://input');
- $decoded = json_decode($rawBody, true);
- if (is_array($decoded)) {
- if (isset($decoded[0]) && is_array($decoded[0])) {
- $reportList = $decoded;
- } elseif (!empty($decoded['list']) && is_array($decoded['list'])) {
- $reportList = $decoded['list'];
- } elseif (!empty($decoded['data']) && is_array($decoded['data'])) {
- $reportList = $decoded['data'];
- }
- }
- }
- if (empty($reportList)) {
- $this->error('请传入报工数据');
- }
- $insertData = [];
- $logList = [];
- $now = date('Y-m-d H:i:s');
- foreach ($reportList as $idx => $item) {
- $rowNo = $idx + 1;
- if (empty($item['staff_no'])) {
- $this->error('第' . $rowNo . '条员工编号不能为空');
- }
- if (empty($item['staff_name'])) {
- $this->error('第' . $rowNo . '条员工姓名不能为空');
- }
- if (empty($item['work_order']) && empty($item['workorder'])) {
- $this->error('第' . $rowNo . '条订单编号不能为空');
- }
- if (empty($item['majorprocess'])) {
- $this->error('第' . $rowNo . '条大工序不能为空');
- }
- $isSewing = $item['majorprocess'] === '车缝';
- if ($isSewing && (!isset($item['part_code']) || $item['part_code'] === '')) {
- $this->error('第' . $rowNo . '条车缝工序必须填写部件编号');
- }
- if (empty($item['process_code'])) {
- $this->error('第' . $rowNo . '条工艺编号不能为空');
- }
- if (!isset($item['number']) || $item['number'] === '') {
- $this->error('第' . $rowNo . '条产量不能为空');
- }
- $workOrder = !empty($item['work_order']) ? trim((string)$item['work_order']) : trim((string)$item['workorder']);
- $processCode = trim((string)$item['process_code']);
- $partCode = null;
- if (isset($item['part_code']) && $item['part_code'] !== '') {
- $partCode = intval($item['part_code']);
- }
- $number = floatval($item['number']);
- if ($number <= 0) {
- $this->error('第' . $rowNo . '条产量必须大于0');
- }
- // 校验工序在工艺资料中仍存在,并以工艺表为准写入名称/工分(避免前端缓存旧数据)
- $processQuery = db('工单_基础工艺资料')
- ->where('work_order', $workOrder)
- ->where('process_code', $processCode)
- ->whereNull('del_rq');
- if ($partCode !== null) {
- $processQuery->where('part_code', $partCode);
- }
- $processInfo = $processQuery
- ->field('process_code,process_name,part_code,standard_hour,standard_minutes,standard_score,money,coefficient,big_process')
- ->find();
- if (empty($processInfo)) {
- $this->error('第' . $rowNo . '条工序不存在或已删除(订单' . $workOrder . ' 工序号' . $processCode
- . ($partCode !== null ? ' 部件' . $partCode : '') . '),请刷新工艺后重试');
- }
- $processName = trim((string)$processInfo['process_name']);
- $standardHour = floatval($processInfo['standard_hour']);
- $standardScore = floatval($processInfo['standard_score']);
- $standardMinutes = floatval($processInfo['standard_minutes']);
- $money = floatval($processInfo['money']);
- $coefficient = isset($processInfo['coefficient']) && $processInfo['coefficient'] !== ''
- ? $processInfo['coefficient']
- : (isset($item['coefficient']) && $item['coefficient'] !== '' ? $item['coefficient'] : 'C');
- if ($partCode === null && isset($processInfo['part_code']) && $processInfo['part_code'] !== '') {
- $partCode = intval($processInfo['part_code']);
- }
- $productionHour = round($standardHour * $number, 2);
- $productionScore = round($standardScore * $number, 2);
- $salary = $this->calcReportSalary($number, $standardScore);
- $sysId = isset($item['sys_id']) ? trim((string)$item['sys_id']) : '';
- $insertData[] = [
- 'staff_no' => $item['staff_no'],
- 'staff_name' => $item['staff_name'],
- 'work_order' => $workOrder,
- 'date' => !empty($item['date']) ? $item['date'] : date('Y-m-d'),
- 'majorprocess' => $item['majorprocess'],
- 'part_code' => $partCode,
- 'process_code' => $processCode,
- 'process_name' => $processName,
- 'standard_hour' => $standardHour,
- 'standard_score' => $standardScore,
- 'standard_minutes' => $standardMinutes,
- 'money' => $money,
- 'coefficient' => $coefficient,
- 'number' => $number,
- 'production_hour' => $productionHour,
- 'production_score' => $productionScore,
- 'salary' => $salary,
- 'machine' => isset($item['machine']) ? trim((string)$item['machine']) : '',
- 'sys_id' => $sysId,
- 'sys_rq' => $now,
- 'mod_id' => isset($item['mod_id']) ? $item['mod_id'] : '',
- 'mod_rq' => null,
- 'del_rq' => null,
- ];
- $logList[] = $this->buildReportingWorkLogRow([
- 'oper_type' => '新增报工',
- 'oper_user' => $sysId !== '' ? $sysId : (isset($item['mod_id']) ? $item['mod_id'] : ''),
- 'oper_time' => $now,
- 'work_order' => $workOrder,
- 'majorprocess' => $item['majorprocess'],
- 'part_code' => $partCode,
- 'process_code' => $processCode,
- 'process_name' => $processName,
- 'staff_no' => $item['staff_no'],
- 'staff_name' => $item['staff_name'],
- 'machine' => isset($item['machine']) ? trim((string)$item['machine']) : '',
- 'report_date' => !empty($item['date']) ? $item['date'] : date('Y-m-d'),
- ], '数量', '', (string)$number);
- }
- Db::startTrans();
- try {
- $result = db('设备_工分计酬')->insertAll($insertData);
- if ($result === false) {
- throw new \Exception('报工失败');
- }
- $this->writeReportingWorkLogs($logList);
- Db::commit();
- } catch (\think\exception\HttpResponseException $e) {
- throw $e;
- } catch (\Exception $e) {
- Db::rollback();
- $this->error('报工失败:' . $e->getMessage());
- }
- $this->success('报工成功', ['count' => count($insertData)]);
- }
- //报工工分数据表左侧菜单栏
- public function GetReportingWorkLeft()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $startDate = date('Y-m-d', strtotime('-39 day'));
- $endDate = date('Y-m-d');
- $list = db('设备_工分计酬')
- ->where('del_rq', null)
- ->where('date', 'between time', [$startDate, $endDate])
- ->where('machine', '<>', '')
- ->field('machine,date')
- ->order('machine asc,date desc')
- ->select();
- $menuMap = [];
- foreach ($list as $row) {
- $machine = $row['machine'];
- $date = $row['date'];
- if (!isset($menuMap[$machine])) {
- $menuMap[$machine] = [];
- }
- if (!in_array($date, $menuMap[$machine])) {
- $menuMap[$machine][] = $date;
- }
- }
- $data = [];
- foreach ($menuMap as $machine => $dateList) {
- $children = [];
- foreach ($dateList as $date) {
- $children[] = [
- 'date' => $date,
- ];
- }
- $data[] = [
- 'machine' => $machine,
- 'children' => $children,
- ];
- }
- $this->success('成功', $data);
- }
- /**
- * 机台报工数据
- * @ApiMethod (GET)
- * @param string $date 日期
- * @param string $machine 机台编号
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function GetReportingWorkData()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- if (empty($params['date'])) {
- $this->error('日期不能为空');
- }
- if (empty($params['machine'])) {
- $this->error('机台编号不能为空');
- }
- $rows = db('设备_工分计酬')
- ->where('del_rq', null)
- ->where('date', 'like', $params['date'] . '%')
- ->where('machine', $params['machine'])
- ->field('id,work_order,majorprocess,part_code,process_code,process_name,staff_no,staff_name,standard_hour,
- standard_score,money,coefficient,number,production_hour,production_score,
- salary,machine,sys_id,sys_rq')
- ->order('process_code asc,staff_no asc')
- ->select();
- $processMap = [];
- foreach ($rows as $row) {
- $groupKey = $row['majorprocess'] . '|' . $row['process_code'] . '|' . $row['process_name'] . '|' . $row['part_code'];
- if (!isset($processMap[$groupKey])) {
- $processMap[$groupKey] = [
- 'work_order' => $row['work_order'],
- 'majorprocess' => $row['majorprocess'],
- 'part_code' => $row['part_code'],
- 'process_code' => $row['process_code'],
- 'process_name' => $row['process_name'],
- 'machine' => $row['machine'],
- 'date' => $params['date'],
- 'staffs' => [],
- ];
- }
- $processMap[$groupKey]['staffs'][] = [
- 'staff_no' => $row['staff_no'],
- 'staff_name' => $row['staff_name'],
- 'standard_hour' => $row['standard_hour'],
- 'standard_score' => $row['standard_score'],
- 'money' => $row['money'],
- 'coefficient' => $row['coefficient'],
- 'number' => $row['number'],
- 'production_hour' => $row['production_hour'],
- 'production_score' => $row['production_score'],
- 'salary' => $row['salary'],
- 'sys_id' => $row['sys_id'],
- 'sys_rq' => $row['sys_rq'],
- 'id' => $row['id'],
- ];
- }
- $data = array_values($processMap);
- $this->success('成功', $data);
- }
- /**
- * 修改工分报工数据
- * @ApiMethod (POST)
- * @param int $id 报工记录ID
- * @param float $number 数量
- * @param float $production_hour 报工工时(可选,不传则按标准工时×数量重算)
- * @param float $production_score 报工工分(可选,不传则按标准工分×数量重算)
- * @param string $mod_id 修改人(可选)
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function UpdateReportingWork()
- {
- if (!$this->request->isPost()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->post();
- if (empty($params['id'])) {
- $this->error('ID不能为空');
- }
- if (!isset($params['number']) || $params['number'] === '') {
- $this->error('产量不能为空');
- }
- $record = db('设备_工分计酬')
- ->where('id', $params['id'])
- ->whereNull('del_rq')
- ->find();
- if (empty($record)) {
- $this->error('报工记录不存在或已删除');
- }
- $number = floatval($params['number']);
- if ($number <= 0) {
- $this->error('产量必须大于0');
- }
- $standardHour = floatval($record['standard_hour']);
- $standardScore = floatval($record['standard_score']);
- $productionHour = round($standardHour * $number, 2);
- $productionScore = round($standardScore * $number, 2);
- $salary = $this->calcReportSalary($number, $standardScore);
- $operTime = date('Y-m-d H:i:s');
- $operUser = !empty($params['mod_id']) ? $params['mod_id'] : ($record['sys_id'] ?? '');
- $data = [
- 'mod_rq' => $operTime,
- 'number' => $number,
- 'production_hour' => $productionHour,
- 'production_score' => $productionScore,
- 'salary' => $salary,
- ];
- if (!empty($params['mod_id'])) {
- $data['mod_id'] = $params['mod_id'];
- }
- $logContext = [
- 'report_id' => intval($record['id']),
- 'oper_type' => '修改报工',
- 'oper_user' => $operUser,
- 'oper_time' => $operTime,
- 'work_order' => $record['work_order'],
- 'majorprocess' => $record['majorprocess'],
- 'part_code' => $record['part_code'],
- 'process_code' => $record['process_code'],
- 'process_name' => $record['process_name'],
- 'staff_no' => $record['staff_no'],
- 'staff_name' => $record['staff_name'],
- 'machine' => $record['machine'] ?? '',
- 'report_date' => $record['date'] ?? null,
- ];
- $logList = $this->buildReportingWorkChangeLogs($logContext, [
- '数量' => [$record['number'], $number],
- '报工工时' => [$record['production_hour'], $productionHour],
- '报工工分' => [$record['production_score'], $productionScore],
- '工资' => [$record['salary'], $salary],
- ]);
- Db::startTrans();
- try {
- $result = db('设备_工分计酬')
- ->where('id', $params['id'])
- ->whereNull('del_rq')
- ->update($data);
- if ($result === false) {
- throw new \Exception('修改失败');
- }
- if ($result === 0) {
- throw new \Exception('报工记录不存在或已删除');
- }
- $this->writeReportingWorkLogs($logList);
- Db::commit();
- } catch (\think\exception\HttpResponseException $e) {
- throw $e;
- } catch (\Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('修改成功', [
- 'number' => $number,
- 'production_hour' => $productionHour,
- 'production_score' => $productionScore,
- 'salary' => $salary,
- ]);
- }
- /**
- * 删除报工数据
- * @ApiMethod (POST)
- * @param array $id ID
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function DeleteReportingWork()
- {
- if (!$this->request->isPost()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->post();
- if (empty($params['id'])) {
- $this->error('ID不能为空');
- }
- $record = db('设备_工分计酬')
- ->where('id', $params['id'])
- ->whereNull('del_rq')
- ->find();
- if (empty($record)) {
- $this->error('报工记录不存在或已删除');
- }
- $operTime = date('Y-m-d H:i:s');
- $operUser = !empty($params['mod_id']) ? $params['mod_id'] : ($record['sys_id'] ?? '');
- $logContext = [
- 'report_id' => intval($record['id']),
- 'oper_type' => '删除报工',
- 'oper_user' => $operUser,
- 'oper_time' => $operTime,
- 'work_order' => $record['work_order'],
- 'majorprocess' => $record['majorprocess'],
- 'part_code' => $record['part_code'],
- 'process_code' => $record['process_code'],
- 'process_name' => $record['process_name'],
- 'staff_no' => $record['staff_no'],
- 'staff_name' => $record['staff_name'],
- 'machine' => $record['machine'] ?? '',
- 'report_date' => $record['date'] ?? null,
- ];
- $logList = $this->buildReportingWorkChangeLogs($logContext, [
- '数量' => [$record['number'], ''],
- '报工工分' => [$record['production_score'], ''],
- '工资' => [$record['salary'], ''],
- ]);
- $data = [
- 'del_rq' => $operTime,
- ];
- if (!empty($params['mod_id'])) {
- $data['mod_id'] = $params['mod_id'];
- $data['mod_rq'] = $operTime;
- }
- Db::startTrans();
- try {
- $result = db('设备_工分计酬')
- ->where('id', $params['id'])
- ->whereNull('del_rq')
- ->update($data);
- if ($result === false) {
- throw new \Exception('删除失败');
- }
- if ($result === 0) {
- throw new \Exception('报工记录不存在或已删除');
- }
- $this->writeReportingWorkLogs($logList);
- Db::commit();
- } catch (\think\exception\HttpResponseException $e) {
- throw $e;
- } catch (\Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('删除成功');
- }
- /**
- * 工分报工操作日志查询
- * @ApiMethod (GET)
- * @param string $workorder 订单编号(可选)
- * @param int $report_id 报工记录ID(可选)
- * @param string $oper_type 操作类型(可选)
- * @param string $date_start 操作时间起(可选,Y-m-d)
- * @param string $date_end 操作时间止(可选,Y-m-d)
- * @param int $page 页码,默认1
- * @param int $limit 每页条数,默认20
- */
- public function GetReportingWorkLog()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $this->ensureReportingWorkLogTable();
- $params = $this->request->param();
- $page = max(1, intval($params['page'] ?? 1));
- $limit = max(1, min(200, intval($params['limit'] ?? 20)));
- $offset = ($page - 1) * $limit;
- $query = Db::table('设备_工分报工操作日志');
- if (!empty($params['workorder'])) {
- $query->where('work_order', $params['workorder']);
- }
- if (!empty($params['report_id'])) {
- $query->where('report_id', intval($params['report_id']));
- }
- if (!empty($params['oper_type'])) {
- $query->where('oper_type', $params['oper_type']);
- }
- if (!empty($params['date_start'])) {
- $query->where('oper_time', '>=', $params['date_start'] . ' 00:00:00');
- }
- if (!empty($params['date_end'])) {
- $query->where('oper_time', '<=', $params['date_end'] . ' 23:59:59');
- }
- $total = (int)(clone $query)->count();
- $list = $query
- ->order('oper_time desc,id desc')
- ->limit($offset, $limit)
- ->select();
- $this->success('成功', [
- 'total' => $total,
- 'page' => $page,
- 'limit' => $limit,
- 'list' => $list,
- ]);
- }
- /**
- * 清理工分报工操作日志(仅保留近180天)
- * @ApiMethod (GET)
- */
- public function cleanReportingWorkLog()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $this->ensureReportingWorkLogTable();
- $days = 180;
- $batch = 1000;
- $deadline = date('Y-m-d H:i:s', strtotime("-{$days} days"));
- $totalDeleted = 0;
- try {
- while (true) {
- $ids = Db::table('设备_工分报工操作日志')
- ->where('oper_time', '<', $deadline)
- ->order('id asc')
- ->limit($batch)
- ->column('id');
- if (empty($ids)) {
- break;
- }
- $affected = Db::table('设备_工分报工操作日志')->where('id', 'in', $ids)->delete();
- $totalDeleted += (int)$affected;
- }
- } catch (\think\exception\HttpResponseException $e) {
- throw $e;
- } catch (\Exception $e) {
- $this->error('清理失败:' . $e->getMessage());
- }
- $this->success('清理成功', [
- 'days' => $days,
- 'deadline' => $deadline,
- 'deleted' => $totalDeleted,
- ]);
- }
- /**
- * 查询当前机台报工记录,并返回近半年报工订单列表
- * @ApiMethod (GET)
- * @param string $date 日期
- * @param string $machine 机台编号
- * @param string $majorprocess 大工序(不传则 orders 返回空)
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function GetReportingWorkRecord()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- // if (empty($params['date'])) {
- // $this->error('日期不能为空');
- // }
- // if (empty($params['machine'])) {
- // $this->error('机台编号不能为空');
- // }
- //按照日期查询当前报工记录
- $rows = db('设备_工分计酬')->alias('a')
- ->join('工单_基本资料 b', 'a.work_order = b.订单编号', 'LEFT')
- ->where('a.del_rq', null)
- ->where('b.Mod_rq', null)
- ->where('a.date', 'like', $params['date'] . '%')
- ->where('a.machine', $params['machine'])
- ->field('
- a.work_order,
- a.majorprocess,
- a.part_code,
- a.process_code,
- a.process_name,
- a.staff_no,
- a.staff_name,
- a.standard_hour,
- a.standard_score,
- a.money,
- a.coefficient,
- a.number,
- a.production_hour,
- a.production_score,
- a.salary,machine,
- a.sys_id,
- a.sys_rq,
- a.id,
- b.生产款号,
- b.款式
- ')
- ->order('a.process_code asc,a.staff_no asc,a.sys_rq desc')
- ->select();
- // 按大工序查询近半年报工订单;未传 majorprocess 时直接返回空
- $orders = [];
- if (!empty($params['majorprocess'])) {
- $since = date('Y-m-d H:i:s', strtotime('-3 months'));
- $orders = db('设备_工分计酬')->alias('a')
- ->join('工单_基本资料 b', 'a.work_order = b.订单编号', 'LEFT')
- ->where('a.del_rq', null)
- ->where('b.Mod_rq', null)
- ->where('a.sys_rq', '>=', $since)
- ->where('a.majorprocess', $params['majorprocess'])
- ->field('
- a.work_order as 订单编号,
- b.生产款号,
- b.款式,
- b.订单数量,
- MAX(a.sys_rq) as sys_rq
- ')
- ->group('a.work_order,b.生产款号,b.款式,b.订单数量')
- ->order('sys_rq desc')
- ->select();
- }
- $count = count($orders);
- $this->success('成功', [
- 'records' => $rows ?: [],
- 'count' => $count,
- 'orders' => $orders ?: []
- ]);
- }
- /**
- * 按新公式批量重算历史报工工资(数量 × 工分 × 0.067,保留2位)
- * @ApiMethod (POST)
- * @param string workorder 可选,限定工单编号
- * @param string date_start 可选,报工日期起(Y-m-d)
- * @param string date_end 可选,报工日期止(Y-m-d)
- */
- public function recalculateHistoricalSalary()
- {
- if (!$this->request->isPost()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->post();
- $applyFilters = function ($query) use ($params) {
- if (!empty($params['workorder'])) {
- $query->where('work_order', $params['workorder']);
- }
- if (!empty($params['date_start'])) {
- $query->where('date', '>=', $params['date_start']);
- }
- if (!empty($params['date_end'])) {
- $query->where('date', '<=', $params['date_end']);
- }
- return $query;
- };
- $total = (int)$applyFilters(Db::table('设备_工分计酬')->whereNull('del_rq'))->count();
- if ($total === 0) {
- $this->error('没有需要重算的报工数据');
- }
- Db::startTrans();
- try {
- $affected = $applyFilters(Db::table('设备_工分计酬')->whereNull('del_rq'))->update([
- 'production_score' => Db::raw('ROUND(`number` * `standard_score`, 2)'),
- 'salary' => Db::raw('ROUND(`number` * `standard_score` * 0.067, 2)'),
- ]);
- if ($affected === false) {
- throw new \Exception('批量更新失败');
- }
- Db::commit();
- } catch (\think\exception\HttpResponseException $e) {
- throw $e;
- } catch (\Exception $e) {
- Db::rollback();
- $this->error('重算失败:' . $e->getMessage());
- }
- $this->success('重算成功', [
- 'matched' => $total,
- 'updated' => (int)$affected,
- ]);
- }
- /**
- * 确保工分报工操作日志表存在
- */
- private function ensureReportingWorkLogTable()
- {
- if (self::$reportingWorkLogTableReady) {
- return;
- }
- $sql = <<<SQL
- CREATE TABLE IF NOT EXISTS `设备_工分报工操作日志` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
- `report_id` int(11) DEFAULT NULL COMMENT '报工记录ID',
- `oper_type` varchar(32) NOT NULL DEFAULT '' COMMENT '操作类型',
- `oper_user` varchar(64) NOT NULL DEFAULT '' COMMENT '操作人',
- `oper_time` datetime NOT NULL COMMENT '操作时间',
- `work_order` varchar(64) NOT NULL DEFAULT '' COMMENT '订单编号',
- `majorprocess` varchar(32) NOT NULL DEFAULT '' COMMENT '大工序',
- `part_code` int(11) DEFAULT NULL COMMENT '部件编号',
- `process_code` varchar(32) NOT NULL DEFAULT '' COMMENT '工艺编号',
- `process_name` varchar(128) NOT NULL DEFAULT '' COMMENT '工艺名称',
- `staff_no` varchar(32) NOT NULL DEFAULT '' COMMENT '员工编号',
- `staff_name` varchar(64) NOT NULL DEFAULT '' COMMENT '员工姓名',
- `machine` varchar(64) NOT NULL DEFAULT '' COMMENT '机台编号',
- `report_date` date DEFAULT NULL COMMENT '报工日期',
- `change_field` varchar(32) NOT NULL DEFAULT '' COMMENT '变更字段',
- `old_value` varchar(255) NOT NULL DEFAULT '' COMMENT '旧值',
- `new_value` varchar(255) NOT NULL DEFAULT '' COMMENT '新值',
- PRIMARY KEY (`id`),
- KEY `idx_report_id` (`report_id`),
- KEY `idx_work_order` (`work_order`),
- KEY `idx_oper_time` (`oper_time`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工分报工操作日志'
- SQL;
- Db::execute($sql);
- self::$reportingWorkLogTableReady = true;
- }
- /**
- * 写入工分报工操作日志
- * @param array $logs
- */
- private function writeReportingWorkLogs(array $logs)
- {
- if (empty($logs)) {
- return;
- }
- $this->ensureReportingWorkLogTable();
- $result = Db::table('设备_工分报工操作日志')->insertAll($logs);
- if ($result === false) {
- throw new \Exception('写入工分报工操作日志失败');
- }
- }
- /**
- * 构建单条工分报工操作日志
- */
- private function buildReportingWorkLogRow(array $context, $changeField, $oldValue, $newValue)
- {
- return [
- 'report_id' => isset($context['report_id']) ? $context['report_id'] : null,
- 'oper_type' => $context['oper_type'] ?? '',
- 'oper_user' => $context['oper_user'] ?? '',
- 'oper_time' => $context['oper_time'] ?? date('Y-m-d H:i:s'),
- 'work_order' => $context['work_order'] ?? '',
- 'majorprocess' => $context['majorprocess'] ?? '',
- 'part_code' => isset($context['part_code']) ? $context['part_code'] : null,
- 'process_code' => $context['process_code'] ?? '',
- 'process_name' => $context['process_name'] ?? '',
- 'staff_no' => $context['staff_no'] ?? '',
- 'staff_name' => $context['staff_name'] ?? '',
- 'machine' => $context['machine'] ?? '',
- 'report_date' => !empty($context['report_date']) ? $context['report_date'] : null,
- 'change_field' => (string)$changeField,
- 'old_value' => $oldValue === null ? '' : (string)$oldValue,
- 'new_value' => $newValue === null ? '' : (string)$newValue,
- ];
- }
- /**
- * 构建字段变更日志(仅记录有变化的字段)
- */
- private function buildReportingWorkChangeLogs(array $context, array $changes)
- {
- $logs = [];
- foreach ($changes as $field => $values) {
- $oldValue = $values[0];
- $newValue = $values[1];
- if ((string)$oldValue === (string)$newValue) {
- continue;
- }
- $logs[] = $this->buildReportingWorkLogRow($context, $field, $oldValue, $newValue);
- }
- return $logs;
- }
- /**
- * 报工工资:数量 × 工分 × 0.067(保留2位,与库字段 decimal(10,2) 一致)
- * @param mixed $number
- * @param mixed $standardScore
- * @return float
- */
- private function calcReportSalary($number, $standardScore)
- {
- return round(floatval($number) * floatval($standardScore) * 0.067, 2);
- }
- /**
- * 左侧菜单 - 工分产量报工
- * 三级结构:大工序 → 机台编号 → 上报日期
- * @ApiMethod (GET)
- */
- public function WorkpointsOutput()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $list = db('设备_工分计酬')
- ->where('del_rq', null)
- ->where('machine', '<>', '')
- ->field('majorprocess, machine, sys_rq')
- ->select();
- $map = [];
- foreach ($list as $row) {
- $proc = trim((string)($row['majorprocess'] ?? ''));
- $machine = trim((string)($row['machine'] ?? ''));
- $date = trim((string)($row['sys_rq'] ?? ''));
- if ($proc === '' || $machine === '' || $date === '') continue;
- $dateOnly = substr($date, 0, 10);
- if (!isset($map[$proc])) $map[$proc] = [];
- if (!isset($map[$proc][$machine])) $map[$proc][$machine] = [];
- if (!in_array($dateOnly, $map[$proc][$machine])) {
- $map[$proc][$machine][] = $dateOnly;
- }
- }
- $data = [];
- $procOrder = ['裁剪', '车缝', '手工', '大烫', '总检', '包装'];
- $procSorted = array_keys($map);
- usort($procSorted, function ($a, $b) use ($procOrder) {
- $ai = array_search($a, $procOrder);
- $bi = array_search($b, $procOrder);
- $ai = $ai === false ? 999 : $ai;
- $bi = $bi === false ? 999 : $bi;
- return $ai - $bi;
- });
- foreach ($procSorted as $proc) {
- $machines = $map[$proc];
- $children1 = [];
- $machineKeys = array_keys($machines);
- sort($machineKeys, SORT_NATURAL); // 机台编号自然排序 1,2,3...
- foreach ($machineKeys as $machine) {
- $dates = $machines[$machine];
- rsort($dates);
- $children2 = [];
- foreach ($dates as $i => $d) {
- $children2[] = [
- 'id' => "date-{$proc}-{$machine}-{$i}",
- 'label' => $d,
- 'sys_rq' => $d,
- ];
- }
- $children1[] = [
- 'id' => "machine-{$proc}-{$machine}",
- 'label' => $machine,
- 'machine' => $machine,
- 'children' => $children2,
- ];
- }
- $data[] = [
- 'id' => "proc-{$proc}",
- 'label' => $proc,
- 'majorprocess' => $proc,
- 'children' => $children1,
- ];
- }
- $this->success('成功', $data);
- }
- /**
- * 工分产量报工列表
- * @ApiMethod (GET)
- * @param string search 关键词搜索(订单编号、员工编号、员工姓名),与菜单模式二选一
- * @param string majorprocess 大工序(菜单模式必填)
- * @param string machine 机台编号(菜单模式必填)
- * @param string sys_rq 上报日期(菜单模式必填,Y-m-d)
- * @param int page 页码,默认1
- * @param int limit 每页条数,默认50
- */
- public function WorkpointsOutputList()
- {
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $params = $this->request->param();
- $page = max(1, intval($params['page'] ?? 1));
- $limit = max(1, min(200, intval($params['limit'] ?? 50)));
- $offset = ($page - 1) * $limit;
- // 关键词搜索模式
- if (!empty($params['search'])) {
- $search = trim($params['search']);
- $staffNo = !empty($params['staff_no']) ? trim($params['staff_no']) : '';
- $staffName = !empty($params['staff_name']) ? trim($params['staff_name']) : '';
- // 先查出生产款号匹配的工单编号
- $matchingWorkOrders = db('工单_基本资料')
- ->where('Mod_rq', null)
- ->where('生产款号', 'like', "%{$search}%")
- ->column('订单编号');
- $searchLike = "%{$search}%";
- $staffNoLike = $staffNo ? "%{$staffNo}%" : '';
- $staffNameLike = $staffName ? "%{$staffName}%" : '';
- // 拼接 OR 条件
- $orderSql = !empty($matchingWorkOrders)
- ? " OR `work_order` IN ('" . implode("','", array_map('addslashes', $matchingWorkOrders)) . "')"
- : "";
- $whereSql = "(`del_rq` IS NULL AND (`work_order` LIKE '$searchLike' OR `staff_no` LIKE '$searchLike' OR `staff_name` LIKE '$searchLike'$orderSql))";
- if ($staffNo) {
- $whereSql .= " AND `staff_no` LIKE '$staffNoLike'";
- }
- if ($staffName) {
- $whereSql .= " AND `staff_name` LIKE '$staffNameLike'";
- }
- $total = (int)db('设备_工分计酬')
- ->where($whereSql)
- ->count();
- $rows = db('设备_工分计酬')
- ->where($whereSql)
- ->order('sys_rq desc,process_code asc,staff_no asc')
- ->limit($offset, $limit)
- ->select();
- } else {
- // 菜单选择模式
- $query = db('设备_工分计酬')
- ->field('id,work_order,majorprocess,process_code,process_name,
- staff_no,staff_name,standard_hour,standard_score,money,coefficient,
- number,production_hour,production_score,salary,machine,sys_id,sys_rq')
- ->where('del_rq', null);
- if (!empty($params['majorprocess'])) {
- $query->where('majorprocess', $params['majorprocess']);
- }
- if (!empty($params['machine'])) {
- $query->where('machine', $params['machine']);
- }
- if (!empty($params['sys_rq'])) {
- $query->where('sys_rq', 'like', $params['sys_rq'] . '%');
- }
- $query->order('sys_rq desc,process_code asc,staff_no asc');
- $total = (int)$query->count();
- $rows = $query->limit($offset, $limit)->select();
- }
- // 批量查询生产款号和款式
- $workOrders = array_unique(array_filter(array_column($rows, 'work_order')));
- $orderMap = [];
- if (!empty($workOrders)) {
- $orderRows = db('工单_基本资料')
- ->whereIn('订单编号', $workOrders)
- ->whereNull('Mod_rq')
- ->field('订单编号,生产款号,款式')
- ->select();
- foreach ($orderRows as $row) {
- $orderMap[$row['订单编号']] = [
- '生产款号' => $row['生产款号'],
- '款式' => $row['款式'],
- ];
- }
- }
- // 返回明细数据
- $list = [];
- foreach ($rows as $row) {
- $orderInfo = $orderMap[$row['work_order']] ?? [];
- $list[] = [
- 'id' => $row['id'],
- '小组' => $row['majorprocess'],
- '员工编号' => $row['staff_no'],
- '员工姓名' => $row['staff_name'],
- '工序名称' => $row['process_name'],
- '设备编号' => $row['machine'],
- '报工数量' => $row['number'],
- '计件单价' => $row['money'],
- '工序产值' => $row['production_score'],
- '报工日期' => substr($row['sys_rq'], 0, 10),
- '订单编号' => $row['work_order'],
- '生产款号' => $orderInfo['生产款号'] ?? '',
- '款式' => $orderInfo['款式'] ?? '',
- 'sys_id' => $row['sys_id'],
- ];
- }
- $this->success('成功', [
- 'total' => $total,
- 'page' => $page,
- 'limit' => $limit,
- 'list' => $list,
- ]);
- }
- }
|