-
Notifications
You must be signed in to change notification settings - Fork 24
Уваров Никита Лаб. 1 Группа 6513 #16
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
base: main
Are you sure you want to change the base?
Changes from all commits
9e2d2ae
0b417eb
5fdc84a
50fa1f5
494e372
871d798
c8e701b
5c5cb8e
b0a7b6c
9f3a8f0
9d3bc73
826be7d
a79906c
ef0152d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "https://localhost:7184/api/Credit" | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| using CreditApp.Api.Services; | ||
| using CreditApp.Domain.Data; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace CreditApp.Api.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Контроллер для работы с кредитными заявками | ||
| /// </summary> | ||
| [ApiController] | ||
| [Route("api/[controller]")] | ||
| public class CreditController : ControllerBase | ||
| { | ||
| private readonly ICreditService _creditService; | ||
| private readonly ILogger<CreditController> _logger; | ||
|
|
||
| public CreditController( | ||
| ICreditService creditService, | ||
| ILogger<CreditController> logger) | ||
| { | ||
| _creditService = creditService; | ||
| _logger = logger; | ||
| } | ||
|
Comment on lines
+14
to
+23
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Использовать праймари конструктор А знаешь, где еще такая же проблема? В #15 |
||
|
|
||
| /// <summary> | ||
| /// Получить кредитную заявку по идентификатору | ||
| /// </summary> | ||
| [HttpGet("{id:int}")] | ||
| [ProducesResponseType(typeof(CreditApplication), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
| public async Task<ActionResult<CreditApplication>> GetCreditApplication( | ||
| int id, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| _logger.LogInformation("Getting credit application with Id: {CreditId}", id); | ||
|
|
||
| if (id <= 0) | ||
| { | ||
| _logger.LogWarning("Invalid credit application Id: {CreditId}", id); | ||
| return BadRequest("Id must be positive number"); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var creditApplication = await _creditService.GetAsync(id, cancellationToken); | ||
|
|
||
| _logger.LogInformation( | ||
| "Successfully retrieved credit application {CreditId}", | ||
| id); | ||
|
|
||
| return Ok(creditApplication); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Error getting credit application {CreditId}", id); | ||
| return StatusCode(500, "Internal server error"); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот код в атрибутах не описан |
||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Сгенерировать кредитную заявку с указанным seed | ||
| /// </summary> | ||
| [HttpGet] | ||
| [ProducesResponseType(typeof(CreditApplication), StatusCodes.Status200OK)] | ||
| public async Task<ActionResult<CreditApplication>> GenerateCredit( | ||
| [FromQuery] int? seed, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| _logger.LogInformation("Generating credit application with seed: {Seed}", seed); | ||
|
|
||
| var id = new Random().Next(1, 10000); | ||
|
|
||
| CreditApplication creditApplication; | ||
|
|
||
| if (seed.HasValue) | ||
| { | ||
| creditApplication = await _creditService.GetAsync(id, seed.Value, cancellationToken); | ||
| _logger.LogInformation("Generated credit application with seed {Seed}: {CreditId}", seed, id); | ||
| } | ||
| else | ||
| { | ||
| creditApplication = await _creditService.GetAsync(id, cancellationToken); | ||
| _logger.LogInformation("Generated random credit application: {CreditId}", id); | ||
| } | ||
|
|
||
| return Ok(creditApplication); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Удалить заявку из кэша | ||
| /// </summary> | ||
| [HttpDelete("{id:int}")] | ||
| [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| public async Task<IActionResult> RemoveCreditApplication( | ||
| int id, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| if (id <= 0) | ||
| { | ||
| return BadRequest("Id must be positive number"); | ||
| } | ||
|
|
||
| await _creditService.RemoveAsync(id, cancellationToken); | ||
| return NoContent(); | ||
| } | ||
| } | ||
|
Comment on lines
+61
to
+108
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не надо вносить функциональность, которая в софте не требуется |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.1.1" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Microsoft.Extensions.Caching.Redis" Version="2.3.0" /> | ||
| <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.3" /> | ||
|
Comment on lines
+12
to
+13
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тебе не нужны эти библиотеки, ты уже пользуешься аспаеровской либой |
||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" /> | ||
| <ProjectReference Include="..\CreditApp.Domain\CreditApp.Domain.csproj" /> | ||
| <ProjectReference Include="..\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| @CreditApp.Api_HostAddress = http://localhost:5144 | ||
|
|
||
| GET {{CreditApp.Api_HostAddress}}/weatherforecast/ | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Классный маршрут, жаль в твоих контроллерах его нет |
||
| Accept: application/json | ||
|
|
||
| ### | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| using CreditApp.Api.Services; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
| builder.AddRedisDistributedCache("redis"); | ||
|
|
||
| builder.Services.AddControllers(); | ||
| builder.Services.AddEndpointsApiExplorer(); | ||
| builder.Services.AddSwaggerGen(); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddPolicy("wasm", policy => | ||
| { | ||
| policy.AllowAnyOrigin() | ||
| .WithMethods("GET") | ||
| .WithHeaders("Content-Type"); | ||
| }); | ||
| }); | ||
|
|
||
| builder.Services.AddSingleton<ICreditGenerator, CreditGenerator>(); | ||
| builder.Services.AddScoped<ICreditService, CreditService>(); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
| } | ||
|
|
||
| app.MapDefaultEndpoints(); | ||
| app.UseHttpsRedirection(); | ||
| app.UseCors("wasm"); | ||
| app.UseAuthorization(); | ||
| app.MapControllers(); | ||
|
|
||
| app.Run(); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| { | ||
| "$schema": "http://json.schemastore.org/launchsettings.json", | ||
| "iisSettings": { | ||
| "windowsAuthentication": false, | ||
| "anonymousAuthentication": true, | ||
| "iisExpress": { | ||
| "applicationUrl": "http://localhost:50546", | ||
| "sslPort": 44330 | ||
| } | ||
| }, | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "http://localhost:5144", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "https://localhost:7184;http://localhost:5144", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "IIS Express": { | ||
| "commandName": "IISExpress", | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Выпилить отсюда лишний функционал |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| using Bogus; | ||
| using CreditApp.Domain.Data; | ||
|
|
||
| namespace CreditApp.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Генератор тестовых данных для кредитных заявок с использованием библиотеки Bogus. | ||
| /// </summary> | ||
| public class CreditGenerator : ICreditGenerator | ||
| { | ||
| private const double CbRate = 16.0; | ||
| private readonly string[] _statuses = { "Новая", "В обработке", "Одобрена", "Отклонена" }; | ||
| private readonly string[] _types = { "Потребительский", "Ипотека", "Автокредит" }; | ||
|
|
||
| /// <summary> | ||
| /// Генерирует кредитную заявку со случайным seed. | ||
| /// </summary> | ||
| public CreditApplication Generate(int id) | ||
| { | ||
| return Generate(id, new Random().Next(1, 10000)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Генерирует кредитную заявку с указанным seed для воспроизводимости результатов. | ||
| /// </summary> | ||
| public CreditApplication Generate(int id, int seed) | ||
| { | ||
| var faker = new Faker<CreditApplication>() | ||
| .RuleFor(x => x.Id, id) | ||
| .RuleFor(x => x.CreditType, f => f.PickRandom(_types)) | ||
| .RuleFor(x => x.RequestedAmount, f => Math.Round(f.Random.Decimal(10000, 5_000_000), 2)) | ||
| .RuleFor(x => x.TermMonths, f => f.Random.Int(6, 360)) | ||
| .RuleFor(x => x.InterestRate, f => Math.Round(f.Random.Double(CbRate, CbRate + 5), 2)) | ||
| .RuleFor(x => x.ApplicationDate, f => DateOnly.FromDateTime(f.Date.Past(2))) | ||
| .RuleFor(x => x.HasInsurance, f => f.Random.Bool()) | ||
| .RuleFor(x => x.Status, f => f.PickRandom(_statuses)) | ||
| .RuleFor(x => x.DecisionDate, (f, x) => | ||
| x.Status is "Одобрена" or "Отклонена" | ||
| ? DateOnly.FromDateTime( | ||
| f.Date.Between( | ||
| x.ApplicationDate.ToDateTime(TimeOnly.MinValue), | ||
| DateTime.Now)) | ||
| : null) | ||
| .RuleFor(x => x.ApprovedAmount, (f, x) => | ||
| x.Status == "Одобрена" | ||
| ? Math.Round(f.Random.Decimal(10000, x.RequestedAmount), 2) | ||
| : null); | ||
|
|
||
|
Comment on lines
+28
to
+48
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вынести в статику, чтобы не создавать каждый запрос |
||
| faker.UseSeed(seed); | ||
|
|
||
| return faker.Generate(); | ||
| } | ||
| } | ||
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.
Мог бы и 10 дотнет с 13 аспаером использовать, раз ты 2026 вижуал студией пользуешься