107 lines
2.2 KiB
C++
107 lines
2.2 KiB
C++
#include "stock.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <stdexcept>
|
|
|
|
#include "../errors/stockFull.hpp"
|
|
#include "../errors/stockEmpty.hpp"
|
|
#include "../errors/invalidItemType.hpp"
|
|
|
|
Stock::Stock(const std::string &name, int capacity, const std::string &comment, int id)
|
|
: name(name), capacity(capacity), comment(comment), id(id)
|
|
{}
|
|
|
|
Stock::~Stock()
|
|
{
|
|
// Destructor logic (if needed)
|
|
}
|
|
|
|
void Stock::addItem(const ItemType &item)
|
|
{
|
|
if (currentSize + item.getSize() > capacity)
|
|
{
|
|
throw StockFull("Cannot add item: Stock is full");
|
|
}
|
|
items.push_back(item);
|
|
currentSize += item.getSize();
|
|
}
|
|
|
|
void Stock::removeItem(int id)
|
|
{
|
|
if (items.empty())
|
|
{
|
|
throw StockEmpty("No items to remove");
|
|
}
|
|
else if (std::none_of(items.begin(), items.end(),
|
|
[id](const ItemType &item) { return item.getId() == id; }))
|
|
{
|
|
throw InvalidItemType("Item with given ID not found");
|
|
}
|
|
|
|
currentSize -= items[id].getSize();
|
|
// Remove the item with the specified ID
|
|
items.erase(std::remove_if(items.begin(), items.end(),
|
|
[id](const ItemType &item) { return item.getId() == id; }), items.end());
|
|
}
|
|
|
|
bool Stock::removeItem(const ItemType &item)
|
|
{
|
|
if (items.empty())
|
|
{
|
|
return false; // No items to remove
|
|
}
|
|
|
|
// Trouver le premier article du même type
|
|
auto it = std::find_if(items.begin(), items.end(),
|
|
[&item](const ItemType &stockItem) {
|
|
return stockItem.getName() == item.getName();
|
|
});
|
|
|
|
if (it != items.end())
|
|
{
|
|
currentSize -= it->getSize();
|
|
items.erase(it);
|
|
return true;
|
|
}
|
|
|
|
return false; // Item type not found in stock
|
|
}
|
|
|
|
ItemType Stock::getItem(int id) const
|
|
{
|
|
for (const auto &item : items)
|
|
{
|
|
if (item.getId() == id)
|
|
{
|
|
return item;
|
|
}
|
|
}
|
|
throw std::runtime_error("Item not found");
|
|
}
|
|
|
|
// Getters implementation
|
|
std::string Stock::getName() const
|
|
{
|
|
return name;
|
|
}
|
|
|
|
int Stock::getCapacity() const
|
|
{
|
|
return capacity;
|
|
}
|
|
|
|
int Stock::getCurrentSize() const
|
|
{
|
|
return currentSize;
|
|
}
|
|
|
|
std::string Stock::getComment() const
|
|
{
|
|
return comment;
|
|
}
|
|
|
|
int Stock::getId() const
|
|
{
|
|
return id;
|
|
}
|