-
Notifications
You must be signed in to change notification settings - Fork 12
Куненков Иван Лаб. 1 Группа 6511 #3
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
Open
razzzenya
wants to merge
11
commits into
itsecd:main
Choose a base branch
from
razzzenya:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
08d4256
готовая лр
razzzenya 59cb056
фикс проблемы с CORS
razzzenya 7867a56
обновил README
razzzenya af07609
Добавил скрины к README
razzzenya c496c33
правки по коду
razzzenya ab4a3a3
Фикс версий проекта
razzzenya edf7c15
правки
razzzenya 9c915c1
правки версий
razzzenya 4b76f33
Merge branch 'main' into main
razzzenya 2a542d6
вернул base address
razzzenya 3737e0c
обернул метод сервиса в try-catch
razzzenya 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
Some comments aren't visible on the classic Files Changed page.
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
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
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 |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| } | ||
| "BaseAddress": "https://localhost:7170/api/credit" | ||
| } | ||
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
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,26 @@ | ||
| using CreditApp.Api.Services.CreditGeneratorService; | ||
| using CreditApp.Domain.Entities; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace CreditApp.Api.Controllers; | ||
|
|
||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public class CreditController(CreditApplicationGeneratorService _generatorService, ILogger<CreditController> _logger) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Получить кредитную заявку по ID, если не найдена в кэше генерируем новую | ||
| /// </summary> | ||
| /// <param name="id">ID кредитной заявки</param> | ||
| /// <param name="cancellationToken">Токен отмены операции</param> | ||
| /// <returns>Кредитная заявка</returns> | ||
| [HttpGet] | ||
| public async Task<ActionResult<CreditApplication>> GetById([FromQuery] int id, CancellationToken cancellationToken) | ||
| { | ||
| _logger.LogInformation("Получен запрос на получение/генерацию заявки {Id}", id); | ||
|
|
||
| var application = await _generatorService.GetByIdAsync(id, cancellationToken); | ||
|
|
||
| return Ok(application); | ||
| } | ||
| } |
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,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| <NoWarn>$(NoWarn);1591</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.24" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.4" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\CreditApp.Domain\CreditApp.Domain.csproj" /> | ||
| <ProjectReference Include="..\CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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,58 @@ | ||
| using CreditApp.Api.Services.CreditGeneratorService; | ||
| using CreditApp.ServiceDefaults; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
|
|
||
| builder.AddRedisDistributedCache("cache"); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddPolicy("AllowBlazorWasm", policy => | ||
| { | ||
| policy.AllowAnyOrigin() | ||
| .AllowAnyMethod() | ||
| .AllowAnyHeader(); | ||
| }); | ||
| }); | ||
|
|
||
| builder.Services.AddScoped<CreditApplicationGeneratorService>(); | ||
|
|
||
| builder.Services.AddControllers(); | ||
| builder.Services.AddEndpointsApiExplorer(); | ||
| builder.Services.AddSwaggerGen(options => | ||
| { | ||
| options.SwaggerDoc("v1", new Microsoft.OpenApi.OpenApiInfo | ||
| { | ||
| Title = "CreditApp API" | ||
| }); | ||
|
|
||
| var xmlFilename = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"; | ||
| var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFilename); | ||
| if (File.Exists(xmlPath)) | ||
| { | ||
| options.IncludeXmlComments(xmlPath); | ||
| } | ||
|
|
||
| var domainXmlPath = Path.Combine(AppContext.BaseDirectory, "CreditApp.Domain.xml"); | ||
| if (File.Exists(domainXmlPath)) | ||
| { | ||
| options.IncludeXmlComments(domainXmlPath); | ||
| } | ||
| }); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
| } | ||
|
|
||
| app.UseHttpsRedirection(); | ||
| app.UseCors("AllowBlazorWasm"); | ||
| app.MapControllers(); | ||
| app.MapDefaultEndpoints(); | ||
|
|
||
| app.Run(); | ||
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,41 @@ | ||
| { | ||
| "$schema": "http://json.schemastore.org/launchsettings.json", | ||
| "iisSettings": { | ||
| "windowsAuthentication": false, | ||
| "anonymousAuthentication": true, | ||
| "iisExpress": { | ||
| "applicationUrl": "http://localhost:46825", | ||
| "sslPort": 44333 | ||
| } | ||
| }, | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "http://localhost:5179", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "https://localhost:7170;http://localhost:5179", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "IIS Express": { | ||
| "commandName": "IISExpress", | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
116 changes: 116 additions & 0 deletions
116
CreditApp.Api/Services/CreditGeneratorService/CreditApplicationGeneratorService.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,116 @@ | ||
| using Bogus; | ||
| using CreditApp.Domain.Entities; | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
| using System.Text.Json; | ||
|
|
||
| namespace CreditApp.Api.Services.CreditGeneratorService; | ||
|
|
||
| public class CreditApplicationGeneratorService(IDistributedCache _cache, IConfiguration _configuration, ILogger<CreditApplicationGeneratorService> _logger) | ||
| { | ||
| private static readonly string[] _creditTypes = | ||
| [ | ||
| "Потребительский", | ||
| "Ипотека", | ||
| "Автокредит", | ||
| "Бизнес-кредит", | ||
| "Образовательный" | ||
| ]; | ||
|
|
||
| private static readonly string[] _statuses = | ||
| [ | ||
| "Новая", | ||
| "В обработке", | ||
| "Одобрена", | ||
| "Отклонена" | ||
| ]; | ||
|
|
||
| private static readonly string[] _terminalStatuses = ["Одобрена", "Отклонена"]; | ||
|
|
||
| private readonly int _expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 10); | ||
|
|
||
| public async Task<CreditApplication> GetByIdAsync(int id, CancellationToken cancellationToken = default) | ||
|
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. Я бы этот метод в try catch обернул |
||
| { | ||
| try | ||
| { | ||
| var cacheKey = $"credit-application-{id}"; | ||
|
|
||
| _logger.LogInformation("Попытка получить заявку {Id} из кэша", id); | ||
|
|
||
| var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken); | ||
|
|
||
| if (!string.IsNullOrEmpty(cachedData)) | ||
| { | ||
| var deserializedApplication = JsonSerializer.Deserialize<CreditApplication>(cachedData); | ||
|
|
||
| if (deserializedApplication != null) | ||
| { | ||
| _logger.LogInformation("Заявка {Id} найдена в кэше", id); | ||
| return deserializedApplication; | ||
| } | ||
|
|
||
| _logger.LogWarning("Заявка {Id} найдена в кэше, но не удалось десериализовать. Генерируем новую", id); | ||
| } | ||
|
|
||
| _logger.LogInformation("Заявка {Id} не найдена в кэше, генерируем новую", id); | ||
|
|
||
| var application = GenerateApplication(id); | ||
|
|
||
| var cacheOptions = new DistributedCacheEntryOptions | ||
| { | ||
| AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_expirationMinutes) | ||
| }; | ||
|
|
||
| await _cache.SetStringAsync( | ||
| cacheKey, | ||
| JsonSerializer.Serialize(application), | ||
| cacheOptions, | ||
| cancellationToken); | ||
|
|
||
| _logger.LogInformation( | ||
| "Кредитная заявка сгенерирована и закэширована: Id={Id}, Тип={Type}, Сумма={Amount}, Статус={Status}", | ||
| application.Id, | ||
| application.Type, | ||
| application.Amount, | ||
| application.Status); | ||
|
|
||
| return application; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Ошибка при получении/генерации заявки {Id}", id); | ||
| throw; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Генерация кредитной заявки с указанным ID | ||
| /// </summary> | ||
| private static CreditApplication GenerateApplication(int id) | ||
| { | ||
| var faker = new Faker<CreditApplication>("ru") | ||
| .RuleFor(c => c.Id, f => id) | ||
| .RuleFor(c => c.Type, f => f.PickRandom(_creditTypes)) | ||
| .RuleFor(c => c.Amount, f => Math.Round(f.Finance.Amount(10000, 10000000), 2)) | ||
| .RuleFor(c => c.Term, f => f.Random.Int(6, 360)) | ||
| .RuleFor(c => c.InterestRate, f => Math.Round(f.Random.Double(16.0, 25.0), 2)) | ||
| .RuleFor(c => c.SubmissionDate, f => f.Date.PastDateOnly(2)) | ||
| .RuleFor(c => c.RequiresInsurance, f => f.Random.Bool()) | ||
| .RuleFor(c => c.Status, f => f.PickRandom(_statuses)) | ||
| .RuleFor(c => c.ApprovalDate, (f, c) => | ||
| { | ||
| if (!_terminalStatuses.Contains(c.Status)) | ||
| return null; | ||
|
|
||
| return f.Date.BetweenDateOnly(c.SubmissionDate, DateOnly.FromDateTime(DateTime.Today)); | ||
| }) | ||
| .RuleFor(c => c.ApprovedAmount, (f, c) => | ||
| { | ||
| if (c.Status != "Одобрена") | ||
| return null; | ||
|
|
||
| return Math.Round(c.Amount * f.Random.Decimal(0.7m, 1.0m), 2); | ||
| }); | ||
|
|
||
| return faker.Generate(); | ||
| } | ||
| } | ||
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,12 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "CacheSettings": { | ||
| "ExpirationMinutes": 10 | ||
| } | ||
| } |
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,12 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "CacheSettings": { | ||
| "ExpirationMinutes": 10 | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.