Реализована логика продажи изделий

This commit is contained in:
Данияр Аглиуллов 2023-03-01 02:38:30 +04:00
parent 369025f7a8
commit ce944a6803

View File

@ -107,34 +107,37 @@ namespace ConfectioneryDatabaseImplement
public bool HasNeedPastries(IPastryModel pastry, int needCount)
{
using var context = new ConfectioneryDatabase();
var resultCount = context.Shops
.Select(shop => shop.Pastries
.FirstOrDefault(x => x.Key == pastry.Id).Value.Item2)
.Sum();
return resultCount >= needCount;
throw new NotImplementedException();
}
public bool SellPastries(IPastryModel pastry, int needCount)
{
if (!HasNeedPastries(pastry, needCount))
{
return false;
}
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 diff = Math.Min(tuple.Item2, needCount);
shop.Pastries[pastry.Id] = (tuple.Item1, tuple.Item2 - diff);
needCount -= diff;
if (needCount <= 0)
var res = Math.Min(needCount, sp.Count);
sp.Count -= res;
needCount -= res;
if (sp.Count == 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;
}
}
}