CodeLiturgy.Dashboard/BlueWest.Api/Context/Extensions/CurrencyExtensions.cs

88 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using BlueWest.Data;
using Microsoft.EntityFrameworkCore;
namespace BlueWest.WebApi.EF
{
/// <summary>
/// Currency table data extensions
/// </summary>
public static class CurrencyExtensions
{
/// <summary>
/// Not found projection
/// </summary>
/// <returns></returns>
public static (bool, Currency) NotFound() => (false, null);
/// <summary>
/// Add new Currency
/// </summary>
/// <param name="dbContext"></param>
/// <param name="currencyToCreate"></param>
/// <returns></returns>
public static (bool, Currency) AddCurrency(this CountryDbContext dbContext, CurrencyCreate currencyToCreate)
{
var newCurrency = new Currency(currencyToCreate);
dbContext.Add(newCurrency);
var resultOperation = dbContext.SaveChanges() >= 0;
return (resultOperation, newCurrency);
}
/// <summary>
/// Updates currency
/// </summary>
/// <param name="dbContext"></param>
/// <param name="currencyId"></param>
/// <param name="currencyToUpdate"></param>
/// <returns></returns>
public static (bool, Currency) UpdateCurrency(this CountryDbContext dbContext, int currencyId, CurrencyUpdate currencyToUpdate)
{
var currency = dbContext.Currencies.FirstOrDefault(x => x.Id == currencyId);
if (currency == null) return NotFound();
currency.Update(currencyToUpdate);
dbContext.Update(currency);
var resultOperation = dbContext.SaveChanges() >= 0;
return (resultOperation, currency);
}
public static (bool, string, CountryUnique) AddCountry(
this CountryDbContext dbContext,
int currencyId, CountryCreate countryCreate,
Expression<Func<Country,bool>>[] duplicationValidations)
{
var currency = dbContext
.Currencies
.Where(data => data.Id == currencyId)
.Include(o => o.Countries)
.FirstOrDefault();
// Check if currency exists
if (currency == null) return (false, $"{nameof(Currency)}: {currencyId} - Not found.", null);
// Check if there's currency with the same code
foreach (var duplicationValidation in duplicationValidations)
{
var currencyToGet = dbContext.Countries.FirstOrDefault(duplicationValidation);
if (currencyToGet != null) return Projection.ErrorMessage<CountryUnique>($"Duplication Validation failed: {duplicationValidation.Body}");
}
// Creates new currency
var newCountry = new Country(countryCreate);
currency.Countries.Add(newCountry);
var success = dbContext.SaveChanges() >= 0;
return Projection.Success(success, new CountryUnique(newCountry));
}
}
}