survey-webapp/SurveyBackend/SurveyBackend.Services/Services/QuestionService.cs
2025-06-10 13:36:18 +05:00

92 lines
No EOL
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using SurveyBackend.Core.Contexts;
using SurveyBackend.Services.Exceptions;
using SurveyLib.Core.Models;
using SurveyLib.Core.Repositories;
using SurveyLib.Core.Services;
namespace SurveyBackend.Services.Services;
public class QuestionService : IQuestionService
{
private readonly IQuestionRepository _questionRepository;
private readonly ISurveyRepository _surveyRepository;
private readonly IUserContext _userContext;
public QuestionService(IQuestionRepository questionRepository, ISurveyRepository surveyRepository,
IUserContext userContext)
{
_questionRepository = questionRepository;
_surveyRepository = surveyRepository;
_userContext = userContext;
}
public async Task AddQuestionAsync(QuestionBase question)
{
var survey = await _surveyRepository.GetByIdAsync(question.SurveyId);
if (survey is null)
{
throw new NotFoundException("Survey not found");
}
await _questionRepository.AddAsync(question);
}
public async Task UpdateQuestionAsync(QuestionBase question)
{
var questionBase = await _questionRepository.GetByIdAsNoTrackingAsync(question.Id);
if (questionBase is null)
{
throw new NotFoundException("Question not found");
}
question.SurveyId = questionBase.SurveyId;
// Если изменился тип вопроса (Discriminator), используем новый тип
if (questionBase.Discriminator != question.Discriminator)
{
// Удаляем старый вопрос
await _questionRepository.DeleteAsync(questionBase.Id);
// Добавляем новый с тем же ID
await _questionRepository.AddAsync(question);
}
else
{
// Если тип не меняется, просто обновляем
await _questionRepository.UpdateAsync(question);
}
}
public async Task DeleteQuestionAsync(int id)
{
var question = await _questionRepository.GetByIdAsync(id);
if (question is null)
{
throw new NotFoundException("Question not found");
}
await _questionRepository.DeleteAsync(id);
}
public async Task<QuestionBase> GetQuestionByIdAsync(int id)
{
var question = await _questionRepository.GetByIdAsync(id);
if (question is null)
{
throw new NotFoundException("Question not found");
}
return question;
}
public async Task<IEnumerable<QuestionBase>> GetQuestionsBySurveyIdAsync(int surveyId)
{
var survey = await _surveyRepository.GetByIdAsync(surveyId);
if (survey is null)
{
throw new NotFoundException("Survey not found");
}
return await _questionRepository.GetQuestionsBySurveyId(surveyId);
}
}