find($contractId); if (!$contract) { throw new \Exception('合同不存在'); } // 2. 验证人员ID数组 if (empty($personnelIds) || !is_array($personnelIds)) { throw new \Exception('人员列表不能为空'); } // 3. 验证人员类型 if (!in_array($type, [1, 2])) { throw new \Exception('人员类型错误'); } // 4. 验证人员是否存在 $this->validatePersonnel($personnelIds, $type); // 5. 开启事务 \think\facade\Db::startTrans(); try { $successCount = 0; foreach ($personnelIds as $personnelId) { // 检查是否已经分发过 $exists = (new ContractSign())->where([ ['contract_id', '=', $contractId], ['personnel_id', '=', $personnelId], ['type', '=', $type] ])->findOrEmpty(); if (!$exists->isEmpty()) { continue; // 跳过已分发的 } $data = [ 'contract_id' => $contractId, 'personnel_id' => $personnelId, 'type' => $type, 'status' => 'pending', 'source_type' => 'manual', 'source_id' => null, 'created_at' => time() ]; $result = (new ContractSign())->create($data); if ($result) { $successCount++; } } // 6. 提交事务 \think\facade\Db::commit(); if ($successCount === 0) { throw new \Exception('所有人员都已分发过该合同'); } return true; } catch (\Exception $e) { // 7. 回滚事务 \think\facade\Db::rollback(); throw $e; } } /** * 验证人员是否存在 * @param array $personnelIds 人员ID数组 * @param int $type 人员类型 * @throws \Exception */ private function validatePersonnel(array $personnelIds, int $type): void { if ($type === 1) { // 内部员工 $count = \app\model\personnel\Personnel::whereIn('id', $personnelIds) ->where('status', 1) ->count(); } else { // 外部会员 $count = \app\model\member\Member::whereIn('id', $personnelIds) ->where('status', 1) ->count(); } if ($count !== count($personnelIds)) { throw new \Exception('部分人员不存在或状态异常'); } } }