Merge branch 'unstable' into 'main'
Unstable into main See merge request internship-2025/survey-webapp/survey-webapp!14
This commit is contained in:
commit
8d9a9fe918
39 changed files with 963 additions and 157 deletions
|
|
@ -1,6 +1,9 @@
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SurveyBackend.Core.Contexts;
|
||||||
|
using SurveyBackend.Core.Services;
|
||||||
using SurveyBackend.DTOs;
|
using SurveyBackend.DTOs;
|
||||||
|
using SurveyBackend.DTOs.User;
|
||||||
using SurveyBackend.Mappers;
|
using SurveyBackend.Mappers;
|
||||||
using IAuthorizationService = SurveyBackend.Core.Services.IAuthorizationService;
|
using IAuthorizationService = SurveyBackend.Core.Services.IAuthorizationService;
|
||||||
|
|
||||||
|
|
@ -14,14 +17,19 @@ namespace SurveyBackend.Controllers;
|
||||||
public class AuthController : ControllerBase
|
public class AuthController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly IAuthorizationService _authorizationService;
|
private readonly IAuthorizationService _authorizationService;
|
||||||
|
private readonly IUserContext _userContext;
|
||||||
|
private readonly IUserService _userService;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Нет ну вы прикалываетесь что ли мне ща каждый контроллер описывать?
|
/// Нет ну вы прикалываетесь что ли мне ща каждый контроллер описывать?
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="authorizationService"></param>
|
/// <param name="authorizationService"></param>
|
||||||
public AuthController(IAuthorizationService authorizationService)
|
public AuthController(IAuthorizationService authorizationService, IUserContext userContext,
|
||||||
|
IUserService userService)
|
||||||
{
|
{
|
||||||
_authorizationService = authorizationService;
|
_authorizationService = authorizationService;
|
||||||
|
_userContext = userContext;
|
||||||
|
_userService = userService;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -55,7 +63,19 @@ public class AuthController : ControllerBase
|
||||||
public async Task<IActionResult> Register([FromBody] UserRegistrationDto registerData)
|
public async Task<IActionResult> Register([FromBody] UserRegistrationDto registerData)
|
||||||
{
|
{
|
||||||
var token = await _authorizationService.RegisterUser(
|
var token = await _authorizationService.RegisterUser(
|
||||||
AuthMapper.UserRegistrationToModel(registerData));
|
UserMapper.UserRegistrationToModel(registerData));
|
||||||
return Ok(new { token = token });
|
return Ok(new { token = token });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[HttpGet("me")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetMe()
|
||||||
|
{
|
||||||
|
var userId = _userContext.UserId;
|
||||||
|
var user = await _userService.GetUserById(userId);
|
||||||
|
var result = UserMapper.ModelToOutput(user);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -29,7 +29,7 @@ public class QuestionController : ControllerBase
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||||
[ProducesResponseType(typeof(List<OutputQuestionDto>), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(List<QuestionOutputDto>), StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> GetBySurveyId([FromRoute] int surveyId)
|
public async Task<IActionResult> GetBySurveyId([FromRoute] int surveyId)
|
||||||
{
|
{
|
||||||
var questions = await _questionService.GetQuestionsBySurveyIdAsync(surveyId);
|
var questions = await _questionService.GetQuestionsBySurveyIdAsync(surveyId);
|
||||||
|
|
@ -47,11 +47,31 @@ public class QuestionController : ControllerBase
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> AddQuestion(CreateQuestionDto dto, [FromRoute] int surveyId)
|
public async Task<IActionResult> AddQuestion(QuestionCreateDto dto, [FromRoute] int surveyId)
|
||||||
{
|
{
|
||||||
var model = QuestionMapper.QuestionCreationToModel(dto, surveyId);
|
var model = QuestionMapper.QuestionCreationToModel(dto, surveyId);
|
||||||
await _questionService.AddQuestionAsync(model);
|
await _questionService.AddQuestionAsync(model);
|
||||||
return Created();
|
var result = QuestionMapper.ModelToQuestionDto(model);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[HttpPut("{id}")]
|
||||||
|
public async Task<IActionResult> UpdateQuestion([FromBody] QuestionUpdateDto dto, [FromRoute] int id,
|
||||||
|
[FromRoute] int surveyId)
|
||||||
|
{
|
||||||
|
var question = QuestionMapper.QuestionUpdateToModel(dto, surveyId, id);
|
||||||
|
await _questionService.UpdateQuestionAsync(question);
|
||||||
|
var result = QuestionMapper.ModelToQuestionDto(question);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
public async Task<IActionResult> DeleteQuestion([FromRoute] int id, [FromRoute] int surveyId)
|
||||||
|
{
|
||||||
|
await _questionService.DeleteQuestionAsync(id);
|
||||||
|
return Ok();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -32,7 +32,7 @@ public class SurveyController : ControllerBase
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[ProducesResponseType(typeof(List<OutputSurveyDto>), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(List<SurveyOutputDto>), StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> Get()
|
public async Task<IActionResult> Get()
|
||||||
{
|
{
|
||||||
var surveys = await _surveyService.GetSurveysAsync();
|
var surveys = await _surveyService.GetSurveysAsync();
|
||||||
|
|
@ -49,7 +49,7 @@ public class SurveyController : ControllerBase
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet("{id}")]
|
[HttpGet("{id}")]
|
||||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||||
[ProducesResponseType(typeof(OutputSurveyDto), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(SurveyOutputDto), StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> Get(int id)
|
public async Task<IActionResult> Get(int id)
|
||||||
{
|
{
|
||||||
var survey = await _surveyService.GetSurveyAsync(id);
|
var survey = await _surveyService.GetSurveyAsync(id);
|
||||||
|
|
@ -65,14 +65,32 @@ public class SurveyController : ControllerBase
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> Post([FromBody] CreateSurveyDto dto)
|
public async Task<IActionResult> Post([FromBody] SurveyCreateDto dto)
|
||||||
{
|
{
|
||||||
var userId = _userContext.UserId;
|
var userId = _userContext.UserId;
|
||||||
|
|
||||||
var survey = SurveyMapper.CreateDtoToModel(dto, userId);
|
var survey = SurveyMapper.CreateDtoToModel(dto, userId);
|
||||||
await _surveyService.AddSurveyAsync(survey);
|
await _surveyService.AddSurveyAsync(survey);
|
||||||
return Created();
|
var result = SurveyMapper.ModelToOutputDto(survey);
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обновляет опрос целиком
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="dto"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[Authorize]
|
||||||
|
[HttpPut("{id}")]
|
||||||
|
public async Task<IActionResult> Put(int id, [FromBody] SurveyUpdateDto dto)
|
||||||
|
{
|
||||||
|
var userId = _userContext.UserId;
|
||||||
|
var survey = SurveyMapper.UpdateDtoToModel(dto, userId, id);
|
||||||
|
await _surveyService.UpdateSurveyAsync(survey);
|
||||||
|
var result = SurveyMapper.ModelToOutputDto(survey);
|
||||||
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -100,7 +118,7 @@ public class SurveyController : ControllerBase
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpGet("my")]
|
[HttpGet("my")]
|
||||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType(typeof(List<OutputSurveyDto>), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(List<SurveyOutputDto>), StatusCodes.Status200OK)]
|
||||||
public async Task<IActionResult> GetMySurveys()
|
public async Task<IActionResult> GetMySurveys()
|
||||||
{
|
{
|
||||||
var userId = _userContext.UserId;
|
var userId = _userContext.UserId;
|
||||||
|
|
|
||||||
|
|
@ -3,19 +3,15 @@ namespace SurveyBackend.DTOs.Question;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Схема для создания нового Question
|
/// Схема для создания нового Question
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class CreateQuestionDto
|
public class QuestionCreateDto
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Название вопроса
|
/// Название вопроса
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required string Title { get; set; }
|
public required string Title { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Тип вопроса
|
/// Тип вопроса
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required string QuestionType { get; set; }
|
public required string QuestionType { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Варианты ответа (только если вопрос с выбором)
|
|
||||||
/// </summary>
|
|
||||||
public List<string>? AnswerVariants { get; set; }
|
|
||||||
}
|
}
|
||||||
|
|
@ -3,7 +3,7 @@ namespace SurveyBackend.DTOs.Question;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выходнпя схема вопроса
|
/// Выходнпя схема вопроса
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class OutputQuestionDto
|
public class QuestionOutputDto
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ID вопроса
|
/// ID вопроса
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
namespace SurveyBackend.DTOs.Question;
|
||||||
|
|
||||||
|
public class QuestionUpdateDto : QuestionCreateDto
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -3,7 +3,7 @@ namespace SurveyBackend.DTOs.Survey;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Схема для создания нового опроса
|
/// Схема для создания нового опроса
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class CreateSurveyDto
|
public class SurveyCreateDto
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Название опроса
|
/// Название опроса
|
||||||
|
|
@ -3,7 +3,7 @@ namespace SurveyBackend.DTOs.Survey;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выходная схема опроса
|
/// Выходная схема опроса
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class OutputSurveyDto
|
public class SurveyOutputDto
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ID опроса
|
/// ID опроса
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
namespace SurveyBackend.DTOs.Survey;
|
||||||
|
|
||||||
|
public class SurveyUpdateDto : SurveyCreateDto
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
namespace SurveyBackend.DTOs;
|
namespace SurveyBackend.DTOs.User;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Схема авторизации пользователя
|
/// Схема авторизации пользователя
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
namespace SurveyBackend.DTOs.User;
|
||||||
|
|
||||||
|
public class UserOutputDto
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public required string Email { get; set; }
|
||||||
|
public required string FirstName { get; set; }
|
||||||
|
public string? LastName { get; set; }
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
namespace SurveyBackend.DTOs;
|
namespace SurveyBackend.DTOs.User;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Схема регистрации пользователя
|
/// Схема регистрации пользователя
|
||||||
|
|
@ -10,11 +10,6 @@ public record UserRegistrationDto
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required string Email { get; set; }
|
public required string Email { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Юзернейм
|
|
||||||
/// </summary>
|
|
||||||
public string Username { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Имя
|
/// Имя
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -17,7 +17,7 @@ public static class QuestionMapper
|
||||||
/// <param name="surveyId"></param>
|
/// <param name="surveyId"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
/// <exception cref="BadRequestException"></exception>
|
/// <exception cref="BadRequestException"></exception>
|
||||||
public static QuestionBase QuestionCreationToModel(CreateQuestionDto dto, int surveyId)
|
public static QuestionBase QuestionCreationToModel(QuestionCreateDto dto, int surveyId)
|
||||||
{
|
{
|
||||||
return dto.QuestionType.ToLower() switch
|
return dto.QuestionType.ToLower() switch
|
||||||
{
|
{
|
||||||
|
|
@ -30,13 +30,13 @@ public static class QuestionMapper
|
||||||
{
|
{
|
||||||
Title = dto.Title,
|
Title = dto.Title,
|
||||||
SurveyId = surveyId,
|
SurveyId = surveyId,
|
||||||
AnswerVariants = dto.AnswerVariants?.Select(v => new AnswerVariant { Text = v }).ToList() ?? [],
|
AnswerVariants = [],
|
||||||
},
|
},
|
||||||
"multipleanswerquestion" => new MultipleAnswerQuestion
|
"multipleanswerquestion" => new MultipleAnswerQuestion
|
||||||
{
|
{
|
||||||
Title = dto.Title,
|
Title = dto.Title,
|
||||||
SurveyId = surveyId,
|
SurveyId = surveyId,
|
||||||
AnswerVariants = dto.AnswerVariants?.Select(v => new AnswerVariant { Text = v }).ToList() ?? []
|
AnswerVariants = []
|
||||||
},
|
},
|
||||||
_ => throw new BadRequestException("Unknown question type")
|
_ => throw new BadRequestException("Unknown question type")
|
||||||
};
|
};
|
||||||
|
|
@ -47,10 +47,10 @@ public static class QuestionMapper
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="question"></param>
|
/// <param name="question"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static OutputQuestionDto ModelToQuestionDto(QuestionBase question)
|
public static QuestionOutputDto ModelToQuestionDto(QuestionBase question)
|
||||||
{
|
{
|
||||||
var withAnswerVariants = question.GetType() != typeof(TextQuestion);
|
var withAnswerVariants = question.GetType() != typeof(TextQuestion);
|
||||||
return new OutputQuestionDto
|
return new QuestionOutputDto
|
||||||
{
|
{
|
||||||
Id = question.Id,
|
Id = question.Id,
|
||||||
SurveyId = question.SurveyId,
|
SurveyId = question.SurveyId,
|
||||||
|
|
@ -60,6 +60,34 @@ public static class QuestionMapper
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static QuestionBase QuestionUpdateToModel(QuestionCreateDto dto, int surveyId, int questionId)
|
||||||
|
{
|
||||||
|
return dto.QuestionType.ToLower() switch
|
||||||
|
{
|
||||||
|
"textquestion" => new TextQuestion
|
||||||
|
{
|
||||||
|
Id = questionId,
|
||||||
|
Title = dto.Title,
|
||||||
|
SurveyId = surveyId,
|
||||||
|
},
|
||||||
|
"singleanswerquestion" => new SingleAnswerQuestion
|
||||||
|
{
|
||||||
|
Id = questionId,
|
||||||
|
Title = dto.Title,
|
||||||
|
SurveyId = surveyId,
|
||||||
|
AnswerVariants = [],
|
||||||
|
},
|
||||||
|
"multipleanswerquestion" => new MultipleAnswerQuestion
|
||||||
|
{
|
||||||
|
Id = questionId,
|
||||||
|
Title = dto.Title,
|
||||||
|
SurveyId = surveyId,
|
||||||
|
AnswerVariants = []
|
||||||
|
},
|
||||||
|
_ => throw new BadRequestException("Unknown question type")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static List<OutputAnswerVariantDto> AnswerVariantsToDto(IEnumerable<AnswerVariant> answerVariants)
|
private static List<OutputAnswerVariantDto> AnswerVariantsToDto(IEnumerable<AnswerVariant> answerVariants)
|
||||||
{
|
{
|
||||||
return answerVariants.Select(av => new OutputAnswerVariantDto
|
return answerVariants.Select(av => new OutputAnswerVariantDto
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ public static class SurveyMapper
|
||||||
/// <param name="dto"></param>
|
/// <param name="dto"></param>
|
||||||
/// <param name="userId"></param>
|
/// <param name="userId"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static Survey CreateDtoToModel(CreateSurveyDto dto, int userId)
|
public static Survey CreateDtoToModel(SurveyCreateDto dto, int userId)
|
||||||
{
|
{
|
||||||
return new Survey
|
return new Survey
|
||||||
{
|
{
|
||||||
|
|
@ -24,14 +24,22 @@ public static class SurveyMapper
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Survey UpdateDtoToModel(SurveyUpdateDto dto, int userId, int surveyId) => new Survey
|
||||||
|
{
|
||||||
|
Id = surveyId,
|
||||||
|
Title = dto.Title,
|
||||||
|
Description = dto.Description,
|
||||||
|
CreatedBy = userId
|
||||||
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Модель в выходную схему
|
/// Модель в выходную схему
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="survey"></param>
|
/// <param name="survey"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static OutputSurveyDto ModelToOutputDto(Survey survey)
|
public static SurveyOutputDto ModelToOutputDto(Survey survey)
|
||||||
{
|
{
|
||||||
return new OutputSurveyDto
|
return new SurveyOutputDto
|
||||||
{
|
{
|
||||||
Id = survey.Id,
|
Id = survey.Id,
|
||||||
Title = survey.Title,
|
Title = survey.Title,
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,13 @@
|
||||||
using SurveyBackend.Core.Models;
|
using SurveyBackend.Core.Models;
|
||||||
using SurveyBackend.DTOs;
|
using SurveyBackend.DTOs;
|
||||||
|
using SurveyBackend.DTOs.User;
|
||||||
|
|
||||||
namespace SurveyBackend.Mappers;
|
namespace SurveyBackend.Mappers;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Маппер всего связанного с авторизацией
|
/// Маппер всего связанного с авторизацией
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class AuthMapper
|
public static class UserMapper
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перегнать схему регистрации в нового юзера
|
/// Перегнать схему регистрации в нового юзера
|
||||||
|
|
@ -20,4 +21,12 @@ public static class AuthMapper
|
||||||
LastName = dto.LastName,
|
LastName = dto.LastName,
|
||||||
Password = dto.Password,
|
Password = dto.Password,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
public static UserOutputDto ModelToOutput(User model) => new UserOutputDto
|
||||||
|
{
|
||||||
|
Id = model.Id,
|
||||||
|
FirstName = model.FirstName,
|
||||||
|
LastName = model.LastName,
|
||||||
|
Email = model.Email,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ namespace SurveyBackend.Core.Services;
|
||||||
public interface IUserService
|
public interface IUserService
|
||||||
{
|
{
|
||||||
public Task<User> GetUserByEmail(string email);
|
public Task<User> GetUserByEmail(string email);
|
||||||
|
public Task<User> GetUserById(int id);
|
||||||
public Task<bool> IsEmailTaken(string email);
|
public Task<bool> IsEmailTaken(string email);
|
||||||
public Task CreateUserAsync(User user);
|
public Task CreateUserAsync(User user);
|
||||||
}
|
}
|
||||||
|
|
@ -10,12 +10,14 @@ public class QuestionService : IQuestionService
|
||||||
{
|
{
|
||||||
private readonly IQuestionRepository _questionRepository;
|
private readonly IQuestionRepository _questionRepository;
|
||||||
private readonly ISurveyRepository _surveyRepository;
|
private readonly ISurveyRepository _surveyRepository;
|
||||||
|
private readonly IUserContext _userContext;
|
||||||
|
|
||||||
public QuestionService(IQuestionRepository questionRepository, ISurveyRepository surveyRepository,
|
public QuestionService(IQuestionRepository questionRepository, ISurveyRepository surveyRepository,
|
||||||
IUserContext userContext)
|
IUserContext userContext)
|
||||||
{
|
{
|
||||||
_questionRepository = questionRepository;
|
_questionRepository = questionRepository;
|
||||||
_surveyRepository = surveyRepository;
|
_surveyRepository = surveyRepository;
|
||||||
|
_userContext = userContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task AddQuestionAsync(QuestionBase question)
|
public async Task AddQuestionAsync(QuestionBase question)
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,11 @@ public class UserService : IUserService
|
||||||
return await _userRepository.GetUserByEmail(email) ?? throw new NotFoundException("Email not found");
|
return await _userRepository.GetUserByEmail(email) ?? throw new NotFoundException("Email not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<User> GetUserById(int id)
|
||||||
|
{
|
||||||
|
return await _userRepository.GetByIdAsync(id) ?? throw new NotFoundException("User not found");
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<bool> IsEmailTaken(string email)
|
public async Task<bool> IsEmailTaken(string email)
|
||||||
{
|
{
|
||||||
return await _userRepository.GetUserByEmail(email) != null;
|
return await _userRepository.GetUserByEmail(email) != null;
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,19 @@
|
||||||
import './App.css'
|
import './App.css'
|
||||||
import {BrowserRouter, Navigate, Route, Routes} from "react-router-dom";
|
import {BrowserRouter, Route, Routes} from "react-router-dom";
|
||||||
import {SurveyCreateAndEditingPage} from "./pages/SurveyCreateAndEditingPage/SurveyCreateAndEditingPage.tsx";
|
import {SurveyCreateAndEditingPage} from "./pages/SurveyCreateAndEditingPage/SurveyCreateAndEditingPage.tsx";
|
||||||
import Survey from "./components/Survey/Survey.tsx";
|
import Survey from "./components/Survey/Survey.tsx";
|
||||||
import SettingSurvey from "./components/SettingSurvey/SettingSurvey.tsx";
|
import SettingSurvey from "./components/SettingSurvey/SettingSurvey.tsx";
|
||||||
import {MySurveysPage} from "./pages/MySurveysPage/MySurveysPage.tsx";
|
import {MySurveysPage} from "./pages/MySurveysPage/MySurveysPage.tsx";
|
||||||
import {Results} from "./components/Results/Results.tsx";
|
import {Results} from "./components/Results/Results.tsx";
|
||||||
import {MySurveyList} from "./components/MySurveyList/MySurveyList.tsx";
|
import {MySurveyList} from "./components/MySurveyList/MySurveyList.tsx";
|
||||||
|
import AuthForm from "./pages/AuthForm/AuthForm.tsx";
|
||||||
|
|
||||||
const App = () => {
|
const App = () => {
|
||||||
return(
|
return(
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Navigate to="/survey/create/questions" replace />} />
|
<Route path="/login" element={<AuthForm />} />
|
||||||
|
<Route path="/register" element={<AuthForm />} />
|
||||||
|
|
||||||
<Route path="survey/create" element={<SurveyCreateAndEditingPage />}>
|
<Route path="survey/create" element={<SurveyCreateAndEditingPage />}>
|
||||||
<Route path="questions" element={<Survey />} />
|
<Route path="questions" element={<Survey />} />
|
||||||
|
|
@ -27,6 +29,8 @@ const App = () => {
|
||||||
<Route path="settings" element={<SettingSurvey />} />
|
<Route path="settings" element={<SettingSurvey />} />
|
||||||
<Route path="results" element={<Results />} />
|
<Route path="results" element={<Results />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
|
<Route path="*" element={<AuthForm />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,17 @@ export const registerUser = async (data: IRegistrationData) => {
|
||||||
const response = await fetch(`${BASE_URL}/auth/register`, {
|
const response = await fetch(`${BASE_URL}/auth/register`, {
|
||||||
...createRequestConfig('POST'), body: JSON.stringify(data),
|
...createRequestConfig('POST'), body: JSON.stringify(data),
|
||||||
})
|
})
|
||||||
return await handleResponse(response);
|
const responseData = await handleResponse(response);
|
||||||
|
|
||||||
|
if (responseData.accessToken) {
|
||||||
|
localStorage.setItem("token", responseData.accessToken);
|
||||||
|
localStorage.setItem("user", JSON.stringify({
|
||||||
|
firstName: data.firstName,
|
||||||
|
lastName: data.lastName
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
} catch (error){
|
} catch (error){
|
||||||
console.error("Registration error:", error);
|
console.error("Registration error:", error);
|
||||||
throw error;
|
throw error;
|
||||||
|
|
@ -24,14 +34,30 @@ export const registerUser = async (data: IRegistrationData) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const authUser = async (data: IAuthData) => {
|
export const authUser = async (data: IAuthData) => {
|
||||||
try{
|
try {
|
||||||
const response = await fetch(`${BASE_URL}/auth/login`, {
|
const response = await fetch(`${BASE_URL}/auth/login`, {
|
||||||
...createRequestConfig('POST'), body: JSON.stringify(data),
|
...createRequestConfig('POST'),
|
||||||
})
|
body: JSON.stringify(data),
|
||||||
return await handleResponse(response);
|
});
|
||||||
|
const responseData = await handleResponse(response);
|
||||||
|
console.log("Полный ответ сервера:", responseData);
|
||||||
|
|
||||||
|
const token = responseData.accessToken || responseData.token;
|
||||||
|
if (token) {
|
||||||
|
localStorage.setItem("token", token);
|
||||||
|
const user = localStorage.getItem("user");
|
||||||
|
if (!responseData.user && user) {
|
||||||
|
responseData.user = JSON.parse(user);
|
||||||
}
|
}
|
||||||
catch(error){
|
|
||||||
|
if (responseData.user) {
|
||||||
|
localStorage.setItem("user", JSON.stringify(responseData.user));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
|
} catch (error) {
|
||||||
console.error("Login error:", error);
|
console.error("Login error:", error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
@ -13,7 +13,8 @@ interface RequestConfig {
|
||||||
* @returns Конфигурация для fetch-запроса
|
* @returns Конфигурация для fetch-запроса
|
||||||
*/
|
*/
|
||||||
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
|
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
|
||||||
const token = localStorage.getItem("accessToken");
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
const config: RequestConfig = {
|
const config: RequestConfig = {
|
||||||
method,
|
method,
|
||||||
headers: {},
|
headers: {},
|
||||||
|
|
@ -37,14 +38,36 @@ const createRequestConfig = (method: string, isFormData: boolean = false): Reque
|
||||||
* @param response Ответ от fetch
|
* @param response Ответ от fetch
|
||||||
* @returns Распарсенные данные или ошибку
|
* @returns Распарсенные данные или ошибку
|
||||||
*/
|
*/
|
||||||
const handleResponse = async (response: Response) => {
|
// const handleResponse = async (response: Response) => {
|
||||||
const data = await response.json();
|
// const data = await response.json();
|
||||||
|
//
|
||||||
|
// if (!response.ok) {
|
||||||
|
// throw new Error(data.message || "Произошла ошибка");
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return data;
|
||||||
|
// };
|
||||||
|
|
||||||
if (!response.ok) {
|
const handleResponse = async (response: Response) => {
|
||||||
throw new Error(data.message || "Произошла ошибка");
|
// Проверяем, есть ли контент в ответе
|
||||||
|
const responseText = await response.text();
|
||||||
|
|
||||||
|
if (!responseText) {
|
||||||
|
if (response.ok) {
|
||||||
|
return null; // Если ответ пустой, но статус 200, возвращаем null
|
||||||
|
}
|
||||||
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(responseText);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.message || `HTTP ${response.status}`);
|
||||||
|
}
|
||||||
return data;
|
return data;
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Не удалось разобрать ответ сервера: ${e}`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export { BASE_URL, createRequestConfig, handleResponse };
|
export { BASE_URL, createRequestConfig, handleResponse };
|
||||||
29
SurveyFrontend/src/api/QuestionApi.ts
Normal file
29
SurveyFrontend/src/api/QuestionApi.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts";
|
||||||
|
|
||||||
|
export interface INewQuestion{
|
||||||
|
title: string;
|
||||||
|
questionType: string;
|
||||||
|
answerVariants: string[];
|
||||||
|
}
|
||||||
|
//
|
||||||
|
// export interface IErrorQuestionResponse {
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
|
||||||
|
export const addNewQuestion = async (surveyId: number, question: INewQuestion) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions`, {
|
||||||
|
...createRequestConfig('POST'),
|
||||||
|
body: JSON.stringify(question),
|
||||||
|
})
|
||||||
|
return await handleResponse(response)
|
||||||
|
} catch (error){
|
||||||
|
throw new Error(`Error when adding a new question: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
117
SurveyFrontend/src/api/SurveyApi.ts
Normal file
117
SurveyFrontend/src/api/SurveyApi.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
||||||
|
import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts";
|
||||||
|
|
||||||
|
export interface ISurvey {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
createdBy: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface INewSurvey{
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* getMySurveys - запрос на получение моих опросов
|
||||||
|
*/
|
||||||
|
export const getMySurveys = async (): Promise<ISurvey[]> => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/my`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
});
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error receiving surveys:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* getAllSurvey - запрос на получение всех опросов
|
||||||
|
*/
|
||||||
|
export const getAllSurveys = async (): Promise<ISurvey[]> => {
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
})
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error receiving surveys:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* postNewSurvey - добавление нового опроса
|
||||||
|
* @param survey
|
||||||
|
*/
|
||||||
|
export const postNewSurvey = async (survey: INewSurvey): Promise<INewSurvey> => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys`, {
|
||||||
|
...createRequestConfig('POST'),
|
||||||
|
body: JSON.stringify(survey)
|
||||||
|
})
|
||||||
|
|
||||||
|
// return await handleResponse(response);
|
||||||
|
|
||||||
|
if (response.status === 201) {
|
||||||
|
return await handleResponse(response);
|
||||||
|
}
|
||||||
|
throw new Error(`Ожидался код 201, получен ${response.status}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error when adding a new survey: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запрос на получение опроса по заданному ID
|
||||||
|
* @param surveyId - ID опроса
|
||||||
|
*/
|
||||||
|
export const getSurveyById = async (surveyId: number): Promise<ISurvey> => {
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
})
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error){
|
||||||
|
console.error(`Error finding the survey by id: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запрос на удаление опроса
|
||||||
|
* @param surveyId - ID выбранного опроса
|
||||||
|
*/
|
||||||
|
export const deleteSurvey = async (surveyId: string) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}`, {
|
||||||
|
...createRequestConfig('DELETE'),
|
||||||
|
})
|
||||||
|
const responseData = await handleResponse(response);
|
||||||
|
if (response.ok && !responseData){
|
||||||
|
return {success: true};
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
} catch (error){
|
||||||
|
console.error(`Error deleting a survey: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,46 +1,67 @@
|
||||||
/*AnswerOption.module.css*/
|
/*!*AnswerOption.module.css*!*/
|
||||||
|
|
||||||
.answer{
|
.answer {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
margin-bottom: 17px;
|
margin-bottom: 17px;
|
||||||
|
align-items: flex-start;
|
||||||
}
|
}
|
||||||
|
|
||||||
.textAnswer{
|
.textAnswer {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
border: none;
|
border: none;
|
||||||
background-color: #ffffff;
|
background: none;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
width: 70%;
|
width: 70%;
|
||||||
|
padding: 0;
|
||||||
|
line-height: 24px;
|
||||||
|
cursor: text;
|
||||||
|
margin-top: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.buttonMarker{
|
.buttonMarker {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
border: none;
|
border: none;
|
||||||
background-color: transparent;
|
background: none;
|
||||||
|
position: relative;
|
||||||
|
top: 0;
|
||||||
|
transition: top 0.1s ease;
|
||||||
|
cursor: pointer;
|
||||||
|
height: 24px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answerIcon{
|
.buttonMarker.editing {
|
||||||
vertical-align: middle;
|
top: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.answerIcon {
|
||||||
width: 24px;
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.answerInput{
|
.answerInput {
|
||||||
vertical-align: middle;
|
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
outline: none;
|
outline: none;
|
||||||
border: none;
|
border: none;
|
||||||
resize: none;
|
resize: none;
|
||||||
display: flex;
|
width: 70%;
|
||||||
align-items: center;
|
padding: 0;
|
||||||
box-sizing: border-box;
|
margin-top: 2px;
|
||||||
|
font-family: inherit;
|
||||||
|
min-height: 24px;
|
||||||
|
height: auto;
|
||||||
|
overflow-y: hidden;
|
||||||
|
line-height: 1.5;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-wrap: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
.deleteButton{
|
.deleteButton {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
border: none;
|
border: none;
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
|
|
|
||||||
|
|
@ -32,8 +32,22 @@ const AnswerOption: React.FC<AnswerOptionProps> = ({index, value, onChange, onDe
|
||||||
|
|
||||||
const handleTextareaChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
const handleTextareaChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
setCurrentValue(event.target.value);
|
setCurrentValue(event.target.value);
|
||||||
|
// Автоматическое изменение высоты
|
||||||
|
if (textAreaRef.current) {
|
||||||
|
textAreaRef.current.style.height = 'auto';
|
||||||
|
textAreaRef.current.style.height = `${textAreaRef.current.scrollHeight}px`;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditing && textAreaRef.current) {
|
||||||
|
textAreaRef.current.focus();
|
||||||
|
// Установка начальной высоты
|
||||||
|
textAreaRef.current.style.height = 'auto';
|
||||||
|
textAreaRef.current.style.height = `${textAreaRef.current.scrollHeight}px`;
|
||||||
|
}
|
||||||
|
}, [isEditing]);
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
onChange(currentValue);
|
onChange(currentValue);
|
||||||
|
|
@ -66,7 +80,10 @@ const AnswerOption: React.FC<AnswerOptionProps> = ({index, value, onChange, onDe
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.answer}>
|
<div className={styles.answer}>
|
||||||
<button className={styles.buttonMarker} onClick={toggleSelect}>
|
<button
|
||||||
|
className={`${styles.buttonMarker} ${isEditing ? styles.editing : ''}`}
|
||||||
|
onClick={toggleSelect}
|
||||||
|
>
|
||||||
<img
|
<img
|
||||||
className={styles.answerIcon}
|
className={styles.answerIcon}
|
||||||
src={getImage()}
|
src={getImage()}
|
||||||
|
|
@ -74,7 +91,8 @@ const AnswerOption: React.FC<AnswerOptionProps> = ({index, value, onChange, onDe
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
{isEditing ? (
|
{isEditing ? (
|
||||||
<textarea className={styles.answerInput}
|
<textarea
|
||||||
|
className={styles.answerInput}
|
||||||
ref={textAreaRef}
|
ref={textAreaRef}
|
||||||
value={currentValue}
|
value={currentValue}
|
||||||
onChange={handleTextareaChange}
|
onChange={handleTextareaChange}
|
||||||
|
|
@ -92,6 +110,7 @@ const AnswerOption: React.FC<AnswerOptionProps> = ({index, value, onChange, onDe
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default AnswerOption;
|
export default AnswerOption;
|
||||||
|
|
@ -2,19 +2,24 @@ import React from "react";
|
||||||
import Logo from "../Logo/Logo.tsx";
|
import Logo from "../Logo/Logo.tsx";
|
||||||
import Account from "../Account/Account.tsx";
|
import Account from "../Account/Account.tsx";
|
||||||
import styles from './Header.module.css'
|
import styles from './Header.module.css'
|
||||||
import {Link, useLocation} from "react-router-dom";
|
import {Link, useLocation, useNavigate} from "react-router-dom";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const Header: React.FC = () => {
|
const Header: React.FC = () => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
const isCreateSurveyActive = location.pathname.includes('/survey/create');
|
const isCreateSurveyActive = location.pathname.includes('/survey/create');
|
||||||
const isSurveyPage = location.pathname.includes('/survey/') && !location.pathname.includes('/survey/create');
|
const isSurveyPage = location.pathname.includes('/survey/') && !location.pathname.includes('/survey/create');
|
||||||
const isMySurveysPage = location.pathname === '/my-surveys' || isSurveyPage;
|
const isMySurveysPage = location.pathname === '/my-surveys' || isSurveyPage;
|
||||||
|
|
||||||
|
const handleLogoClick = () => {
|
||||||
|
navigate(location.pathname, { replace: true });
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.header}>
|
<div className={styles.header}>
|
||||||
<Logo href='/' />
|
<Logo href={location.pathname} onClick={handleLogoClick} />
|
||||||
<nav className={styles.pagesNav}>
|
<nav className={styles.pagesNav}>
|
||||||
<Link to='/survey/create/questions'
|
<Link to='/survey/create/questions'
|
||||||
className={`${styles.pageLink} ${isCreateSurveyActive ? styles.active : ''}`}>
|
className={`${styles.pageLink} ${isCreateSurveyActive ? styles.active : ''}`}>
|
||||||
|
|
@ -27,10 +32,7 @@ const Header: React.FC = () => {
|
||||||
{isMySurveysPage && <hr className={styles.activeLine}/>}
|
{isMySurveysPage && <hr className={styles.activeLine}/>}
|
||||||
</Link>
|
</Link>
|
||||||
</nav>
|
</nav>
|
||||||
<Account
|
<Account href={'/profile'} user={'Иванов Иван'}/>
|
||||||
href='/profile'
|
|
||||||
user='Иванов Иван'
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
85
SurveyFrontend/src/components/LoginForm/LoginForm.module.css
Normal file
85
SurveyFrontend/src/components/LoginForm/LoginForm.module.css
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
.loginContainer{
|
||||||
|
width: 31%;
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
padding: 42.5px 65px;
|
||||||
|
margin: auto;
|
||||||
|
border-radius: 43px;
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title{
|
||||||
|
text-align: center;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 40px;
|
||||||
|
line-height: 88%;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 80px;
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form{
|
||||||
|
text-align: center;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 80px;
|
||||||
|
margin-bottom: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 88%;
|
||||||
|
color: #000000; /* Цвет текста по умолчанию */
|
||||||
|
outline: none;
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid rgba(0, 0, 0, 0.2); /* Нижняя граница с прозрачностью */
|
||||||
|
padding: 5px 0;
|
||||||
|
opacity: 1; /* Установите opacity в 1 для input, а для placeholder используйте opacity */
|
||||||
|
}
|
||||||
|
|
||||||
|
.input::placeholder {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 88%;
|
||||||
|
color: #000000;
|
||||||
|
opacity: 0.2; /* Прозрачность placeholder */
|
||||||
|
}
|
||||||
|
|
||||||
|
.input:focus::placeholder {
|
||||||
|
opacity: 0; /* Убираем placeholder при фокусе */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Отключаем стиль для input, когда в нём есть данные */
|
||||||
|
.input:not(:placeholder-shown) {
|
||||||
|
color: black;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input:focus {
|
||||||
|
border-bottom: 1px solid black; /* Чёрная граница при фокусе */
|
||||||
|
}
|
||||||
|
|
||||||
|
.signIn{
|
||||||
|
margin: auto;
|
||||||
|
padding: 26.5px 67px;
|
||||||
|
width: fit-content;
|
||||||
|
border-radius: 24px;
|
||||||
|
background-color: #3788D6;
|
||||||
|
color: #FFFFFF;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 120%;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendation{
|
||||||
|
text-align: center;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendationLink{
|
||||||
|
color: #3788D6;
|
||||||
|
margin-left: 5px;
|
||||||
|
}
|
||||||
65
SurveyFrontend/src/components/LoginForm/LoginForm.tsx
Normal file
65
SurveyFrontend/src/components/LoginForm/LoginForm.tsx
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
import {Link, useNavigate} from "react-router-dom";
|
||||||
|
import styles from './LoginForm.module.css';
|
||||||
|
import {useRef, useState} from 'react';
|
||||||
|
import {authUser} from "../../api/AuthApi.ts";
|
||||||
|
|
||||||
|
const LoginForm = () => {
|
||||||
|
const [focused, setFocused] = useState({
|
||||||
|
email: false,
|
||||||
|
password: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const emailRef = useRef<HTMLInputElement>(null); // ref для поля email
|
||||||
|
const passwordRef = useRef<HTMLInputElement>(null); // ref для поля password
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const email = emailRef.current?.value || '';
|
||||||
|
const password = passwordRef.current?.value || '';
|
||||||
|
|
||||||
|
try{
|
||||||
|
const responseData = await authUser({email, password});
|
||||||
|
if (responseData && !responseData.error)
|
||||||
|
navigate('/my-surveys');
|
||||||
|
else
|
||||||
|
console.error('Ошибка аутентификации:', responseData);
|
||||||
|
}
|
||||||
|
catch(err){
|
||||||
|
console.error('Ошибка при отправке запроса:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.loginContainer}>
|
||||||
|
<h2 className={styles.title}>С возвращением!</h2>
|
||||||
|
<form className={styles.form} onSubmit={handleSubmit}>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.email}`}
|
||||||
|
type={'email'}
|
||||||
|
placeholder='Почта'
|
||||||
|
ref={emailRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, email: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, email: false })}
|
||||||
|
style={{ color: focused.email ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.password}`}
|
||||||
|
type='password'
|
||||||
|
placeholder='Пароль'
|
||||||
|
ref={passwordRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, password: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, password: false })}
|
||||||
|
style={{ color: focused.password ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<button className={styles.signIn} type="submit">Войти</button>
|
||||||
|
</form>
|
||||||
|
<p className={styles.recommendation}>Еще не с нами?
|
||||||
|
<Link className={styles.recommendationLink} to='/register'>Зарегистрируйтесь!</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default LoginForm;
|
||||||
|
|
@ -3,11 +3,12 @@ import styles from './Logo.module.css'
|
||||||
|
|
||||||
interface LogoProps {
|
interface LogoProps {
|
||||||
href: string;
|
href: string;
|
||||||
|
onClick: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const Logo: React.FC<LogoProps> = ({href}) => {
|
const Logo: React.FC<LogoProps> = ({href, onClick}) => {
|
||||||
return (
|
return (
|
||||||
<a className={styles.logo} href={href}>
|
<a className={styles.logo} href={href} onClick={onClick}>
|
||||||
<img src='../../../public/logo.svg' alt="" />
|
<img src='../../../public/logo.svg' alt="" />
|
||||||
</a>
|
</a>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,35 +1,58 @@
|
||||||
import styles from './MySurveysList.module.css'
|
import styles from './MySurveysList.module.css'
|
||||||
import {useNavigate} from "react-router-dom";
|
import {useNavigate} from "react-router-dom";
|
||||||
|
import {useEffect, useState} from "react";
|
||||||
|
import {getMySurveys, ISurvey} from "../../api/SurveyApi.ts";
|
||||||
|
|
||||||
interface MySurveyItem{
|
|
||||||
id: string,
|
interface MySurveyItem extends ISurvey{
|
||||||
title: string,
|
|
||||||
description: string,
|
|
||||||
date: string
|
|
||||||
status: 'active' | 'completed'
|
status: 'active' | 'completed'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MySurveyList = () => {
|
export const MySurveyList = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [surveys, setSurveys] = useState<MySurveyItem[]>([]);
|
||||||
|
|
||||||
const surveys: MySurveyItem[] = [
|
useEffect(() => {
|
||||||
{
|
const fetchSurvey = async () => {
|
||||||
id: '1',
|
try {
|
||||||
title: 'Опрос 1',
|
const mySurveys = await getMySurveys();
|
||||||
description: 'Описание опроса 1',
|
const surveysWithStatus: MySurveyItem[] = mySurveys.map((survey: ISurvey) => ({
|
||||||
date: '27-04-2025',
|
...survey,
|
||||||
status: 'active',
|
status: 'active',
|
||||||
},
|
}));
|
||||||
{
|
setSurveys(surveysWithStatus);
|
||||||
id: '2',
|
} catch (error) {
|
||||||
title: 'Опрос 2',
|
console.error('Ошибка при получении списка опросов:', error);
|
||||||
description: 'Описание опроса 2',
|
|
||||||
date: '01-01-2025',
|
|
||||||
status: 'completed',
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
const handleSurveyClick = (id: string) => {
|
if (error instanceof Error && error.message.includes("401")) {
|
||||||
|
// Если ошибка 401, перенаправляем на страницу входа
|
||||||
|
navigate('/login');
|
||||||
|
} else {
|
||||||
|
alert("Ошибка при загрузке опросов: " + (error instanceof Error && error.message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchSurvey();
|
||||||
|
}, [navigate]);
|
||||||
|
|
||||||
|
// const surveys: MySurveyItem[] = [
|
||||||
|
// {
|
||||||
|
// id: '1',
|
||||||
|
// title: 'Опрос 1',
|
||||||
|
// description: 'Описание опроса 1',
|
||||||
|
// createdBy: '27-04-2025',
|
||||||
|
// status: 'active',
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// id: '2',
|
||||||
|
// title: 'Опрос 2',
|
||||||
|
// description: 'Описание опроса 2',
|
||||||
|
// createdBy: '01-01-2025',
|
||||||
|
// status: 'completed',
|
||||||
|
// }
|
||||||
|
// ]
|
||||||
|
|
||||||
|
const handleSurveyClick = (id: number) => {
|
||||||
navigate(`/survey/${id}/questions`)
|
navigate(`/survey/${id}/questions`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,7 +69,7 @@ export const MySurveyList = () => {
|
||||||
<h1 className={styles.title}>{survey.title}</h1>
|
<h1 className={styles.title}>{survey.title}</h1>
|
||||||
<h2 className={styles.description}>{survey.description}</h2>
|
<h2 className={styles.description}>{survey.description}</h2>
|
||||||
</div>
|
</div>
|
||||||
<span className={styles.date}>Дата создания: {survey.date}</span>
|
<span className={styles.date}>Дата создания: {survey.createdBy}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className={`${styles.status} ${
|
<div className={`${styles.status} ${
|
||||||
survey.status === 'active' ? styles.active : styles.completed
|
survey.status === 'active' ? styles.active : styles.completed
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,9 @@
|
||||||
margin-bottom: 5px;
|
margin-bottom: 5px;
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
line-height: 1.5;
|
||||||
|
overflow-y: hidden;
|
||||||
|
min-height: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.buttonQuestion{
|
.buttonQuestion{
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,11 @@ const QuestionItem: React.FC<QuestionItemProps> = ({indexQuestion, initialTextQu
|
||||||
|
|
||||||
const handleTextareaQuestionChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
const handleTextareaQuestionChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
setTextQuestion(event.target.value);
|
setTextQuestion(event.target.value);
|
||||||
|
|
||||||
|
if (textareaQuestionRef.current) {
|
||||||
|
textareaQuestionRef.current.style.height = 'auto';
|
||||||
|
textareaQuestionRef.current.style.height = `${textareaQuestionRef.current.scrollHeight}px`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSaveQuestion = () => {
|
const handleSaveQuestion = () => {
|
||||||
|
|
@ -59,6 +64,8 @@ const QuestionItem: React.FC<QuestionItemProps> = ({indexQuestion, initialTextQu
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEditingQuestion && textareaQuestionRef.current) {
|
if (isEditingQuestion && textareaQuestionRef.current) {
|
||||||
textareaQuestionRef.current.focus();
|
textareaQuestionRef.current.focus();
|
||||||
|
textareaQuestionRef.current.style.height = 'auto';
|
||||||
|
textareaQuestionRef.current.style.height = `${textareaQuestionRef.current.scrollHeight}px`;
|
||||||
}
|
}
|
||||||
}, [isEditingQuestion]);
|
}, [isEditingQuestion]);
|
||||||
|
|
||||||
|
|
@ -109,6 +116,7 @@ const QuestionItem: React.FC<QuestionItemProps> = ({indexQuestion, initialTextQu
|
||||||
onKeyDown={handleQuestionKeyDown}
|
onKeyDown={handleQuestionKeyDown}
|
||||||
onBlur={handleQuestionBlur}
|
onBlur={handleQuestionBlur}
|
||||||
placeholder={initialTextQuestion}
|
placeholder={initialTextQuestion}
|
||||||
|
rows={1}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<button className={styles.buttonQuestion} onClick={handleQuestionClick}>
|
<button className={styles.buttonQuestion} onClick={handleQuestionClick}>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,84 @@
|
||||||
|
.registerContainer{
|
||||||
|
width: 31%;
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
padding: 94px 80px;
|
||||||
|
margin: auto;
|
||||||
|
border-radius: 43px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title{
|
||||||
|
text-align: center;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 40px;
|
||||||
|
line-height: 88%;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 80px;
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form{
|
||||||
|
text-align: center;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 80px;
|
||||||
|
margin-bottom: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 88%;
|
||||||
|
color: #000000; /* Цвет текста по умолчанию */
|
||||||
|
outline: none;
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid rgba(0, 0, 0, 0.2); /* Нижняя граница с прозрачностью */
|
||||||
|
padding: 5px 0;
|
||||||
|
opacity: 1; /* Установите opacity в 1 для input, а для placeholder используйте opacity */
|
||||||
|
}
|
||||||
|
|
||||||
|
.input::placeholder {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 88%;
|
||||||
|
color: #000000;
|
||||||
|
opacity: 0.2; /* Прозрачность placeholder */
|
||||||
|
}
|
||||||
|
|
||||||
|
.input:focus::placeholder {
|
||||||
|
opacity: 0; /* Убираем placeholder при фокусе */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Отключаем стиль для input, когда в нём есть данные */
|
||||||
|
.input:not(:placeholder-shown) {
|
||||||
|
color: black;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input:focus {
|
||||||
|
border-bottom: 1px solid black; /* Чёрная граница при фокусе */
|
||||||
|
}
|
||||||
|
|
||||||
|
.signUp{
|
||||||
|
margin: auto;
|
||||||
|
padding: 25.5px 16px;
|
||||||
|
width: fit-content;
|
||||||
|
border-radius: 24px;
|
||||||
|
background-color: #3788D6;
|
||||||
|
color: #FFFFFF;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 120%;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendation{
|
||||||
|
text-align: center;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recommendationLink{
|
||||||
|
color: #3788D6;
|
||||||
|
margin-left: 5px;
|
||||||
|
}
|
||||||
99
SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx
Normal file
99
SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
import {Link, useNavigate} from "react-router-dom";
|
||||||
|
import styles from './RegisterForm.module.css';
|
||||||
|
import {useRef, useState} from 'react';
|
||||||
|
import {registerUser} from "../../api/AuthApi.ts";
|
||||||
|
|
||||||
|
const RegisterForm = () => {
|
||||||
|
const [focused, setFocused] = useState({
|
||||||
|
firstName: false,
|
||||||
|
lastName: false,
|
||||||
|
email: false,
|
||||||
|
password: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const nameRef = useRef<HTMLInputElement>(null);
|
||||||
|
const surnameRef = useRef<HTMLInputElement>(null);
|
||||||
|
const emailRef = useRef<HTMLInputElement>(null);
|
||||||
|
const passwordRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const firstName = nameRef.current?.value || '';
|
||||||
|
const lastName = surnameRef.current?.value || '';
|
||||||
|
const email = emailRef.current?.value || '';
|
||||||
|
const password = passwordRef.current?.value || '';
|
||||||
|
const username = firstName + lastName || '';
|
||||||
|
|
||||||
|
try{
|
||||||
|
const responseData = await registerUser({username, firstName, lastName, email, password});
|
||||||
|
console.log(responseData); //проверка вывода данных
|
||||||
|
if (responseData && !responseData.error) {
|
||||||
|
console.log('Регистрация успешна');
|
||||||
|
localStorage.setItem("user", JSON.stringify({
|
||||||
|
firstName,
|
||||||
|
lastName
|
||||||
|
}));
|
||||||
|
navigate('/my-surveys');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.error(`Ошибка регистрации: ${responseData}`);
|
||||||
|
console.log('Регистраиця не удалась');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`Ошибка при отправке запроса ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.registerContainer}>
|
||||||
|
<h2 className={styles.title}>Регистрация</h2>
|
||||||
|
<form className={styles.form} onSubmit={handleSubmit}>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.name}`}
|
||||||
|
type={'text'}
|
||||||
|
placeholder='Имя'
|
||||||
|
ref={nameRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, firstName: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, firstName: false })}
|
||||||
|
style={{ color: focused.firstName ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.surname}`}
|
||||||
|
type={'text'}
|
||||||
|
placeholder='Фамилия'
|
||||||
|
ref={surnameRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, lastName: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, lastName: false })}
|
||||||
|
style={{ color: focused.lastName ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.email}`}
|
||||||
|
type={'email'}
|
||||||
|
placeholder='Почта'
|
||||||
|
ref={emailRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, email: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, email: false })}
|
||||||
|
style={{ color: focused.email ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
className={`${styles.input} ${styles.password}`}
|
||||||
|
type='password'
|
||||||
|
placeholder='Пароль'
|
||||||
|
ref={passwordRef}
|
||||||
|
onFocus={() => setFocused({ ...focused, password: true })}
|
||||||
|
onBlur={() => setFocused({ ...focused, password: false })}
|
||||||
|
style={{ color: focused.password ? 'black' : 'inherit' }}
|
||||||
|
/>
|
||||||
|
<button className={styles.signUp} type='submit'>Зарегистрироваться</button>
|
||||||
|
</form>
|
||||||
|
<p className={styles.recommendation}>Уже с нами?
|
||||||
|
<Link className={styles.recommendationLink} to='/login'>Войдите!</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RegisterForm;
|
||||||
|
|
@ -11,6 +11,7 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
.param{
|
.param{
|
||||||
|
border-radius: 4px;
|
||||||
background-color: #FFFFFF;
|
background-color: #FFFFFF;
|
||||||
padding-top: 15px;
|
padding-top: 15px;
|
||||||
padding-bottom: 97px;
|
padding-bottom: 97px;
|
||||||
|
|
|
||||||
|
|
@ -24,50 +24,60 @@
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
line-height: 20px;
|
|
||||||
margin-bottom: 23px;
|
margin-bottom: 23px;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.textareaTitle{
|
.textareaTitle,
|
||||||
margin-top: -17px;
|
.textareaDescrip {
|
||||||
width: 80%;
|
width: 100%;
|
||||||
padding-top: 35px;
|
|
||||||
resize: none;
|
resize: none;
|
||||||
text-align: center;
|
|
||||||
font-size: 40px;
|
|
||||||
font-weight: 600;
|
|
||||||
border: none;
|
border: none;
|
||||||
outline: none;
|
outline: none;
|
||||||
line-height: 30px;
|
font-family: inherit;
|
||||||
word-break: break-word;
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
background: transparent;
|
||||||
|
display: block;
|
||||||
|
overflow-y: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.description{
|
.textareaTitle {
|
||||||
|
font-size: 32px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.2;
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.textareaDescrip {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 500;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.4;
|
||||||
|
min-height: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.descriptionWrapper {
|
||||||
|
width: 80%;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 5px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
border: none;
|
border: none;
|
||||||
font-size: 24px;
|
font-size: 18px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
background-color: white;
|
background-color: white;
|
||||||
display: block;
|
display: block;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
|
padding: 5px 0;
|
||||||
|
width: 80%;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
padding: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.textareaDescrip{
|
|
||||||
width: 80%;
|
|
||||||
outline: none;
|
|
||||||
border: none;
|
|
||||||
resize: none;
|
|
||||||
text-align: center;
|
|
||||||
margin: 0 auto;
|
|
||||||
font-size: 22px;
|
|
||||||
font-weight: 500;
|
|
||||||
word-break: break-word;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.descripButton{
|
.descripButton{
|
||||||
border: none;
|
border: none;
|
||||||
|
|
|
||||||
|
|
@ -9,34 +9,50 @@ const SurveyInfo: React.FC = () => {
|
||||||
const titleTextareaRef = useRef<HTMLTextAreaElement>(null);
|
const titleTextareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
const descriptionTextareaRef = useRef<HTMLTextAreaElement>(null);
|
const descriptionTextareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
const adjustTextareaHeight = (textarea: HTMLTextAreaElement | null) => {
|
||||||
|
if (textarea) {
|
||||||
|
// Сброс высоты перед расчетом
|
||||||
|
textarea.style.height = 'auto';
|
||||||
|
// Устанавливаем высоту равной scrollHeight + небольшой отступ
|
||||||
|
textarea.style.height = `${textarea.scrollHeight}px`;
|
||||||
|
// Центрируем содержимое вертикально
|
||||||
|
textarea.style.paddingTop = `${Math.max(0, (textarea.clientHeight - textarea.scrollHeight) / 2)}px`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleDescriptionChange = (descripEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
|
const handleDescriptionChange = (descripEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
setDescriptionSurvey(descripEvent.target.value);
|
setDescriptionSurvey(descripEvent.target.value);
|
||||||
}
|
adjustTextareaHeight(descripEvent.target);
|
||||||
|
};
|
||||||
|
|
||||||
const handleNewTitleChange = (titleEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
|
const handleNewTitleChange = (titleEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
setTitleSurvey(titleEvent.target.value);
|
setTitleSurvey(titleEvent.target.value);
|
||||||
|
adjustTextareaHeight(titleEvent.target);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (showNewTitleField && titleTextareaRef.current) {
|
||||||
|
titleTextareaRef.current.focus();
|
||||||
|
adjustTextareaHeight(titleTextareaRef.current);
|
||||||
}
|
}
|
||||||
|
}, [showNewTitleField]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (showDescriptionField && descriptionTextareaRef.current) {
|
||||||
|
descriptionTextareaRef.current.focus();
|
||||||
|
adjustTextareaHeight(descriptionTextareaRef.current);
|
||||||
|
}
|
||||||
|
}, [showDescriptionField]);
|
||||||
|
|
||||||
|
|
||||||
const handleAddNewTitleClick = () => {
|
const handleAddNewTitleClick = () => {
|
||||||
setShowNewTitleField(true);
|
setShowNewTitleField(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (showNewTitleField && titleTextareaRef.current) {
|
|
||||||
titleTextareaRef.current.focus();
|
|
||||||
}
|
|
||||||
}, [showNewTitleField]);
|
|
||||||
|
|
||||||
const handleAddDescriptionClick = () => {
|
const handleAddDescriptionClick = () => {
|
||||||
setShowDescriptionField(true);
|
setShowDescriptionField(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (showDescriptionField && descriptionTextareaRef.current){
|
|
||||||
descriptionTextareaRef.current.focus();
|
|
||||||
}
|
|
||||||
}, [showDescriptionField]);
|
|
||||||
|
|
||||||
const handleTitleKeyDown = (titleClickEnter: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
const handleTitleKeyDown = (titleClickEnter: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||||
if (titleClickEnter.key === 'Enter'){
|
if (titleClickEnter.key === 'Enter'){
|
||||||
titleClickEnter.preventDefault();
|
titleClickEnter.preventDefault();
|
||||||
|
|
@ -64,7 +80,7 @@ const SurveyInfo: React.FC = () => {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const renderDescription = ()=> {
|
const renderDescription = () => {
|
||||||
if (descriptionSurvey && !showDescriptionField) {
|
if (descriptionSurvey && !showDescriptionField) {
|
||||||
return (
|
return (
|
||||||
<button className={styles.description} onClick={handleParagraphClick}>
|
<button className={styles.description} onClick={handleParagraphClick}>
|
||||||
|
|
@ -73,7 +89,7 @@ const SurveyInfo: React.FC = () => {
|
||||||
);
|
);
|
||||||
} else if (showDescriptionField) {
|
} else if (showDescriptionField) {
|
||||||
return (
|
return (
|
||||||
<p className={styles.description}>
|
<div className={styles.descriptionWrapper}>
|
||||||
<textarea
|
<textarea
|
||||||
ref={descriptionTextareaRef}
|
ref={descriptionTextareaRef}
|
||||||
className={styles.textareaDescrip}
|
className={styles.textareaDescrip}
|
||||||
|
|
@ -82,8 +98,9 @@ const SurveyInfo: React.FC = () => {
|
||||||
onChange={handleDescriptionChange}
|
onChange={handleDescriptionChange}
|
||||||
onKeyDown={handleDescriptionKeyDown}
|
onKeyDown={handleDescriptionKeyDown}
|
||||||
onBlur={handleDescriptionBlur}
|
onBlur={handleDescriptionBlur}
|
||||||
|
rows={1} // Начальное количество строк
|
||||||
/>
|
/>
|
||||||
</p>
|
</div>
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
12
SurveyFrontend/src/pages/AuthForm/AuthForm.module.css
Normal file
12
SurveyFrontend/src/pages/AuthForm/AuthForm.module.css
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
.page{
|
||||||
|
width: 100%;
|
||||||
|
min-height: 100vh;
|
||||||
|
background-color: #F6F6F6;
|
||||||
|
padding: 61.5px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pageLogin{
|
||||||
|
width: 100%;
|
||||||
|
background-color: #F6F6F6;
|
||||||
|
padding: 157px 0;
|
||||||
|
}
|
||||||
35
SurveyFrontend/src/pages/AuthForm/AuthForm.tsx
Normal file
35
SurveyFrontend/src/pages/AuthForm/AuthForm.tsx
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import styles from './AuthForm.module.css';
|
||||||
|
import LoginForm from "../../components/LoginForm/LoginForm.tsx";
|
||||||
|
import RegisterForm from "../../components/RegisterForm/RegisterForm.tsx";
|
||||||
|
import {useLocation} from "react-router-dom";
|
||||||
|
|
||||||
|
|
||||||
|
const AuthForm = () => {
|
||||||
|
// const location = useLocation();
|
||||||
|
// const isLogin = location.pathname === '/login';
|
||||||
|
//
|
||||||
|
// return (
|
||||||
|
// <div className={`${isLogin ? styles.pageLogin : styles.page}`}>
|
||||||
|
// {isLogin ? <LoginForm /> : <RegisterForm/>}
|
||||||
|
// </div>
|
||||||
|
// );
|
||||||
|
|
||||||
|
const location = useLocation();
|
||||||
|
const isLoginPage = location.pathname === '/login';
|
||||||
|
const isRegisterPage = location.pathname === '/register';
|
||||||
|
|
||||||
|
let content;
|
||||||
|
if (isLoginPage) {
|
||||||
|
content = <LoginForm />;
|
||||||
|
} else if (isRegisterPage) {
|
||||||
|
content = <RegisterForm />;
|
||||||
|
} else {
|
||||||
|
content = <LoginForm />; // По умолчанию показываем LoginForm
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`${(isLoginPage || location.pathname === '/') ? styles.pageLogin : styles.page}`}>{content}</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AuthForm;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue