/
SupplierService.cs
98 lines (80 loc) · 2.83 KB
/
SupplierService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
namespace Suppliers.Services
{
using Suppliers.Domain.Exceptions;
using Suppliers.Domain.Models;
using Suppliers.Domain.Providers;
using Suppliers.Domain.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class SupplierService : ISupplierService
{
private readonly ISupplierDao _supplierDao;
public SupplierService(ISupplierDao supplierDao)
{
_supplierDao = supplierDao;
}
public IList<SupplierDTO> GetAll()
{
return _supplierDao.GetAll();
}
public SupplierDTO Get(int supplierId)
{
return _supplierDao.Get(supplierId);
}
public IList<SupplierDTO> FindSuppliersBy(int supplierId, decimal rate)
{
return _supplierDao.FindSuppliersBy(supplierId, rate);
}
public SupplierRateDTO AddSupplierRate(int supplierId, decimal rate, DateTime startDate, DateTime? endDate)
{
if (endDate.HasValue && startDate >= endDate.Value)
{
throw new ValidationException("The end date must be greater than start date");
}
SupplierDTO supplier = Get(supplierId);
if (supplier == null)
{
throw new NotFoundException($"The supplier of id {supplierId} does not exists");
}
ValidateOverLapping(startDate, endDate, supplier.SupplierRates);
var supplierRate = new SupplierRateDTO
{
Rate = rate,
StartDate = startDate,
EndDate = endDate
};
return _supplierDao.SaveSupplierRate(supplier.SupplierId, supplierRate);
}
#region Privates
private void ValidateOverLapping(DateTime startDate, DateTime? endDate, IList<SupplierRateDTO> supplierRates)
{
foreach (var item in supplierRates)
{
if (IsOverlapped(item.StartDate, item.EndDate, startDate, endDate))
{
throw new ValidationException("The supplied date period was overlapped by an existing periods, try another period");
}
}
}
private bool IsOverlapped(
DateTime startDate, DateTime? endDate,
DateTime startDate2, DateTime? endDate2)
{
if (!endDate2.HasValue && !endDate.HasValue)
{
return true;
}
if (!endDate2.HasValue)
{
return startDate2 < endDate.Value;
}
if (!endDate.HasValue)
{
return startDate < endDate2.Value;
}
return startDate < endDate2.Value && startDate2 < endDate.Value;
}
#endregion
}
}