88 lines
2.7 KiB
C#

namespace AAIntegration.SimmonsBank.API.Controllers;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using AAIntegration.SimmonsBank.API.Models.Transactions;
using AAIntegration.SimmonsBank.API.Services;
using AAIntegration.SimmonsBank.API.Config;
using System.Runtime.InteropServices;
using AAIntegration.SimmonsBank.API.Entities;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
[Authorize]
[ApiController]
[Route("[controller]")]
public class TransactionsController : ControllerBase
{
private ITransactionService _transactionService;
private IMapper _mapper;
private readonly AppSettings _appSettings;
public TransactionsController(
ITransactionService transactionService,
IMapper mapper,
IOptions<AppSettings> appSettings)
{
_transactionService = transactionService;
_mapper = mapper;
_appSettings = appSettings.Value;
}
[HttpGet]
public IActionResult GetAll(int? accountId = null)
{
List<TransactionDto> transactionDtos = new List<TransactionDto>();
foreach (Transaction tran in _transactionService.GetAll())
{
if (accountId.HasValue
&& (tran.DebitAccount == null || tran.DebitAccount.Id != accountId)
&& (tran.CreditAccount == null || tran.CreditAccount.Id != accountId))
continue;
transactionDtos.Add(_mapper.Map<Transaction, TransactionDto>(tran));
}
// Sort by Date
transactionDtos.Sort((t1, t2) => t2.Date.CompareTo(t1.Date));
return Ok(transactionDtos);
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
Transaction tran = _transactionService.GetById(id);
return Ok(_mapper.Map<Transaction, TransactionDto>(tran));
}
[HttpPost("BulkAdd")]
public IActionResult BulkCreate([FromBody]List<TransactionCreate> model)
{
List<Transaction> trans = _transactionService.BulkCreate(model).ToList();
return Ok(new { message = $"{trans.Count()} transaction(s) created." });
}
[HttpPost]
public IActionResult Create([FromBody]TransactionCreate model)
{
Transaction tran = _transactionService.Create(model);
return Ok(new { message = $"transaction '{tran.Description}' created with id '{tran.Id}'." });
}
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody]TransactionUpdateRequest model)
{
_transactionService.Update(id, model);
return Ok(new { message = $"transaction with id '{id}' updated" });
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_transactionService.Delete(id);
return Ok(new { message = "transaction deleted" });
}
}