using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using gehGassi.Core.Interfaces;
using gehGassi.Domain.Common;
using gehGassi.Domain.Shop;
using Microsoft.EntityFrameworkCore;
namespace gehGassi.Core.Services
{
///
/// Service der die Verwaltung von Versandkosten ermöglicht
///
public class ShipmentCostService : ServiceBase, IShipmentCostService
{
private readonly IShopSettingsService _shopSettingsService;
///
/// Erstellt eine Instanz
///
/// Instanz eines IUnitOfWork
/// Instanz eines IShopSettingsService
public ShipmentCostService(IUnitOfWork unitOfWork, IShopSettingsService shopSettingsService) : base(unitOfWork)
{
_shopSettingsService = shopSettingsService;
}
///
/// Gibt eine gefilterte Liste von Versandkosten zurück
///
/// Filterbegriff der in bestimmten Feldern gesucht wird
/// List betroffener Versandkosten
public IQueryable Filter(string filter)
{
return Repository.Query(c => c.TargetCountryIso.Contains(filter));
}
///
/// Erstellen von Versandkosten
///
/// Versandkosten
public ShipmentCost Create()
{
var item = new ShipmentCost
{
};
return item;
}
///
/// Gibt eine gefilterte Liste von Versandkosten zurück. Sucht nur im Land
///
/// Filterbegriff der in bestimmten Feldern gesucht wird
/// List betroffener Versandkosten
public async Task> SearchAsync(string filter)
{
return (await Repository.FindAsync(c => c.TargetCountryIso.Contains(filter)).ConfigureAwait(false)).ToList();
}
///
/// Berechnen der Versandkosten
///
/// Zielland
/// Gewicht
/// Zwischensumme netto
/// Summe der zusätzlichen Versandkosten je Produkt aber in Summe
/// Versandkosten netto
public async Task CalculateShipmentAsync(string targetCountry, decimal weight, decimal subtotal, decimal additionalShipmentCosts)
{
targetCountry = targetCountry.ToUpper();
var result = 0M;
var shopSettings = await _shopSettingsService.GetAsync();
var rulesQuery = Repository.Query(c => (c.TargetCountryIso == "--" || c.TargetCountryIso == targetCountry));
if (shopSettings.ShipmentCalculationType == ShipmentCalculationType.Weight)
{
rulesQuery = rulesQuery.Where(c => c.WeightFrom <= weight && c.WeightTo >= weight);
}
else
{
rulesQuery = rulesQuery.Where(c => c.SubtotalFrom <= subtotal && c.SubtotalTo >= subtotal);
}
var rules = await rulesQuery.ToListAsync();
if (rules.Any())
{
//Wenn es mehrere Regeln gibt, dann jene für das Zielland wählen
var ruleToAppy = rules.FirstOrDefault(c => c.TargetCountryIso == targetCountry) ?? rules.FirstOrDefault();
if (ruleToAppy != null)
{
if (shopSettings.ShipmentCalculationType == ShipmentCalculationType.Weight)
{
result = ruleToAppy.FixedPrice;
}
else
{
result = (subtotal / 100) * ruleToAppy.SubtotalPercent;
}
}
}
result += additionalShipmentCosts;
return result;
}
}
}