-
Notifications
You must be signed in to change notification settings - Fork 80
Лаб. 4 6411 Емец Тимофей #286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6f5aa27
lab1: created class structure and unit-tests
Cure232 b2c3c90
lab2+3
Cure232 70bcd07
lab4 added grpc
Cure232 08f3a14
pr fixes: added controllers summaries for swagger, fixed break in grp…
Cure232 ba5eab7
fix: tried to fix encoding + additional documentation
Cure232 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| * text=auto | ||
| *.cs text encoding=UTF-8 | ||
| *.json text encoding=UTF-8 | ||
| *.xml text encoding=UTF-8 | ||
| *.config text encoding=UTF-8 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.MongoDB.Driver" Version="13.0.0" /> | ||
| <PackageReference Include="Grpc.AspNetCore" Version="2.71.0" /> | ||
| <PackageReference Include="Grpc.Net.Client" Version="2.71.0" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="10.0.1" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="..\Agency.Application\Agency.Application.csproj" /> | ||
| <ProjectReference Include="..\Agency.Infrastructure.EfCore\Agency.Infrastructure.EfCore.csproj" /> | ||
| <ProjectReference Include="..\Agency.ServiceDefaults\Agency.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <Protobuf Include="..\Agency.Application.Contracts\Protos\ContractRequest.proto" GrpcServices="Client"> | ||
| <Link>Protos\ContractRequest.proto</Link> | ||
| </Protobuf> | ||
| </ItemGroup> | ||
| </Project> |
176 changes: 176 additions & 0 deletions
176
RealEstateAgency/Agency.Api.Host/Controllers/AnalyticsController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| using Agency.Application.Contracts; | ||
| using Agency.Application.Contracts.Counterparties; | ||
| using Agency.Domain.Model; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Agency.Api.Host.Controllers; | ||
|
|
||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public class AnalyticsController(IAnalyticsService service, ILogger<AnalyticsController> logger) : ControllerBase | ||
| { | ||
|
|
||
| /// <summary> | ||
| /// Получает список всех продавцов, которые оставили заявки на продажу за указанный период времени | ||
| /// </summary> | ||
| /// <param name="from">Начальная дата периода (включительно)</param> | ||
| /// <param name="to">Конечная дата периода (включительно)</param> | ||
| /// <returns>Список контрагентов-продавцов, оставивших заявки в указанный период</returns> | ||
| /// <response code="200">Успешное получение списка продавцов</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("sellers-with-requests-in-period")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetSellersWithRequestsInPeriod([FromQuery] DateTime from, [FromQuery] DateTime to) | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetSellersWithRequestsInPeriod(from, to); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetSellersWithRequestsInPeriod"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает топ-5 клиентов по количеству заявок на покупку недвижимости | ||
| /// </summary> | ||
| /// <returns>Список пяти клиентов с наибольшим количеством заявок на покупку</returns> | ||
| /// <response code="200">Успешное получение списка топ-5 покупателей</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("top5-buyers-by-request-count")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetTop5BuyersByRequestCount() | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetTop5BuyersByRequestCount(); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetTop5BuyersByRequestCount"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает топ-5 клиентов по количеству заявок на продажу недвижимости | ||
| /// </summary> | ||
| /// <returns>Список пяти клиентов с наибольшим количеством заявок на продажу</returns> | ||
| /// <response code="200">Успешное получение списка топ-5 продавцов</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("top5-sellers-by-request-count")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetTop5SellersByRequestCount() | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetTop5SellersByRequestCount(); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetTop5SellersByRequestCount"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает статистику по количеству заявок для каждого типа недвижимости | ||
| /// </summary> | ||
| /// <returns>Словарь, где ключ - тип недвижимости, значение - количество заявок</returns> | ||
| /// <response code="200">Успешное получение статистики по типам недвижимости</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("request-count-by-property-type")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<Dictionary<RealEstateType, int>>> GetRequestCountByPropertyType() | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetRequestCountByPropertyType(); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetRequestCountByPropertyType"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает список клиентов, которые открыли заявки с минимальной стоимостью | ||
| /// </summary> | ||
| /// <returns>Список клиентов, чьи заявки имеют минимальную сумму</returns> | ||
| /// <response code="200">Успешное получение списка клиентов с минимальными заявками</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("clients-with-minimal-request-amount")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetClientsWithMinimalRequestAmount() | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetClientsWithMinimalRequestAmount(); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetClientsWithMinimalRequestAmount"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает список всех клиентов, ищущих недвижимость заданного типа (покупка) | ||
| /// </summary> | ||
| /// <param name="propertyType">Тип недвижимости для поиска</param> | ||
| /// <returns>Список клиентов, ищущих недвижимость указанного типа, отсортированный по ФИО</returns> | ||
| /// <response code="200">Успешное получение списка клиентов по типу недвижимости</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("clients-searching-for-property-type")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetClientsSearchingForPropertyType([FromQuery] RealEstateType propertyType) | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetClientsSearchingForPropertyType(propertyType); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetClientsSearchingForPropertyType"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает список всех клиентов, ищущих дома (тип недвижимости House), отсортированный по ФИО | ||
| /// </summary> | ||
| /// <returns>Список клиентов, ищущих дома, отсортированный по ФИО в алфавитном порядке</returns> | ||
| /// <response code="200">Успешное получение списка клиентов, ищущих дома</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("clients-searching-for-houses-ordered-by-fullname")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<CounterpartyDto>>> GetClientsSearchingForHousesOrderedByFullName() | ||
| { | ||
| try | ||
| { | ||
| var result = await service.GetClientsSearchingForHousesOrderedByFullName(); | ||
| return Ok(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in GetClientsSearchingForHousesOrderedByFullName"); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
| } |
11 changes: 11 additions & 0 deletions
11
RealEstateAgency/Agency.Api.Host/Controllers/ContractRequestController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| using Agency.Application.Contracts.ContractRequests; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Agency.Api.Host.Controllers; | ||
|
|
||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public class ContractRequestController(IContractRequestService service, ILogger<ContractRequestController> logger) | ||
| : CrudControllerBase<ContractRequestDto, ContractRequestCreateUpdateDto, int>(service, logger) | ||
| { | ||
| } |
11 changes: 11 additions & 0 deletions
11
RealEstateAgency/Agency.Api.Host/Controllers/CounterpartyController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| using Agency.Application.Contracts.Counterparties; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Agency.Api.Host.Controllers; | ||
|
|
||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public class CounterpartyController(ICounterpartyService service, ILogger<CounterpartyController> logger) | ||
| : CrudControllerBase<CounterpartyDto, CounterpartyCreateUpdateDto, int>(service, logger) | ||
| { | ||
| } |
155 changes: 155 additions & 0 deletions
155
RealEstateAgency/Agency.Api.Host/Controllers/CrudControllerBase.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| using Agency.Application.Contracts; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Agency.Api.Host.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Базовый CRUD контроллер, предоставляющий стандартные операции для работы с сущностями | ||
| /// </summary> | ||
| /// <typeparam name="TDto">Тип DTO для чтения/получения данных сущности</typeparam> | ||
| /// <typeparam name="TCreateUpdateDto">Тип DTO для создания и обновления сущности</typeparam> | ||
| /// <typeparam name="TKey">Тип идентификатора сущности (int, Guid, long и т.д.)</typeparam> | ||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public abstract class CrudControllerBase<TDto, TCreateUpdateDto, TKey>( | ||
| IApplicationService<TDto, TCreateUpdateDto, TKey> appService, | ||
| ILogger<CrudControllerBase<TDto, TCreateUpdateDto, TKey>> logger) : ControllerBase | ||
| where TDto : class | ||
| where TCreateUpdateDto : class | ||
| where TKey : struct | ||
| { | ||
| /// <summary> | ||
| /// Создает новую сущность | ||
| /// </summary> | ||
| /// <param name="newDto">Данные для создания новой сущности</param> | ||
| /// <returns>Созданная сущность с присвоенным идентификатором</returns> | ||
| /// <response code="201">Сущность успешно создана</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpPost] | ||
| [ProducesResponseType(201)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<TDto>> Create(TCreateUpdateDto newDto) | ||
| { | ||
| logger.LogInformation("{Method} of {Controller} called with {@Dto}", nameof(Create), GetType().Name, newDto); | ||
| try | ||
| { | ||
| var res = await appService.Create(newDto); | ||
| return CreatedAtAction(nameof(Create), res); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in {Method} of {Controller}", nameof(Create), GetType().Name); | ||
| return StatusCode(500, $"{ex.Message}\n{ex.InnerException?.Message}"); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Обновляет существующую сущность по идентификатору | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор обновляемой сущности</param> | ||
| /// <param name="newDto">Новые данные для сущности</param> | ||
| /// <returns>Обновленная сущность</returns> | ||
| /// <response code="200">Сущность успешно обновлена</response> | ||
| /// <response code="404">Сущность с указанным идентификатором не найдена</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpPut("{id}")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(404)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<TDto>> Edit(TKey id, TCreateUpdateDto newDto) | ||
| { | ||
| try | ||
| { | ||
| var res = await appService.Update(newDto, id); | ||
| return Ok(res); | ||
| } | ||
| catch (KeyNotFoundException) | ||
| { | ||
| return NotFound(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in {Method} of {Controller}", nameof(Edit), GetType().Name); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Удаляет сущность по идентификатору | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор удаляемой сущности</param> | ||
| /// <returns>Статус выполнения операции</returns> | ||
| /// <response code="200">Сущность успешно удалена</response> | ||
| /// <response code="204">Сущность не найдена (ничего не удалено)</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpDelete("{id}")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(204)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<IActionResult> Delete(TKey id) | ||
| { | ||
| try | ||
| { | ||
| var res = await appService.Delete(id); | ||
| return res ? Ok() : NoContent(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in {Method} of {Controller}", nameof(Delete), GetType().Name); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает список всех сущностей | ||
| /// </summary> | ||
| /// <returns>Список всех сущностей</returns> | ||
| /// <response code="200">Успешное получение списка</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<IList<TDto>>> GetAll() | ||
| { | ||
| try | ||
| { | ||
| var res = await appService.GetAll(); | ||
| return Ok(res); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in {Method} of {Controller}", nameof(GetAll), GetType().Name); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Получает сущность по идентификатору | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор запрашиваемой сущности</param> | ||
| /// <returns>Сущность с указанным идентификатором</returns> | ||
| /// <response code="200">Сущность найдена</response> | ||
| /// <response code="404">Сущность с указанным идентификатором не найдена</response> | ||
| /// <response code="500">Внутренняя ошибка сервера</response> | ||
| [HttpGet("{id}")] | ||
| [ProducesResponseType(200)] | ||
| [ProducesResponseType(404)] | ||
| [ProducesResponseType(500)] | ||
| public async Task<ActionResult<TDto>> Get(TKey id) | ||
| { | ||
| try | ||
| { | ||
| var res = await appService.Get(id); | ||
| return res == null ? NotFound() : Ok(res); | ||
| } | ||
| catch (KeyNotFoundException) | ||
| { | ||
| return NotFound(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Error in {Method} of {Controller}", nameof(Get), GetType().Name); | ||
| return StatusCode(500, ex.Message); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Всем методам во всех контроллерах надо добавить
summaryдля того, чтобы в сваггере была документация