MatchKnowledgeJob.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\Question;
  4. use App\Models\QuestionKpRelation;
  5. use App\Services\AiKnowledgeService;
  6. use Illuminate\Bus\Queueable;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Foundation\Bus\Dispatchable;
  9. use Illuminate\Queue\InteractsWithQueue;
  10. use Illuminate\Queue\SerializesModels;
  11. class MatchKnowledgeJob implements ShouldQueue
  12. {
  13. use Dispatchable;
  14. use InteractsWithQueue;
  15. use Queueable;
  16. use SerializesModels;
  17. public function __construct(public readonly int $questionId)
  18. {
  19. }
  20. public function handle(AiKnowledgeService $service): void
  21. {
  22. $question = Question::find($this->questionId);
  23. if (!$question) {
  24. return;
  25. }
  26. $matches = $service->matchKnowledgePoints($question->stem ?? '');
  27. $hasValidKp = $service->isValidKnowledgePoint($question->kp_code);
  28. if (empty($matches) || !$hasValidKp) {
  29. $matches = $service->matchKnowledgePointsByAi($question->stem ?? '');
  30. }
  31. if (!empty($matches)) {
  32. $question->kp_code = $matches[0]['kp_code'] ?? $question->kp_code;
  33. $question->save();
  34. }
  35. foreach ($matches as $match) {
  36. QuestionKpRelation::updateOrCreate([
  37. 'question_id' => $question->id,
  38. 'kp_code' => $match['kp_code'] ?? '',
  39. ], [
  40. 'weight' => $match['weight'] ?? 1,
  41. ]);
  42. }
  43. }
  44. }