From 205708f252e55feba173f53feb303fdd885c2d21 Mon Sep 17 00:00:00 2001 From: Marouane Boukhriss Ouchab Date: Sat, 14 Sep 2024 23:17:15 +0200 Subject: [PATCH] First commit --- .github/workflows/dotnet-ci.yml | 32 ++ .gitignore | 484 ++++++++++++++++++ MaruanBH.Api/.gitignore | 484 ++++++++++++++++++ MaruanBH.Api/BlueHarvest.Api.http | 6 + .../DependenciesInjectorConfiguration.cs | 56 ++ .../Configuration/GeneralConfiguration.cs | 26 + MaruanBH.Api/Controllers/AccountController.cs | 121 +++++ .../Controllers/Base/ApiController.cs | 31 ++ .../Controllers/CustomerController.cs | 114 +++++ MaruanBH.Api/MaruanBH.Api.csproj | 31 ++ MaruanBH.Api/Program.cs | 38 ++ MaruanBH.Api/Properties/launchSettings.json | 41 ++ MaruanBH.Api/Startup.cs | 37 ++ MaruanBH.Api/appsettings.Development.json | 8 + MaruanBH.Api/appsettings.json | 27 + MaruanBH.Business/.gitignore | 484 ++++++++++++++++++ .../CreateAccountCommandHandler.cs | 61 +++ .../GetAccountDetailsQueryHandler.cs | 80 +++ .../CreateCustomerCommandHandler.cs | 43 ++ .../GetCustomerDetailsQueryHandler.cs | 53 ++ MaruanBH.Business/MaruanBH.Business.csproj | 19 + MaruanBH.Business/Services/AccountService.cs | 35 ++ MaruanBH.Business/Services/CustomerService.cs | 53 ++ .../Services/TransactionService.cs | 41 ++ MaruanBH.Core/.gitignore | 484 ++++++++++++++++++ .../Commands/CreateAccountCommand.cs | 15 + .../AccountContext/DTOs/AccountDetailsDto.cs | 17 + .../AccountContext/DTOs/CreateAccountDto.cs | 8 + .../DTOs/CreateAccountResponseDto.cs | 8 + .../Queries/GetAccountDetailsQuery.cs | 15 + .../Validators/CreateAccountDtoValidator.cs | 15 + .../Base/Exceptions/CustomException.cs | 19 + .../Commands/CreateCustomerCommand.cs | 16 + .../CustomerContext/DTOs/CreateCustomerDto.cs | 9 + .../DTOs/CreateCustomerResponseDto.cs | 7 + .../CustomerContext/DTOs/CustomerDetailDto.cs | 12 + .../CustomerContext/DTOs/TransactionDto.cs | 16 + .../Queries/GetCustomerDetailsQuery.cs | 18 + .../Validators/CreateCustomerDtoValidator.cs | 15 + .../GetCustomerDetailsQueryValidator.cs | 15 + MaruanBH.Core/MaruanBH.Core.csproj | 19 + MaruanBH.Core/Services/IAccountService.cs | 13 + MaruanBH.Core/Services/ICustomerService.cs | 13 + MaruanBH.Core/Services/ITransactionService.cs | 14 + MaruanBH.Domain/.gitignore | 484 ++++++++++++++++++ MaruanBH.Domain/Base/Error/EResponse.cs | 9 + MaruanBH.Domain/Base/Error/Error.cs | 48 ++ MaruanBH.Domain/Base/Error/Etype.cs | 9 + MaruanBH.Domain/Entities/Account.cs | 20 + MaruanBH.Domain/Entities/Customer.cs | 24 + MaruanBH.Domain/Entities/Transaction.cs | 23 + MaruanBH.Domain/MaruanBH.Domain.csproj | 13 + .../Respositories/IAccountRepository.cs | 14 + .../Respositories/ICustomerRepository.cs | 11 + .../Respositories/ITransactionRespository.cs | 13 + MaruanBH.Persistance/.gitignore | 484 ++++++++++++++++++ .../MaruanBH.Persistance.csproj | 19 + .../Respositories/AccountRepository.cs | 71 +++ .../Respositories/CustomerRepository.cs | 46 ++ .../Respositories/TransactionRepository.cs | 66 +++ MaruanBH.Tests/.gitignore | 484 ++++++++++++++++++ .../CreateAccountCommandHandlerTests.cs | 85 +++ .../GetAccountDetailsQueryHandlerTests.cs | 63 +++ .../CreateCustomerCommandHandlerTests.cs | 64 +++ .../GetCustomerDetailsQueryHandlerTests.cs | 66 +++ .../Repositories/AccountRepositoryTests.cs | 75 +++ .../Repositories/CustomerRepositoryTests.cs | 74 +++ .../TransactionRepositoryTests.cs | 66 +++ .../UnitTests/Services/AccountServiceTests.cs | 54 ++ .../Services/CustomerServiceTests.cs | 66 +++ .../Services/TransactionServiceTests.cs | 57 +++ MaruanBH.Tests/MaruanBH.Tests.csproj | 37 ++ MaruanBH.sln | 29 ++ README.md | 73 +++ 74 files changed, 5800 insertions(+) create mode 100644 .github/workflows/dotnet-ci.yml create mode 100644 .gitignore create mode 100644 MaruanBH.Api/.gitignore create mode 100644 MaruanBH.Api/BlueHarvest.Api.http create mode 100644 MaruanBH.Api/Configuration/DependenciesInjectorConfiguration.cs create mode 100644 MaruanBH.Api/Configuration/GeneralConfiguration.cs create mode 100644 MaruanBH.Api/Controllers/AccountController.cs create mode 100644 MaruanBH.Api/Controllers/Base/ApiController.cs create mode 100644 MaruanBH.Api/Controllers/CustomerController.cs create mode 100644 MaruanBH.Api/MaruanBH.Api.csproj create mode 100644 MaruanBH.Api/Program.cs create mode 100644 MaruanBH.Api/Properties/launchSettings.json create mode 100644 MaruanBH.Api/Startup.cs create mode 100644 MaruanBH.Api/appsettings.Development.json create mode 100644 MaruanBH.Api/appsettings.json create mode 100644 MaruanBH.Business/.gitignore create mode 100644 MaruanBH.Business/AccountContext/CommandHandler/CreateAccountCommandHandler.cs create mode 100644 MaruanBH.Business/AccountContext/QueryHandler/GetAccountDetailsQueryHandler.cs create mode 100644 MaruanBH.Business/CustomerContext/CommandHandler/CreateCustomerCommandHandler.cs create mode 100644 MaruanBH.Business/CustomerContext/QueryHandler/GetCustomerDetailsQueryHandler.cs create mode 100644 MaruanBH.Business/MaruanBH.Business.csproj create mode 100644 MaruanBH.Business/Services/AccountService.cs create mode 100644 MaruanBH.Business/Services/CustomerService.cs create mode 100644 MaruanBH.Business/Services/TransactionService.cs create mode 100644 MaruanBH.Core/.gitignore create mode 100644 MaruanBH.Core/AccountContext/Commands/CreateAccountCommand.cs create mode 100644 MaruanBH.Core/AccountContext/DTOs/AccountDetailsDto.cs create mode 100644 MaruanBH.Core/AccountContext/DTOs/CreateAccountDto.cs create mode 100644 MaruanBH.Core/AccountContext/DTOs/CreateAccountResponseDto.cs create mode 100644 MaruanBH.Core/AccountContext/Queries/GetAccountDetailsQuery.cs create mode 100644 MaruanBH.Core/AccountContext/Validators/CreateAccountDtoValidator.cs create mode 100644 MaruanBH.Core/Base/Exceptions/CustomException.cs create mode 100644 MaruanBH.Core/CustomerContext/Commands/CreateCustomerCommand.cs create mode 100644 MaruanBH.Core/CustomerContext/DTOs/CreateCustomerDto.cs create mode 100644 MaruanBH.Core/CustomerContext/DTOs/CreateCustomerResponseDto.cs create mode 100644 MaruanBH.Core/CustomerContext/DTOs/CustomerDetailDto.cs create mode 100644 MaruanBH.Core/CustomerContext/DTOs/TransactionDto.cs create mode 100644 MaruanBH.Core/CustomerContext/Queries/GetCustomerDetailsQuery.cs create mode 100644 MaruanBH.Core/CustomerContext/Validators/CreateCustomerDtoValidator.cs create mode 100644 MaruanBH.Core/CustomerContext/Validators/GetCustomerDetailsQueryValidator.cs create mode 100644 MaruanBH.Core/MaruanBH.Core.csproj create mode 100644 MaruanBH.Core/Services/IAccountService.cs create mode 100644 MaruanBH.Core/Services/ICustomerService.cs create mode 100644 MaruanBH.Core/Services/ITransactionService.cs create mode 100644 MaruanBH.Domain/.gitignore create mode 100644 MaruanBH.Domain/Base/Error/EResponse.cs create mode 100644 MaruanBH.Domain/Base/Error/Error.cs create mode 100644 MaruanBH.Domain/Base/Error/Etype.cs create mode 100644 MaruanBH.Domain/Entities/Account.cs create mode 100644 MaruanBH.Domain/Entities/Customer.cs create mode 100644 MaruanBH.Domain/Entities/Transaction.cs create mode 100644 MaruanBH.Domain/MaruanBH.Domain.csproj create mode 100644 MaruanBH.Domain/Respositories/IAccountRepository.cs create mode 100644 MaruanBH.Domain/Respositories/ICustomerRepository.cs create mode 100644 MaruanBH.Domain/Respositories/ITransactionRespository.cs create mode 100644 MaruanBH.Persistance/.gitignore create mode 100644 MaruanBH.Persistance/MaruanBH.Persistance.csproj create mode 100644 MaruanBH.Persistance/Respositories/AccountRepository.cs create mode 100644 MaruanBH.Persistance/Respositories/CustomerRepository.cs create mode 100644 MaruanBH.Persistance/Respositories/TransactionRepository.cs create mode 100644 MaruanBH.Tests/.gitignore create mode 100644 MaruanBH.Tests/Business/UnitTests/AccountContext/Commands/CreateAccountCommandHandlerTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/AccountContext/Query/GetAccountDetailsQueryHandlerTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/CustomerContext/Commands/CreateCustomerCommandHandlerTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/CustomerContext/Query/GetCustomerDetailsQueryHandlerTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Repositories/AccountRepositoryTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Repositories/CustomerRepositoryTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Repositories/TransactionRepositoryTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Services/AccountServiceTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Services/CustomerServiceTests.cs create mode 100644 MaruanBH.Tests/Business/UnitTests/Services/TransactionServiceTests.cs create mode 100644 MaruanBH.Tests/MaruanBH.Tests.csproj create mode 100644 MaruanBH.sln create mode 100644 README.md diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml new file mode 100644 index 0000000..c88f8ba --- /dev/null +++ b/.github/workflows/dotnet-ci.yml @@ -0,0 +1,32 @@ +name: .MaruanBH CI Pipeline + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Setup dotnet + uses: actions/setup-dotnet@v3 + with: + dotnet-version: '8.x' + + - name: Clean dotnet + run: dotnet clean MaruanBH.sln + + - name: Restore dotnet dependencies + run: dotnet restore MaruanBH.sln + + - name: Build dotnet + run: dotnet build MaruanBH.sln --configuration Release --no-restore + + - name: Test with dotnet + run: dotnet test MaruanBH.Tests/MaruanBH.Tests.csproj --verbosity normal \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Api/.gitignore b/MaruanBH.Api/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Api/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Api/BlueHarvest.Api.http b/MaruanBH.Api/BlueHarvest.Api.http new file mode 100644 index 0000000..b4c3fc4 --- /dev/null +++ b/MaruanBH.Api/BlueHarvest.Api.http @@ -0,0 +1,6 @@ +@MaruanBH.Api_HostAddress = http://localhost:5118 + +GET {{MaruanBH.Api_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/MaruanBH.Api/Configuration/DependenciesInjectorConfiguration.cs b/MaruanBH.Api/Configuration/DependenciesInjectorConfiguration.cs new file mode 100644 index 0000000..9cba593 --- /dev/null +++ b/MaruanBH.Api/Configuration/DependenciesInjectorConfiguration.cs @@ -0,0 +1,56 @@ +using MaruanBH.Domain.Repositories; +using MaruanBH.Persistance.Repositories; +using MaruanBH.Business.CustomerContext.QueryHandler; +using MaruanBH.Business.CustomerContext.CommandHandler; +using MaruanBH.Core.Services; +using MaruanBH.Business.Services; +using MaruanBH.Core.CustomerContext.Validators; +using MaruanBH.Core.CustomerContext.Queries; +using FluentValidation.AspNetCore; +using FluentValidation; +using Serilog; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Business.AccountContext.QueryHandler; +using MaruanBH.Core.AccountContext.Validators; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Business.AccountContext.CommandHandler; +// DI +namespace MaruanBH.Api.Configuration +{ + public static class DependenciesInjectorConfiguration + { + // For the sake of simplicity and speed during development, we are manually registering the repositories here. + // In a more robust solution, we would typically implement a Unit of Work pattern alongside repository pattern. + // This would improve testability and facilitate Test-Driven Development (TDD) by decoupling the data access layer. + public static void AddRepositories(this IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + + public static void AddServices(this IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddLogging(logBuilder => logBuilder.AddSerilog(dispose: true)); + services.AddMemoryCache(); + } + + public static void AddCQRS(this IServiceCollection services) + { + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(GetCustomerDetailsQueryHandler).Assembly)); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(CreateCustomerCommandHandler).Assembly)); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(GetAccountDetailsQueryHandler).Assembly)); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(CreateAccountCommandHandler).Assembly)); + } + + public static void AddValidators(this IServiceCollection services) + { + services.AddScoped, GetCustomerDetailsQueryValidator>(); + services.AddScoped, CreateCustomerDtoValidator>(); + services.AddScoped, CreateAccountDtoValidator>(); + } + } +} \ No newline at end of file diff --git a/MaruanBH.Api/Configuration/GeneralConfiguration.cs b/MaruanBH.Api/Configuration/GeneralConfiguration.cs new file mode 100644 index 0000000..15f35dc --- /dev/null +++ b/MaruanBH.Api/Configuration/GeneralConfiguration.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace MaruanBH.Api.Configuration +{ + public static class GeneralConfiguration + { + public static void UseSwagger(this IApplicationBuilder app, string endpointName) + { + app.UseSwagger(); + app.UseSwaggerUI(); + } + + public static void AddLogging(this IServiceCollection services, IConfiguration configuration) + { + services.AddLogging(loggingBuilder => + { + loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); + loggingBuilder.AddConsole(); + loggingBuilder.AddDebug(); + }); + } + + } +} diff --git a/MaruanBH.Api/Controllers/AccountController.cs b/MaruanBH.Api/Controllers/AccountController.cs new file mode 100644 index 0000000..19000e7 --- /dev/null +++ b/MaruanBH.Api/Controllers/AccountController.cs @@ -0,0 +1,121 @@ +using MediatR; +using Microsoft.AspNetCore.Mvc; +using MaruanBH.Core.AccountContext.Queries; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Core.AccountContext.Commands; +using FluentValidation; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Domain.Base.Error; + +namespace MaruanBH.Api.Controllers +{ + [ApiController] + [Route("api/account")] + public class AccountController : ApiController + { + + private readonly IValidator _createAccountValidator; + + public AccountController(IMediator mediator, ILogger logger, IValidator validator) : base(mediator, logger) + { + _createAccountValidator = validator; + } + + /// + /// Creates a new account and associates it with an existing customer. + /// + /// + /// This method handles the creation of a new account linked to a customer identified by their customerID. + /// The API exposes an endpoint that accepts the customerID and initialCredit as input parameters. + /// + /// If the initialCredit is greater than 0, a transaction will be automatically created and associated with the newly created account. + /// + /// Workflow: + /// 1. A new account is created for the customer. + /// 2. If the initialCredit is greater than 0, we add a new transaction for the account. + /// + /// The customer data to create. + /// The unique identifier of the newly created customer. + /// Returns the Guid of the created customer. + /// If the request is invalid. + /// If an internal server error occurs. + [HttpPost("create")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CreateAccountResponseDto))] + [ProducesResponseType(typeof(ErrorResponse), 404)] + [ProducesResponseType(typeof(ErrorResponse), 500)] + [ProducesResponseType(typeof(string[]), 400)] + public async Task CreateAccount([FromBody] CreateAccountDto dto) + { + + var validationResult = _createAccountValidator.Validate(dto); + + if (!validationResult.IsValid) + { + return BadRequest(validationResult.Errors.Select(e => e.ErrorMessage)); + } + + try + { + Logger.LogInformation("Processing CreateAccount"); + var command = new CreateAccountCommand(dto); + var id = await Mediator.Send(command); + return Ok(new CreateAccountResponseDto { AccountId = id }); + } + catch (CustomException ex) + { + Logger.LogWarning(ex, "Something went wrong while creating the account"); + return NotFound(new { message = ex.Message }); + } + catch (Exception ex) + { + Logger.LogError(ex, "An error occurred while processing the request to create the user"); + return StatusCode(500, new { message = "An error occurred while processing the request." }); + } + } + + /// + /// Retrieves the details of an account based on the provided account ID. + /// + /// + /// This method fetches and returns the account details, including the associated customer's information, account balance, and transaction history. + /// + /// The output will display: + /// - Customer's Name and Surname + /// - Account Balance + /// - List of Transactions for the account + /// + /// The unique identifier of the account. + /// + /// A task representing the asynchronous operation. The task result contains an that represents the result of the operation. + /// If the account is found, it returns an with the account details. + /// If the account is not found, it returns a with an error message. + /// If an unexpected error occurs, it returns a with a 500 status code and an error message. + /// + /// Returns the details of the account if found. + /// If the account is not found. + /// If an internal server error occurs. + [ProducesResponseType(typeof(AccountDetailsDto), 200)] + [ProducesResponseType(typeof(ErrorResponse), 404)] + [ProducesResponseType(typeof(ErrorResponse), 500)] + [ProducesResponseType(typeof(string[]), 400)] + [HttpGet("details/{id}")] + public async Task GetAccountDetails(Guid id) + { + try + { + var accountDetails = await Mediator.Send(new GetAccountDetailsQuery(id)); + return Ok(accountDetails); + } + catch (CustomException ex) + { + Logger.LogWarning(ex, "Something went wrong while getting the account details for customer ID {Id}", id); + return NotFound(new { message = ex.Message }); + } + catch (Exception ex) + { + Logger.LogError(ex, "An error occurred while processing the request for customer ID {Id}", id); + return StatusCode(500, new { message = "An error occurred while processing the request." }); + } + } + } +} diff --git a/MaruanBH.Api/Controllers/Base/ApiController.cs b/MaruanBH.Api/Controllers/Base/ApiController.cs new file mode 100644 index 0000000..0cb09ba --- /dev/null +++ b/MaruanBH.Api/Controllers/Base/ApiController.cs @@ -0,0 +1,31 @@ +using MediatR; +using Microsoft.AspNetCore.Mvc; +using FluentValidation; + +namespace MaruanBH.Api.Controllers + +{ + [Route("[controller]")] + public class ApiController : Controller + { + public ApiController(IMediator mediator, ILogger logger) + { + Mediator = mediator; + Logger = logger; + } + + protected IMediator Mediator { get; } + protected ILogger Logger { get; } + + protected IActionResult? ValidateRequest(T request, IValidator validator) + { + var validationResult = validator.Validate(request); + if (!validationResult.IsValid) + { + return BadRequest(validationResult.Errors.Select(e => e.ErrorMessage)); + } + + return null; + } + } +} \ No newline at end of file diff --git a/MaruanBH.Api/Controllers/CustomerController.cs b/MaruanBH.Api/Controllers/CustomerController.cs new file mode 100644 index 0000000..9b03607 --- /dev/null +++ b/MaruanBH.Api/Controllers/CustomerController.cs @@ -0,0 +1,114 @@ +using Microsoft.AspNetCore.Mvc; +using MaruanBH.Core.CustomerContext.Queries; +using MaruanBH.Core.CustomerContext.Commands; +using MediatR; +using FluentValidation; +using MaruanBH.Domain.Base.Error; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Core.CustomerContext.DTOs; +using CSharpFunctionalExtensions; + +namespace MaruanBH.Api.Controllers +{ + [ApiController] + [Route("api/customer")] + public class CustomerController : ApiController + { + private readonly IValidator _getCustomerDetailsQueryValidator; + private readonly IValidator _createCustomerValidator; + + public CustomerController(IMediator mediator, IValidator validator, ILogger logger, IValidator createCustomerValidator) : base(mediator, logger) + { + _getCustomerDetailsQueryValidator = validator; + _createCustomerValidator = createCustomerValidator; + } + + /// + /// Creates a new customer. + /// + /// The customer data to create. + /// The unique identifier of the newly created customer. + /// Returns the Guid of the created customer. + /// If the request is invalid. + /// If an internal server error occurs. + [HttpPost("create")] + [ProducesResponseType(typeof(CreateCustomerResponseDto), 201)] + [ProducesResponseType(typeof(ErrorResponse), 400)] + [ProducesResponseType(typeof(ErrorResponse), 500)] + public async Task CreateCustomer([FromBody] CreateCustomerDto dto) + { + var validationResult = _createCustomerValidator.Validate(dto); + if (!validationResult.IsValid) + { + return BadRequest(validationResult.Errors.Select(e => e.ErrorMessage)); + } + + try + { + Logger.LogInformation("Processing CreateCustomer request for customer with name {Name}", dto.Name); + var command = new CreateCustomerCommand(dto); + var customerId = await Mediator.Send(command); + return Ok(new CreateCustomerResponseDto { CustomerId = customerId }); + } + catch (Exception ex) + { + Logger.LogError(ex, "An error occurred while creating the customer."); + return StatusCode(500, new { message = "An error occurred while creating the customer." }); + } + } + + /// + /// Retrieves the details of a customer by their ID. + /// This endpoint is primarily for developer experience (DX) purposes. + /// For retrieving customer information including Name, Surname, Balance, and transactions of the accounts, + /// please refer to the account/details/{id} endpoint in the AccountController for comprehensive account details. + /// + /// The unique identifier of the customer. + /// Customer details including Name, Surname, Balance, and transactions of the accounts. + /// Returns customer details successfully. + /// If the customer with the given ID is not found. + /// If an internal server error occurs. + /// If the request is invalid. + [HttpGet("details/{id}")] + [ProducesResponseType(typeof(CustomerDetailDto), 200)] + [ProducesResponseType(typeof(ErrorResponse), 404)] + [ProducesResponseType(typeof(ErrorResponse), 500)] + [ProducesResponseType(typeof(string[]), 400)] + public async Task GetCustomerDetails(Guid id) + { + var query = new GetCustomerDetailsQuery(id); + + var validationResult = ValidateRequest(query, _getCustomerDetailsQueryValidator); + if (validationResult != null) + { + return validationResult; + } + + try + { + Logger.LogInformation("Processing GetCustomerDetails query for customer ID {Id}", id); + Result result = await Mediator.Send(query); + if (result.IsSuccess) + { + return Ok(result.Value); + } + else + { + // not all code paths return a value + Logger.LogWarning("Customer not found for ID {Id}", id); + return NotFound(new { message = result.Error.ToString() }); + } + } + catch (CustomException ex) + { + Logger.LogWarning(ex, "Customer not found for ID {Id}", id); + return NotFound(new { message = ex.Message }); + } + catch (Exception ex) + { + Logger.LogError(ex, "An error occurred while processing the request for customer ID {Id}", id); + return StatusCode(500, new { message = "An error occurred while processing the request." }); + } + } + } +} diff --git a/MaruanBH.Api/MaruanBH.Api.csproj b/MaruanBH.Api/MaruanBH.Api.csproj new file mode 100644 index 0000000..4b90f83 --- /dev/null +++ b/MaruanBH.Api/MaruanBH.Api.csproj @@ -0,0 +1,31 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MaruanBH.Api/Program.cs b/MaruanBH.Api/Program.cs new file mode 100644 index 0000000..d0194f9 --- /dev/null +++ b/MaruanBH.Api/Program.cs @@ -0,0 +1,38 @@ +using Serilog; + +namespace MaruanBH.Api +{ + public class Program + { + public static void Main(string[] args) + { + Log.Logger = new LoggerConfiguration() + .WriteTo.Console() + .WriteTo.File("logs/maruanBH-api.log", rollingInterval: RollingInterval.Day) + .CreateLogger(); + + try + { + Log.Information("Starting up"); + CreateHostBuilder(args).Build().Run(); + } + catch (Exception ex) + { + Log.Fatal(ex, "Application start-up failed"); + throw; + } + finally + { + Log.CloseAndFlush(); + } + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .UseSerilog() + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/MaruanBH.Api/Properties/launchSettings.json b/MaruanBH.Api/Properties/launchSettings.json new file mode 100644 index 0000000..3ad4237 --- /dev/null +++ b/MaruanBH.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:45930", + "sslPort": 44384 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5118", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7191;http://localhost:5118", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/MaruanBH.Api/Startup.cs b/MaruanBH.Api/Startup.cs new file mode 100644 index 0000000..829ccf9 --- /dev/null +++ b/MaruanBH.Api/Startup.cs @@ -0,0 +1,37 @@ +using MaruanBH.Api.Configuration; + +namespace MaruanBH.Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + services.AddSwaggerGen(); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); + services.AddControllers(); + services.AddRepositories(); + services.AddServices(); + services.AddCQRS(); + services.AddValidators(); + } + + public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) + { + app.UseSwagger("MaruanBH"); + app.UseRouting(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + + } + } +} diff --git a/MaruanBH.Api/appsettings.Development.json b/MaruanBH.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/MaruanBH.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/MaruanBH.Api/appsettings.json b/MaruanBH.Api/appsettings.json new file mode 100644 index 0000000..1b1f62b --- /dev/null +++ b/MaruanBH.Api/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Serilog": { + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Warning", + "System": "Warning" + } + }, + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "logs/maruanBH-api-.log", + "rollingInterval": "Day" + } + } + ] + } +} diff --git a/MaruanBH.Business/.gitignore b/MaruanBH.Business/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Business/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Business/AccountContext/CommandHandler/CreateAccountCommandHandler.cs b/MaruanBH.Business/AccountContext/CommandHandler/CreateAccountCommandHandler.cs new file mode 100644 index 0000000..adc7ae9 --- /dev/null +++ b/MaruanBH.Business/AccountContext/CommandHandler/CreateAccountCommandHandler.cs @@ -0,0 +1,61 @@ +using MediatR; +using MaruanBH.Core.AccountContext.Commands; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Domain.Base.Error; +using Microsoft.Extensions.Logging; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Core.AccountContext.DTOs; +using FluentValidation.Results; + +namespace MaruanBH.Business.AccountContext.CommandHandler +{ + public class CreateAccountCommandHandler : IRequestHandler + { + private readonly IAccountService _accountService; + private readonly ITransactionService _transactionService; + private readonly ICustomerService _customerService; + protected ILogger Logger { get; } + + public CreateAccountCommandHandler(IAccountService accountService, ITransactionService transactionService, ICustomerService customerService, ILogger logger) + { + _accountService = accountService; + _transactionService = transactionService; + _customerService = customerService; + Logger = logger; + } + + public async Task Handle(CreateAccountCommand request, CancellationToken cancellationToken) + { + + var customer = await _customerService.GetCustomerByIdAsync(request.AccountDto.CustomerId); + + var initialCredit = request.AccountDto.InitialCredit; + + var account = new Account + ( + request.AccountDto.CustomerId, + initialCredit + ); + + var accountResult = await _accountService.CreateAccountAsync(account); + + if (accountResult.IsFailure) + { + throw new CustomException(accountResult.Error); + } + + var accountId = accountResult.Value; + + if (initialCredit > 0) + { + Logger.LogWarning("Initial credit is higher than 0, creating transaction"); + await _transactionService.CreateTransactionAsync(accountId, initialCredit); + } + + return accountId; + } + } +} diff --git a/MaruanBH.Business/AccountContext/QueryHandler/GetAccountDetailsQueryHandler.cs b/MaruanBH.Business/AccountContext/QueryHandler/GetAccountDetailsQueryHandler.cs new file mode 100644 index 0000000..0a1d718 --- /dev/null +++ b/MaruanBH.Business/AccountContext/QueryHandler/GetAccountDetailsQueryHandler.cs @@ -0,0 +1,80 @@ +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Domain.Repositories; +using MediatR; +using System.Threading; +using System.Threading.Tasks; +using MaruanBH.Business.Services; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Domain.Base.Error; +using MaruanBH.Core.Services; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Core.AccountContext.Queries; + +namespace MaruanBH.Business.AccountContext.QueryHandler +{ + public class GetAccountDetailsQueryHandler : IRequestHandler + { + private readonly IAccountService _accountService; + private readonly ICustomerService _customerService; + private readonly ITransactionService _transactionService; + + public GetAccountDetailsQueryHandler( + IAccountService accountService, + ICustomerService customerService, + ITransactionService transactionService) + { + _accountService = accountService; + _customerService = customerService; + _transactionService = transactionService; + } + + public async Task Handle(GetAccountDetailsQuery request, CancellationToken cancellationToken) + { + var accountResult = await _accountService.GetByIdAsync(request.AccountId); + + if (accountResult.IsFailure) + { + throw new CustomException(accountResult.Error); + } + + var account = accountResult.Value; + + var customerResult = await _customerService.GetCustomerByIdAsync(account.CustomerId); + + if (customerResult.IsFailure) + { + throw new CustomException(customerResult.Error); + } + + var customer = customerResult.Value; + + var transactionResult = await _transactionService.GetTransactionsForCustomer(request.AccountId); + + if (transactionResult.IsFailure) + { + throw new CustomException(transactionResult.Error); + } + + var transactions = transactionResult.Value; + + var balance = transactions.Sum(t => t.Amount) + account.InitialCredit + customer.Balance; + + var transactionDtos = transactions.Select(t => new TransactionDto( + t.Amount, + t.Date + )).ToList(); + + return new AccountDetailsDto + { + Id = account.Id, + Name = customer.Name, + Surname = customer.Surname, + Balance = balance, + Transactions = transactionDtos, + CustomerId = account.CustomerId, + InitialCredit = account.InitialCredit + }; + } + + } +} diff --git a/MaruanBH.Business/CustomerContext/CommandHandler/CreateCustomerCommandHandler.cs b/MaruanBH.Business/CustomerContext/CommandHandler/CreateCustomerCommandHandler.cs new file mode 100644 index 0000000..6b335e1 --- /dev/null +++ b/MaruanBH.Business/CustomerContext/CommandHandler/CreateCustomerCommandHandler.cs @@ -0,0 +1,43 @@ +using MediatR; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Entities; +using MaruanBH.Core.CustomerContext.Commands; +using MaruanBH.Domain.Repositories; + +namespace MaruanBH.Business.CustomerContext.CommandHandler +{ + public class CreateCustomerCommandHandler : IRequestHandler + { + private readonly ICustomerRepository _customerRepository; + private readonly IAccountRepository _accountRepository; + + public CreateCustomerCommandHandler(ICustomerRepository customerRepository, IAccountRepository accountRepository) + { + _customerRepository = customerRepository; + _accountRepository = accountRepository; + } + + public async Task Handle(CreateCustomerCommand request, CancellationToken cancellationToken) + { + var customer = new Customer + ( + request.CustomerDto.Name, + request.CustomerDto.Surname, + request.CustomerDto.Balance + ); + + await _customerRepository.AddAsync(customer); + + var account = new Account + ( + customer.Id, + customer.Balance + ); + + await _accountRepository.AddAsync(account); + + return customer.Id; + } + } + +} \ No newline at end of file diff --git a/MaruanBH.Business/CustomerContext/QueryHandler/GetCustomerDetailsQueryHandler.cs b/MaruanBH.Business/CustomerContext/QueryHandler/GetCustomerDetailsQueryHandler.cs new file mode 100644 index 0000000..2616c2d --- /dev/null +++ b/MaruanBH.Business/CustomerContext/QueryHandler/GetCustomerDetailsQueryHandler.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using MediatR; +using MaruanBH.Core.Services; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Core.CustomerContext.Queries; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Base.Error; +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Business.CustomerContext.QueryHandler +{ + public class GetCustomerDetailsQueryHandler : IRequestHandler> + { + private readonly ICustomerService _customerService; + private readonly ITransactionService _transactionService; + + public GetCustomerDetailsQueryHandler(ICustomerService customerService, ITransactionService transactionService) + { + _customerService = customerService; + _transactionService = transactionService; + } + + public async Task> Handle(GetCustomerDetailsQuery request, CancellationToken cancellationToken) + { + var customerResult = await _customerService.GetCustomerByIdAsync(request.Id); + + if (customerResult.IsFailure) + return Result.Failure(customerResult.Error); + + var transactionsResult = await _transactionService.GetTransactionsForCustomer(request.Id); + + if (transactionsResult.IsFailure) + return Result.Failure(Error.NotFound(transactionsResult.Error)); + + return Result.Success(CreateCustomerDetailDto(customerResult.Value, transactionsResult.Value)); + } + + private static CustomerDetailDto CreateCustomerDetailDto(Customer customer, List transactions) => + new CustomerDetailDto + { + Name = customer.Name, + Surname = customer.Surname, + Balance = transactions.Sum(t => t.Amount) + customer.Balance, + Transactions = transactions.Select(CreateTransactionDto).ToList() + }; + + private static TransactionDto CreateTransactionDto(Transaction t) => + new TransactionDto(t.Amount, t.Date); + } +} diff --git a/MaruanBH.Business/MaruanBH.Business.csproj b/MaruanBH.Business/MaruanBH.Business.csproj new file mode 100644 index 0000000..e83f840 --- /dev/null +++ b/MaruanBH.Business/MaruanBH.Business.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/MaruanBH.Business/Services/AccountService.cs b/MaruanBH.Business/Services/AccountService.cs new file mode 100644 index 0000000..f76cc31 --- /dev/null +++ b/MaruanBH.Business/Services/AccountService.cs @@ -0,0 +1,35 @@ +using System; +using System.Threading.Tasks; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Base.Error; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Domain.Repositories; +using MaruanBH.Domain.Entities; +using CSharpFunctionalExtensions; + +namespace MaruanBH.Business.Services +{ + public class AccountService : IAccountService + { + private readonly IAccountRepository _accountRepository; + + public AccountService(IAccountRepository accountRepository) + { + _accountRepository = accountRepository; + } + + public Task> CreateAccountAsync(Account account) => + Result.Success(account) + .Ensure(acc => acc != null, "Account cannot be null") + .Tap(async acc => await _accountRepository.AddAsync(acc)) + .Map(acc => acc.Id); + + + public Task> GetByIdAsync(Guid id) => + Result.Success(id) + .Ensure(accountId => accountId != Guid.Empty, "Invalid account ID") + .Bind(async accountId => await _accountRepository.GetByIdAsync(accountId) + .ToResult("Account not found")); + + } +} diff --git a/MaruanBH.Business/Services/CustomerService.cs b/MaruanBH.Business/Services/CustomerService.cs new file mode 100644 index 0000000..f7af5ad --- /dev/null +++ b/MaruanBH.Business/Services/CustomerService.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Base.Error; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Domain.Repositories; +using MaruanBH.Domain.Entities; +using Microsoft.Extensions.Logging; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Core.CustomerContext.DTOs; + +namespace MaruanBH.Business.Services +{ + public class CustomerService : ICustomerService + { + private readonly ICustomerRepository _customerRepository; + private readonly IAccountRepository _accountRepository; + private readonly ITransactionRepository _transactionRepository; + protected ILogger Logger { get; } + + public CustomerService(ICustomerRepository customerRepository, IAccountRepository accountRepository, ITransactionRepository transactionRepository, ILogger logger) + { + _customerRepository = customerRepository; + _accountRepository = accountRepository; + _transactionRepository = transactionRepository; + Logger = logger; + } + + public Task> GetCustomerByIdAsync(Guid id) => + Result.SuccessIf(id != Guid.Empty, id, Error.BadRequest("Invalid customer ID")) + .Bind(async validId => + (await _customerRepository.GetCustomerByIdAsync(validId)) + .ToResult(Error.NotFound("Customer not found"))) + .TapError(error => throw new CustomException(error)); + + + + public async Task> CreateCustomerAsync(Customer customer) => + + await Result.Success(customer) + .Ensure(cust => cust != null, "Customer cannot be null") + .Bind(async cust => + { + var addResult = await _customerRepository.AddAsync(cust); + + return addResult + .Map(() => cust.Id); + }); + + + } +} diff --git a/MaruanBH.Business/Services/TransactionService.cs b/MaruanBH.Business/Services/TransactionService.cs new file mode 100644 index 0000000..6b98100 --- /dev/null +++ b/MaruanBH.Business/Services/TransactionService.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Repositories; +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Business.Services +{ + public class TransactionService : ITransactionService + { + private readonly ITransactionRepository _transactionRepository; + + public TransactionService(ITransactionRepository transactionRepository) + { + _transactionRepository = transactionRepository; + } + + public Task>> GetTransactionsForCustomer(Guid accountId) => + _transactionRepository.GetTransactionsForCustomer(accountId) + .ContinueWith(task => Result.Success(task.Result)); + + public Task> CreateTransactionAsync(Guid accountId, decimal amount) => + Result.Success(new Transaction + ( + DateTime.UtcNow, + accountId, + amount + )) + .Ensure(transaction => transaction.Amount > 0, "Transaction amount must be positive") + .Bind(transaction => + _transactionRepository.AddAsync(accountId, transaction) + .ContinueWith(task => + task.IsCompletedSuccessfully + ? Result.Success(transaction.Id) + : Result.Failure($"Failed to add transaction for account {accountId}") + ) + ); + } +} diff --git a/MaruanBH.Core/.gitignore b/MaruanBH.Core/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Core/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Core/AccountContext/Commands/CreateAccountCommand.cs b/MaruanBH.Core/AccountContext/Commands/CreateAccountCommand.cs new file mode 100644 index 0000000..af9f1d3 --- /dev/null +++ b/MaruanBH.Core/AccountContext/Commands/CreateAccountCommand.cs @@ -0,0 +1,15 @@ +using MediatR; +using MaruanBH.Core.AccountContext.DTOs; + +namespace MaruanBH.Core.AccountContext.Commands +{ + public class CreateAccountCommand : IRequest + { + public CreateAccountDto AccountDto { get; } + + public CreateAccountCommand(CreateAccountDto accountDto) + { + AccountDto = accountDto; + } + } +} diff --git a/MaruanBH.Core/AccountContext/DTOs/AccountDetailsDto.cs b/MaruanBH.Core/AccountContext/DTOs/AccountDetailsDto.cs new file mode 100644 index 0000000..8cb9f1e --- /dev/null +++ b/MaruanBH.Core/AccountContext/DTOs/AccountDetailsDto.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using MaruanBH.Core.CustomerContext.DTOs; + +namespace MaruanBH.Core.AccountContext.DTOs +{ + public class AccountDetailsDto + { + public Guid Id { get; set; } + public string Name { get; set; } = string.Empty; + public string Surname { get; set; } = string.Empty; + public Guid CustomerId { get; set; } + public decimal InitialCredit { get; set; } + public decimal Balance { get; set; } + public List Transactions { get; set; } = new List(); + } +} \ No newline at end of file diff --git a/MaruanBH.Core/AccountContext/DTOs/CreateAccountDto.cs b/MaruanBH.Core/AccountContext/DTOs/CreateAccountDto.cs new file mode 100644 index 0000000..dfcee99 --- /dev/null +++ b/MaruanBH.Core/AccountContext/DTOs/CreateAccountDto.cs @@ -0,0 +1,8 @@ +namespace MaruanBH.Core.AccountContext.DTOs +{ + public class CreateAccountDto + { + public Guid CustomerId { get; set; } + public decimal InitialCredit { get; set; } + } +} \ No newline at end of file diff --git a/MaruanBH.Core/AccountContext/DTOs/CreateAccountResponseDto.cs b/MaruanBH.Core/AccountContext/DTOs/CreateAccountResponseDto.cs new file mode 100644 index 0000000..fcad6e2 --- /dev/null +++ b/MaruanBH.Core/AccountContext/DTOs/CreateAccountResponseDto.cs @@ -0,0 +1,8 @@ +namespace MaruanBH.Core.AccountContext.DTOs +{ + public class CreateAccountResponseDto + { + public Guid AccountId { get; set; } + + } +} \ No newline at end of file diff --git a/MaruanBH.Core/AccountContext/Queries/GetAccountDetailsQuery.cs b/MaruanBH.Core/AccountContext/Queries/GetAccountDetailsQuery.cs new file mode 100644 index 0000000..e8b7284 --- /dev/null +++ b/MaruanBH.Core/AccountContext/Queries/GetAccountDetailsQuery.cs @@ -0,0 +1,15 @@ +using MediatR; +using MaruanBH.Core.AccountContext.DTOs; + +namespace MaruanBH.Core.AccountContext.Queries +{ + public class GetAccountDetailsQuery : IRequest + { + public Guid AccountId { get; } + + public GetAccountDetailsQuery(Guid accountId) + { + AccountId = accountId; + } + } +} diff --git a/MaruanBH.Core/AccountContext/Validators/CreateAccountDtoValidator.cs b/MaruanBH.Core/AccountContext/Validators/CreateAccountDtoValidator.cs new file mode 100644 index 0000000..3de88c6 --- /dev/null +++ b/MaruanBH.Core/AccountContext/Validators/CreateAccountDtoValidator.cs @@ -0,0 +1,15 @@ +using FluentValidation; +using MaruanBH.Core.AccountContext.DTOs; + +namespace MaruanBH.Core.AccountContext.Validators + +{ + public class CreateAccountDtoValidator : AbstractValidator + { + public CreateAccountDtoValidator() + { + RuleFor(c => c.CustomerId).NotEmpty().WithMessage("CustomerId is required."); + RuleFor(c => c.InitialCredit).GreaterThanOrEqualTo(0).WithMessage("InitialCredit must be greater than or equal to 0."); + } + } +} diff --git a/MaruanBH.Core/Base/Exceptions/CustomException.cs b/MaruanBH.Core/Base/Exceptions/CustomException.cs new file mode 100644 index 0000000..4a1f102 --- /dev/null +++ b/MaruanBH.Core/Base/Exceptions/CustomException.cs @@ -0,0 +1,19 @@ +using System; +using MaruanBH.Domain.Base.Error; + +namespace MaruanBH.Core.Base.Exceptions +{ + public class CustomException : Exception + { + public Error Error { get; } + + public CustomException(string message) : base(message) + { + } + public CustomException(Error error) + : base(error.Messages.FirstOrDefault()) + { + Error = error; + } + } +} diff --git a/MaruanBH.Core/CustomerContext/Commands/CreateCustomerCommand.cs b/MaruanBH.Core/CustomerContext/Commands/CreateCustomerCommand.cs new file mode 100644 index 0000000..da9b6af --- /dev/null +++ b/MaruanBH.Core/CustomerContext/Commands/CreateCustomerCommand.cs @@ -0,0 +1,16 @@ + +using MediatR; +using MaruanBH.Core.CustomerContext.DTOs; + +namespace MaruanBH.Core.CustomerContext.Commands +{ + public class CreateCustomerCommand : IRequest + { + public CreateCustomerDto CustomerDto { get; } + + public CreateCustomerCommand(CreateCustomerDto customerDto) + { + CustomerDto = customerDto; + } + } +} \ No newline at end of file diff --git a/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerDto.cs b/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerDto.cs new file mode 100644 index 0000000..f947360 --- /dev/null +++ b/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerDto.cs @@ -0,0 +1,9 @@ +namespace MaruanBH.Core.CustomerContext.DTOs +{ + public class CreateCustomerDto + { + public string Name { get; set; } = string.Empty; + public string Surname { get; set; } = string.Empty; + public decimal Balance { get; set; } + } +} diff --git a/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerResponseDto.cs b/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerResponseDto.cs new file mode 100644 index 0000000..45604f0 --- /dev/null +++ b/MaruanBH.Core/CustomerContext/DTOs/CreateCustomerResponseDto.cs @@ -0,0 +1,7 @@ +namespace MaruanBH.Core.CustomerContext.DTOs +{ + public class CreateCustomerResponseDto + { + public Guid CustomerId { get; set; } + } +} \ No newline at end of file diff --git a/MaruanBH.Core/CustomerContext/DTOs/CustomerDetailDto.cs b/MaruanBH.Core/CustomerContext/DTOs/CustomerDetailDto.cs new file mode 100644 index 0000000..1ca470d --- /dev/null +++ b/MaruanBH.Core/CustomerContext/DTOs/CustomerDetailDto.cs @@ -0,0 +1,12 @@ +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Core.CustomerContext.DTOs +{ + public class CustomerDetailDto + { + public string Name { get; set; } = string.Empty; + public string Surname { get; set; } = string.Empty; + public decimal Balance { get; set; } + public List Transactions { get; set; } = new List(); + } +} \ No newline at end of file diff --git a/MaruanBH.Core/CustomerContext/DTOs/TransactionDto.cs b/MaruanBH.Core/CustomerContext/DTOs/TransactionDto.cs new file mode 100644 index 0000000..aec81d8 --- /dev/null +++ b/MaruanBH.Core/CustomerContext/DTOs/TransactionDto.cs @@ -0,0 +1,16 @@ +using System; + +namespace MaruanBH.Core.CustomerContext.DTOs +{ + public record TransactionDto + { + public decimal Amount { get; init; } + public DateTime Date { get; init; } + + public TransactionDto(decimal amount, DateTime date) + { + Amount = amount; + Date = date; + } + } +} \ No newline at end of file diff --git a/MaruanBH.Core/CustomerContext/Queries/GetCustomerDetailsQuery.cs b/MaruanBH.Core/CustomerContext/Queries/GetCustomerDetailsQuery.cs new file mode 100644 index 0000000..0b2836d --- /dev/null +++ b/MaruanBH.Core/CustomerContext/Queries/GetCustomerDetailsQuery.cs @@ -0,0 +1,18 @@ +using System; +using MediatR; +using MaruanBH.Core.CustomerContext.DTOs; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Base.Error; + +namespace MaruanBH.Core.CustomerContext.Queries +{ + public class GetCustomerDetailsQuery : IRequest> + { + public Guid Id { get; } + + public GetCustomerDetailsQuery(Guid id) + { + Id = id; + } + } +} diff --git a/MaruanBH.Core/CustomerContext/Validators/CreateCustomerDtoValidator.cs b/MaruanBH.Core/CustomerContext/Validators/CreateCustomerDtoValidator.cs new file mode 100644 index 0000000..fae6ce5 --- /dev/null +++ b/MaruanBH.Core/CustomerContext/Validators/CreateCustomerDtoValidator.cs @@ -0,0 +1,15 @@ +using FluentValidation; +using MaruanBH.Core.CustomerContext.DTOs; + +namespace MaruanBH.Core.CustomerContext.Validators +{ + public class CreateCustomerDtoValidator : AbstractValidator + { + public CreateCustomerDtoValidator() + { + RuleFor(c => c.Name).NotEmpty().WithMessage("Name is required."); + RuleFor(c => c.Surname).NotEmpty().WithMessage("Surname is required."); + RuleFor(c => c.Balance).GreaterThanOrEqualTo(0).WithMessage("Balance must be a positive value."); + } + } +} diff --git a/MaruanBH.Core/CustomerContext/Validators/GetCustomerDetailsQueryValidator.cs b/MaruanBH.Core/CustomerContext/Validators/GetCustomerDetailsQueryValidator.cs new file mode 100644 index 0000000..11c9ebf --- /dev/null +++ b/MaruanBH.Core/CustomerContext/Validators/GetCustomerDetailsQueryValidator.cs @@ -0,0 +1,15 @@ +using FluentValidation; +using MaruanBH.Core.CustomerContext.Queries; + +namespace MaruanBH.Core.CustomerContext.Validators +{ + public class GetCustomerDetailsQueryValidator : AbstractValidator + { + public GetCustomerDetailsQueryValidator() + { + RuleFor(query => query.Id) + .NotNull().WithMessage("Customer ID must be provided.") + .NotEmpty().WithMessage("Customer ID must not be an empty GUID."); + } + } +} diff --git a/MaruanBH.Core/MaruanBH.Core.csproj b/MaruanBH.Core/MaruanBH.Core.csproj new file mode 100644 index 0000000..a20e12c --- /dev/null +++ b/MaruanBH.Core/MaruanBH.Core.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/MaruanBH.Core/Services/IAccountService.cs b/MaruanBH.Core/Services/IAccountService.cs new file mode 100644 index 0000000..f1d54fc --- /dev/null +++ b/MaruanBH.Core/Services/IAccountService.cs @@ -0,0 +1,13 @@ +using System; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Core.Services +{ + public interface IAccountService + { + Task> CreateAccountAsync(Account account); + Task> GetByIdAsync(Guid id); + } +} \ No newline at end of file diff --git a/MaruanBH.Core/Services/ICustomerService.cs b/MaruanBH.Core/Services/ICustomerService.cs new file mode 100644 index 0000000..e45fc47 --- /dev/null +++ b/MaruanBH.Core/Services/ICustomerService.cs @@ -0,0 +1,13 @@ +using MaruanBH.Domain.Entities; +using MaruanBH.Core.AccountContext.DTOs; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Base.Error; + +namespace MaruanBH.Core.Services +{ + public interface ICustomerService + { + Task> GetCustomerByIdAsync(Guid id); + Task> CreateCustomerAsync(Customer customer); + } +} diff --git a/MaruanBH.Core/Services/ITransactionService.cs b/MaruanBH.Core/Services/ITransactionService.cs new file mode 100644 index 0000000..d47fd98 --- /dev/null +++ b/MaruanBH.Core/Services/ITransactionService.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Core.Services +{ + public interface ITransactionService + { + Task>> GetTransactionsForCustomer(Guid accountId); + Task> CreateTransactionAsync(Guid accountId, decimal amount); + } +} \ No newline at end of file diff --git a/MaruanBH.Domain/.gitignore b/MaruanBH.Domain/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Domain/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Domain/Base/Error/EResponse.cs b/MaruanBH.Domain/Base/Error/EResponse.cs new file mode 100644 index 0000000..2c854d0 --- /dev/null +++ b/MaruanBH.Domain/Base/Error/EResponse.cs @@ -0,0 +1,9 @@ +namespace MaruanBH.Domain.Base.Error +{ + public class ErrorResponse + { + public string Type { get; set; } = string.Empty; + public DateTime Date { get; set; } + public IReadOnlyList Messages { get; set; } = new List(); + } +} \ No newline at end of file diff --git a/MaruanBH.Domain/Base/Error/Error.cs b/MaruanBH.Domain/Base/Error/Error.cs new file mode 100644 index 0000000..ab3b1ab --- /dev/null +++ b/MaruanBH.Domain/Base/Error/Error.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MaruanBH.Domain.Base.Error +{ + public readonly struct Error + { + private Error(ErrorType errorType, IEnumerable messages) + : this(errorType, messages.ToArray()) + { + } + + private Error(ErrorType errorType, params string[] messages) + { + Type = errorType; + Date = DateTime.Now; + Messages = messages; + } + + public IReadOnlyList Messages { get; } + + public DateTime Date { get; } + + public ErrorType Type { get; } + + public static Error NotFound(string error) => + new Error(ErrorType.NotFound, error); + + public static Error NotFound(IEnumerable errors) => + new Error(ErrorType.NotFound, errors); + + + public static Error BadRequest(string error) => + new Error(ErrorType.BadRequest, error); + + public static Error BadRequest(IEnumerable errors) => + new Error(ErrorType.BadRequest, errors); + + public ErrorResponse ToErrorResponse() => + new ErrorResponse + { + Type = Type.ToString(), + Date = Date, + Messages = Messages + }; + } +} diff --git a/MaruanBH.Domain/Base/Error/Etype.cs b/MaruanBH.Domain/Base/Error/Etype.cs new file mode 100644 index 0000000..95062b0 --- /dev/null +++ b/MaruanBH.Domain/Base/Error/Etype.cs @@ -0,0 +1,9 @@ +namespace MaruanBH.Domain.Base.Error + +{ + public enum ErrorType + { + NotFound, + BadRequest + } +} \ No newline at end of file diff --git a/MaruanBH.Domain/Entities/Account.cs b/MaruanBH.Domain/Entities/Account.cs new file mode 100644 index 0000000..7492bc0 --- /dev/null +++ b/MaruanBH.Domain/Entities/Account.cs @@ -0,0 +1,20 @@ +namespace MaruanBH.Domain.Entities +{ + + /// + /// Immutable entity with readonly properties + /// + public class Account + { + public Guid Id { get; set; } + public Guid CustomerId { get; set; } // foreign key + public decimal InitialCredit { get; set; } + + public Account(Guid customerId, decimal initialCredit) + { + Id = Guid.NewGuid(); + CustomerId = customerId; + InitialCredit = initialCredit; + } + } +} diff --git a/MaruanBH.Domain/Entities/Customer.cs b/MaruanBH.Domain/Entities/Customer.cs new file mode 100644 index 0000000..f7476cc --- /dev/null +++ b/MaruanBH.Domain/Entities/Customer.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; + +namespace MaruanBH.Domain.Entities +{ + /// + /// Immutable entity with readonly properties + /// + public class Customer + { + public Guid Id { get; init; } = Guid.NewGuid(); + public string Name { get; init; } = string.Empty; + public string Surname { get; init; } = string.Empty; + public decimal Balance { get; init; } + public IReadOnlyList Transactions { get; init; } = new List(); + + public Customer(string name, string surname, decimal balance) + { + Name = name; + Surname = surname; + Balance = balance; + } + } +} diff --git a/MaruanBH.Domain/Entities/Transaction.cs b/MaruanBH.Domain/Entities/Transaction.cs new file mode 100644 index 0000000..fce7b0f --- /dev/null +++ b/MaruanBH.Domain/Entities/Transaction.cs @@ -0,0 +1,23 @@ +using System; + +namespace MaruanBH.Domain.Entities +{ + /// + /// Immutable entity with readonly properties + /// + public record Transaction + { + public Guid Id { get; init; } + public DateTime Date { get; init; } + public Guid AccountId { get; init; } // foreign key + public decimal Amount { get; init; } + + public Transaction(DateTime date, Guid accountId, decimal amount) + { + Id = Guid.NewGuid(); + Date = date; + AccountId = accountId; + Amount = amount; + } + } +} \ No newline at end of file diff --git a/MaruanBH.Domain/MaruanBH.Domain.csproj b/MaruanBH.Domain/MaruanBH.Domain.csproj new file mode 100644 index 0000000..face9ac --- /dev/null +++ b/MaruanBH.Domain/MaruanBH.Domain.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/MaruanBH.Domain/Respositories/IAccountRepository.cs b/MaruanBH.Domain/Respositories/IAccountRepository.cs new file mode 100644 index 0000000..8538eb3 --- /dev/null +++ b/MaruanBH.Domain/Respositories/IAccountRepository.cs @@ -0,0 +1,14 @@ +using System; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Base.Error; + +namespace MaruanBH.Domain.Repositories +{ + public interface IAccountRepository + { + Task AddAsync(Account account); + Task> GetByIdAsync(Guid accountId); + } +} diff --git a/MaruanBH.Domain/Respositories/ICustomerRepository.cs b/MaruanBH.Domain/Respositories/ICustomerRepository.cs new file mode 100644 index 0000000..9bc8c7f --- /dev/null +++ b/MaruanBH.Domain/Respositories/ICustomerRepository.cs @@ -0,0 +1,11 @@ +using MaruanBH.Domain.Entities; +using CSharpFunctionalExtensions; + +namespace MaruanBH.Domain.Repositories +{ + public interface ICustomerRepository + { + Task> GetCustomerByIdAsync(Guid id); + Task AddAsync(Customer customer); + } +} \ No newline at end of file diff --git a/MaruanBH.Domain/Respositories/ITransactionRespository.cs b/MaruanBH.Domain/Respositories/ITransactionRespository.cs new file mode 100644 index 0000000..758706c --- /dev/null +++ b/MaruanBH.Domain/Respositories/ITransactionRespository.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using MaruanBH.Domain.Entities; + +namespace MaruanBH.Domain.Repositories +{ + public interface ITransactionRepository + { + Task> GetTransactionsForCustomer(Guid id); + Task AddAsync(Guid accountId, Transaction transaction); + } +} \ No newline at end of file diff --git a/MaruanBH.Persistance/.gitignore b/MaruanBH.Persistance/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Persistance/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Persistance/MaruanBH.Persistance.csproj b/MaruanBH.Persistance/MaruanBH.Persistance.csproj new file mode 100644 index 0000000..97682b0 --- /dev/null +++ b/MaruanBH.Persistance/MaruanBH.Persistance.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/MaruanBH.Persistance/Respositories/AccountRepository.cs b/MaruanBH.Persistance/Respositories/AccountRepository.cs new file mode 100644 index 0000000..9b9b2da --- /dev/null +++ b/MaruanBH.Persistance/Respositories/AccountRepository.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using MaruanBH.Core.Base.Exceptions; + +namespace MaruanBH.Persistance.Repositories +{ + public class AccountRepository : IAccountRepository + { + private readonly IMemoryCache _cache; + private readonly ILogger _logger; + private const string AccountCacheKey = "Accounts"; + + public AccountRepository(IMemoryCache cache, ILogger logger) + { + _cache = cache; + _logger = logger; + InitializeCache(); + } + + public Task AddAsync(Account account) => + Result.Success() + .Tap(() => _logger.LogInformation("Creating account with ID {AccountId}", account.Id)) + .Tap(() => + { + var accounts = GetAccountDictionary(); + accounts[account.Id] = account; + _cache.Set(AccountCacheKey, accounts); + _logger.LogInformation("Added account with ID {AccountId}", account.Id); + }) + .Finally(result => + { + if (result.IsFailure) + { + _logger.LogWarning("Failed to add account: {Error}", result.Error); + } + return Task.FromResult(result); + }); + + + public Task> GetByIdAsync(Guid accountId) => + Task.FromResult( + Maybe + .From(GetAccountDictionary().TryGetValue(accountId, out var account) ? account : null) + .Match( + account => + { + _logger.LogInformation($"Retrieved account with ID {accountId}"); + return Maybe.From(account); + }, + () => + { + _logger.LogInformation($"No account found with ID {accountId}"); + return Maybe.None; + } + ) + ); + + private void InitializeCache() => + _cache.GetOrCreate(AccountCacheKey, _ => new Dictionary()); + + private Dictionary GetAccountDictionary() => + _cache.Get>(AccountCacheKey) + ?? new Dictionary(); + } +} diff --git a/MaruanBH.Persistance/Respositories/CustomerRepository.cs b/MaruanBH.Persistance/Respositories/CustomerRepository.cs new file mode 100644 index 0000000..5116c38 --- /dev/null +++ b/MaruanBH.Persistance/Respositories/CustomerRepository.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Memory; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using CSharpFunctionalExtensions; + +namespace MaruanBH.Persistance.Repositories +{ + public class CustomerRepository : ICustomerRepository + { + private readonly IMemoryCache _cache; + private const string CustomerCacheKey = "Customers"; + + public CustomerRepository(IMemoryCache cache) + { + _cache = cache; + InitializeCache(); + } + + public Task> GetCustomerByIdAsync(Guid id) => + Task.FromResult( + Maybe> + .From(_cache.Get>(CustomerCacheKey)) + .Bind(customers => customers.TryGetValue(id, out var customer) + ? Maybe.From(customer) + : Maybe.None) + ); + + public Task AddAsync(Customer customer) => + Task.FromResult( + Result.Success() + .Tap(() => + { + var customers = _cache.Get>(CustomerCacheKey) + ?? new Dictionary(); + customers[customer.Id] = customer; + _cache.Set(CustomerCacheKey, customers); + }) + ); + + private void InitializeCache() => + _cache.GetOrCreate(CustomerCacheKey, _ => new Dictionary()); + } +} diff --git a/MaruanBH.Persistance/Respositories/TransactionRepository.cs b/MaruanBH.Persistance/Respositories/TransactionRepository.cs new file mode 100644 index 0000000..3ef29f8 --- /dev/null +++ b/MaruanBH.Persistance/Respositories/TransactionRepository.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using MaruanBH.Core.Base.Exceptions; + +namespace MaruanBH.Persistance.Repositories +{ + public class TransactionRepository : ITransactionRepository + { + private readonly IMemoryCache _cache; + private readonly ILogger _logger; + private const string TransactionCacheKey = "Transactions"; + + public TransactionRepository(IMemoryCache cache, ILogger logger) + { + _cache = cache; + _logger = logger; + InitializeCache(); + } + + public Task> GetTransactionsForCustomer(Guid accountId) => + Task.FromResult( + Maybe> + .From(GetTransactionDictionary().TryGetValue(accountId, out var transactions) ? transactions : null) + .ToResult($"No transactions found for account {accountId}") + .Tap(t => _logger.LogInformation($"Retrieved {t.Count} transactions for account {accountId}")) + .GetValueOrDefault(new List()) + ); + + public Task AddAsync(Guid accountId, Transaction transaction) => + Result.SuccessIf(transaction.Amount > 0, "Transaction amount must be positive") + .Tap(() => _logger.LogInformation("Creating transaction for account {AccountId} with amount {Amount}", accountId, transaction.Amount)) + .Bind(() => + { + var dict = GetTransactionDictionary(); + if (!dict.TryGetValue(accountId, out var accountTransactions)) + { + dict[accountId] = new List(); + } + dict[accountId].Add(transaction); + _cache.Set(TransactionCacheKey, dict); + _logger.LogInformation($"Added transaction for account {accountId}: Amount={transaction.Amount}, Date={transaction.Date}"); + return Result.Success(); + }) + .Finally(result => + { + if (result.IsFailure) + { + _logger.LogWarning($"Failed to add transaction: {result.Error}"); + } + return result.IsSuccess ? Task.CompletedTask : Task.FromException(new CustomException(result.Error)); + }); + + private void InitializeCache() => + _cache.GetOrCreate(TransactionCacheKey, _ => new Dictionary>()); + + private Dictionary> GetTransactionDictionary() => + _cache.Get>>(TransactionCacheKey) + ?? new Dictionary>(); + } +} diff --git a/MaruanBH.Tests/.gitignore b/MaruanBH.Tests/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/MaruanBH.Tests/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/MaruanBH.Tests/Business/UnitTests/AccountContext/Commands/CreateAccountCommandHandlerTests.cs b/MaruanBH.Tests/Business/UnitTests/AccountContext/Commands/CreateAccountCommandHandlerTests.cs new file mode 100644 index 0000000..3185f04 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/AccountContext/Commands/CreateAccountCommandHandlerTests.cs @@ -0,0 +1,85 @@ +using Xunit; +using Moq; +using MaruanBH.Core.AccountContext.Commands; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Entities; +using MaruanBH.Core.Base.Exceptions; +using Microsoft.Extensions.Logging; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Business.AccountContext.CommandHandler; + +public class CreateAccountCommandHandlerTests +{ + private readonly Mock _accountServiceMock; + private readonly Mock _transactionServiceMock; + private readonly Mock _customerServiceMock; + private readonly Mock> _loggerMock; + private readonly CreateAccountCommandHandler _handler; + + public CreateAccountCommandHandlerTests() + { + _accountServiceMock = new Mock(); + _transactionServiceMock = new Mock(); + _customerServiceMock = new Mock(); + _loggerMock = new Mock>(); + + _handler = new CreateAccountCommandHandler( + _accountServiceMock.Object, + _transactionServiceMock.Object, + _customerServiceMock.Object, + _loggerMock.Object); + } + + [Fact] + public async Task Handle_ValidCommand_ShouldCreateAccount() + { + var customerId = Guid.NewGuid(); + var initialCredit = 100; + var command = new CreateAccountCommand(new CreateAccountDto + { + CustomerId = customerId, + InitialCredit = initialCredit + }); + + _customerServiceMock + .Setup(s => s.GetCustomerByIdAsync(customerId)) + .ReturnsAsync(new Customer("Marouane", "Boukhriss", 0)); + + var newAccountId = Guid.NewGuid(); + _accountServiceMock + .Setup(s => s.CreateAccountAsync(It.IsAny())) + .ReturnsAsync(newAccountId); + + var result = await _handler.Handle(command, CancellationToken.None); + + _accountServiceMock.Verify(s => s.CreateAccountAsync(It.IsAny()), Times.Once); + _transactionServiceMock.Verify(s => s.CreateTransactionAsync(newAccountId, initialCredit), Times.Once); + Assert.Equal(newAccountId, result); + } + + [Fact] + public async Task Handle_InitialCreditGreaterThanZero_ShouldCreateTransaction() + { + var customerId = Guid.NewGuid(); + var initialCredit = 200; + var command = new CreateAccountCommand(new CreateAccountDto + { + CustomerId = customerId, + InitialCredit = initialCredit + }); + + _customerServiceMock + .Setup(s => s.GetCustomerByIdAsync(customerId)) + .ReturnsAsync(new Customer("Marouane", "Bo", 1000)); + + var newAccountId = Guid.NewGuid(); + _accountServiceMock + .Setup(s => s.CreateAccountAsync(It.IsAny())) + .ReturnsAsync(newAccountId); + + await _handler.Handle(command, CancellationToken.None); + + _transactionServiceMock.Verify(s => s.CreateTransactionAsync(newAccountId, initialCredit), Times.Once); + } +} diff --git a/MaruanBH.Tests/Business/UnitTests/AccountContext/Query/GetAccountDetailsQueryHandlerTests.cs b/MaruanBH.Tests/Business/UnitTests/AccountContext/Query/GetAccountDetailsQueryHandlerTests.cs new file mode 100644 index 0000000..1f7f638 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/AccountContext/Query/GetAccountDetailsQueryHandlerTests.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MaruanBH.Business.AccountContext.QueryHandler; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Core.AccountContext.Queries; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Entities; +using Moq; +using Xunit; + +public class GetAccountDetailsQueryHandlerTests +{ + private readonly Mock _mockAccountService; + private readonly Mock _mockCustomerService; + private readonly Mock _mockTransactionService; + private readonly GetAccountDetailsQueryHandler _handler; + + public GetAccountDetailsQueryHandlerTests() + { + _mockAccountService = new Mock(); + _mockCustomerService = new Mock(); + _mockTransactionService = new Mock(); + _handler = new GetAccountDetailsQueryHandler( + _mockAccountService.Object, + _mockCustomerService.Object, + _mockTransactionService.Object + ); + } + + [Fact] + public async Task Handle_ReturnsAccountDetails_WhenAccountAndCustomerExist() + { + var accountId = Guid.NewGuid(); + var customerId = Guid.NewGuid(); + var query = new GetAccountDetailsQuery(accountId); + + var account = new Account(customerId, 100m); + var customer = new Customer("Marouane", "Boukhriss Ouchab", 50m); + var transactions = new List + { + new Transaction (DateTime.Now.AddDays(-1), Guid.NewGuid(), 25m), + }; + + _mockAccountService.Setup(s => s.GetByIdAsync(accountId)).ReturnsAsync(account); + _mockCustomerService.Setup(s => s.GetCustomerByIdAsync(customerId)).ReturnsAsync(customer); + _mockTransactionService.Setup(s => s.GetTransactionsForCustomer(accountId)).ReturnsAsync(transactions); + + var result = await _handler.Handle(query, CancellationToken.None); + + Assert.NotNull(result); + Assert.Equal(account.Id, result.Id); + Assert.Equal(customer.Name, result.Name); + Assert.Equal(customer.Surname, result.Surname); + Assert.Equal(175m, result.Balance); + Assert.Single(result.Transactions); + Assert.Equal(customerId, result.CustomerId); + Assert.Equal(account.InitialCredit, result.InitialCredit); + } +} + diff --git a/MaruanBH.Tests/Business/UnitTests/CustomerContext/Commands/CreateCustomerCommandHandlerTests.cs b/MaruanBH.Tests/Business/UnitTests/CustomerContext/Commands/CreateCustomerCommandHandlerTests.cs new file mode 100644 index 0000000..e5a080c --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/CustomerContext/Commands/CreateCustomerCommandHandlerTests.cs @@ -0,0 +1,64 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MaruanBH.Business.CustomerContext.CommandHandler; +using MaruanBH.Core.CustomerContext.Commands; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using Moq; +using Xunit; +using CSharpFunctionalExtensions; + + +public class CreateCustomerCommandHandlerTests +{ + private readonly Mock _mockCustomerRepository; + private readonly Mock _mockAccountRepository; + private readonly CreateCustomerCommandHandler _handler; + + public CreateCustomerCommandHandlerTests() + { + _mockCustomerRepository = new Mock(); + _mockAccountRepository = new Mock(); + _handler = new CreateCustomerCommandHandler(_mockCustomerRepository.Object, _mockAccountRepository.Object); + } + + [Fact] + public async Task Handle_CreatesCustomerAndAccount_ReturnsCustomerId() + { + var customerDto = new CreateCustomerDto + { + Name = "Marouane", + Surname = "Boukhriss Ouchab", + Balance = 100m + }; + var command = new CreateCustomerCommand(customerDto); + + Customer? capturedCustomer = null; + Account? capturedAccount = null; + + _mockCustomerRepository.Setup(r => r.AddAsync(It.IsAny())) + .Callback(c => capturedCustomer = c) + .ReturnsAsync(Result.Success()); + + _mockAccountRepository.Setup(r => r.AddAsync(It.IsAny())) + .Callback(a => capturedAccount = a) + .ReturnsAsync(Result.Success()); + + + var result = await _handler.Handle(command, CancellationToken.None); + + Assert.NotEqual(Guid.Empty, result); + Assert.NotNull(capturedCustomer); + Assert.Equal(result, capturedCustomer.Id); + Assert.Equal(customerDto.Name, capturedCustomer.Name); + Assert.Equal(customerDto.Surname, capturedCustomer.Surname); + Assert.Equal(customerDto.Balance, capturedCustomer.Balance); + Assert.NotNull(capturedAccount); + Assert.NotEqual(Guid.Empty, capturedAccount.Id); + Assert.Equal(result, capturedAccount.CustomerId); + Assert.Equal(customerDto.Balance, capturedAccount.InitialCredit); + } +} + diff --git a/MaruanBH.Tests/Business/UnitTests/CustomerContext/Query/GetCustomerDetailsQueryHandlerTests.cs b/MaruanBH.Tests/Business/UnitTests/CustomerContext/Query/GetCustomerDetailsQueryHandlerTests.cs new file mode 100644 index 0000000..11c3d58 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/CustomerContext/Query/GetCustomerDetailsQueryHandlerTests.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MaruanBH.Business.CustomerContext.QueryHandler; +using MaruanBH.Core.CustomerContext.DTOs; +using MaruanBH.Core.CustomerContext.Queries; +using MaruanBH.Core.Services; +using MaruanBH.Domain.Entities; +using Moq; +using Xunit; +using CSharpFunctionalExtensions; +using MaruanBH.Domain.Base.Error; + +public class GetCustomerDetailsQueryHandlerTests +{ + private readonly Mock _mockCustomerService; + private readonly Mock _mockTransactionService; + private readonly GetCustomerDetailsQueryHandler _handler; + + public GetCustomerDetailsQueryHandlerTests() + { + _mockCustomerService = new Mock(); + _mockTransactionService = new Mock(); + _handler = new GetCustomerDetailsQueryHandler( + _mockCustomerService.Object, + _mockTransactionService.Object + ); + } + + [Fact] + public async Task Handle_ReturnsCustomerDetails_WhenCustomerExists() + { + var customerId = Guid.NewGuid(); + var query = new GetCustomerDetailsQuery(customerId); + + var customer = new Customer + ( + "Marouane", + "Boukhriss Ouchab", + 100m + ); + + var transactions = new List + { + new Transaction (DateTime.Now.AddDays(-1), Guid.NewGuid(), 50m), + new Transaction (DateTime.Now, Guid.NewGuid(), 20m) + }; + + _mockCustomerService.Setup(s => s.GetCustomerByIdAsync(customerId)).ReturnsAsync(customer); + _mockTransactionService.Setup(s => s.GetTransactionsForCustomer(customerId)).ReturnsAsync(transactions); + + var result = await _handler.Handle(query, CancellationToken.None); + + Assert.True(result.IsSuccess); + var customerDetails = result.Value; + Assert.NotNull(customerDetails); + Assert.Equal(customer.Name, customerDetails.Name); + Assert.Equal(customer.Surname, customerDetails.Surname); + Assert.Equal(170m, customerDetails.Balance); + Assert.Equal(2, customerDetails.Transactions.Count); + Assert.Equal(50m, customerDetails.Transactions[0].Amount); + Assert.Equal(20m, customerDetails.Transactions[1].Amount); + } +} + diff --git a/MaruanBH.Tests/Business/UnitTests/Repositories/AccountRepositoryTests.cs b/MaruanBH.Tests/Business/UnitTests/Repositories/AccountRepositoryTests.cs new file mode 100644 index 0000000..9b2c938 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Repositories/AccountRepositoryTests.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using MaruanBH.Domain.Entities; +using MaruanBH.Persistance.Repositories; +using Microsoft.Extensions.Caching.Memory; +using Moq; +using Xunit; +using MaruanBH.Domain.Repositories; +using Microsoft.Extensions.Logging; + +public class AccountRepositoryTests +{ + private readonly Mock _mockCache; + private readonly AccountRepository _accountRepository; + private readonly Mock> _loggerMock; + + private readonly Mock _mockCacheEntry; + + public AccountRepositoryTests() + { + _mockCache = new Mock(); + _mockCacheEntry = new Mock(); + _loggerMock = new Mock>(); + + _mockCache + .Setup(m => m.CreateEntry(It.IsAny())) + .Returns(_mockCacheEntry.Object); + + _accountRepository = new AccountRepository(_mockCache.Object, _loggerMock.Object); + } + + + [Fact] + public async Task AddAsync_AddsAccountToCache() + { + var account = new Account(Guid.NewGuid(), 100m); + var accountsCache = new Dictionary(); + + object? outValue = accountsCache; + _mockCache + .Setup(m => m.TryGetValue(It.IsAny(), out outValue)) + .Returns(true); + + _mockCache + .Setup(m => m.CreateEntry(It.IsAny())) + .Returns(_mockCacheEntry.Object); + + await _accountRepository.AddAsync(account); + + _mockCache.Verify(m => m.CreateEntry(It.IsAny()), Times.Exactly(2)); + _mockCacheEntry.VerifySet(e => e.Value = It.Is>(d => d.ContainsKey(account.Id))); + Assert.Contains(account.Id, accountsCache.Keys); + Assert.Equal(account, accountsCache[account.Id]); + } + + [Fact] + public async Task GetByIdAsync_ReturnsAccount_WhenAccountExistsInCache() + { + var accountId = Guid.NewGuid(); + var account = new Account(Guid.NewGuid(), 100m); + var accountsCache = new Dictionary { { accountId, account } }; + + object? outValue = accountsCache; + _mockCache + .Setup(m => m.TryGetValue(It.IsAny(), out outValue)) + .Returns(true); + + var retrievedAccount = await _accountRepository.GetByIdAsync(accountId); + + Assert.True(retrievedAccount.HasValue); + Assert.Equal(account, retrievedAccount.Value); + } + +} diff --git a/MaruanBH.Tests/Business/UnitTests/Repositories/CustomerRepositoryTests.cs b/MaruanBH.Tests/Business/UnitTests/Repositories/CustomerRepositoryTests.cs new file mode 100644 index 0000000..b94864b --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Repositories/CustomerRepositoryTests.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using MaruanBH.Domain.Entities; +using MaruanBH.Persistance.Repositories; +using Microsoft.Extensions.Caching.Memory; +using Moq; +using Xunit; + +namespace MaruanBH.Tests.Repositories +{ + public class CustomerRepositoryTests + { + private readonly Mock _mockCache; + private readonly Mock _mockCacheEntry; + private readonly string _customerCacheKey = "Customers"; + + public CustomerRepositoryTests() + { + _mockCache = new Mock(); + _mockCacheEntry = new Mock(); + + _mockCache + .Setup(m => m.CreateEntry(It.IsAny())) + .Returns(_mockCacheEntry.Object); + } + + [Fact] + public void Constructor_InitializesCache() + { + object? value = null; + _mockCache.Setup(m => m.TryGetValue(It.IsAny(), out value)).Returns(false); + + var repository = new CustomerRepository(_mockCache.Object); + + _mockCache.Verify(m => m.CreateEntry(_customerCacheKey), Times.Once); + } + + [Fact] + public async Task GetCustomerByIdAsync_ReturnsCustomer_WhenCustomerExists() + { + var customerId = Guid.NewGuid(); + var customer = new Customer("Marouane", " Boukhriss Ouchab", 0); + var customers = new Dictionary { { customerId, customer } }; + object? outValue = customers; + + _mockCache.Setup(m => m.TryGetValue(_customerCacheKey, out outValue)).Returns(true); + + var repository = new CustomerRepository(_mockCache.Object); + + var result = await repository.GetCustomerByIdAsync(customerId); + + Assert.True(result.HasValue); + Assert.Equal(customer, result.Value); + } + + [Fact] + public async Task AddAsync_AddsCustomerToCache() + { + var customer = new Customer("Marouane ", "Boukhriss Ouchab", 0); + var customers = new Dictionary(); + object? outValue = customers; + + _mockCache.Setup(m => m.TryGetValue(_customerCacheKey, out outValue)).Returns(true); + _mockCache.Setup(m => m.CreateEntry(It.IsAny())).Returns(_mockCacheEntry.Object); + + var repository = new CustomerRepository(_mockCache.Object); + + await repository.AddAsync(customer); + + _mockCacheEntry.VerifySet(m => m.Value = It.Is>(d => d.ContainsKey(customer.Id)), Times.Once); + } + } +} diff --git a/MaruanBH.Tests/Business/UnitTests/Repositories/TransactionRepositoryTests.cs b/MaruanBH.Tests/Business/UnitTests/Repositories/TransactionRepositoryTests.cs new file mode 100644 index 0000000..d181e73 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Repositories/TransactionRepositoryTests.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using MaruanBH.Domain.Entities; +using MaruanBH.Persistance.Repositories; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using Moq; +using Xunit; + +public class TransactionRepositoryTests +{ + private readonly Mock _mockCache; + private readonly TransactionRepository _transactionRepository; + private readonly Mock _mockCacheEntry; + + public TransactionRepositoryTests() + { + _mockCache = new Mock(); + _mockCacheEntry = new Mock(); + + _mockCache + .Setup(m => m.CreateEntry(It.IsAny())) + .Returns(_mockCacheEntry.Object); + + _transactionRepository = new TransactionRepository(_mockCache.Object, Mock.Of>()); + } + + [Fact] + public async Task GetTransactionsForCustomer_ReturnsTransactions_WhenTransactionsExist() + { + var accountId = Guid.NewGuid(); + var transaction1 = new Transaction(DateTime.Now, Guid.NewGuid(), 100m); + var transaction2 = new Transaction(DateTime.Now, Guid.NewGuid(), 200m); + + var transactions = new List { transaction1, transaction2 }; + + var cacheDict = new Dictionary> { { accountId, transactions } }; + object? outValue = cacheDict; + + _mockCache + .Setup(m => m.TryGetValue(It.IsAny(), out outValue)) + .Returns(true); + + var retrievedTransactions = await _transactionRepository.GetTransactionsForCustomer(accountId); + + Assert.NotNull(retrievedTransactions); + Assert.Equal(transactions, retrievedTransactions); + } + + [Fact] + public async Task GetTransactionsForCustomer_ReturnsEmptyList_WhenNoTransactionsExist() + { + var accountId = Guid.NewGuid(); + object? outValue = null; + + _mockCache + .Setup(m => m.TryGetValue(It.IsAny(), out outValue)) + .Returns(false); + + var retrievedTransactions = await _transactionRepository.GetTransactionsForCustomer(accountId); + + Assert.NotNull(retrievedTransactions); + Assert.Empty(retrievedTransactions); + } +} diff --git a/MaruanBH.Tests/Business/UnitTests/Services/AccountServiceTests.cs b/MaruanBH.Tests/Business/UnitTests/Services/AccountServiceTests.cs new file mode 100644 index 0000000..582ccd4 --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Services/AccountServiceTests.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading.Tasks; +using MaruanBH.Business.Services; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using Moq; +using Xunit; +using CSharpFunctionalExtensions; + +public class AccountServiceTests +{ + private readonly Mock _mockAccountRepository; + private readonly AccountService _accountService; + + public AccountServiceTests() + { + _mockAccountRepository = new Mock(); + _accountService = new AccountService(_mockAccountRepository.Object); + } + + [Fact] + public async Task CreateAccountAsync_ReturnsAccountId_WhenAccountCreated() + { + var account = new Account(Guid.NewGuid(), 100m); + + _mockAccountRepository.Setup(repo => repo.AddAsync(It.IsAny())) + .ReturnsAsync(Result.Success()); + + var result = await _accountService.CreateAccountAsync(account); + + Assert.True(result.IsSuccess); + Assert.Equal(account.Id, result.Value); + _mockAccountRepository.Verify(repo => repo.AddAsync(account), Times.Once); + } + + [Fact] + public async Task GetByIdAsync_ReturnsAccount_WhenAccountExists() + { + var accountId = Guid.NewGuid(); + var account = new Account + ( + Guid.NewGuid(), + 100m + ); + + _mockAccountRepository.Setup(repo => repo.GetByIdAsync(accountId)) + .ReturnsAsync(Maybe.From(account)); + + var result = await _accountService.GetByIdAsync(accountId); + + Assert.True(result.IsSuccess); + Assert.Equal(account, result.Value); + } +} \ No newline at end of file diff --git a/MaruanBH.Tests/Business/UnitTests/Services/CustomerServiceTests.cs b/MaruanBH.Tests/Business/UnitTests/Services/CustomerServiceTests.cs new file mode 100644 index 0000000..07f6cec --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Services/CustomerServiceTests.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MaruanBH.Business.Services; +using MaruanBH.Core.AccountContext.DTOs; +using MaruanBH.Core.Base.Exceptions; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using Microsoft.Extensions.Logging; +using Moq; +using Xunit; +using CSharpFunctionalExtensions; + +public class CustomerServiceTests +{ + private readonly Mock _mockCustomerRepository; + private readonly Mock _mockAccountRepository; + private readonly Mock _mockTransactionRepository; + private readonly Mock> _mockLogger; + private readonly CustomerService _customerService; + + public CustomerServiceTests() + { + _mockCustomerRepository = new Mock(); + _mockAccountRepository = new Mock(); + _mockTransactionRepository = new Mock(); + _mockLogger = new Mock>(); + _customerService = new CustomerService( + _mockCustomerRepository.Object, + _mockAccountRepository.Object, + _mockTransactionRepository.Object, + _mockLogger.Object + ); + } + + [Fact] + public async Task GetCustomerByIdAsync_ReturnsCustomer_WhenCustomerExists() + { + var customerId = Guid.NewGuid(); + var customer = new Customer("Marouane", "Boukhriss Ouchab", 0); + _mockCustomerRepository.Setup(repo => repo.GetCustomerByIdAsync(customerId)) + .ReturnsAsync(customer); + + var result = await _customerService.GetCustomerByIdAsync(customerId); + + Assert.Equal(customer, result); + } + + [Fact] + public async Task CreateCustomerAsync_CreatesCustomerAndAccount_ReturnsCustomerId() + { + var customer = new Customer("Marouane", "Boukhriss Ouchab", 100m); + + _mockCustomerRepository.Setup(repo => repo.AddAsync(customer)) + .ReturnsAsync(Result.Success(true)); + + var result = await _customerService.CreateCustomerAsync(customer); + + Assert.True(result.IsSuccess); + Assert.Equal(customer.Id, result.Value); + _mockCustomerRepository.Verify(repo => repo.AddAsync(customer), Times.Once); + } + +} + diff --git a/MaruanBH.Tests/Business/UnitTests/Services/TransactionServiceTests.cs b/MaruanBH.Tests/Business/UnitTests/Services/TransactionServiceTests.cs new file mode 100644 index 0000000..d3cf3ff --- /dev/null +++ b/MaruanBH.Tests/Business/UnitTests/Services/TransactionServiceTests.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using MaruanBH.Business.Services; +using MaruanBH.Domain.Entities; +using MaruanBH.Domain.Repositories; +using Moq; +using Xunit; +using CSharpFunctionalExtensions; + +public class TransactionServiceTests +{ + private readonly Mock _mockTransactionRepository; + private readonly TransactionService _transactionService; + + public TransactionServiceTests() + { + _mockTransactionRepository = new Mock(); + _transactionService = new TransactionService(_mockTransactionRepository.Object); + } + + [Fact] + public async Task GetTransactionsForCustomer_ReturnsTransactions_WhenTransactionsExist() + { + var accountId = Guid.NewGuid(); + var transactions = new List + { + new Transaction(DateTime.Now, accountId, 100m), + new Transaction(DateTime.Now, accountId, 200m) + }; + + _mockTransactionRepository.Setup(repo => repo.GetTransactionsForCustomer(accountId)) + .ReturnsAsync(transactions); + + var result = await _transactionService.GetTransactionsForCustomer(accountId); + + Assert.True(result.IsSuccess); + Assert.Equal(transactions, result.Value); + } + + [Fact] + public async Task CreateTransactionAsync_ReturnsTransactionId_WhenTransactionCreated() + { + var accountId = Guid.NewGuid(); + var amount = 100m; + + _mockTransactionRepository.Setup(repo => repo.AddAsync(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + var result = await _transactionService.CreateTransactionAsync(accountId, amount); + + Assert.True(result.IsSuccess); + Assert.NotEqual(Guid.Empty, result.Value); + _mockTransactionRepository.Verify(repo => repo.AddAsync(accountId, + It.Is(t => t.AccountId == accountId && t.Amount == amount)), Times.Once); + } +} diff --git a/MaruanBH.Tests/MaruanBH.Tests.csproj b/MaruanBH.Tests/MaruanBH.Tests.csproj new file mode 100644 index 0000000..c8e8348 --- /dev/null +++ b/MaruanBH.Tests/MaruanBH.Tests.csproj @@ -0,0 +1,37 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + diff --git a/MaruanBH.sln b/MaruanBH.sln new file mode 100644 index 0000000..f2bed85 --- /dev/null +++ b/MaruanBH.sln @@ -0,0 +1,29 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.002.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E8AE280F-E833-47A5-9CCC-C31259441183}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaruanBH.Api", ".\MaruanBH.Api\MaruanBH.Api.csproj", "{58912E6E-29D6-4B3F-B844-7357637481E8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {58912E6E-29D6-4B3F-B844-7357637481E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58912E6E-29D6-4B3F-B844-7357637481E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58912E6E-29D6-4B3F-B844-7357637481E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58912E6E-29D6-4B3F-B844-7357637481E8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {58912E6E-29D6-4B3F-B844-7357637481E8} = {E8AE280F-E833-47A5-9CCC-C31259441183} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E2732142-F709-413E-AAC6-1758BB8DB33A} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md new file mode 100644 index 0000000..7fe2051 --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# MaruanBH + +This project is built using C# 8.0 and .NET Web API, following enterprise-level architecture patterns, including: + +- **Github CI Pipeline** A CD pipeline was not provided as the application is intended for local or development environments and does not require deployment to production or staging. The focus was on setting up a CI pipeline to ensure automated testing and integration of code changes +- **Domain-Driven Design (DDD)** +- **Test-Driven Development (TDD)** +- **Command Query Responsibility Segregation (CQRS)** with command/query validation +- **S.O.L.I.D principles** +- **Mediator Pattern** +- **Functional Programming principles** Check the CQRS (Immutability), I did not have the time to implement side effect, pure functions and so on. +- **Logging**: We utilizes file-based logging to track application behavior and issues, facilitating easier debugging and monitoring for **showcase purposes** (Usually we should use **Event sourcing** with **Kafka** data pipeline). +- **Error Handling** We implements general error handling strategies to log system messages and errors for **showcase purposes**. +- **Api Documentation (Swagger)** + +The data is stored in memory, allowing for easier testing and evaluation, and the application uses a multi-layered architecture with proper abstractions for testability. + +--- + +## API Endpoints + +All data is exposed through the Web API to facilitate testing purposes, including the following endpoints: + +- **Create Customer**: Endpoint to create a new customer in the system. +- **Get Customer**: Endpoint to retrieve customer details. This is provided for demonstration and user experience purposes. +- **Create Account**: Endpoint to create a new account associated with a customer. +- **Get Account Details**: Endpoint to retrieve account details, including information about transactions and balance. + +## Setup and Running the Application + +### Prerequisites + +Ensure you have the following installed on your machine: + +- [.NET 8.0 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) + +### 1. Clone the repository + +```bash +git clone https://github.com/your-username/MaruanBH.git +cd MaruanBH +``` + +### 2. Build the project + +To build the solution, run the following command: + +```bash +dotnet build MaruanBH.sln --configuration Release +``` + +### 3. Run the application + +You can run the API by using: +```bash +dotnet run --project MaruanBH.Api +``` + +The Swagger API should now be running at http://localhost:5118/swagger/index.html. + +### 4. Testing + +The test are located at **MaruanBH.Tests directory**, to execute the tests, run the following command: + +```bash +dotnet test MaruanBH.Tests/MaruanBH.Tests.csproj +``` + +### License + +This project is licensed under the MIT License. + +> This project was created by Marouane Boukhriss Ouchab, including logic, directory structure, architecture, coding, testing, and software engineering decisions.