Adapted the repositories to the controllers

This commit is contained in:
2024-05-23 16:29:35 +02:00
parent c7d4307f47
commit 3b7ca0973e
7 changed files with 101 additions and 93 deletions

View File

@ -4,13 +4,14 @@ namespace Accounting.BLI
{ {
public interface IAccountRecords public interface IAccountRecords
{ {
bool AddAccountRecord(AccountRecord record); Task<bool> AddAccountRecordAsync(AccountRecord record);
AccountRecord SaveAcountRecord(AccountRecord record); Task<AccountRecord> SaveAcountRecordAsync(AccountRecord record);
bool DeleteAccountRecord(AccountRecord record); Task<bool> DeleteAccountRecordAsync(AccountRecord record);
bool DeleteAllAccountRecords(); bool DeleteAllAccountRecords();
IEnumerable<AccountRecord> GetAllAccBetweenDates(DateTime dateFrom, DateTime dateTo); IEnumerable<AccountRecord> GetAllAccBetweenDates(DateTime dateFrom, DateTime dateTo);
IEnumerable<AccountRecord> GetAllAccounts(); Task<IEnumerable<AccountRecord>> GetAllAccountsAsync();
AccountRecord GetAccount(int id); Task<AccountRecord> GetAccountAsync(int id);
AccountRecord GetAccountByDateBelKonto(DateTime _date, double _belopp, string _konto); Task<AccountRecord> GetAccountByDateBelKontoAsync(DateTime _date, double _belopp, string _konto);
Task<List<AccountRecord>> AddAccRecordsFromJsonAsync(string jsonFile);
} }
} }

View File

@ -1,7 +1,9 @@
using Accounting.BLI; using Accounting.BLI;
using Accounting.DAL; using Accounting.DAL;
using Accounting.Models; using Accounting.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Accounting.BLR namespace Accounting.BLR
{ {
@ -17,12 +19,12 @@ namespace Accounting.BLR
} }
public bool AddAccountRecord(AccountRecord record) public async Task<bool> AddAccountRecordAsync(AccountRecord record)
{ {
try try
{ {
_dataContext.AccountRecords.Add(record); await _dataContext.AccountRecords.AddAsync(record);
_dataContext.SaveChanges(); await _dataContext.SaveChangesAsync();
return true; return true;
} }
catch (Exception e) catch (Exception e)
@ -30,20 +32,19 @@ namespace Accounting.BLR
_logger.LogError("Error occured in AddAccountRecord :-->{iMessage}", e.Message); _logger.LogError("Error occured in AddAccountRecord :-->{iMessage}", e.Message);
} }
return false; return false;
} }
public AccountRecord SaveAcountRecord(AccountRecord record) public async Task<AccountRecord?> SaveAcountRecordAsync(AccountRecord record)
{ {
try try
{ {
var entity = (from account in _dataContext.AccountRecords var entity = await (from account in _dataContext.AccountRecords
where account.Id == record.Id where account.Id == record.Id
select account).FirstOrDefault(); select account).FirstOrDefaultAsync();
if (entity == null) if (entity == null)
{ {
entity = new AccountRecord(); entity = new AccountRecord();
_dataContext.AccountRecords.Add(entity); await _dataContext.AccountRecords.AddAsync(entity);
} }
else else
{ {
@ -56,7 +57,7 @@ namespace Accounting.BLR
entity.Konto = record.Konto; entity.Konto = record.Konto;
entity.Mottagare = record.Mottagare; entity.Mottagare = record.Mottagare;
_dataContext.SaveChanges(); await _dataContext.SaveChangesAsync();
record.Id = entity.Id; record.Id = entity.Id;
@ -70,12 +71,12 @@ namespace Accounting.BLR
} }
public bool DeleteAccountRecord(AccountRecord record) public async Task<bool> DeleteAccountRecordAsync(AccountRecord record)
{ {
try try
{ {
_dataContext.AccountRecords.Remove(record); _dataContext.AccountRecords.Remove(record);
_dataContext.SaveChanges(); await _dataContext.SaveChangesAsync();
return true; return true;
} }
catch (Exception e) catch (Exception e)
@ -119,21 +120,58 @@ namespace Accounting.BLR
return result; return result;
} }
public IEnumerable<AccountRecord> GetAllAccounts() public async Task<IEnumerable<AccountRecord>> GetAllAccountsAsync()
{ {
return _dataContext.AccountRecords; return await _dataContext.AccountRecords.ToListAsync();
} }
public AccountRecord GetAccount(int id) public async Task<AccountRecord> GetAccountAsync(int id)
{ {
var accountRec = _dataContext.AccountRecords.FirstOrDefault(a => a.Id == id); var accountRec = await _dataContext.AccountRecords.FirstOrDefaultAsync(a => a.Id == id);
return accountRec; return accountRec;
} }
public AccountRecord GetAccountByDateBelKonto(DateTime _date, double _belopp, string _konto) public async Task<AccountRecord> GetAccountByDateBelKontoAsync(DateTime _date, double _belopp, string _konto)
{ {
var accountRec = _dataContext.AccountRecords.FirstOrDefault(a => a.BetalDatum == _date && a.Belopp == _belopp && a.Konto == _konto); var accountRec = await _dataContext.AccountRecords.FirstOrDefaultAsync(a => a.BetalDatum == _date && a.Belopp == _belopp && a.Konto == _konto);
return accountRec; return accountRec;
} }
public async Task<List<AccountRecord>> AddAccRecordsFromJsonAsync(string jsonFile)
{
var jsonText = await System.IO.File.ReadAllTextAsync(jsonFile);
var accRecords = JsonConvert.DeserializeObject<List<AccountRecord>>(jsonText);
if (accRecords == null)
{
_logger.LogError("Error occured in AddAccRecordsFromJsonAsync Deserialization unsuccessful");
return null;
}
using (var transaction = _dataContext.Database.BeginTransaction())
{
try
{
await _dataContext.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.AccountRecords ON");
await _dataContext.AccountRecords.AddRangeAsync(accRecords);
await _dataContext.SaveChangesAsync();
await _dataContext.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.AccountRecords OFF");
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_logger.LogError("Error occured in AddAccRecordsFromJsonAsync transaction unsuccessful ({0})", ex.Message);
return null;
}
}
return await _dataContext.AccountRecords.ToListAsync();
}
} }
} }

View File

@ -18,6 +18,10 @@
</COMReference> </COMReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Accounting.BLI\Accounting.BLI.csproj" /> <ProjectReference Include="..\Accounting.BLI\Accounting.BLI.csproj" />
<ProjectReference Include="..\Accounting.DAL\Accounting.DAL.csproj" /> <ProjectReference Include="..\Accounting.DAL\Accounting.DAL.csproj" />

View File

@ -140,8 +140,8 @@ namespace Accounting.BLR
restab.ToList().ForEach(x => restab.ToList().ForEach(x =>
{ {
if (_accountRecords.GetAccountByDateBelKonto(x.BetalDatum, x.Belopp, x.Konto) == null) if (_accountRecords.GetAccountByDateBelKontoAsync(x.BetalDatum, x.Belopp, x.Konto) == null)
_accountRecords.AddAccountRecord(x); _accountRecords.AddAccountRecordAsync(x);
else { }; else { };
}); });

View File

@ -20,6 +20,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Accounting.BLI\Accounting.BLI.csproj" /> <ProjectReference Include="..\Accounting.BLI\Accounting.BLI.csproj" />
<ProjectReference Include="..\Accounting.BLR\Accounting.BLR.csproj" />
<ProjectReference Include="..\Accounting.DAL\Accounting.DAL.csproj" /> <ProjectReference Include="..\Accounting.DAL\Accounting.DAL.csproj" />
<ProjectReference Include="..\Accounting.Models\Accounting.Models.csproj" /> <ProjectReference Include="..\Accounting.Models\Accounting.Models.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -1,6 +1,5 @@
using Accounting.DAL; using Accounting.BLI;
using Accounting.Models; using Accounting.Models;
using Newtonsoft.Json;
namespace Accounting.Controllers; namespace Accounting.Controllers;
@ -9,40 +8,27 @@ namespace Accounting.Controllers;
[ApiController] [ApiController]
public class AccountingController : ControllerBase public class AccountingController : ControllerBase
{ {
private readonly DataContext _context; private readonly IAccountRecords _accountRecords;
public AccountingController(DataContext dataContext) public AccountingController(IAccountRecords accountRecords)
{ {
_context = dataContext; _accountRecords = accountRecords;
} }
[HttpGet] [HttpGet]
public async Task<ActionResult<List<AccountRecord>>> GetAllAccRecords() public async Task<ActionResult<List<AccountRecord>>> GetAllAccRecords()
{ {
var accRecords = await _context.AccountRecords.ToListAsync(); var accRecords = await _accountRecords.GetAllAccountsAsync();
return Ok(accRecords); return Ok(accRecords);
//var accRecords = new List<AccountRecord>{
// new AccountRecord {
// Id = 1,
// Avisering = "Efaktura",
// Belopp = 250.50D,
// BetalDatum = DateTime.Parse("2024-05-30"),
// Konto = "1234-5678",
// Mottagare = "Tele2",
// Stored = DateTime.Now
// }
//};
} }
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<AccountRecord>> GetAccountRecord(int id) public async Task<ActionResult<AccountRecord>> GetAccountRecord(int id)
{ {
var accRecord = await _context.AccountRecords.FindAsync(id); var accRecord = await _accountRecords.GetAccountAsync(id);
if (accRecord is null) if (accRecord is null)
return NotFound("AccountRecord not found"); return NotFound("AccountRecord not found");
@ -50,45 +36,23 @@ public class AccountingController : ControllerBase
} }
[HttpPost("Addrecord")] [HttpPost("Addrecord")]
public async Task<ActionResult<List<AccountRecord>>> AddAccRecord(AccountRecord accRecord) public async Task<bool> AddAccRecord(AccountRecord accRecord)
{ {
_context.AccountRecords.Add(accRecord); var answ = await _accountRecords.AddAccountRecordAsync(accRecord);
await _context.SaveChangesAsync(); return answ;
return Ok(await _context.AccountRecords.ToListAsync());
} }
[HttpPost("AddAccRecordsFromJson/{jsonFile}")] [HttpPost("AddAccRecordsFromJson/{jsonFile}")]
public async Task<ActionResult<List<AccountRecord>>> AddAccRecordsFromJson(string jsonFile) public async Task<ActionResult<List<AccountRecord>>> AddAccRecordsFromJson(string jsonFile)
{ {
var jsonText = await System.IO.File.ReadAllTextAsync(jsonFile);
var accRecords = JsonConvert.DeserializeObject<List<AccountRecord>>(jsonText); var accRecords = await _accountRecords.AddAccRecordsFromJsonAsync(jsonFile);
if (accRecords == null) if (accRecords == null)
return BadRequest($"File not found : {jsonText}"); return BadRequest($"Repository-Error see logfile!");
else
return Ok(accRecords);
using (var transaction = _context.Database.BeginTransaction())
{
try
{
await _context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.AccountRecords ON");
await _context.AccountRecords.AddRangeAsync(accRecords);
await _context.SaveChangesAsync();
await _context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.AccountRecords OFF");
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
return BadRequest($"Error in call {ex.Message}");
}
}
return Ok(await _context.AccountRecords.ToListAsync());
} }
@ -96,32 +60,28 @@ public class AccountingController : ControllerBase
[HttpPut] [HttpPut]
public async Task<ActionResult<List<AccountRecord>>> UpdateAccRecord(AccountRecord updatedAccRecord) public async Task<ActionResult<List<AccountRecord>>> UpdateAccRecord(AccountRecord updatedAccRecord)
{ {
var accRecord = await _context.AccountRecords.FindAsync(updatedAccRecord.Id); var accRecord = await _accountRecords.SaveAcountRecordAsync(updatedAccRecord);
if (accRecord is null) if (accRecord is null)
return NotFound("Record not found"); return NotFound("Record not found");
accRecord.Stored = updatedAccRecord.Stored; return Ok(accRecord);
accRecord.BetalDatum = updatedAccRecord.BetalDatum;
accRecord.Avisering = updatedAccRecord.Avisering;
accRecord.Mottagare = updatedAccRecord.Mottagare;
accRecord.Belopp = updatedAccRecord.Belopp;
accRecord.Konto = updatedAccRecord.Konto;
await _context.SaveChangesAsync();
return Ok(await _context.AccountRecords.ToListAsync());
} }
[HttpDelete] [HttpDelete]
public async Task<ActionResult<List<AccountRecord>>> DeleteAccRecord(int id) public async Task<ActionResult<List<AccountRecord>>> DeleteAccRecord(int id)
{ {
var AccRecord = await _context.AccountRecords.FindAsync(id); var accRecord = await _accountRecords.GetAccountAsync(id);
if (AccRecord is null) if (accRecord is null)
return NotFound("AccRecord not found"); return NotFound("AccountRecord not found");
_context.AccountRecords.Remove(AccRecord); var result = await _accountRecords.DeleteAccountRecordAsync(accRecord);
await _context.SaveChangesAsync(); if (result == false)
return NotFound("Remove unsuccessful");
return Ok(await _context.AccountRecords.ToListAsync()); var records = await _accountRecords.GetAllAccountsAsync();
if (records.ToList().Count < 1)
return BadRequest("Nothing left");
return Ok(records.ToList());
} }
} }

View File

@ -1,4 +1,6 @@
using Accounting.BLI;
using Accounting.BLR;
using Accounting.DAL; using Accounting.DAL;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -15,7 +17,9 @@ builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
}); });
builder.Services.AddTransient<IAccountRecords, AccountRecords>();
builder.Services.AddTransient<IExcellent, Excellent>();
builder.Services.AddTransient<IReadingIn, ReadingIn>();
var app = builder.Build(); var app = builder.Build();