Реализована логика продажи изделий
This commit is contained in:
parent
369025f7a8
commit
ce944a6803
@ -107,34 +107,37 @@ namespace ConfectioneryDatabaseImplement
|
|||||||
|
|
||||||
public bool HasNeedPastries(IPastryModel pastry, int needCount)
|
public bool HasNeedPastries(IPastryModel pastry, int needCount)
|
||||||
{
|
{
|
||||||
using var context = new ConfectioneryDatabase();
|
throw new NotImplementedException();
|
||||||
var resultCount = context.Shops
|
|
||||||
.Select(shop => shop.Pastries
|
|
||||||
.FirstOrDefault(x => x.Key == pastry.Id).Value.Item2)
|
|
||||||
.Sum();
|
|
||||||
return resultCount >= needCount;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool SellPastries(IPastryModel pastry, int needCount)
|
public bool SellPastries(IPastryModel pastry, int needCount)
|
||||||
{
|
{
|
||||||
if (!HasNeedPastries(pastry, needCount))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
using var context = new ConfectioneryDatabase();
|
using var context = new ConfectioneryDatabase();
|
||||||
foreach (var shop in context.Shops.Where(shop => shop.Pastries.ContainsKey(pastry.Id)))
|
using var transaction = context.Database.BeginTransaction();
|
||||||
|
foreach (var sp in context.ShopPastries.Where(x => x.PastryId == pastry.Id))
|
||||||
{
|
{
|
||||||
var tuple = shop.Pastries[pastry.Id];
|
var res = Math.Min(needCount, sp.Count);
|
||||||
var diff = Math.Min(tuple.Item2, needCount);
|
sp.Count -= res;
|
||||||
shop.Pastries[pastry.Id] = (tuple.Item1, tuple.Item2 - diff);
|
needCount -= res;
|
||||||
|
if (sp.Count == 0) // Изделия больше нет в магазине, значит удаляем его
|
||||||
needCount -= diff;
|
|
||||||
if (needCount <= 0)
|
|
||||||
{
|
{
|
||||||
return true;
|
context.ShopPastries.Remove(sp);
|
||||||
|
}
|
||||||
|
if (needCount == 0) // Нельзя коммитить изменения в цикле, что использует контекст, поэтому выходим
|
||||||
|
{
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
if (needCount == 0)
|
||||||
|
{
|
||||||
|
context.SaveChanges();
|
||||||
|
transaction.Commit();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
transaction.Rollback();
|
||||||
|
}
|
||||||
|
return needCount == 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user