TaskConditionService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. <?php
  2. namespace App\Module\Task\Services;
  3. use App\Module\Task\Enums\TASK_STATUS;
  4. use App\Module\Task\Models\Task;
  5. use App\Module\Task\Models\TaskUserTask;
  6. use App\Module\Task\Repositorys\TaskAchievementConditionRepository;
  7. use App\Module\Task\Repositorys\TaskConditionRepository;
  8. use App\Module\Task\Repositorys\TaskUserProgressRepository;
  9. use App\Module\Task\Repositorys\TaskUserTaskRepository;
  10. use App\Module\Task\Services\TaskRewardGroupService;
  11. use App\Module\Game\Services\TaskTempService;
  12. use Illuminate\Support\Carbon;
  13. use Illuminate\Support\Facades\Log;
  14. /**
  15. * 任务条件服务类
  16. *
  17. * 提供任务条件相关的服务,包括条件验证、进度更新等功能。
  18. * 该类主要处理任务条件的逻辑,与TaskProgressService配合使用。
  19. */
  20. class TaskConditionService
  21. {
  22. /**
  23. * 任务条件数据仓库
  24. *
  25. * @var TaskConditionRepository
  26. */
  27. protected $conditionRepository;
  28. /**
  29. * 任务达成条件数据仓库
  30. *
  31. * @var TaskAchievementConditionRepository
  32. */
  33. protected $achievementConditionRepository;
  34. /**
  35. * 用户任务数据仓库
  36. *
  37. * @var TaskUserTaskRepository
  38. */
  39. protected $userTaskRepository;
  40. /**
  41. * 用户任务进度数据仓库
  42. *
  43. * @var TaskUserProgressRepository
  44. */
  45. protected $userProgressRepository;
  46. /**
  47. * 构造函数
  48. *
  49. * @param TaskConditionRepository $conditionRepository
  50. * @param TaskAchievementConditionRepository $achievementConditionRepository
  51. * @param TaskUserTaskRepository $userTaskRepository
  52. * @param TaskUserProgressRepository $userProgressRepository
  53. */
  54. public function __construct(
  55. TaskConditionRepository $conditionRepository,
  56. TaskAchievementConditionRepository $achievementConditionRepository,
  57. TaskUserTaskRepository $userTaskRepository,
  58. TaskUserProgressRepository $userProgressRepository
  59. ) {
  60. $this->conditionRepository = $conditionRepository;
  61. $this->achievementConditionRepository = $achievementConditionRepository;
  62. $this->userTaskRepository = $userTaskRepository;
  63. $this->userProgressRepository = $userProgressRepository;
  64. }
  65. /**
  66. * 获取所有可用的任务条件
  67. *
  68. * @return array 条件列表
  69. */
  70. public function getAllConditions(): array
  71. {
  72. return $this->conditionRepository->getActiveConditions();
  73. }
  74. /**
  75. * 获取任务的所有达成条件
  76. *
  77. * @param int $taskId 任务ID
  78. * @param string|null $conditionType 条件类型(prerequisite=前置条件,progress=进度条件)
  79. * @return array 达成条件列表
  80. */
  81. public function getTaskConditions(int $taskId, ?string $conditionType = null): array
  82. {
  83. return $this->achievementConditionRepository->getConditionsByTaskId($taskId, $conditionType);
  84. }
  85. /**
  86. * 验证任务前置条件
  87. *
  88. * @param int $userId 用户ID
  89. * @param int $taskId 任务ID
  90. * @return array 验证结果
  91. */
  92. public function validatePrerequisiteConditions(int $userId, int $taskId): array
  93. {
  94. try {
  95. // 获取任务的前置条件
  96. $prerequisites = $this->getTaskConditions($taskId, 'prerequisite');
  97. if (empty($prerequisites)) {
  98. return [
  99. 'success' => true,
  100. 'message' => '无前置条件',
  101. ];
  102. }
  103. // 验证每个前置条件
  104. $failedConditions = [];
  105. foreach ($prerequisites as $prerequisite) {
  106. $condition = $this->conditionRepository->find($prerequisite['condition_id']);
  107. if (!$condition) {
  108. continue;
  109. }
  110. // 获取条件处理器类
  111. $handlerClass = $condition->handler_class;
  112. if (!class_exists($handlerClass)) {
  113. Log::error('条件处理器类不存在', [
  114. 'condition_id' => $condition->id,
  115. 'handler_class' => $handlerClass,
  116. ]);
  117. continue;
  118. }
  119. // 实例化条件处理器
  120. $handler = new $handlerClass();
  121. // 验证条件
  122. $isValid = $handler->validate($userId, $prerequisite['condition_params']);
  123. if (!$isValid) {
  124. $failedConditions[] = [
  125. 'condition_id' => $condition->id,
  126. 'name' => $condition->name,
  127. 'description' => $condition->description,
  128. ];
  129. }
  130. }
  131. if (!empty($failedConditions)) {
  132. return [
  133. 'success' => false,
  134. 'message' => '前置条件未满足',
  135. 'failed_conditions' => $failedConditions,
  136. ];
  137. }
  138. return [
  139. 'success' => true,
  140. 'message' => '前置条件已满足',
  141. ];
  142. } catch (\Exception $e) {
  143. Log::error('验证前置条件失败', [
  144. 'user_id' => $userId,
  145. 'task_id' => $taskId,
  146. 'error' => $e->getMessage(),
  147. ]);
  148. return [
  149. 'success' => false,
  150. 'message' => '验证前置条件失败: ' . $e->getMessage(),
  151. ];
  152. }
  153. }
  154. /**
  155. * 更新任务进度条件
  156. *
  157. * @param int $userId 用户ID
  158. * @param string $conditionCode 条件代码
  159. * @param array $params 条件参数
  160. * @param int $increment 增量值
  161. * @return array 更新结果
  162. */
  163. public function updateProgressCondition(int $userId, string $conditionCode, array $params, int $increment = 1): array
  164. {
  165. try {
  166. // 获取条件
  167. $condition = $this->conditionRepository->getByCode($conditionCode);
  168. if (!$condition) {
  169. throw new \Exception('条件不存在');
  170. }
  171. // 获取使用该条件的任务达成条件
  172. $achievementConditions = $condition->achievementConditions()
  173. ->where('condition_type', 'progress')
  174. ->get();
  175. if ($achievementConditions->isEmpty()) {
  176. return [
  177. 'success' => true,
  178. 'message' => '无相关任务进度需要更新',
  179. 'updated_tasks' => [],
  180. ];
  181. }
  182. // 获取条件处理器类
  183. $handlerClass = $condition->handler_class;
  184. if (empty($handlerClass)) {
  185. throw new \Exception('条件处理器类未配置: ' . $condition->code);
  186. }
  187. if (!class_exists($handlerClass)) {
  188. throw new \Exception('条件处理器类不存在: ' . $handlerClass);
  189. }
  190. // 实例化条件处理器
  191. $handler = new $handlerClass();
  192. // 更新任务进度
  193. $updatedTasks = [];
  194. foreach ($achievementConditions as $achievementCondition) {
  195. // 获取用户任务
  196. $userTask = $this->userTaskRepository->getUserTask($userId, $achievementCondition->task_id);
  197. if (!$userTask || $userTask->status !== TASK_STATUS::IN_PROGRESS->value) {
  198. continue;
  199. }
  200. // 检查条件参数是否匹配
  201. $conditionParams = $achievementCondition->condition_params ?? [];
  202. if (!$handler->isMatch($params, $conditionParams)) {
  203. Log::info('跳过任务:条件参数不匹配', [
  204. 'event_params' => $params,
  205. 'condition_params' => $conditionParams
  206. ]);
  207. continue;
  208. }
  209. // 计算实际的进度增量
  210. $actualIncrement = $handler->calculateProgress($params, $conditionParams);
  211. Log::info('计算进度增量', [
  212. 'actual_increment' => $actualIncrement,
  213. 'params' => $params,
  214. 'condition_params' => $conditionParams
  215. ]);
  216. if ($actualIncrement <= 0) {
  217. Log::info('跳过任务:进度增量为0或负数');
  218. continue;
  219. }
  220. // 获取用户任务进度
  221. $userProgress = $this->userProgressRepository->getUserProgress($userId, $achievementCondition->id);
  222. Log::info('获取用户任务进度', [
  223. 'user_progress_exists' => $userProgress ? 'yes' : 'no',
  224. 'achievement_condition_id' => $achievementCondition->id
  225. ]);
  226. // 如果进度记录不存在,创建新记录
  227. if (!$userProgress) {
  228. Log::info('创建新的进度记录', [
  229. 'user_id' => $userId,
  230. 'task_id' => $achievementCondition->task_id,
  231. 'achievement_condition_id' => $achievementCondition->id,
  232. 'target_value' => $achievementCondition->target_value
  233. ]);
  234. $userProgress = $this->userProgressRepository->createUserProgress([
  235. 'user_id' => $userId,
  236. 'task_id' => $achievementCondition->task_id,
  237. 'achievement_condition_id' => $achievementCondition->id,
  238. 'current_value' => 0,
  239. 'target_value' => $achievementCondition->target_value,
  240. ]);
  241. Log::info('进度记录创建结果', [
  242. 'created_progress_id' => $userProgress ? $userProgress->id : 'null'
  243. ]);
  244. }
  245. // 更新进度值
  246. $oldValue = $userProgress->current_value;
  247. $newValue = $oldValue + $actualIncrement;
  248. if ($newValue > $userProgress->target_value) {
  249. $newValue = $userProgress->target_value;
  250. }
  251. Log::info('更新进度值', [
  252. 'old_value' => $oldValue,
  253. 'increment' => $actualIncrement,
  254. 'new_value' => $newValue,
  255. 'target_value' => $userProgress->target_value
  256. ]);
  257. $userProgress->current_value = $newValue;
  258. $saveResult = $userProgress->save();
  259. Log::info('保存进度结果', [
  260. 'save_result' => $saveResult,
  261. 'final_current_value' => $userProgress->current_value
  262. ]);
  263. // 计算任务总进度
  264. $progressResult = $this->calculateTaskTotalProgress($userId, $achievementCondition->task_id);
  265. // 检查任务是否完成,如果是自动任务则自动处理
  266. if ($progressResult['success'] && $progressResult['progress'] >= 100) {
  267. $this->handleAutoTaskCompletion($userId, $achievementCondition->task_id);
  268. }
  269. $taskProgress = min(100, round($newValue / $userProgress->target_value * 100));
  270. // 记录任务进度更新到暂存系统
  271. $task = $userTask->task;
  272. TaskTempService::recordTaskProgressUpdate(
  273. $userId,
  274. $achievementCondition->task_id,
  275. $task->name ?? '未知任务',
  276. $progressResult['progress'] ?? $taskProgress,
  277. [
  278. 'condition_id' => $achievementCondition->id,
  279. 'condition_name' => $condition->name ?? '未知条件',
  280. 'current_value' => $newValue,
  281. 'target_value' => $userProgress->target_value,
  282. 'increment' => $actualIncrement,
  283. ]
  284. );
  285. $updatedTasks[] = [
  286. 'task_id' => $achievementCondition->task_id,
  287. 'condition_id' => $achievementCondition->id,
  288. 'current_value' => $newValue,
  289. 'target_value' => $userProgress->target_value,
  290. 'progress' => $taskProgress,
  291. ];
  292. }
  293. return [
  294. 'success' => true,
  295. 'message' => '任务进度更新成功',
  296. 'updated_tasks' => $updatedTasks,
  297. ];
  298. } catch (\Exception $e) {
  299. Log::error('更新任务进度失败', [
  300. 'user_id' => $userId,
  301. 'condition_code' => $conditionCode,
  302. 'params' => $params,
  303. 'increment' => $increment,
  304. 'error' => $e->getMessage(),
  305. ]);
  306. return [
  307. 'success' => false,
  308. 'message' => '更新任务进度失败: ' . $e->getMessage(),
  309. ];
  310. }
  311. }
  312. /**
  313. * 计算任务总进度
  314. *
  315. * @param int $userId 用户ID
  316. * @param int $taskId 任务ID
  317. * @return array 计算结果
  318. */
  319. public function calculateTaskTotalProgress(int $userId, int $taskId): array
  320. {
  321. try {
  322. // 获取用户任务
  323. $userTask = $this->userTaskRepository->getUserTask($userId, $taskId);
  324. if (!$userTask || $userTask->status !== TASK_STATUS::IN_PROGRESS->value) {
  325. throw new \Exception('任务不存在或状态不正确');
  326. }
  327. // 获取任务的进度条件
  328. $progressConditions = $this->getTaskConditions($taskId, 'progress');
  329. if (empty($progressConditions)) {
  330. throw new \Exception('任务没有进度条件');
  331. }
  332. // 计算总进度
  333. $totalProgress = 0;
  334. $completedConditions = 0;
  335. foreach ($progressConditions as $condition) {
  336. // 获取用户任务进度
  337. $userProgress = $this->userProgressRepository->getUserProgress($userId, $condition['id']);
  338. if (!$userProgress) {
  339. continue;
  340. }
  341. // 计算条件进度百分比
  342. $conditionProgress = min(100, round($userProgress->current_value / $userProgress->target_value * 100));
  343. // 如果条件是必要条件,累加进度
  344. if ($condition['is_required']) {
  345. $totalProgress += $conditionProgress;
  346. }
  347. // 如果条件已完成,增加完成条件计数
  348. if ($conditionProgress >= 100) {
  349. $completedConditions++;
  350. }
  351. }
  352. // 计算平均进度
  353. $requiredConditions = array_filter($progressConditions, function ($condition) {
  354. return $condition['is_required'];
  355. });
  356. $requiredCount = count($requiredConditions);
  357. if ($requiredCount > 0) {
  358. $totalProgress = round($totalProgress / $requiredCount);
  359. } else {
  360. $totalProgress = 0;
  361. }
  362. // 更新用户任务进度
  363. $userTask->progress = $totalProgress;
  364. $userTask->save();
  365. return [
  366. 'success' => true,
  367. 'message' => '任务总进度计算成功',
  368. 'progress' => $totalProgress,
  369. 'completed_conditions' => $completedConditions,
  370. 'total_conditions' => count($progressConditions),
  371. ];
  372. } catch (\Exception $e) {
  373. Log::error('计算任务总进度失败', [
  374. 'user_id' => $userId,
  375. 'task_id' => $taskId,
  376. 'error' => $e->getMessage(),
  377. ]);
  378. return [
  379. 'success' => false,
  380. 'message' => '计算任务总进度失败: ' . $e->getMessage(),
  381. ];
  382. }
  383. }
  384. /**
  385. * 重置任务进度
  386. *
  387. * @param int $userId 用户ID
  388. * @param int $taskId 任务ID
  389. * @return array 重置结果
  390. */
  391. public function resetTaskProgress(int $userId, int $taskId): array
  392. {
  393. try {
  394. // 获取用户任务
  395. $userTask = $this->userTaskRepository->getUserTask($userId, $taskId);
  396. if (!$userTask) {
  397. throw new \Exception('任务不存在');
  398. }
  399. // 获取任务的进度条件
  400. $progressConditions = $this->getTaskConditions($taskId, 'progress');
  401. // 重置每个条件的进度
  402. foreach ($progressConditions as $condition) {
  403. $userProgress = $this->userProgressRepository->getUserProgress($userId, $condition['id']);
  404. if ($userProgress) {
  405. $userProgress->current_value = 0;
  406. $userProgress->save();
  407. }
  408. }
  409. // 重置用户任务进度
  410. $userTask->progress = 0;
  411. $userTask->status = TASK_STATUS::IN_PROGRESS->value;
  412. $userTask->completed_at = null;
  413. $userTask->rewarded_at = null;
  414. $userTask->save();
  415. return [
  416. 'success' => true,
  417. 'message' => '任务进度重置成功',
  418. ];
  419. } catch (\Exception $e) {
  420. Log::error('重置任务进度失败', [
  421. 'user_id' => $userId,
  422. 'task_id' => $taskId,
  423. 'error' => $e->getMessage(),
  424. ]);
  425. return [
  426. 'success' => false,
  427. 'message' => '重置任务进度失败: ' . $e->getMessage(),
  428. ];
  429. }
  430. }
  431. /**
  432. * 处理自动任务完成
  433. *
  434. * @param int $userId 用户ID
  435. * @param int $taskId 任务ID
  436. * @return void
  437. */
  438. protected function handleAutoTaskCompletion(int $userId, int $taskId): void
  439. {
  440. try {
  441. // 获取任务信息
  442. $task = Task::find($taskId);
  443. if (!$task) {
  444. return;
  445. }
  446. // 检查是否是自动完成任务(使用新的auto_complete字段)
  447. if (!$task->auto_complete) {
  448. return;
  449. }
  450. // 获取用户任务
  451. $userTask = $this->userTaskRepository->getUserTask($userId, $taskId);
  452. if (!$userTask || $userTask->status !== TASK_STATUS::IN_PROGRESS->value) {
  453. return;
  454. }
  455. // 自动完成任务
  456. $this->autoCompleteTask($userId, $taskId, $task, $userTask);
  457. } catch (\Exception $e) {
  458. Log::error('处理自动任务完成失败', [
  459. 'user_id' => $userId,
  460. 'task_id' => $taskId,
  461. 'error' => $e->getMessage()
  462. ]);
  463. }
  464. }
  465. /**
  466. * 自动完成任务
  467. *
  468. * @param int $userId 用户ID
  469. * @param int $taskId 任务ID
  470. * @param mixed $task 任务对象
  471. * @param mixed $userTask 用户任务对象
  472. * @return void
  473. */
  474. protected function autoCompleteTask(int $userId, int $taskId, $task, $userTask): void
  475. {
  476. try {
  477. // 检查事务状态,确保调用者已开启事务
  478. \UCore\Db\Helper::check_tr();
  479. // 标记任务为已完成
  480. $userTask->status = TASK_STATUS::COMPLETED->value;
  481. $userTask->completed_at = Carbon::now();
  482. $userTask->save();
  483. Log::info('自动完成任务', [
  484. 'user_id' => $userId,
  485. 'task_id' => $taskId,
  486. 'task_name' => $task->name
  487. ]);
  488. // 检查是否自动发放奖励(使用新的auto_reward字段)
  489. if ($task->auto_reward) {
  490. $this->autoClaimReward($userId, $taskId, $task, $userTask);
  491. }
  492. // 检查是否需要自动重置(循环任务)
  493. if ($task->auto_reset && $task->reset_type === 'immediate' && $task->max_completions === -1) {
  494. $this->autoResetTask($userId, $taskId, $task);
  495. }
  496. } catch (\Exception $e) {
  497. Log::error('自动完成任务失败', [
  498. 'user_id' => $userId,
  499. 'task_id' => $taskId,
  500. 'error' => $e->getMessage()
  501. ]);
  502. }
  503. }
  504. /**
  505. * 自动领取奖励
  506. *
  507. * @param int $userId 用户ID
  508. * @param int $taskId 任务ID
  509. * @param mixed $task 任务对象
  510. * @param mixed $userTask 用户任务对象
  511. * @return void
  512. */
  513. protected function autoClaimReward(int $userId, int $taskId, $task, $userTask): void
  514. {
  515. try {
  516. // 检查任务是否有奖励组
  517. if (!$task->reward_group_id) {
  518. return;
  519. }
  520. // 使用奖励组服务发放奖励
  521. $result = TaskRewardGroupService::distributeRewards(
  522. $userId,
  523. $taskId,
  524. $userTask->id
  525. );
  526. if ($result['success']) {
  527. // 更新任务状态为已领取奖励
  528. $userTask->status = TASK_STATUS::REWARDED->value;
  529. $userTask->rewarded_at = Carbon::now();
  530. $userTask->save();
  531. Log::info('自动领取任务奖励成功', [
  532. 'user_id' => $userId,
  533. 'task_id' => $taskId,
  534. 'task_name' => $task->name,
  535. 'rewards' => $result['rewards'] ?? []
  536. ]);
  537. } else {
  538. Log::error('自动领取任务奖励失败', [
  539. 'user_id' => $userId,
  540. 'task_id' => $taskId,
  541. 'error' => $result['message'] ?? '未知错误'
  542. ]);
  543. }
  544. } catch (\Exception $e) {
  545. Log::error('自动领取奖励异常', [
  546. 'user_id' => $userId,
  547. 'task_id' => $taskId,
  548. 'error' => $e->getMessage()
  549. ]);
  550. }
  551. }
  552. /**
  553. * 自动重置任务(循环任务)
  554. *
  555. * @param int $userId 用户ID
  556. * @param int $taskId 任务ID
  557. * @param mixed $task 任务对象
  558. * @return void
  559. */
  560. protected function autoResetTask(int $userId, int $taskId, $task): void
  561. {
  562. try {
  563. // 重置任务进度
  564. $resetResult = $this->resetTaskProgress($userId, $taskId);
  565. if ($resetResult['success']) {
  566. Log::info('自动重置循环任务成功', [
  567. 'user_id' => $userId,
  568. 'task_id' => $taskId,
  569. 'task_name' => $task->name
  570. ]);
  571. } else {
  572. Log::error('自动重置循环任务失败', [
  573. 'user_id' => $userId,
  574. 'task_id' => $taskId,
  575. 'error' => $resetResult['message']
  576. ]);
  577. }
  578. } catch (\Exception $e) {
  579. Log::error('自动重置任务异常', [
  580. 'user_id' => $userId,
  581. 'task_id' => $taskId,
  582. 'error' => $e->getMessage()
  583. ]);
  584. }
  585. }
  586. /**
  587. * 自动接取任务
  588. *
  589. * @param int $userId 用户ID
  590. * @param int $taskId 任务ID
  591. * @return bool 是否成功接取
  592. */
  593. public function autoAcceptTask(int $userId, int $taskId): bool
  594. {
  595. try {
  596. // 获取任务信息
  597. $task = Task::find($taskId);
  598. if (!$task || !$task->is_active) {
  599. return false;
  600. }
  601. // 检查是否是自动接取任务(使用新的auto_accept字段)
  602. if (!$task->auto_accept) {
  603. return false;
  604. }
  605. // 检查用户是否已接取该任务
  606. $userTask = $this->userTaskRepository->getUserTask($userId, $taskId);
  607. if ($userTask) {
  608. return true; // 已接取
  609. }
  610. // 创建用户任务记录
  611. $userTask = TaskUserTask::create([
  612. 'user_id' => $userId,
  613. 'task_id' => $taskId,
  614. 'status' => TASK_STATUS::IN_PROGRESS->value,
  615. 'progress' => 0,
  616. 'accepted_at' => Carbon::now(),
  617. ]);
  618. Log::info('自动接取任务成功', [
  619. 'user_id' => $userId,
  620. 'task_id' => $taskId,
  621. 'task_name' => $task->name
  622. ]);
  623. return true;
  624. } catch (\Exception $e) {
  625. Log::error('自动接取任务失败', [
  626. 'user_id' => $userId,
  627. 'task_id' => $taskId,
  628. 'error' => $e->getMessage()
  629. ]);
  630. return false;
  631. }
  632. }
  633. /**
  634. * 自动接取所有符合条件的自动任务
  635. *
  636. * @param int $userId 用户ID
  637. * @return void
  638. */
  639. public function autoAcceptAllEligibleTasks(int $userId): void
  640. {
  641. try {
  642. // 获取所有配置了自动接取的激活任务
  643. $autoAcceptTasks = Task::where('is_active', 1)
  644. ->where('auto_accept', 1)
  645. ->get();
  646. foreach ($autoAcceptTasks as $task) {
  647. // 检查用户是否已接取该任务
  648. $userTask = $this->userTaskRepository->getUserTask($userId, $task->id);
  649. if ($userTask) {
  650. continue; // 已接取,跳过
  651. }
  652. // 尝试自动接取任务
  653. $this->autoAcceptTask($userId, $task->id);
  654. }
  655. } catch (\Exception $e) {
  656. Log::error('自动接取所有符合条件的任务失败', [
  657. 'user_id' => $userId,
  658. 'error' => $e->getMessage()
  659. ]);
  660. }
  661. }
  662. }