diff --git a/kuzarin_maxim_lab_3/.dockerignore b/kuzarin_maxim_lab_3/.dockerignore new file mode 100644 index 0000000..fe1152b --- /dev/null +++ b/kuzarin_maxim_lab_3/.dockerignore @@ -0,0 +1,30 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md +!**/.gitignore +!.git/HEAD +!.git/config +!.git/packed-refs +!.git/refs/heads/** \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/.gitattributes b/kuzarin_maxim_lab_3/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/kuzarin_maxim_lab_3/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/kuzarin_maxim_lab_3/.gitignore b/kuzarin_maxim_lab_3/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/kuzarin_maxim_lab_3/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC.sln b/kuzarin_maxim_lab_3/DSaC.sln new file mode 100644 index 0000000..c72e3c6 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.34916.146 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DSaC", "DSaC\DSaC.csproj", "{C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DSaC_second", "DSaC_second\DSaC_second.csproj", "{64F78585-2BBC-4656-BC50-41FBB8917719}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1051C12-D7D0-4C77-AFBC-4F5FFD8EE367}.Release|Any CPU.Build.0 = Release|Any CPU + {64F78585-2BBC-4656-BC50-41FBB8917719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64F78585-2BBC-4656-BC50-41FBB8917719}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64F78585-2BBC-4656-BC50-41FBB8917719}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64F78585-2BBC-4656-BC50-41FBB8917719}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {30D05708-634E-4FDE-9BCA-5A1B7A5EFF59} + EndGlobalSection +EndGlobal diff --git a/kuzarin_maxim_lab_3/DSaC/Controllers/CounterpartiesController.cs b/kuzarin_maxim_lab_3/DSaC/Controllers/CounterpartiesController.cs new file mode 100644 index 0000000..3857f97 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Controllers/CounterpartiesController.cs @@ -0,0 +1,88 @@ +using DSaC.Models.DTOs; +using DSaC.Models.Internal.Queries; +using DSaC.Models.Internal.Сommands; +using MediatR; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace DSaC.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class CounterpartiesController : ControllerBase + { + private readonly IMediator mediator; + + public CounterpartiesController(IMediator mediator) + { + this.mediator = mediator; + } + + [HttpGet("")] + public async Task GetCounterparties( + [FromQuery] int page = 0, + [FromQuery] int pageSize = 10, + [FromQuery] List? ids = null + ) + { + var request = new GetCounterpartiesQuery + { + Page = page, + PageSize = pageSize, + Ids = ids + }; + + var response = await mediator.Send(request); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpGet("{uuid:guid}")] + public async Task GetFullCounterparty([FromRoute] Guid uuid) + { + var request = new GetCounterpartyQuery + { + Id = uuid + }; + + var response = await mediator.Send(request); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpPost("")] + public async Task CreateCounterparty([FromBody] CounterpartyBaseDto dto) + { + var response = await mediator.Send(new CreateCounterpartyCommand() + { + Model = dto + }); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpPut("{uuid:guid}")] + public async Task UpdateRecord([FromRoute] Guid uuid, [FromBody] CounterpartyViewDto dto) + { + var response = await mediator.Send(new UpdateCounterpartyCommand() + { + Id=uuid, + Model = dto + }); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpDelete("{uuid:guid}")] + public async Task DeleteRecord([FromRoute] Guid uuid) + { + var response = await mediator.Send(new DeleteCounterpartyCommand() + { + Id = uuid, + }); + + return !response.IsError ? Ok() : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/DSaC.csproj b/kuzarin_maxim_lab_3/DSaC/DSaC.csproj new file mode 100644 index 0000000..a32cd7b --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/DSaC.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + enable + enable + 55894bef-8317-4e30-a5f0-4dcd5c3f861e + Linux + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/kuzarin_maxim_lab_3/DSaC/Database/DsacContext.cs b/kuzarin_maxim_lab_3/DSaC/Database/DsacContext.cs new file mode 100644 index 0000000..c74afe6 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Database/DsacContext.cs @@ -0,0 +1,14 @@ +using DSaC.Database.Models; +using Microsoft.EntityFrameworkCore; + +namespace DSaC.Database +{ + public class DsacContext: DbContext + { + public DsacContext(DbContextOptions options) : base(options) + { + } + + public DbSet Counterparties { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Database/Models/Counterparty.cs b/kuzarin_maxim_lab_3/DSaC/Database/Models/Counterparty.cs new file mode 100644 index 0000000..84b3629 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Database/Models/Counterparty.cs @@ -0,0 +1,24 @@ +using AutoMapper; +using DSaC.Models.DTOs; +using DSaC.Models.Internal.Сommands; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DSaC.Database.Models +{ + [Table("counterparty")] + [AutoMap(typeof(CounterpartyBaseDto))] + [AutoMap(typeof(CounterpartyViewDto))] + public class Counterparty + { + [Key] + [Column("id")] + public Guid Id { get; set; } + + [Required] + [MaxLength(255)] + [Column("name")] + public string Name { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Dockerfile b/kuzarin_maxim_lab_3/DSaC/Dockerfile new file mode 100644 index 0000000..29bbfe1 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Dockerfile @@ -0,0 +1,24 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["DSaC.csproj", "DSaC/"] +RUN dotnet restore "DSaC/DSaC.csproj" +WORKDIR "/src/DSaC" +COPY . . +RUN dotnet build "DSaC.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "DSaC.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "DSaC.dll"] \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/CreateCounterpartyCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/CreateCounterpartyCommandHandler.cs new file mode 100644 index 0000000..a50ed4d --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/CreateCounterpartyCommandHandler.cs @@ -0,0 +1,51 @@ +using AutoMapper; +using DSaC.Database; +using DSaC.Database.Models; +using DSaC.Logic.Handlers.Queries; +using DSaC.Models.DTOs; +using DSaC.Models.Internal; +using DSaC.Models.Internal.Сommands; +using MediatR; + +namespace DSaC.Logic.Handlers.Commands +{ + public class CreateCounterpartyCommandHandler : IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public CreateCounterpartyCommandHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task> Handle(CreateCounterpartyCommand request, CancellationToken cancellationToken) + { + try + { + var model = _mapper.Map(request.Model); + + var res = await _context.AddAsync(model); + + await _context.SaveChangesAsync(); + + return new() + { + Value = _mapper.Map(res.Entity) + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on creating counterparty"); + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot create counterparty" + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/DeleteCounterpartyCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/DeleteCounterpartyCommandHandler.cs new file mode 100644 index 0000000..7c78127 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/DeleteCounterpartyCommandHandler.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using DSaC.Database; +using DSaC.Database.Models; +using DSaC.Models.DTOs; +using DSaC.Models.Internal; +using DSaC.Models.Internal.Сommands; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC.Logic.Handlers.Commands +{ + public class DeleteCounterpartyCommandHandler: IRequestHandler + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public DeleteCounterpartyCommandHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task Handle(DeleteCounterpartyCommand request, CancellationToken cancellationToken) + { + try + { + var res = await _context.Counterparties.Where(x=>x.Id == request.Id).ExecuteDeleteAsync(); + + if (res == 1)return new(); + + return new() + { + ErrorText = "Cannot find object to delete", + StatusCode = System.Net.HttpStatusCode.NotFound + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on deleteing counterparty"); + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot delete counterparty" + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/UpdateCounterpartyCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/UpdateCounterpartyCommandHandler.cs new file mode 100644 index 0000000..43fe7b3 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Commands/UpdateCounterpartyCommandHandler.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using DSaC.Database; +using DSaC.Database.Models; +using DSaC.Models.DTOs; +using DSaC.Models.Internal; +using DSaC.Models.Internal.Сommands; +using MediatR; + +namespace DSaC.Logic.Handlers.Commands +{ + public class UpdateCounterpartyCommandHandler: IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public UpdateCounterpartyCommandHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task> Handle(UpdateCounterpartyCommand request, CancellationToken cancellationToken) + { + try + { + var model = _mapper.Map(request.Model); + + var res = _context.Update(model); + + await _context.SaveChangesAsync(); + + return new() + { + Value = _mapper.Map(res.Entity) + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on updating counterparty"); + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot update counterparty" + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartiesQueryHandler.cs b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartiesQueryHandler.cs new file mode 100644 index 0000000..b311574 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartiesQueryHandler.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using DSaC.Database; +using DSaC.Models.DTOs; +using DSaC.Models.Internal; +using DSaC.Models.Internal.Queries; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC.Logic.Handlers.Queries +{ + public class GetCounterpartiesQueryHandler : IRequestHandler>> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public GetCounterpartiesQueryHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task>> Handle(GetCounterpartiesQuery request, CancellationToken cancellationToken) + { + try + { + var res = await _context.Counterparties + .Where(x=>request.Ids == null || request.Ids.Contains(x.Id)) + .Skip(request.Page * request.PageSize).Take(request.PageSize) + .ToListAsync(); + + return new() + { + Value = res.Select(_mapper.Map).ToList(), + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on getting records"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.BadRequest, + ErrorText = "Cannot get Counterparties by this request", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartyQueryHandler.cs b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartyQueryHandler.cs new file mode 100644 index 0000000..4b3eadc --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Logic/Handlers/Queries/GetCounterpartyQueryHandler.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using DSaC.Database; +using DSaC.Models.DTOs; +using DSaC.Models.Internal; +using DSaC.Models.Internal.Queries; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC.Logic.Handlers.Queries +{ + public class GetCounterpartyQueryHandler: IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public GetCounterpartyQueryHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task> Handle(GetCounterpartyQuery request, CancellationToken cancellationToken) + { + try + { + var res = await _context.Counterparties.FirstOrDefaultAsync(x=>x.Id == request.Id); + + if (res == null) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Counterparty with this ID does not exsist", + }; + + return new() + { + Value = _mapper.Map(res), + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on getting record"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot get Counterparty by id", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.Designer.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.Designer.cs new file mode 100644 index 0000000..12551a6 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.Designer.cs @@ -0,0 +1,60 @@ +// +using System; +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC.Migrations +{ + [DbContext(typeof(DsacContext))] + [Migration("20240907133944_InitMigraton")] + partial class InitMigraton + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC.Database.Models.Counterparty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContractNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("contract_number"); + + b.Property("ManagerName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("manager_name"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("counterparty"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.cs new file mode 100644 index 0000000..79eabc6 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907133944_InitMigraton.cs @@ -0,0 +1,36 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DSaC.Migrations +{ + /// + public partial class InitMigraton : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "counterparty", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + name = table.Column(type: "character varying(255)", maxLength: 255, nullable: false), + contract_number = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + manager_name = table.Column(type: "character varying(255)", maxLength: 255, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_counterparty", x => x.id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "counterparty"); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.Designer.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.Designer.cs new file mode 100644 index 0000000..750edea --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.Designer.cs @@ -0,0 +1,64 @@ +// +using System; +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC.Migrations +{ + [DbContext(typeof(DsacContext))] + [Migration("20240907140843_ChangingContractInfo")] + partial class ChangingContractInfo + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC.Database.Models.Counterparty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContractNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("contract_number"); + + b.Property("IsContractClosed") + .HasColumnType("boolean") + .HasColumnName("is_contract_closed"); + + b.Property("ManagerName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("manager_name"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("counterparty"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.cs new file mode 100644 index 0000000..1b48b00 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907140843_ChangingContractInfo.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DSaC.Migrations +{ + /// + public partial class ChangingContractInfo : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "is_contract_closed", + table: "counterparty", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "is_contract_closed", + table: "counterparty"); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.Designer.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.Designer.cs new file mode 100644 index 0000000..996c2cf --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.Designer.cs @@ -0,0 +1,63 @@ +// +using System; +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC.Migrations +{ + [DbContext(typeof(DsacContext))] + [Migration("20240907141343_SmallHotfix")] + partial class SmallHotfix + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC.Database.Models.Counterparty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContractNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("contract_number"); + + b.Property("IsContractClosed") + .HasColumnType("boolean") + .HasColumnName("is_contract_closed"); + + b.Property("ManagerName") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("manager_name"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("counterparty"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.cs new file mode 100644 index 0000000..c82024a --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240907141343_SmallHotfix.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DSaC.Migrations +{ + /// + public partial class SmallHotfix : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "manager_name", + table: "counterparty", + type: "character varying(255)", + maxLength: 255, + nullable: true, + oldClrType: typeof(string), + oldType: "character varying(255)", + oldMaxLength: 255); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "manager_name", + table: "counterparty", + type: "character varying(255)", + maxLength: 255, + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "character varying(255)", + oldMaxLength: 255, + oldNullable: true); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.Designer.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.Designer.cs new file mode 100644 index 0000000..2a38398 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.Designer.cs @@ -0,0 +1,48 @@ +// +using System; +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC.Migrations +{ + [DbContext(typeof(DsacContext))] + [Migration("20240914065929_after-reconstruction")] + partial class afterreconstruction + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC.Database.Models.Counterparty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("counterparty"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.cs new file mode 100644 index 0000000..3abc7b3 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/20240914065929_after-reconstruction.cs @@ -0,0 +1,52 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DSaC.Migrations +{ + /// + public partial class afterreconstruction : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "contract_number", + table: "counterparty"); + + migrationBuilder.DropColumn( + name: "is_contract_closed", + table: "counterparty"); + + migrationBuilder.DropColumn( + name: "manager_name", + table: "counterparty"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "contract_number", + table: "counterparty", + type: "character varying(50)", + maxLength: 50, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "is_contract_closed", + table: "counterparty", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "manager_name", + table: "counterparty", + type: "character varying(255)", + maxLength: 255, + nullable: true); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Migrations/DsacContextModelSnapshot.cs b/kuzarin_maxim_lab_3/DSaC/Migrations/DsacContextModelSnapshot.cs new file mode 100644 index 0000000..153ecb1 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Migrations/DsacContextModelSnapshot.cs @@ -0,0 +1,45 @@ +// +using System; +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC.Migrations +{ + [DbContext(typeof(DsacContext))] + partial class DsacContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC.Database.Models.Counterparty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("counterparty"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/DTOs/ContractViewDto.cs b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/ContractViewDto.cs new file mode 100644 index 0000000..8790566 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/ContractViewDto.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations; + +namespace DSaC.Models.DTOs +{ + public class ContractViewDto + { + [Required(ErrorMessage = "Contract number must be present")] + public string ContractNumber { get; set; } = null!; + + [Required(ErrorMessage = "Manager name must be present")] + public string ManagerName { get; set; } = null!; + + public DateTime CreatinTime { get; set; } + + public bool IsClosed { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyBaseDto.cs b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyBaseDto.cs new file mode 100644 index 0000000..c1dad6d --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyBaseDto.cs @@ -0,0 +1,13 @@ + +using AutoMapper; +using DSaC.Database.Models; +using System.ComponentModel.DataAnnotations; + +namespace DSaC.Models.DTOs +{ + public class CounterpartyBaseDto + { + [Required(ErrorMessage = "Cpty name must be present")] + public string Name { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyViewDto.cs b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyViewDto.cs new file mode 100644 index 0000000..97df697 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/DTOs/CounterpartyViewDto.cs @@ -0,0 +1,11 @@ +using AutoMapper; +using DSaC.Database.Models; + +namespace DSaC.Models.DTOs +{ + [AutoMap(typeof(Counterparty))] + public class CounterpartyViewDto: CounterpartyBaseDto + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartiesQuery.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartiesQuery.cs new file mode 100644 index 0000000..ad17f69 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartiesQuery.cs @@ -0,0 +1,14 @@ +using DSaC.Models.DTOs; +using MediatR; + +namespace DSaC.Models.Internal.Queries +{ + public class GetCounterpartiesQuery: IRequest>> + { + public List? Ids { get; set; } + + public int Page { get; set; } + + public int PageSize { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartyQuery.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartyQuery.cs new file mode 100644 index 0000000..254f082 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Queries/GetCounterpartyQuery.cs @@ -0,0 +1,10 @@ +using DSaC.Models.DTOs; +using MediatR; + +namespace DSaC.Models.Internal.Queries +{ + public class GetCounterpartyQuery: IRequest> + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/ResponseModel.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/ResponseModel.cs new file mode 100644 index 0000000..f832eaf --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/ResponseModel.cs @@ -0,0 +1,30 @@ +using System.Net; + +namespace DSaC.Models.Internal +{ + public class ResponseModel + { + public string? ErrorText; + + public bool IsError => !string.IsNullOrEmpty(ErrorText); + + private int? _errorCode = 200; + + public int? ErrorCode + { + get => _errorCode; + set => _errorCode = value; + } + + public HttpStatusCode? StatusCode + { + get => (HttpStatusCode?)_errorCode; + set => _errorCode = (int?)value; + } + } + + public class ResponseModel : ResponseModel + { + public T? Value { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/CreateCounterpartyCommand.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/CreateCounterpartyCommand.cs new file mode 100644 index 0000000..6084a23 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/CreateCounterpartyCommand.cs @@ -0,0 +1,10 @@ +using DSaC.Models.DTOs; +using MediatR; + +namespace DSaC.Models.Internal.Сommands +{ + public class CreateCounterpartyCommand : IRequest> + { + public CounterpartyBaseDto Model { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/DeleteCounterpartyCommand.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/DeleteCounterpartyCommand.cs new file mode 100644 index 0000000..b968e14 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/DeleteCounterpartyCommand.cs @@ -0,0 +1,9 @@ +using MediatR; + +namespace DSaC.Models.Internal.Сommands +{ + public class DeleteCounterpartyCommand: IRequest + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/UpdateCounterpartyCommand.cs b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/UpdateCounterpartyCommand.cs new file mode 100644 index 0000000..58e8b55 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Models/Internal/Сommands/UpdateCounterpartyCommand.cs @@ -0,0 +1,14 @@ +using DSaC.Models.DTOs; +using MediatR; +using System.ComponentModel.DataAnnotations; + +namespace DSaC.Models.Internal.Сommands +{ + public class UpdateCounterpartyCommand: IRequest> + { + public Guid Id { get; set; } + + [Required(ErrorMessage = "UpdateMessageMust be present")] + public CounterpartyViewDto Model { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/Program.cs b/kuzarin_maxim_lab_3/DSaC/Program.cs new file mode 100644 index 0000000..c60c692 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Program.cs @@ -0,0 +1,128 @@ +using DSaC.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; +using NLog.Config; +using NLog.Extensions.Logging; +using NLog.Targets; +using PIHelperSh.Configuration; +using PIHelperSh.Configuration.Attributes; +using System.Reflection; +using LogLevel = NLog.LogLevel; + +[TrackedType] +public class Program +{ + private static WebApplication? app; + + [Constant(BlockName = "Database")] + private static string ConnectionString; + + [Constant(BlockName = "GatewaySettings")] + private static string AppPrefix; + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + + ConfigureLogger(builder); + + ConfigureServices(builder); + + ConfigureDatabase(builder); + + app = builder.Build(); + + var t = MigrateDatabase(); + + app.UseSwagger(c => + { + if (!string.IsNullOrEmpty(AppPrefix)) + { + //c.RouteTemplate = AppPrefix + "/swagger/{documentName}/swagger.json"; + + c.PreSerializeFilters.Add((swaggerDoc, httpReq) => + { + swaggerDoc.Servers = new List { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/{AppPrefix}" } }; + }); + } + }); + app.UseSwaggerUI(c => + { + //if (!string.IsNullOrEmpty(AppPrefix)) + //{ + // c.SwaggerEndpoint($"/{AppPrefix}/swagger/v1/swagger.json", $"APP API"); + // c.RoutePrefix = $"{AppPrefix}/swagger"; + //} + }); + + app.UseHttpsRedirection(); + + app.UseAuthorization(); + + app.MapControllers(); + + t.Wait(); + + app.Run(); + } + + private static void ConfigureLogger(WebApplicationBuilder builder) + { + var nLogConfig = new LoggingConfiguration(); + var logConsole = new ConsoleTarget(); + var blackhole = new NullTarget(); + + var logFile = new FileTarget() + { + FileName = "${basedir}/logs/${shortdate}_logs.log" + }; + + nLogConfig.AddRule(LogLevel.Trace, LogLevel.Trace, blackhole, "Microsoft.AspNetCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.EntityFrameworkCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.AspNetCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "System.Net.Http.HttpClient.Refit.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Error, logConsole); + nLogConfig.AddRule(LogLevel.Debug, LogLevel.Error, logFile); + + builder.Logging.ClearProviders(); + builder.Services.AddLogging(m => m.AddNLog(nLogConfig)); + } + + private static void ConfigureServices(WebApplicationBuilder builder) + { + builder.Services.AddConfigurations(builder.Configuration); + builder.Configuration.AddConstants(); + builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + + builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); + + builder.Services.AddControllers().AddNewtonsoftJson(); + + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo + { + Title = "Distributed computing and applications", + Version = "v1", + Description = "" + }); + + //c.EnableAnnotations(); + }); + } + + private static void ConfigureDatabase(WebApplicationBuilder builder) + { + builder.Services.AddDbContext(options => + { + options.UseNpgsql(ConnectionString); + }); + } + + private static async Task MigrateDatabase() + { + var context = app?.Services.CreateScope().ServiceProvider.GetService(); + if(context != null) + await context.Database.MigrateAsync(); + } +} \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC/Properties/launchSettings.json b/kuzarin_maxim_lab_3/DSaC/Properties/launchSettings.json new file mode 100644 index 0000000..6349710 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/Properties/launchSettings.json @@ -0,0 +1,52 @@ +{ + "profiles": { + "http": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5062" + }, + "https": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7219;http://localhost:5062" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Container (Dockerfile)": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "environmentVariables": { + "ASPNETCORE_HTTPS_PORTS": "8081", + "ASPNETCORE_HTTP_PORTS": "8080" + }, + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:9154", + "sslPort": 44381 + } + } +} \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC/appsettings.Development.json b/kuzarin_maxim_lab_3/DSaC/appsettings.Development.json new file mode 100644 index 0000000..3711bea --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/appsettings.Development.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Database": { + "ConnectionString": "Host=db.dev-moio.online;Port=31153;Database=dsac_maxim;Username=postgres;Password=postgres_password" + }, + "GatewaySettings": { + "AppPrefix": "" + } +} diff --git a/kuzarin_maxim_lab_3/DSaC/appsettings.json b/kuzarin_maxim_lab_3/DSaC/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Controllers/ContractController.cs b/kuzarin_maxim_lab_3/DSaC_second/Controllers/ContractController.cs new file mode 100644 index 0000000..1fc805f --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Controllers/ContractController.cs @@ -0,0 +1,88 @@ +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal.Queries; +using DSaC_second.Models.Internal.Сommands; +using MediatR; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace DSaC_second.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ContractController : ControllerBase + { + private readonly IMediator _mediator; + + public ContractController(IMediator mediator) + { + _mediator = mediator; + } + + [HttpGet("")] + public async Task GetContracts( + [FromQuery] int page = 0, + [FromQuery] int pageSize = 10, + [FromQuery] List? ids = null + ) + { + var request = new GetContractsQuery + { + Page = page, + PageSize = pageSize, + Ids = ids + }; + + var response = await _mediator.Send(request); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpGet("{uuid:guid}")] + public async Task GetFullContract([FromRoute] Guid uuid) + { + var request = new GetContractQuery + { + Id = uuid + }; + + var response = await _mediator.Send(request); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpPost("")] + public async Task CreateContract([FromBody] ContractBaseDto dto) + { + var response = await _mediator.Send(new CreateContractCommand() + { + Model = dto + }); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpPut("{uuid:guid}")] + public async Task UpdateContract([FromRoute] Guid uuid, [FromBody] ContractViewDto dto) + { + var response = await _mediator.Send(new UpdateContractCommand() + { + Id = uuid, + Model = dto + }); + + return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + + [HttpDelete("{uuid:guid}")] + public async Task DeleteContract([FromRoute] Guid uuid) + { + var response = await _mediator.Send(new DeleteContractCommand() + { + Id = uuid, + }); + + return !response.IsError ? Ok() : StatusCode(response.ErrorCode!.Value, response.ErrorText); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/DSaC_second.csproj b/kuzarin_maxim_lab_3/DSaC_second/DSaC_second.csproj new file mode 100644 index 0000000..9205aad --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/DSaC_second.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + 39d29416-63e9-4884-9c5f-9d6ff461995f + Linux + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/kuzarin_maxim_lab_3/DSaC_second/Database/DsacContext.cs b/kuzarin_maxim_lab_3/DSaC_second/Database/DsacContext.cs new file mode 100644 index 0000000..3341751 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Database/DsacContext.cs @@ -0,0 +1,15 @@ +using DSaC_second.Database.Models; +using Microsoft.EntityFrameworkCore; + +namespace DSaC_second.Database +{ + public class DsacContext : DbContext + { + public DsacContext(DbContextOptions options) : base(options) + { + AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); + } + + public DbSet Contracts { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Database/Models/Contract.cs b/kuzarin_maxim_lab_3/DSaC_second/Database/Models/Contract.cs new file mode 100644 index 0000000..b83b77d --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Database/Models/Contract.cs @@ -0,0 +1,38 @@ +using AutoMapper; +using DSaC_second.Models.DTOs; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DSaC_second.Database.Models +{ + [Table("contract")] + [AutoMap(typeof(ContractBaseDto))] + [AutoMap(typeof(ContractViewDto))] + public class Contract + { + [Key] + [Column("id")] + public Guid Id { get; set; } + + [Column("contract_number")] + [Required] + public string ContractNumber { get; set; } + + [Column("manager_name")] + [Required] + public string ManagerName { get; set; } + + [Column("counterparty_id")] + [Required] + public Guid CounterpartyId { get; set; } + + [Column("creation_time")] + [Required] + public DateTime CreatinTime { get; set; } = DateTime.Now; + + [Column("is_closed")] + [DefaultValue(false)] + public bool IsClosed { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Dockerfile b/kuzarin_maxim_lab_3/DSaC_second/Dockerfile new file mode 100644 index 0000000..d0dad02 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Dockerfile @@ -0,0 +1,24 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["DSaC_second.csproj", "DSaC_second/"] +RUN dotnet restore "DSaC_second/DSaC_second.csproj" +WORKDIR "/src/DSaC_second" +COPY . . +RUN dotnet build "DSaC_second.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "DSaC_second.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "DSaC_second.dll"] \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/CreateContractCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/CreateContractCommandHandler.cs new file mode 100644 index 0000000..e885bbc --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/CreateContractCommandHandler.cs @@ -0,0 +1,76 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Database.Models; +using DSaC_second.Logic.Handlers.Queries; +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Queries; +using DSaC_second.Models.Internal.Сommands; +using MediatR; + +namespace DSaC_second.Logic.Handlers.Commands +{ + public class CreateContractCommandHandler : IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + private readonly IMediator _mediator; + + public CreateContractCommandHandler(ILogger logger, DsacContext context, IMapper mapper, IMediator mediator) + { + _logger = logger; + _context = context; + _mapper = mapper; + _mediator = mediator; + } + + public async Task> Handle(CreateContractCommand request, CancellationToken cancellationToken) + { + try + { + var counterparty = await _mediator.Send(new GetConunterpartyQuery() + { + Id = request.Model.CounterpartyId, + }, cancellationToken: cancellationToken); + + if (counterparty.IsError) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = counterparty.ErrorText, + }; + if (counterparty.Value == null) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cpty with this id not found", + }; + + var model = _mapper.Map(request.Model); + + var outModel = await _context.Contracts.AddAsync(model, cancellationToken: cancellationToken); + + await _context.SaveChangesAsync(cancellationToken); + + var res = _mapper.Map(model); + res.Counterparty = counterparty.Value!; + + return new() + { + Value = res, + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on creating record"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot create contract", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/DeleteContractCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/DeleteContractCommandHandler.cs new file mode 100644 index 0000000..fd3a811 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/DeleteContractCommandHandler.cs @@ -0,0 +1,43 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Сommands; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC_second.Logic.Handlers.Commands +{ + public class DeleteContractCommandHandler: IRequestHandler + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public DeleteContractCommandHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task Handle(DeleteContractCommand request, CancellationToken cancellationToken) + { + try + { + await _context.Contracts.Where(x => x.Id == request.Id).ExecuteDeleteAsync(cancellationToken); + + return new(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on deleting record"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot delete contract by id", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/UpdateContractCommandHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/UpdateContractCommandHandler.cs new file mode 100644 index 0000000..4574634 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Commands/UpdateContractCommandHandler.cs @@ -0,0 +1,78 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Database.Models; +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Queries; +using DSaC_second.Models.Internal.Сommands; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC_second.Logic.Handlers.Commands +{ + public class UpdateContractCommandHandler : IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + private readonly IMediator _mediator; + + public UpdateContractCommandHandler(ILogger logger, DsacContext context, IMapper mapper, IMediator mediator) + { + _logger = logger; + _context = context; + _mapper = mapper; + _mediator = mediator; + } + + public async Task> Handle(UpdateContractCommand request, CancellationToken cancellationToken) + { + try + { + var counterparty = await _mediator.Send(new GetConunterpartyQuery() + { + Id = request.Model.CounterpartyId, + }, cancellationToken: cancellationToken); + + if (counterparty.IsError) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = counterparty.ErrorText, + }; + if(counterparty.Value == null) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cpty with this id not found", + }; + + var model = _mapper.Map(request.Model); + + _context.Contracts.Update(model); + + await _context.SaveChangesAsync(cancellationToken: cancellationToken); + + var res = _mapper.Map(model); + + res.Counterparty = counterparty.Value!; + + return new() + { + Value = res + }; + + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on updating record"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot update contract by id", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractQueryHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractQueryHandler.cs new file mode 100644 index 0000000..001f9ea --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractQueryHandler.cs @@ -0,0 +1,71 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Queries; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC_second.Logic.Handlers.Queries +{ + public class GetContractQueryHandler : IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + private readonly IMediator _mediator; + + public GetContractQueryHandler(ILogger logger, DsacContext context, IMapper mapper, IMediator mediator) + { + _logger = logger; + _context = context; + _mapper = mapper; + _mediator = mediator; + } + + public async Task> Handle(GetContractQuery request, CancellationToken cancellationToken) + { + try + { + var res = await _context.Contracts.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken: cancellationToken); + + if (res == null) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Contract with whit Id is not exist" + }; + var counterparty = await _mediator.Send(new GetConunterpartyQuery() + { + Id = res.CounterpartyId + }, cancellationToken: cancellationToken); + + if (counterparty.IsError) + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = counterparty.ErrorText + }; + + var model = _mapper.Map(res); + model.Counterparty = counterparty.Value!; + + return new() + { + Value = model, + }; + + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on getting record"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot get contract by id", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractsQueryHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractsQueryHandler.cs new file mode 100644 index 0000000..74fc87f --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetContractsQueryHandler.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Queries; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace DSaC_second.Logic.Handlers.Queries +{ + public class GetContractsQueryHandler : IRequestHandler>> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + + public GetContractsQueryHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + } + + public async Task>> Handle(GetContractsQuery request, CancellationToken cancellationToken) + { + try + { + var res = await _context.Contracts + .Where(x=>request.Ids == null || request.Ids.Contains(x.Id)) + .Skip(request.Page * request.PageSize).Take(request.PageSize) + .ToListAsync(cancellationToken: cancellationToken); + + return new() + { + Value = res.Select(_mapper.Map).ToList(), + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on getting records"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot get contracts", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetConunterpartyQueryHandler.cs b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetConunterpartyQueryHandler.cs new file mode 100644 index 0000000..0510b86 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Logic/Handlers/Queries/GetConunterpartyQueryHandler.cs @@ -0,0 +1,72 @@ +using AutoMapper; +using DSaC_second.Database; +using DSaC_second.Logic.Handlers.Commands; +using DSaC_second.Models.DTOs; +using DSaC_second.Models.Internal; +using DSaC_second.Models.Internal.Queries; +using MediatR; +using PIHelperSh.Configuration.Attributes; +using RestSharp; + +namespace DSaC_second.Logic.Handlers.Queries +{ + [TrackedType] + public class GetConunterpartyQueryHandler : IRequestHandler> + { + private readonly ILogger _logger; + private readonly DsacContext _context; + private readonly IMapper _mapper; + private readonly RestClient _restClient; + + [Constant(BlockName = "FirstService")] + private static string BaseUrl; + + [Constant(BlockName = "FirstService")] + private static string GetCounterpartyPostfix; + + public GetConunterpartyQueryHandler(ILogger logger, DsacContext context, IMapper mapper) + { + _logger = logger; + _context = context; + _mapper = mapper; + _restClient = new RestClient(BaseUrl); + } + + ~GetConunterpartyQueryHandler() + { + _restClient.Dispose(); + } + + public async Task> Handle(GetConunterpartyQuery request, CancellationToken cancellationToken) + { + try + { + var rq = new RestRequest($"{GetCounterpartyPostfix}/{request.Id.ToString()}"); + + var res = await _restClient.ExecuteAsync(rq, cancellationToken:cancellationToken); + + if (res.IsSuccessful) + return new() + { + Value = res.Data + }; + + return new() + { + StatusCode = res.StatusCode, + ErrorText = res.ErrorMessage, + }; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error on getting record from first service"); + + return new() + { + StatusCode = System.Net.HttpStatusCode.NotFound, + ErrorText = "Cannot get cpty from first service", + }; + } + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.Designer.cs b/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.Designer.cs new file mode 100644 index 0000000..d16d35a --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.Designer.cs @@ -0,0 +1,64 @@ +// +using System; +using DSaC_second.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC_second.Migrations +{ + [DbContext(typeof(DsacContext))] + [Migration("20240914152154_initial")] + partial class initial + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC_second.Database.Models.Contract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContractNumber") + .IsRequired() + .HasColumnType("text") + .HasColumnName("contract_number"); + + b.Property("CounterpartyId") + .HasColumnType("uuid") + .HasColumnName("counterparty_id"); + + b.Property("CreatinTime") + .HasColumnType("timestamp with time zone") + .HasColumnName("creation_time"); + + b.Property("IsClosed") + .HasColumnType("boolean") + .HasColumnName("is_closed"); + + b.Property("ManagerName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("manager_name"); + + b.HasKey("Id"); + + b.ToTable("contract"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.cs b/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.cs new file mode 100644 index 0000000..dabac45 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Migrations/20240914152154_initial.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace DSaC_second.Migrations +{ + /// + public partial class initial : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "contract", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + contract_number = table.Column(type: "text", nullable: false), + manager_name = table.Column(type: "text", nullable: false), + counterparty_id = table.Column(type: "uuid", nullable: false), + creation_time = table.Column(type: "timestamp with time zone", nullable: false), + is_closed = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_contract", x => x.id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "contract"); + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Migrations/DsacContextModelSnapshot.cs b/kuzarin_maxim_lab_3/DSaC_second/Migrations/DsacContextModelSnapshot.cs new file mode 100644 index 0000000..d3b6a2e --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Migrations/DsacContextModelSnapshot.cs @@ -0,0 +1,61 @@ +// +using System; +using DSaC_second.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace DSaC_second.Migrations +{ + [DbContext(typeof(DsacContext))] + partial class DsacContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("DSaC_second.Database.Models.Contract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContractNumber") + .IsRequired() + .HasColumnType("text") + .HasColumnName("contract_number"); + + b.Property("CounterpartyId") + .HasColumnType("uuid") + .HasColumnName("counterparty_id"); + + b.Property("CreatinTime") + .HasColumnType("timestamp with time zone") + .HasColumnName("creation_time"); + + b.Property("IsClosed") + .HasColumnType("boolean") + .HasColumnName("is_closed"); + + b.Property("ManagerName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("manager_name"); + + b.HasKey("Id"); + + b.ToTable("contract"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractBaseDto.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractBaseDto.cs new file mode 100644 index 0000000..f21ceea --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractBaseDto.cs @@ -0,0 +1,17 @@ +using AutoMapper; +using System.ComponentModel.DataAnnotations; + +namespace DSaC_second.Models.DTOs +{ + public class ContractBaseDto + { + [Required(ErrorMessage = "Contract number must be present")] + public string ContractNumber { get; set; } = null!; + + [Required(ErrorMessage = "Manager name must be present")] + public string ManagerName { get; set; } = null!; + + [Required(ErrorMessage = "Counterparty id must be present")] + public Guid CounterpartyId { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractFullDto.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractFullDto.cs new file mode 100644 index 0000000..85b8372 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractFullDto.cs @@ -0,0 +1,11 @@ +using AutoMapper; +using DSaC_second.Database.Models; + +namespace DSaC_second.Models.DTOs +{ + [AutoMap(typeof(Contract))] + public class ContractFullDto: ContractViewDto + { + public CounterpartyViewDto Counterparty { get; set; } = new(); + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractViewDto.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractViewDto.cs new file mode 100644 index 0000000..7010a9a --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/ContractViewDto.cs @@ -0,0 +1,15 @@ +using AutoMapper; +using DSaC_second.Database.Models; + +namespace DSaC_second.Models.DTOs +{ + [AutoMap(typeof(Contract))] + public class ContractViewDto: ContractBaseDto + { + public Guid Id { get; set; } + + public DateTime CreatinTime { get; set; } + + public bool IsClosed { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/CounterpartyViewDto.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/CounterpartyViewDto.cs new file mode 100644 index 0000000..645f649 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/DTOs/CounterpartyViewDto.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace DSaC_second.Models.DTOs +{ + public class CounterpartyViewDto + { + public Guid Id { get; set; } + + [Required(ErrorMessage = "Cpty name must be present")] + public string Name { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractQuery.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractQuery.cs new file mode 100644 index 0000000..f75bfc1 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractQuery.cs @@ -0,0 +1,10 @@ +using DSaC_second.Models.DTOs; +using MediatR; + +namespace DSaC_second.Models.Internal.Queries +{ + public class GetContractQuery : IRequest> + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractsQuery.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractsQuery.cs new file mode 100644 index 0000000..94aa470 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetContractsQuery.cs @@ -0,0 +1,14 @@ +using DSaC_second.Models.DTOs; +using MediatR; + +namespace DSaC_second.Models.Internal.Queries +{ + public class GetContractsQuery : IRequest>> + { + public List? Ids { get; set; } + + public int Page { get; set; } + + public int PageSize { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetConunterpartyQuery.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetConunterpartyQuery.cs new file mode 100644 index 0000000..ebd0f71 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Queries/GetConunterpartyQuery.cs @@ -0,0 +1,10 @@ +using DSaC_second.Models.DTOs; +using MediatR; + +namespace DSaC_second.Models.Internal.Queries +{ + public class GetConunterpartyQuery: IRequest> + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/ResponseModel.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/ResponseModel.cs new file mode 100644 index 0000000..83c6b40 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/ResponseModel.cs @@ -0,0 +1,30 @@ +using System.Net; + +namespace DSaC_second.Models.Internal +{ + public class ResponseModel + { + public string? ErrorText; + + public bool IsError => !string.IsNullOrEmpty(ErrorText); + + private int? _errorCode = 200; + + public int? ErrorCode + { + get => _errorCode; + set => _errorCode = value; + } + + public HttpStatusCode? StatusCode + { + get => (HttpStatusCode?)_errorCode; + set => _errorCode = (int?)value; + } + } + + public class ResponseModel : ResponseModel + { + public T? Value { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/CreateContractCommand.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/CreateContractCommand.cs new file mode 100644 index 0000000..3b8c241 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/CreateContractCommand.cs @@ -0,0 +1,10 @@ +using DSaC_second.Models.DTOs; +using MediatR; + +namespace DSaC_second.Models.Internal.Сommands +{ + public class CreateContractCommand : IRequest> + { + public ContractBaseDto Model { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/DeleteContractCommand.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/DeleteContractCommand.cs new file mode 100644 index 0000000..c144c1c --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/DeleteContractCommand.cs @@ -0,0 +1,9 @@ +using MediatR; + +namespace DSaC_second.Models.Internal.Сommands +{ + public class DeleteContractCommand : IRequest + { + public Guid Id { get; set; } + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/UpdateContractCommand.cs b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/UpdateContractCommand.cs new file mode 100644 index 0000000..10fc2b9 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Models/Internal/Сommands/UpdateContractCommand.cs @@ -0,0 +1,14 @@ +using DSaC_second.Models.DTOs; +using MediatR; +using System.ComponentModel.DataAnnotations; + +namespace DSaC_second.Models.Internal.Сommands +{ + public class UpdateContractCommand : IRequest> + { + public Guid Id { get; set; } + + [Required(ErrorMessage = "Update model msust be present")] + public ContractViewDto Model { get; set; } = null!; + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/Program.cs b/kuzarin_maxim_lab_3/DSaC_second/Program.cs new file mode 100644 index 0000000..25eb501 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Program.cs @@ -0,0 +1,130 @@ +using DSaC_second.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; +using NLog.Config; +using NLog.Extensions.Logging; +using NLog.Targets; +using PIHelperSh.Configuration; +using PIHelperSh.Configuration.Attributes; +using System; +using System.Reflection; +using LogLevel = NLog.LogLevel; + +[TrackedType] +public class Program +{ + private static WebApplication? app; + + [Constant(BlockName = "Database")] + private static string ConnectionString; + + [Constant(BlockName = "GatewaySettings")] + private static string AppPrefix; + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + + ConfigureLogger(builder); + + ConfigureServices(builder); + + ConfigureDatabase(builder); + + app = builder.Build(); + + var t = MigrateDatabase(); + + app.UseSwagger(c => + { + if (!string.IsNullOrEmpty(AppPrefix)) + { + //c.RouteTemplate = AppPrefix + "/swagger/{documentName}/swagger.json"; + + c.PreSerializeFilters.Add((swaggerDoc, httpReq) => + { + swaggerDoc.Servers = new List { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/{AppPrefix}" } }; + }); + } + + }); + app.UseSwaggerUI(c => + { + //if (!string.IsNullOrEmpty(AppPrefix)) + //{ + // c.SwaggerEndpoint($"/{AppPrefix}/swagger/v1/swagger.json", $"APP API"); + // c.RoutePrefix = $"{AppPrefix}/swagger"; + //} + }); + + app.UseHttpsRedirection(); + + app.UseAuthorization(); + + app.MapControllers(); + + t.Wait(); + + app.Run(); + } + + private static void ConfigureLogger(WebApplicationBuilder builder) + { + var nLogConfig = new LoggingConfiguration(); + var logConsole = new ConsoleTarget(); + var blackhole = new NullTarget(); + + var logFile = new FileTarget() + { + FileName = "${basedir}/logs/${shortdate}_logs.log" + }; + + nLogConfig.AddRule(LogLevel.Trace, LogLevel.Trace, blackhole, "Microsoft.AspNetCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.EntityFrameworkCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "Microsoft.AspNetCore.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Warn, logFile, "System.Net.Http.HttpClient.Refit.*", true); + nLogConfig.AddRule(LogLevel.Info, LogLevel.Error, logConsole); + nLogConfig.AddRule(LogLevel.Debug, LogLevel.Error, logFile); + + builder.Logging.ClearProviders(); + builder.Services.AddLogging(m => m.AddNLog(nLogConfig)); + } + + private static void ConfigureServices(WebApplicationBuilder builder) + { + builder.Services.AddConfigurations(builder.Configuration); + builder.Configuration.AddConstants(); + builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + + builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); + + builder.Services.AddControllers().AddNewtonsoftJson(); + + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo + { + Title = "Distributed computing and applications", + Version = "v1", + Description = "" + }); + + //c.EnableAnnotations(); + }); + } + + private static void ConfigureDatabase(WebApplicationBuilder builder) + { + builder.Services.AddDbContext(options => + { + options.UseNpgsql(ConnectionString); + }); + } + + private static async Task MigrateDatabase() + { + var context = app?.Services.CreateScope().ServiceProvider.GetService(); + if(context != null) + await context.Database.MigrateAsync(); + } +} \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC_second/Properties/launchSettings.json b/kuzarin_maxim_lab_3/DSaC_second/Properties/launchSettings.json new file mode 100644 index 0000000..8f8496f --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/Properties/launchSettings.json @@ -0,0 +1,53 @@ +{ + "profiles": { + "http": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "GATEWAY_SETTINGS_APP_PREFIX": "first" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5246" + }, + "https": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7239;http://localhost:5246" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Container (Dockerfile)": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "environmentVariables": { + "ASPNETCORE_HTTPS_PORTS": "8081", + "ASPNETCORE_HTTP_PORTS": "8080" + }, + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:56866", + "sslPort": 44308 + } + } +} \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/DSaC_second/appsettings.Development.json b/kuzarin_maxim_lab_3/DSaC_second/appsettings.Development.json new file mode 100644 index 0000000..d4d8f8b --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/appsettings.Development.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Database": { + "ConnectionString": "Host=db.dev-moio.online;Port=31153;Database=dsac_maxim;Username=postgres;Password=postgres_password" + }, + "FirstService": { + "BaseUrl": "http://localhost:5062/api", + "GetCounterpartyPostfix": "/Counterparties" + }, + "GatewaySettings": { + "AppPrefix": "" + } +} diff --git a/kuzarin_maxim_lab_3/DSaC_second/appsettings.json b/kuzarin_maxim_lab_3/DSaC_second/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/kuzarin_maxim_lab_3/DSaC_second/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/kuzarin_maxim_lab_3/README.md b/kuzarin_maxim_lab_3/README.md new file mode 100644 index 0000000..f85e69a --- /dev/null +++ b/kuzarin_maxim_lab_3/README.md @@ -0,0 +1,18 @@ +# Лабораторная работа 3 +Данная работа посвящена теме синхронного обмена сообщениями между сервисами, а так же шлюзам, для взаимодействия с внешним миром. +## Описание +В качестве предметной области использовался пример 18-го варианта. Имеются 2 сущность: контрагент(только имя) и договор(номер, ФИО менеджера, дата создания и статус). +Для реализации была выбрана платформа ASP.net. Информация хранится в СУБД Postgres, которая так же поднимается в контейнере(вместе с остальными сервисами) +Система позволяет проводить с сущностями базовые CRUD операции. В случае договора, имеется возможность получения его в связке с информацией по контрагенту(не просто Id, но и имя). В этот момент сервисы и взаимодействуют друг с другом. Для этого используется шлюз(напрямую сервисы друг о друге могут и не знать, общение как с внешним миром так и между собой только через nginx шлюз) +В качестве интерфейса имеется Swagger, который можно использовать для отправки запросов. Он и будет показан в видеодеомнстрации +## Запуск +Для запуска лабораторной работы необходимо иметь запущенный движок Docker на устройстве. +Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду: +``` +docker compose up -d --build +``` +Важно, чтобы в этот момент на компьютере был свободен порт 80. +В результате, после сборки вся система запустится и Swagger-ы будут доступны по путям http://localhost/first/swagger и http://localhost/second/swagger +## Видеодемонстрация +Был записан видеоролик, демонстрирующий процесс запуска и работы системы, а так же всех её основных функйи. Он расположен по [адресу](https://drive.google.com/file/d/17OwZ6kEJ-AaW0uMTIfNtolyp-oyy9OfT/view?usp=sharing) + diff --git a/kuzarin_maxim_lab_3/compose.yaml b/kuzarin_maxim_lab_3/compose.yaml new file mode 100644 index 0000000..8e4df01 --- /dev/null +++ b/kuzarin_maxim_lab_3/compose.yaml @@ -0,0 +1,37 @@ +services: + postgres: + image: postgres + ports: + - 5432:5432 + environment: + POSTGRES_PASSWORD: "password" + + nginx: + image: nginx + depends_on: + - second + - first + volumes: + - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf + ports: + - 80:80 + + first: + build: .\DSaC + depends_on: + - postgres + environment: + DATABASE_CONNECTION_STRING: "Host=postgres;Database=dsac_maxim_1;Username=postgres;Password=password" + GATEWAY_SETTINGS_APP_PREFIX: "first" # Нужно, чтобы запросы из Swagger работали нормально + + second: + build: .\DSaC_second + depends_on: + - first + environment: + DATABASE_CONNECTION_STRING: "Host=postgres;Database=dsac_maxim_2;Username=postgres;Password=password" + FIRST_SERVICE_BASE_URL: "http://nginx/first/api" + FIRST_SERVICE_GET_COUNTERPARTY_POSTFIX: "/Counterparties" + GATEWAY_SETTINGS_APP_PREFIX: "second" + + \ No newline at end of file diff --git a/kuzarin_maxim_lab_3/nginx/nginx.conf b/kuzarin_maxim_lab_3/nginx/nginx.conf new file mode 100644 index 0000000..63e5ddc --- /dev/null +++ b/kuzarin_maxim_lab_3/nginx/nginx.conf @@ -0,0 +1,22 @@ + +server { + listen 80; + listen [::]:80; + server_name localhost; + + location /first/ { + proxy_pass http://first:8080/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Prefix /test; + } + + location /second/ { + proxy_pass http://second:8080/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Prefix /admin; + } +}