From cb8fdfdb54e0b27f531e561ac5e29c01a265c118 Mon Sep 17 00:00:00 2001 From: "github-classroom[bot]" <66690702+github-classroom[bot]@users.noreply.github.com> Date: Fri, 20 Jan 2023 12:52:25 +0000 Subject: [PATCH 1/6] Setting up GitHub Classroom Feedback From d2a1fefbc34c9e558389fb557a108b2b925ca11c Mon Sep 17 00:00:00 2001 From: pixmacfy Date: Fri, 20 Jan 2023 15:29:32 +0100 Subject: [PATCH 2/6] Seperate data and services into distinct classes - PART 1 --- .gitignore | 3 + .idea/.gitignore | 8 + ALCOL.iml | 11 + README.md | 31 +++ src/core/Bank.java | 57 ----- src/core/Client.java | 3 + src/core/Provider.java | 55 ----- src/core/Store.java | 262 ----------------------- src/core/{ => data}/Account.java | 12 +- src/core/{ => data}/Cart.java | 14 +- src/core/{ => data}/ItemInStock.java | 10 +- src/core/{ => data}/Order.java | 75 +++---- src/core/data/Provider.java | 38 ++++ src/core/data/Store.java | 121 +++++++++++ src/core/service/AccountService.java | 17 ++ src/core/service/BankService.java | 58 +++++ src/core/service/CartService.java | 17 ++ src/core/service/ItemInStockService.java | 12 ++ src/core/service/OrderService.java | 51 +++++ src/core/service/ProviderService.java | 28 +++ src/core/service/StoreService.java | 164 ++++++++++++++ src/main/Main.java | 5 +- 22 files changed, 600 insertions(+), 452 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 ALCOL.iml delete mode 100644 src/core/Bank.java delete mode 100644 src/core/Provider.java delete mode 100644 src/core/Store.java rename src/core/{ => data}/Account.java (69%) rename src/core/{ => data}/Cart.java (55%) rename src/core/{ => data}/ItemInStock.java (77%) rename src/core/{ => data}/Order.java (57%) create mode 100644 src/core/data/Provider.java create mode 100644 src/core/data/Store.java create mode 100644 src/core/service/AccountService.java create mode 100644 src/core/service/BankService.java create mode 100644 src/core/service/CartService.java create mode 100644 src/core/service/ItemInStockService.java create mode 100644 src/core/service/OrderService.java create mode 100644 src/core/service/ProviderService.java create mode 100644 src/core/service/StoreService.java diff --git a/.gitignore b/.gitignore index d5bdd21..0c830d6 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,6 @@ hs_err_pid* # Eclipse .classpath .project + +# IntellJ +.idea/* diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/ALCOL.iml b/ALCOL.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/ALCOL.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index d0f0c65..94ab596 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,34 @@ # estore Projet pour l'enseignement des composants logiciels + +Réponses google forms (en cours) : + +https://github.com/Master-DL/m2-estore-pojo-r + +BAYCHELIER Rémi PEYRICHOUX Rémy + +Classes : +- Account : withdraw() +- Bank: transfert(), dépendance à Account (et jeu de données set-up dans le constructeur) +- Cart: addItems(), dépendance à Client +- Client: Jeu de données dans le constructeur et scénarios, dépendance à Store +- ItemInStock : changeQuantity, dépendance à Provider +- Order : addItem() et computeAmount(), dépendance à Client +- Provider : order() +- Store : isAvailable(), addItemToCart(), pay(), oneShotOrder(), treatOrder(), dépendance à Bank et Provider + +Lecture des attributs du code, distinction des méthodes de type getter/setter aux méthodes qui font du traitement plus complexe sur les objets et qui sont pour la plupart publiques. + +Voir dépendances dans la question 1 + +- Account : withdraw() - soustrait un montant d'un compte +- Bank: transfert() - virement d'un montant d'un compte vers un autre +- Cart: addItem() - ajout d'un produit dans le panier +- ItemInStock : changeQuantity() - changer l'inventaire d'un produit en stock +- Order : addItem() - ajout du prix d'un produit dans la commande et change l'inventaire de ce produit, computeAmount() - calculer le montant de la commande +- Provider : order() - retourne une valeur aléatoire dépendant d'une quantité +- Store : isAvailable() - retourne vrai si l'objet donné est en stock + addItemToCart() - ajoute un produit dans le panier avec une quantité + pay() - crée la commande, calcule son montant et effectue le virement entre les comptes + oneShotOrder() - commande d'un seul type de produit avec une quantité \ No newline at end of file diff --git a/src/core/Bank.java b/src/core/Bank.java deleted file mode 100644 index 0eb17bc..0000000 --- a/src/core/Bank.java +++ /dev/null @@ -1,57 +0,0 @@ -package core; - -import estorePojo.exceptions.InsufficientBalanceException; -import estorePojo.exceptions.UnknownAccountException; - -public class Bank { - - private Account estore; - private Account anne, bob; - - public Bank() { - estore = new Account(); - anne = new Account(); - bob = new Account(); - - estore.setOwner("Estore"); - estore.setAmount(0); - anne.setOwner("Anne"); - anne.setAmount(30); - bob.setOwner("Bob"); - bob.setAmount(100); - } - - public void transfert(String from, String to, double amount) - throws InsufficientBalanceException, UnknownAccountException { - Account Afrom = null, Ato = null; - - if (from.equals("E-Store")) - Afrom = estore; - if (from.equals("Anne")) - Afrom = anne; - if (from.equals("Bob")) - Afrom = bob; - - if (to.equals("E-Store")) - Ato = estore; - if (to.equals("Anne")) - Ato = anne; - if (to.equals("Bob")) - Ato = bob; - - // Get the balance of the account to widthdraw - double fromBalance = Afrom.getAmount(); - - // Check whether the account is sufficiently balanced - if (fromBalance < amount) - throw new InsufficientBalanceException(from.toString()); - - // Get the balance of the account to credit - double toBalance = Ato.getAmount(); - - // Perform the transfert - Afrom.setAmount(fromBalance - amount); - Ato.setAmount(toBalance + amount); - } - -} diff --git a/src/core/Client.java b/src/core/Client.java index 4069d13..fb276ba 100644 --- a/src/core/Client.java +++ b/src/core/Client.java @@ -1,5 +1,8 @@ package core; +import core.data.Cart; +import core.data.Order; +import core.data.Store; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; diff --git a/src/core/Provider.java b/src/core/Provider.java deleted file mode 100644 index b6af0ee..0000000 --- a/src/core/Provider.java +++ /dev/null @@ -1,55 +0,0 @@ -package core; - -import java.util.HashMap; -import java.util.Map; - -import estorePojo.exceptions.UnknownItemException; - -public class Provider { - - private Map itemPrices = new HashMap<>(); - - /** - * Constructs a new ProviderImpl - */ - public Provider() { - itemPrices.put("CD", 15d); - itemPrices.put("DVD", 20d); - } - - /** - * Get the price of an item provided by this provider. - * - * @param item - * @return - */ - public double getPrice(Object item) throws UnknownItemException { - - if (!itemPrices.containsKey(item)) - throw new UnknownItemException("Item " + item + " is not an item delivered by this provider."); - - Double price = (Double) itemPrices.get(item); - return price.doubleValue(); - } - - /** - * Emit an order for items. The provider returns the delay for delivering the - * items. - * - * @param store the store that emits the order - * @param item the item ordered - * @param qty the quantity ordered - * @return the delay (in hours) - */ - public int order(Store store, Object item, int qty) throws UnknownItemException { - - if (!itemPrices.containsKey(item)) - throw new UnknownItemException("Item " + item + " is not an item delivered by this provider."); - - // Actually the production process is quite chaotic - // We only know that the production a random number of hours!! - double r = Math.random() * 10 * qty; - return (int) r; - } - -} diff --git a/src/core/Store.java b/src/core/Store.java deleted file mode 100644 index 7c7f6d1..0000000 --- a/src/core/Store.java +++ /dev/null @@ -1,262 +0,0 @@ -package core; - - import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import estorePojo.exceptions.InsufficientBalanceException; -import estorePojo.exceptions.InvalidCartException; -import estorePojo.exceptions.UnknownAccountException; -import estorePojo.exceptions.UnknownItemException; - -public class Store { - - private Provider provider; - private Bank bank; - - /** - * Constructs a new StoreImpl - */ - public Store(Provider prov, Bank bk) { - provider = prov; - bank = bk; - } - - /** - * @param item a given item - * @return the price of a given item - * @throws UnknownItemException - */ - public double getPrice( Object item ) throws UnknownItemException { - return provider.getPrice(item); - } - - /** - * @param item a given item - * @param qty a given quantity - * @return - * true if the given quantity of the given item is available - * directly from the store - * i.e. without having to re-order it from the provider - */ - public boolean isAvailable( Object item, int qty ) - throws UnknownItemException { - - if ( ! itemsInStock.containsKey(item) ) - throw new UnknownItemException( - "Item "+item+ - " does not correspond to any known reference"); - - ItemInStock iis = (ItemInStock) itemsInStock.get(item); - boolean isAvailable = (iis.getQuantity() >= qty); - - return isAvailable; - } - - /** - * Add an item to a cart. - * If the cart does not exist yet, create a new one. - * This method is called for each item one wants to add to the cart. - * - * @param cart a previously created cart or null - * @param client - * @param item - * @param qty - * @return - * Implementation dependant. - * Either a new cart at each call or the same cart updated. - * - * @throws UnknownItemException - * @throws MismatchClientCartException - * if the given client does not own the given cart - */ - public Cart addItemToCart( - Cart cart, - Client client, - Object item, - int qty ) - throws UnknownItemException, InvalidCartException { - - if ( cart == null ) { - // If no cart is provided, create a new one - cart = new Cart(client); - } - else { - if ( client != cart.getClient() ) - throw new InvalidCartException( - "Cart "+cart+" does not belong to "+client); - } - - cart.addItem(item,qty); - - return cart; - } - - /** - * Once all the items have been added to the cart, - * this method finish make the payment - * - * @param cart - * @param address - * @param bankAccountRef - * @return the order - * - * @throws UnknownItemException - */ - public Order pay( Cart cart, String address, String bankAccountRef ) - throws - InvalidCartException, UnknownItemException, - InsufficientBalanceException, UnknownAccountException { - - if ( cart == null ) - throw new InvalidCartException("Cart shouldn't be null"); - - // Create a new order - Order order = new Order( cart.getClient(), address, bankAccountRef ); - orders.put(order.getKey(), order ); - - // Order all the items of the cart - Set entries = cart.getItems().entrySet(); - for (Iterator iter = entries.iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - Object item = entry.getKey(); - int qty = ((Integer) entry.getValue()).intValue(); - - treatOrder(order,item,qty); - } - double amount = order.computeAmount(); - - // Make the payment - // Throws InsuffisiantBalanceException if the client account is - // not sufficiently balanced - bank.transfert(bankAccountRef,toString(),amount); - - return order; - } - - /** - * A map of emitted orders. - * keys = order keys as Integers - * values = Order instances - */ - private Map orders = new HashMap<>(); - - /** - * A map of items available in the stock of the store. - * keys = the references of the items as Objects - * values = ItemInStock instances - */ - private Map itemsInStock = new HashMap<>(); - - /** - * Used by a client to order an item. - * The whole process of ordering is encapsulated by this method. - * If several items need to be ordered, this method needs to be - * called several times, but the items will appear in separate orders. - * - * @param client - * @param item - * @param qty - * @param address - * @param bankAccountRef - * @return the order - * - * @throws UnknownItemException - * @throws InsufficientBalanceException - * @throws UnknownAccountException - */ - public Order oneShotOrder( - Client client, - Object item, - int qty, - String address, - String bankAccountRef - ) - throws - UnknownItemException, - InsufficientBalanceException, UnknownAccountException { - - // Create a new order - Order order = new Order( client, address, bankAccountRef ); - orders.put(order.getKey(), order ); - - // Treat the item ordered - treatOrder(order,item,qty); - double amount = order.computeAmount(); - - // Make the payment - // Throws InsuffisiantBalanceException if the client account is - // not sufficiently balanced - bank.transfert(bankAccountRef,toString(),amount); - - return order; - } - - /** - * Treat an item ordered by a client and update the corresponding order. - * - * @param order - * @param item - * @param qty - * @return - * - * @throws UnknownItemException - * @throws InsufficientBalanceException - * @throws UnknownAccountException - */ - private void treatOrder( Order order, Object item, int qty ) - throws UnknownItemException { - - // The number of additional item to order - // in case we need to place an order to the provider - final int more = 10; - - // The price of the ordered item - // Throws UnknownItemException if the item does not exist - final double price = provider.getPrice(item); - - final double totalAmount = price*qty; - - // The delay (in hours) for delivering the order - // By default, it takes 2 hours to ship items from the stock - // This delay increases if an order is to be placed to the provider - int delay = 2; - - // Check whether the item is available in the stock - // If not, place an order for it to the provider - ItemInStock iis = (ItemInStock) itemsInStock.get(item); - if ( iis == null ) { - int quantity = qty + more; - delay += provider.order(this,item,quantity); - ItemInStock newItem = new ItemInStock(item,more,price,provider); - itemsInStock.put(item,newItem); - } - else { - // The item is in the stock - // Check whether there is a sufficient number of them - // to match the order - if ( iis.getQuantity() >= qty ) { - iis.changeQuantity(qty); - } - else { - // An order to the provider needs to be issued - int quantity = qty + more; - delay += provider.order(this,item,quantity); - iis.changeQuantity(more); - } - } - - // Update the order - order.addItem(item,qty,price); - order.setDelay(delay); - } - - // ----------------------------------------------------- - // Other methods - // ----------------------------------------------------- - - public String toString() { - return "E-Store"; - } - } diff --git a/src/core/Account.java b/src/core/data/Account.java similarity index 69% rename from src/core/Account.java rename to src/core/data/Account.java index 6ce1f19..a4a2a3c 100644 --- a/src/core/Account.java +++ b/src/core/data/Account.java @@ -1,4 +1,4 @@ -package core; +package core.data; import estorePojo.exceptions.InsufficientBalanceException; @@ -23,16 +23,6 @@ public void setAmount(double amount) { this.amount = amount; } - public void credit(double amount) { - this.amount += amount; - } - - public void withdraw(double amount) throws InsufficientBalanceException { - if ( this.amount < amount ) - throw new InsufficientBalanceException(owner); - this.amount -= amount; - } - /** * Two AccountImpl instances are considered equals * if they share the same owner. diff --git a/src/core/Cart.java b/src/core/data/Cart.java similarity index 55% rename from src/core/Cart.java rename to src/core/data/Cart.java index fe5f16c..d07c834 100644 --- a/src/core/Cart.java +++ b/src/core/data/Cart.java @@ -1,4 +1,6 @@ -package core; +package core.data; + +import core.Client; import java.util.HashMap; import java.util.Map; @@ -16,16 +18,6 @@ public Cart(Client client) { this.client = client; } - public void addItem( Object item, int qty ) { - int oldQty = 0; - if ( items.containsKey(item) ) { - // The item has already been put in the cart - // Increase the number - oldQty = ((Integer) items.get(item)).intValue(); - } - items.put( item, qty+oldQty ); - } - public Map getItems() { return items; } diff --git a/src/core/ItemInStock.java b/src/core/data/ItemInStock.java similarity index 77% rename from src/core/ItemInStock.java rename to src/core/data/ItemInStock.java index f259a3f..ae13d28 100644 --- a/src/core/ItemInStock.java +++ b/src/core/data/ItemInStock.java @@ -1,4 +1,4 @@ -package core; +package core.data; public class ItemInStock { @@ -28,11 +28,9 @@ public ItemInStock(Object item, int quantity, double price, Provider provider) { public int getQuantity() { return quantity; } - - public void changeQuantity(int qtyToAddOrRemove) { - if ((qtyToAddOrRemove >= 0 ) || (quantity >= -qtyToAddOrRemove)) { - quantity += qtyToAddOrRemove ; - } + + public void setQuantity(int quantity) { + this.quantity = quantity; } @Override diff --git a/src/core/Order.java b/src/core/data/Order.java similarity index 57% rename from src/core/Order.java rename to src/core/data/Order.java index 074a89a..2bc5c4f 100644 --- a/src/core/Order.java +++ b/src/core/data/Order.java @@ -1,12 +1,13 @@ -package core; +package core.data; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Set; +import core.Client; +import core.service.OrderService; import estorePojo.exceptions.UnknownItemException; public class Order { @@ -49,50 +50,6 @@ public Order(Client client, String address, String bankAccountRef) { this.bankAccountRef = bankAccountRef; } - /** - * Add an item to the order. - * - * @param item - * @param qty - * @param price - * @throws UnknownItemException - */ - public void addItem(Object item, int qty, double price) throws UnknownItemException { - - if (itemPrices.containsKey(item)) { - double oldPrice = ((Double) itemPrices.get(item)).doubleValue(); - if (oldPrice != price) - throw new UnknownItemException( - "Item " + item + " price (" + price + ") added to cart is different from the price (" + oldPrice - + ") of the same item already in the cart"); - } - - items.add(item); - itemPrices.put(item, price); - - int newQty = qty; - if (itemQuantities.containsKey(item)) { - newQty += ((Integer) itemQuantities.get(item)).intValue(); - } - itemQuantities.put(item, newQty); - } - - /** - * Compute the total amount of the order - */ - public double computeAmount() { - - double amount = 0; - - for (Object item : items) { - int qty = ((Integer) itemQuantities.get(item)).intValue(); - double price = ((Double) itemPrices.get(item)).doubleValue(); - amount += qty * price; - } - - return amount; - } - /** * @return Returns the delay for delivering this order. */ @@ -113,9 +70,33 @@ public int getKey() { return num; } + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + + public Map getItemQuantities() { + return itemQuantities; + } + + public void setItemQuantities(Map itemQuantities) { + this.itemQuantities = itemQuantities; + } + + public Map getItemPrices() { + return itemPrices; + } + + public void setItemPrices(Map itemPrices) { + this.itemPrices = itemPrices; + } + public String toString() { String msg = "Order #" + num + " "; - msg += "amount: " + computeAmount() + " "; + msg += "amount: " + new OrderService().computeAmount(this) + " "; //todo : pb de couplage, à changer msg += "delay: " + getDelay() + "h "; msg += "issued on: " + date; return msg; diff --git a/src/core/data/Provider.java b/src/core/data/Provider.java new file mode 100644 index 0000000..5636b1d --- /dev/null +++ b/src/core/data/Provider.java @@ -0,0 +1,38 @@ +package core.data; + +import java.util.HashMap; +import java.util.Map; + +import estorePojo.exceptions.UnknownItemException; + +public class Provider { + + private Map itemPrices = new HashMap<>(); + + /** + * Constructs a new ProviderImpl + */ + public Provider() { + itemPrices.put("CD", 15d); + itemPrices.put("DVD", 20d); + } + + /** + * Get the price of an item provided by this provider. + * + * @param item + * @return + */ + public double getPrice(Object item) throws UnknownItemException { + + if (!itemPrices.containsKey(item)) + throw new UnknownItemException("Item " + item + " is not an item delivered by this provider."); + + Double price = (Double) itemPrices.get(item); + return price.doubleValue(); + } + + public Map getItemPrices() { + return itemPrices; + } +} diff --git a/src/core/data/Store.java b/src/core/data/Store.java new file mode 100644 index 0000000..841218e --- /dev/null +++ b/src/core/data/Store.java @@ -0,0 +1,121 @@ +package core.data; + + import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + + import core.Client; + import core.service.BankService; + import estorePojo.exceptions.InsufficientBalanceException; +import estorePojo.exceptions.InvalidCartException; +import estorePojo.exceptions.UnknownAccountException; +import estorePojo.exceptions.UnknownItemException; + +public class Store { + + private Provider provider; + private BankService bank; + + /** + * Constructs a new StoreImpl + */ + public Store(Provider prov, BankService bk) { + provider = prov; + bank = bk; + } + + /** + * @param item a given item + * @return the price of a given item + * @throws UnknownItemException + */ + public double getPrice( Object item ) throws UnknownItemException { + return provider.getPrice(item); + } + + + + /** + * A map of emitted orders. + * keys = order keys as Integers + * values = Order instances + */ + private Map orders = new HashMap<>(); + + /** + * A map of items available in the stock of the store. + * keys = the references of the items as Objects + * values = ItemInStock instances + */ + private Map itemsInStock = new HashMap<>(); + + + + /** + * Treat an item ordered by a client and update the corresponding order. + * + * @param order + * @param item + * @param qty + * @return + * + * @throws UnknownItemException + * @throws InsufficientBalanceException + * @throws UnknownAccountException + */ + private void treatOrder( Order order, Object item, int qty ) + throws UnknownItemException { + + // The number of additional item to order + // in case we need to place an order to the provider + final int more = 10; + + // The price of the ordered item + // Throws UnknownItemException if the item does not exist + final double price = provider.getPrice(item); + + final double totalAmount = price*qty; + + // The delay (in hours) for delivering the order + // By default, it takes 2 hours to ship items from the stock + // This delay increases if an order is to be placed to the provider + int delay = 2; + + // Check whether the item is available in the stock + // If not, place an order for it to the provider + ItemInStock iis = (ItemInStock) itemsInStock.get(item); + if ( iis == null ) { + int quantity = qty + more; + delay += provider.order(this,item,quantity); + ItemInStock newItem = new ItemInStock(item,more,price,provider); + itemsInStock.put(item,newItem); + } + else { + // The item is in the stock + // Check whether there is a sufficient number of them + // to match the order + if ( iis.getQuantity() >= qty ) { + iis.changeQuantity(qty); + } + else { + // An order to the provider needs to be issued + int quantity = qty + more; + delay += provider.order(this,item,quantity); + iis.changeQuantity(more); + } + } + + // Update the order + order.addItem(item,qty,price); + order.setDelay(delay); + } + + // ----------------------------------------------------- + // Other methods + // ----------------------------------------------------- + + public String toString() { + return "E-Store"; + } + } diff --git a/src/core/service/AccountService.java b/src/core/service/AccountService.java new file mode 100644 index 0000000..0a46582 --- /dev/null +++ b/src/core/service/AccountService.java @@ -0,0 +1,17 @@ +package core.service; + +import core.data.Account; +import estorePojo.exceptions.InsufficientBalanceException; + +public class AccountService { + + public void credit(Account account, double amount) { + account.setAmount(account.getAmount()+amount); + } + + public void withdraw(Account account, double amount) throws InsufficientBalanceException { + if ( account.getAmount() < amount ) + throw new InsufficientBalanceException(account.getOwner()); + credit(account, -amount); + } +} diff --git a/src/core/service/BankService.java b/src/core/service/BankService.java new file mode 100644 index 0000000..13b5a42 --- /dev/null +++ b/src/core/service/BankService.java @@ -0,0 +1,58 @@ +package core.service; + +import core.data.Account; +import estorePojo.exceptions.InsufficientBalanceException; +import estorePojo.exceptions.UnknownAccountException; + +public class BankService { + + private Account estore; + private Account anne, bob; + + public BankService() { + estore = new Account(); + anne = new Account(); + bob = new Account(); + + estore.setOwner("Estore"); + estore.setAmount(0); + anne.setOwner("Anne"); + anne.setAmount(30); + bob.setOwner("Bob"); + bob.setAmount(100); + } + + public void transfert(String from, String to, double amount) + throws InsufficientBalanceException, UnknownAccountException { + Account Afrom = null, Ato = null; + + if (from.equals("E-Store")) + Afrom = estore; + if (from.equals("Anne")) + Afrom = anne; + if (from.equals("Bob")) + Afrom = bob; + + if (to.equals("E-Store")) + Ato = estore; + if (to.equals("Anne")) + Ato = anne; + if (to.equals("Bob")) + Ato = bob; + + // Get the balance of the account to widthdraw + double fromBalance = Afrom.getAmount(); + + // Check whether the account is sufficiently balanced + if (fromBalance < amount) + throw new InsufficientBalanceException(from.toString()); + + // Get the balance of the account to credit + double toBalance = Ato.getAmount(); + + // Perform the transfert + Afrom.setAmount(fromBalance - amount); + Ato.setAmount(toBalance + amount); + } + +} diff --git a/src/core/service/CartService.java b/src/core/service/CartService.java new file mode 100644 index 0000000..70dfd4e --- /dev/null +++ b/src/core/service/CartService.java @@ -0,0 +1,17 @@ +package core.service; + +import core.data.Cart; + +public class CartService { + + public void addItem(Cart cart, Object item, int qty ) { + int oldQty = 0; + if ( cart.getItems().containsKey(item) ) { + // The item has already been put in the cart + // Increase the number + oldQty = ((Integer) cart.getItems().get(item)).intValue(); + } + cart.getItems().put( item, qty+oldQty ); + } + +} diff --git a/src/core/service/ItemInStockService.java b/src/core/service/ItemInStockService.java new file mode 100644 index 0000000..9d14884 --- /dev/null +++ b/src/core/service/ItemInStockService.java @@ -0,0 +1,12 @@ +package core.service; + +import core.data.ItemInStock; + +public class ItemInStockService { + + public void changeQuantity(ItemInStock item, int qtyToAddOrRemove) { + if ((qtyToAddOrRemove >= 0 ) || (item.getQuantity() >= -qtyToAddOrRemove)) { + item.setQuantity(item.getQuantity() + qtyToAddOrRemove); + } + } +} diff --git a/src/core/service/OrderService.java b/src/core/service/OrderService.java new file mode 100644 index 0000000..d65d82a --- /dev/null +++ b/src/core/service/OrderService.java @@ -0,0 +1,51 @@ +package core.service; + +import core.data.Order; +import estorePojo.exceptions.UnknownItemException; + +public class OrderService { + + /** + * Add an item to the order. + * + * @param item + * @param qty + * @param price + * @throws UnknownItemException + */ + public void addItem(Order order, Object item, int qty, double price) throws UnknownItemException { + + if (order.getItemPrices().containsKey(item)) { + double oldPrice = ((Double) order.getItemPrices().get(item)).doubleValue(); + if (oldPrice != price) + throw new UnknownItemException( + "Item " + item + " price (" + price + ") added to cart is different from the price (" + oldPrice + + ") of the same item already in the cart"); + } + + order.getItems().add(item); + order.getItemPrices().put(item, price); + + int newQty = qty; + if (order.getItemQuantities().containsKey(item)) { + newQty += ((Integer) order.getItemQuantities().get(item)).intValue(); + } + order.getItemQuantities().put(item, newQty); + } + + /** + * Compute the total amount of the order + */ + public double computeAmount(Order order) { + + double amount = 0; + + for (Object item : order.getItems()) { + int qty = ((Integer) order.getItemQuantities().get(item)).intValue(); + double price = ((Double) order.getItemPrices().get(item)).doubleValue(); + amount += qty * price; + } + + return amount; + } +} diff --git a/src/core/service/ProviderService.java b/src/core/service/ProviderService.java new file mode 100644 index 0000000..d07ea32 --- /dev/null +++ b/src/core/service/ProviderService.java @@ -0,0 +1,28 @@ +package core.service; + +import core.data.Provider; +import core.data.Store; +import estorePojo.exceptions.UnknownItemException; + +public class ProviderService { + + /** + * Emit an order for items. The provider returns the delay for delivering the + * items. + * + * @param store the store that emits the order + * @param item the item ordered + * @param qty the quantity ordered + * @return the delay (in hours) + */ + public int order(Provider provider, Store store, Object item, int qty) throws UnknownItemException { + + if (!provider.getItemPrices().containsKey(item)) + throw new UnknownItemException("Item " + item + " is not an item delivered by this provider."); + + // Actually the production process is quite chaotic + // We only know that the production a random number of hours!! + double r = Math.random() * 10 * qty; + return (int) r; + } +} diff --git a/src/core/service/StoreService.java b/src/core/service/StoreService.java new file mode 100644 index 0000000..ceb27db --- /dev/null +++ b/src/core/service/StoreService.java @@ -0,0 +1,164 @@ +package core.service; + +import core.Client; +import core.data.Cart; +import core.data.ItemInStock; +import core.data.Order; +import estorePojo.exceptions.InsufficientBalanceException; +import estorePojo.exceptions.InvalidCartException; +import estorePojo.exceptions.UnknownAccountException; +import estorePojo.exceptions.UnknownItemException; + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class StoreService { + + /** + * @param item a given item + * @param qty a given quantity + * @return + * true if the given quantity of the given item is available + * directly from the store + * i.e. without having to re-order it from the provider + */ + public boolean isAvailable( Object item, int qty ) + throws UnknownItemException { + + if ( ! .containsKey(item) ) + throw new UnknownItemException( + "Item "+item+ + " does not correspond to any known reference"); + + ItemInStock iis = (ItemInStock) itemsInStock.get(item); + boolean isAvailable = (iis.getQuantity() >= qty); + + return isAvailable; + } + + /** + * Add an item to a cart. + * If the cart does not exist yet, create a new one. + * This method is called for each item one wants to add to the cart. + * + * @param cart a previously created cart or null + * @param client + * @param item + * @param qty + * @return + * Implementation dependant. + * Either a new cart at each call or the same cart updated. + * + * @throws UnknownItemException + * @throws MismatchClientCartException + * if the given client does not own the given cart + */ + public Cart addItemToCart( + Cart cart, + Client client, + Object item, + int qty ) + throws UnknownItemException, InvalidCartException { + + if ( cart == null ) { + // If no cart is provided, create a new one + cart = new Cart(client); + } + else { + if ( client != cart.getClient() ) + throw new InvalidCartException( + "Cart "+cart+" does not belong to "+client); + } + + cart.addItem(item,qty); + + return cart; + } + + /** + * Once all the items have been added to the cart, + * this method finish make the payment + * + * @param cart + * @param address + * @param bankAccountRef + * @return the order + * + * @throws UnknownItemException + */ + public Order pay(Cart cart, String address, String bankAccountRef ) + throws + InvalidCartException, UnknownItemException, + InsufficientBalanceException, UnknownAccountException { + + if ( cart == null ) + throw new InvalidCartException("Cart shouldn't be null"); + + // Create a new order + Order order = new Order( cart.getClient(), address, bankAccountRef ); + orders.put(order.getKey(), order ); + + // Order all the items of the cart + Set entries = cart.getItems().entrySet(); + for (Iterator iter = entries.iterator(); iter.hasNext();) { + Map.Entry entry = (Map.Entry) iter.next(); + Object item = entry.getKey(); + int qty = ((Integer) entry.getValue()).intValue(); + + treatOrder(order,item,qty); + } + double amount = order.computeAmount(); + + // Make the payment + // Throws InsuffisiantBalanceException if the client account is + // not sufficiently balanced + bank.transfert(bankAccountRef,toString(),amount); + + return order; + } + + /** + * Used by a client to order an item. + * The whole process of ordering is encapsulated by this method. + * If several items need to be ordered, this method needs to be + * called several times, but the items will appear in separate orders. + * + * @param client + * @param item + * @param qty + * @param address + * @param bankAccountRef + * @return the order + * + * @throws UnknownItemException + * @throws InsufficientBalanceException + * @throws UnknownAccountException + */ + public Order oneShotOrder( + Client client, + Object item, + int qty, + String address, + String bankAccountRef + ) + throws + UnknownItemException, + InsufficientBalanceException, UnknownAccountException { + + // Create a new order + Order order = new Order( client, address, bankAccountRef ); + orders.put(order.getKey(), order ); + + // Treat the item ordered + treatOrder(order,item,qty); + double amount = order.computeAmount(); + + // Make the payment + // Throws InsuffisiantBalanceException if the client account is + // not sufficiently balanced + bank.transfert(bankAccountRef,toString(),amount); + + return order; + } +} diff --git a/src/main/Main.java b/src/main/Main.java index 6c65d51..899faf2 100644 --- a/src/main/Main.java +++ b/src/main/Main.java @@ -1,9 +1,8 @@ package main; -import core.Bank; import core.Client; -import core.Provider; -import core.Store; +import core.data.Provider; +import core.data.Store; public class Main { From 39fbbc2e717dad5dad0b175b7bcbd88b8b8f2ec1 Mon Sep 17 00:00:00 2001 From: layn Date: Sun, 22 Jan 2023 14:16:29 +0100 Subject: [PATCH 3/6] remi personal setup --- .gitignore | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/.gitignore b/.gitignore index 0c830d6..55f4a82 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,59 @@ hs_err_pid* # IntellJ .idea/* + +src/main/java + +# Created by https://www.toptal.com/developers/gitignore/api/maven +# Edit at https://www.toptal.com/developers/gitignore?templates=maven + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Eclipse m2e generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# End of https://www.toptal.com/developers/gitignore/api/maven + +# Created by https://www.toptal.com/developers/gitignore/api/vim +# Edit at https://www.toptal.com/developers/gitignore?templates=vim + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +# End of https://www.toptal.com/developers/gitignore/api/vim + +.settings +pom.xml +memo.txt From ae0217db26c671e7259bd9e72fd38f0a2ec8d152 Mon Sep 17 00:00:00 2001 From: pixmacfy Date: Sun, 22 Jan 2023 19:45:33 +0100 Subject: [PATCH 4/6] Seperate data and services into distinct classes - PART 2 --- src/core/Client.java | 7 +- src/core/data/Store.java | 157 ++++++++++------------------- src/core/service/StoreService.java | 92 +++++++++++++---- 3 files changed, 134 insertions(+), 122 deletions(-) diff --git a/src/core/Client.java b/src/core/Client.java index fb276ba..edcde06 100644 --- a/src/core/Client.java +++ b/src/core/Client.java @@ -3,6 +3,7 @@ import core.data.Cart; import core.data.Order; import core.data.Store; +import core.service.StoreService; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; @@ -55,7 +56,7 @@ private void _scenario1( InsufficientBalanceException, UnknownAccountException{ System.out.println("Ordering "+qty+" "+item+" for "+account+"..."); - Order order = store.oneShotOrder(this,item,qty,address,account); + Order order = new StoreService().oneShotOrder(store, this,item,qty,address,account); System.out.println(order); } @@ -81,9 +82,9 @@ private void _scenario2( Cart cart = null; for (int i = 0; i < items.length; i++) { System.out.println("Item: "+items[i]+", quantity: "+qties[i]); - cart = store.addItemToCart(cart,this,items[i],qties[i]); + cart = new StoreService().addItemToCart(cart,this,items[i],qties[i]); } - Order order = store.pay(cart,address,account); + Order order = new StoreService().pay(store, cart,address,account); System.out.println(order); } } diff --git a/src/core/data/Store.java b/src/core/data/Store.java index 841218e..828c3f2 100644 --- a/src/core/data/Store.java +++ b/src/core/data/Store.java @@ -1,121 +1,74 @@ package core.data; - import java.util.HashMap; +import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; - import core.Client; - import core.service.BankService; - import estorePojo.exceptions.InsufficientBalanceException; +import core.Client; +import core.service.BankService; +import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; import estorePojo.exceptions.UnknownItemException; public class Store { - private Provider provider; - private BankService bank; + private Provider provider; + private BankService bank; - /** - * Constructs a new StoreImpl - */ - public Store(Provider prov, BankService bk) { - provider = prov; - bank = bk; - } + /** + * Constructs a new StoreImpl + */ + public Store(Provider prov, BankService bk) { + provider = prov; + bank = bk; + } - /** - * @param item a given item - * @return the price of a given item - * @throws UnknownItemException - */ - public double getPrice( Object item ) throws UnknownItemException { - return provider.getPrice(item); - } - + /** + * @param item a given item + * @return the price of a given item + * @throws UnknownItemException + */ + public double getPrice(Object item) throws UnknownItemException { + return provider.getPrice(item); + } + /** + * A map of emitted orders. + * keys = order keys as Integers + * values = Order instances + */ + private Map orders = new HashMap<>(); - /** - * A map of emitted orders. - * keys = order keys as Integers - * values = Order instances - */ - private Map orders = new HashMap<>(); - - /** - * A map of items available in the stock of the store. - * keys = the references of the items as Objects - * values = ItemInStock instances - */ - private Map itemsInStock = new HashMap<>(); + /** + * A map of items available in the stock of the store. + * keys = the references of the items as Objects + * values = ItemInStock instances + */ + private Map itemsInStock = new HashMap<>(); + public Provider getProvider() { + return provider; + } - - /** - * Treat an item ordered by a client and update the corresponding order. - * - * @param order - * @param item - * @param qty - * @return - * - * @throws UnknownItemException - * @throws InsufficientBalanceException - * @throws UnknownAccountException - */ - private void treatOrder( Order order, Object item, int qty ) - throws UnknownItemException { - - // The number of additional item to order - // in case we need to place an order to the provider - final int more = 10; - - // The price of the ordered item - // Throws UnknownItemException if the item does not exist - final double price = provider.getPrice(item); - - final double totalAmount = price*qty; - - // The delay (in hours) for delivering the order - // By default, it takes 2 hours to ship items from the stock - // This delay increases if an order is to be placed to the provider - int delay = 2; - - // Check whether the item is available in the stock - // If not, place an order for it to the provider - ItemInStock iis = (ItemInStock) itemsInStock.get(item); - if ( iis == null ) { - int quantity = qty + more; - delay += provider.order(this,item,quantity); - ItemInStock newItem = new ItemInStock(item,more,price,provider); - itemsInStock.put(item,newItem); - } - else { - // The item is in the stock - // Check whether there is a sufficient number of them - // to match the order - if ( iis.getQuantity() >= qty ) { - iis.changeQuantity(qty); - } - else { - // An order to the provider needs to be issued - int quantity = qty + more; - delay += provider.order(this,item,quantity); - iis.changeQuantity(more); - } - } - - // Update the order - order.addItem(item,qty,price); - order.setDelay(delay); - } + public BankService getBank() { + return bank; + } - // ----------------------------------------------------- - // Other methods - // ----------------------------------------------------- - - public String toString() { - return "E-Store"; - } - } + public Map getOrders() { + return orders; + } + + public Map getItemsInStock() { + return itemsInStock; + } + + // ----------------------------------------------------- + // Other methods + // ----------------------------------------------------- + + public String toString() { + return "E-Store"; + } +} diff --git a/src/core/service/StoreService.java b/src/core/service/StoreService.java index ceb27db..d54f7f5 100644 --- a/src/core/service/StoreService.java +++ b/src/core/service/StoreService.java @@ -1,9 +1,7 @@ package core.service; import core.Client; -import core.data.Cart; -import core.data.ItemInStock; -import core.data.Order; +import core.data.*; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; @@ -23,15 +21,15 @@ public class StoreService { * directly from the store * i.e. without having to re-order it from the provider */ - public boolean isAvailable( Object item, int qty ) + public boolean isAvailable(Store store, Object item, int qty ) throws UnknownItemException { - if ( ! .containsKey(item) ) + if ( ! store.getItemsInStock().containsKey(item) ) throw new UnknownItemException( "Item "+item+ " does not correspond to any known reference"); - ItemInStock iis = (ItemInStock) itemsInStock.get(item); + ItemInStock iis = (ItemInStock) store.getItemsInStock().get(item); boolean isAvailable = (iis.getQuantity() >= qty); return isAvailable; @@ -51,7 +49,7 @@ public boolean isAvailable( Object item, int qty ) * Either a new cart at each call or the same cart updated. * * @throws UnknownItemException - * @throws MismatchClientCartException + * //@throws MismatchClientCartException * if the given client does not own the given cart */ public Cart addItemToCart( @@ -71,7 +69,7 @@ public Cart addItemToCart( "Cart "+cart+" does not belong to "+client); } - cart.addItem(item,qty); + new CartService().addItem(cart, item, qty); return cart; } @@ -87,7 +85,7 @@ public Cart addItemToCart( * * @throws UnknownItemException */ - public Order pay(Cart cart, String address, String bankAccountRef ) + public Order pay(Store store, Cart cart, String address, String bankAccountRef ) throws InvalidCartException, UnknownItemException, InsufficientBalanceException, UnknownAccountException { @@ -97,7 +95,7 @@ public Order pay(Cart cart, String address, String bankAccountRef ) // Create a new order Order order = new Order( cart.getClient(), address, bankAccountRef ); - orders.put(order.getKey(), order ); + store.getOrders().put(order.getKey(), order ); // Order all the items of the cart Set entries = cart.getItems().entrySet(); @@ -106,14 +104,14 @@ public Order pay(Cart cart, String address, String bankAccountRef ) Object item = entry.getKey(); int qty = ((Integer) entry.getValue()).intValue(); - treatOrder(order,item,qty); + treatOrder(store, order,item,qty); } - double amount = order.computeAmount(); + double amount = new OrderService().computeAmount(order); // Make the payment // Throws InsuffisiantBalanceException if the client account is // not sufficiently balanced - bank.transfert(bankAccountRef,toString(),amount); + store.getBank().transfert(bankAccountRef,toString(),amount); return order; } @@ -136,6 +134,7 @@ public Order pay(Cart cart, String address, String bankAccountRef ) * @throws UnknownAccountException */ public Order oneShotOrder( + Store store, Client client, Object item, int qty, @@ -148,17 +147,76 @@ public Order oneShotOrder( // Create a new order Order order = new Order( client, address, bankAccountRef ); - orders.put(order.getKey(), order ); + store.getOrders().put(order.getKey(), order ); // Treat the item ordered - treatOrder(order,item,qty); - double amount = order.computeAmount(); + treatOrder(store, order,item,qty); + double amount = new OrderService().computeAmount(order); // Make the payment // Throws InsuffisiantBalanceException if the client account is // not sufficiently balanced - bank.transfert(bankAccountRef,toString(),amount); + store.getBank().transfert(bankAccountRef,toString(),amount); return order; } + + /** + * Treat an item ordered by a client and update the corresponding order. + * + * @param order + * @param item + * @param qty + * @return + * + * @throws UnknownItemException + * @throws InsufficientBalanceException + * @throws UnknownAccountException + */ + private void treatOrder( Store store, Order order, Object item, int qty ) + throws UnknownItemException { + + // The number of additional item to order + // in case we need to place an order to the provider + final int more = 10; + + // The price of the ordered item + // Throws UnknownItemException if the item does not exist + final double price = store.getProvider().getPrice(item); + + final double totalAmount = price*qty; + + // The delay (in hours) for delivering the order + // By default, it takes 2 hours to ship items from the stock + // This delay increases if an order is to be placed to the provider + int delay = 2; + + // Check whether the item is available in the stock + // If not, place an order for it to the provider + ItemInStock iis = (ItemInStock) store.getItemsInStock().get(item); + if ( iis == null ) { + int quantity = qty + more; + delay += new ProviderService().order(store.getProvider(), store, item, quantity); + ItemInStock newItem = new ItemInStock(item,more,price,store.getProvider()); + store.getItemsInStock().put(item,newItem); + } + else { + // The item is in the stock + // Check whether there is a sufficient number of them + // to match the order + if ( iis.getQuantity() >= qty ) { + new ItemInStockService().changeQuantity(iis, qty); + } + else { + // An order to the provider needs to be issued + int quantity = qty + more; + new ProviderService().order(store.getProvider(), store, item, quantity); + new ItemInStockService().changeQuantity(iis, more); + } + } + + // Update the order + new OrderService().addItem(order, item, qty, price); + order.setDelay(delay); + } } From b80f1e63d1cffdb7c85db88f0b03daebfaa3221b Mon Sep 17 00:00:00 2001 From: pixmacfy Date: Sun, 22 Jan 2023 20:29:57 +0100 Subject: [PATCH 5/6] Added interfaces --- README.md | 14 +++++++++++++- src/core/data/Product.java | 14 ++++++++++++++ src/core/data/interfaces/ISeller.java | 7 +++++++ src/core/service/interfaces/IBankService.java | 13 +++++++++++++ src/core/service/interfaces/IItemService.java | 9 +++++++++ src/core/service/interfaces/ISellerService.java | 11 +++++++++++ 6 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 src/core/data/Product.java create mode 100644 src/core/data/interfaces/ISeller.java create mode 100644 src/core/service/interfaces/IBankService.java create mode 100644 src/core/service/interfaces/IItemService.java create mode 100644 src/core/service/interfaces/ISellerService.java diff --git a/README.md b/README.md index 94ab596..e5649a8 100644 --- a/README.md +++ b/README.md @@ -31,4 +31,16 @@ Voir dépendances dans la question 1 - Store : isAvailable() - retourne vrai si l'objet donné est en stock addItemToCart() - ajoute un produit dans le panier avec une quantité pay() - crée la commande, calcule son montant et effectue le virement entre les comptes - oneShotOrder() - commande d'un seul type de produit avec une quantité \ No newline at end of file + oneShotOrder() - commande d'un seul type de produit avec une quantité + +IBankService : Bank, Account +IItemService: Cart, ItemInStock, Order +ISellerService : Provider, Store + +IBankService : transfert(), withdraw(), credit() +IItemService : addItem(), setQuantity(), computeAmount() +ISellerService : order(), pay() + +8 (+ quelques méthodes uniques à certains services) + +Je ne comprends pas la question, ce ne sont pas les mêmes services que ceux exprimés deux questions plus tôt ? \ No newline at end of file diff --git a/src/core/data/Product.java b/src/core/data/Product.java new file mode 100644 index 0000000..466a921 --- /dev/null +++ b/src/core/data/Product.java @@ -0,0 +1,14 @@ +package core.data; + +public class Product { + + private String name; + + public Product(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/src/core/data/interfaces/ISeller.java b/src/core/data/interfaces/ISeller.java new file mode 100644 index 0000000..7e7dd7f --- /dev/null +++ b/src/core/data/interfaces/ISeller.java @@ -0,0 +1,7 @@ +package core.data.interfaces; + +import core.data.Product; + +public interface ISeller { + public double getPrice(Product product); +} \ No newline at end of file diff --git a/src/core/service/interfaces/IBankService.java b/src/core/service/interfaces/IBankService.java new file mode 100644 index 0000000..0622b6c --- /dev/null +++ b/src/core/service/interfaces/IBankService.java @@ -0,0 +1,13 @@ +package core.service.interfaces; + +import core.data.Account; + +public interface IBankService { + + void trasnfert(Account sender, Account receiver); + + void credit(Account account, double amount); + + void withdraw(Account account, double amount); + +} diff --git a/src/core/service/interfaces/IItemService.java b/src/core/service/interfaces/IItemService.java new file mode 100644 index 0000000..8753eb8 --- /dev/null +++ b/src/core/service/interfaces/IItemService.java @@ -0,0 +1,9 @@ +package core.service.interfaces; + +import core.data.Product; + +public interface IItemService { + void addItem(Product product, int quantity, double price); + void setQuantity(Product product, int quantity); + double computeAmount(Product product); +} diff --git a/src/core/service/interfaces/ISellerService.java b/src/core/service/interfaces/ISellerService.java new file mode 100644 index 0000000..8dae29d --- /dev/null +++ b/src/core/service/interfaces/ISellerService.java @@ -0,0 +1,11 @@ +package core.service.interfaces; + +import core.data.Account; +import core.data.Cart; +import core.data.Product; +import core.data.interfaces.ISeller; + +public interface ISellerService { + void pay(ISeller seller, Cart cart, String address, Account account); + void order(ISeller provider, ISeller store, Product product, int quantity); +} From 83e4b297d897c1639ccafdd25bc10a0b71b596af Mon Sep 17 00:00:00 2001 From: pixmacfy Date: Tue, 24 Jan 2023 20:22:07 +0100 Subject: [PATCH 6/6] Big update --- src/core/Client.java | 90 ------- src/core/data/Account.java | 3 +- src/core/data/Cart.java | 14 +- src/core/data/ItemInStock.java | 43 ---- src/core/data/ItemStock.java | 13 + src/core/data/Order.java | 112 ++++----- src/core/data/Product.java | 2 +- src/core/data/Provider.java | 25 +- src/core/data/Store.java | 66 +++--- src/core/data/interfaces/IItemList.java | 9 + src/core/data/interfaces/ISeller.java | 3 +- src/core/service/AccountService.java | 17 -- src/core/service/BankService.java | 60 ++--- src/core/service/CartService.java | 41 +++- src/core/service/ItemInStockService.java | 12 - src/core/service/OrderService.java | 66 +++--- src/core/service/ProviderService.java | 8 +- src/core/service/StoreService.java | 223 ++---------------- src/core/service/interfaces/IBankService.java | 2 +- src/core/service/interfaces/IItemService.java | 13 +- .../service/interfaces/ISellerService.java | 14 +- src/main/Main.java | 108 +++++++-- 22 files changed, 337 insertions(+), 607 deletions(-) delete mode 100644 src/core/Client.java delete mode 100644 src/core/data/ItemInStock.java create mode 100644 src/core/data/ItemStock.java create mode 100644 src/core/data/interfaces/IItemList.java delete mode 100644 src/core/service/AccountService.java delete mode 100644 src/core/service/ItemInStockService.java diff --git a/src/core/Client.java b/src/core/Client.java deleted file mode 100644 index edcde06..0000000 --- a/src/core/Client.java +++ /dev/null @@ -1,90 +0,0 @@ -package core; - -import core.data.Cart; -import core.data.Order; -import core.data.Store; -import core.service.StoreService; -import estorePojo.exceptions.InsufficientBalanceException; -import estorePojo.exceptions.InvalidCartException; -import estorePojo.exceptions.UnknownAccountException; -import estorePojo.exceptions.UnknownItemException; - -public class Client implements Runnable { - - private Store store; - - public Client (Store s){ - store = s; - } - // ----------------------------------------------------- - // Implementation of the Runnable interface - // ----------------------------------------------------- - - public void run() { - - // Scenario 1 - // Direct ordering of an item - // The scenario is run twice - System.out.println("Scenario 1"); - scenario1("CD",2,"Lille","Bob"); - scenario1("CD",1,"Lille","Anne"); - System.out.println(); - - // Scenario 2 - // Ordering of several items by using a cart - System.out.println("Scenario 2"); - scenario2(new String[]{"DVD","CD"},new int[]{2,1},"Lille","Bob"); - System.out.println(); - } - - private void scenario1( - String item, int qty, String address, String account ) { - - try { - _scenario1(item,qty,address,account); - } - catch (Exception e) { - System.err.println("Exception: "+e.getMessage()); - e.printStackTrace(); - } - } - - private void _scenario1( - String item, int qty, String address, String account ) - throws - UnknownItemException, - InsufficientBalanceException, UnknownAccountException{ - - System.out.println("Ordering "+qty+" "+item+" for "+account+"..."); - Order order = new StoreService().oneShotOrder(store, this,item,qty,address,account); - System.out.println(order); - } - - private void scenario2( - String[] items, int[] qties, String address, String account ) { - - try { - _scenario2(items,qties,address,account); - } - catch (Exception e) { - System.err.println("Exception: "+e.getMessage()); - e.printStackTrace(); - } - } - - private void _scenario2( - String[] items, int[] qties, String address, String account ) - throws - InsufficientBalanceException, UnknownAccountException, - UnknownItemException, InvalidCartException{ - - System.out.println("Ordering for "+account+"..."); - Cart cart = null; - for (int i = 0; i < items.length; i++) { - System.out.println("Item: "+items[i]+", quantity: "+qties[i]); - cart = new StoreService().addItemToCart(cart,this,items[i],qties[i]); - } - Order order = new StoreService().pay(store, cart,address,account); - System.out.println(order); - } -} diff --git a/src/core/data/Account.java b/src/core/data/Account.java index a4a2a3c..530d01e 100644 --- a/src/core/data/Account.java +++ b/src/core/data/Account.java @@ -30,9 +30,8 @@ public void setAmount(double amount) { * we should have a account number. */ public boolean equals( Object other ) { - if( ! (other instanceof Account) ) + if( ! (other instanceof Account otherAccount) ) return false; - Account otherAccount = (Account) other; return ( otherAccount.owner == owner); } diff --git a/src/core/data/Cart.java b/src/core/data/Cart.java index d07c834..d28ec60 100644 --- a/src/core/data/Cart.java +++ b/src/core/data/Cart.java @@ -1,28 +1,34 @@ package core.data; import core.Client; +import core.data.interfaces.IItemList; import java.util.HashMap; import java.util.Map; -public class Cart { +public class Cart implements IItemList { /** The client owning the cart. */ private final Client client; /** The items currently added to the cart. key=item, value=quantity. */ - private Map items = new HashMap<>(); + private final Map cartContent = new HashMap<>(); public Cart(Client client) { this.client = client; } - public Map getItems() { - return items; + public Map getCartContent() { + return cartContent; } public Client getClient() { return client; } + + @Override + public Map getContent() { + return cartContent; + } } diff --git a/src/core/data/ItemInStock.java b/src/core/data/ItemInStock.java deleted file mode 100644 index ae13d28..0000000 --- a/src/core/data/ItemInStock.java +++ /dev/null @@ -1,43 +0,0 @@ -package core.data; - -public class ItemInStock { - - /** The total number of ItemInStock instances created. */ - private static int numItems; - - /** The index of this item. */ - private int num; - - private Object item; - private int quantity; - private double price; - private Provider provider; - - private ItemInStock() { - num = numItems++; - } - - public ItemInStock(Object item, int quantity, double price, Provider provider) { - this(); - this.item = item; - this.quantity = quantity; - this.price = price; - this.provider = provider; - } - - public int getQuantity() { - return quantity; - } - - public void setQuantity(int quantity) { - this.quantity = quantity; - } - - @Override - public String toString() { - return "ItemInStock [num=" + num + ", item=" + item + ", quantity=" + quantity + ", price=" + price - + ", provider=" + provider + "]"; - } - - -} diff --git a/src/core/data/ItemStock.java b/src/core/data/ItemStock.java new file mode 100644 index 0000000..14b0905 --- /dev/null +++ b/src/core/data/ItemStock.java @@ -0,0 +1,13 @@ +package core.data; + +import core.data.interfaces.IItemList; + +import java.util.Map; + +public class ItemStock implements IItemList { + Map itemStock; + @Override + public Map getContent() { + return itemStock; + } +} diff --git a/src/core/data/Order.java b/src/core/data/Order.java index 2bc5c4f..0cab935 100644 --- a/src/core/data/Order.java +++ b/src/core/data/Order.java @@ -6,99 +6,85 @@ import java.util.Map; import java.util.Set; -import core.Client; +import core.data.interfaces.IItemList; +import core.data.interfaces.ISeller; import core.service.OrderService; import estorePojo.exceptions.UnknownItemException; -public class Order { +public class Order implements IItemList { - /** The total number of orders emitted so far. */ - private static int numOrders; + private Account clientAccount; + private String deliveryAddress; + private ISeller store; + public Date deliveryDate; + private int deliveryDelay; + private Map orderContent; - /** The index of this order. */ - private int num; + private Integer orderId; - private Client client; - private Object item; - private String address; - private String bankAccountRef; - - /** The date at which the ordered is issued. */ - public Date date; - - /** The delay for delivering the items in the order. */ - private int delay; - - /** The items currently in the order. */ - private Set items = new HashSet<>(); + public Order(Account clientAccount, String deliveryAddress, ISeller store, Date deliveryDate, int deliveryDelay) { + this.clientAccount = clientAccount; + this.deliveryAddress = deliveryAddress; + this.store = store; + this.deliveryDate = deliveryDate; + this.deliveryDelay = deliveryDelay; + this.orderContent = new HashMap<>(); + } - /** The quantities of each item ordered. key=item, value=quantity. */ - private Map itemQuantities = new HashMap<>(); + public Map getOrderContent() { + return orderContent; + } - /** The individual prices of each item ordered. key=item, value=price. */ - private Map itemPrices = new HashMap<>(); + public Account getClientAccount() { + return clientAccount; + } - private Order() { - num = numOrders++; - date = new Date(); + public void setClientAccount(Account clientAccount) { + this.clientAccount = clientAccount; } - public Order(Client client, String address, String bankAccountRef) { - this(); - this.client = client; - this.address = address; - this.bankAccountRef = bankAccountRef; + public String getDeliveryAddress() { + return deliveryAddress; } - /** - * @return Returns the delay for delivering this order. - */ - public int getDelay() { - return delay; + public void setDeliveryAddress(String deliveryAddress) { + this.deliveryAddress = deliveryAddress; } - /** - * Set the delay for this order. The delay is the highest delay for delivering - * all the items of an order. - */ - public void setDelay(int delay) { - if (delay > this.delay) - this.delay = delay; + public ISeller getStore() { + return store; } - public int getKey() { - return num; + public void setStore(ISeller store) { + this.store = store; } - public Set getItems() { - return items; + public Date getDeliveryDate() { + return deliveryDate; } - public void setItems(Set items) { - this.items = items; + public void setDeliveryDate(Date deliveryDate) { + this.deliveryDate = deliveryDate; } - public Map getItemQuantities() { - return itemQuantities; + public int getDeliveryDelay() { + return deliveryDelay; } - public void setItemQuantities(Map itemQuantities) { - this.itemQuantities = itemQuantities; + public void setDeliveryDelay(int deliveryDelay) { + this.deliveryDelay = deliveryDelay; } - public Map getItemPrices() { - return itemPrices; + @Override + public Map getContent() { + return orderContent; } - public void setItemPrices(Map itemPrices) { - this.itemPrices = itemPrices; + public Integer getOrderId() { + return orderId; } - public String toString() { - String msg = "Order #" + num + " "; - msg += "amount: " + new OrderService().computeAmount(this) + " "; //todo : pb de couplage, à changer - msg += "delay: " + getDelay() + "h "; - msg += "issued on: " + date; - return msg; + public void setContent(Map content) { + this.orderContent = content; } } diff --git a/src/core/data/Product.java b/src/core/data/Product.java index 466a921..8337834 100644 --- a/src/core/data/Product.java +++ b/src/core/data/Product.java @@ -2,7 +2,7 @@ public class Product { - private String name; + private final String name; public Product(String name) { this.name = name; diff --git a/src/core/data/Provider.java b/src/core/data/Provider.java index 5636b1d..cd3ed39 100644 --- a/src/core/data/Provider.java +++ b/src/core/data/Provider.java @@ -3,36 +3,31 @@ import java.util.HashMap; import java.util.Map; +import core.data.interfaces.ISeller; import estorePojo.exceptions.UnknownItemException; -public class Provider { +public class Provider implements ISeller { - private Map itemPrices = new HashMap<>(); + private final Map itemPrices = new HashMap<>(); - /** - * Constructs a new ProviderImpl - */ - public Provider() { - itemPrices.put("CD", 15d); - itemPrices.put("DVD", 20d); - } /** * Get the price of an item provided by this provider. * - * @param item + * @param product * @return */ - public double getPrice(Object item) throws UnknownItemException { + @Override + public double getPrice(Product product) throws UnknownItemException { - if (!itemPrices.containsKey(item)) - throw new UnknownItemException("Item " + item + " is not an item delivered by this provider."); + if (!itemPrices.containsKey(product)) + throw new UnknownItemException("Item " + product + " is not an item delivered by this provider."); - Double price = (Double) itemPrices.get(item); + Double price = itemPrices.get(product); return price.doubleValue(); } - public Map getItemPrices() { + public Map getItemPrices() { return itemPrices; } } diff --git a/src/core/data/Store.java b/src/core/data/Store.java index 828c3f2..596eab5 100644 --- a/src/core/data/Store.java +++ b/src/core/data/Store.java @@ -1,37 +1,31 @@ package core.data; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +import java.util.*; -import core.Client; +import core.data.interfaces.IItemList; +import core.data.interfaces.ISeller; import core.service.BankService; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; import estorePojo.exceptions.UnknownItemException; -public class Store { +public class Store implements ISeller { - private Provider provider; - private BankService bank; + private final ISeller provider; + private IItemList itemStock; + private Account account; + + private final Map itemPrices = new HashMap<>(); + + private Map storeOrders; /** * Constructs a new StoreImpl */ - public Store(Provider prov, BankService bk) { + public Store(ISeller prov, Account account) { provider = prov; - bank = bk; - } - - /** - * @param item a given item - * @return the price of a given item - * @throws UnknownItemException - */ - public double getPrice(Object item) throws UnknownItemException { - return provider.getPrice(item); + account = account; } /** @@ -39,36 +33,36 @@ public double getPrice(Object item) throws UnknownItemException { * keys = order keys as Integers * values = Order instances */ - private Map orders = new HashMap<>(); + private final Map orders = new HashMap<>(); - /** - * A map of items available in the stock of the store. - * keys = the references of the items as Objects - * values = ItemInStock instances - */ - private Map itemsInStock = new HashMap<>(); - public Provider getProvider() { + public ISeller getProvider() { return provider; } - public BankService getBank() { - return bank; + public Account getAccount() { + return account; } public Map getOrders() { return orders; } - public Map getItemsInStock() { - return itemsInStock; + @Override + public double getPrice(Product product) throws UnknownItemException { + + if (!itemPrices.containsKey(product)) + throw new UnknownItemException("Item " + product + " is not an item delivered by this provider."); + + Double price = itemPrices.get(product); + return price.doubleValue(); } - // ----------------------------------------------------- - // Other methods - // ----------------------------------------------------- + public Map getItemsInStock() { + return this.itemStock.getContent(); + } - public String toString() { - return "E-Store"; + public Map getStoreOrders() { + return storeOrders; } } diff --git a/src/core/data/interfaces/IItemList.java b/src/core/data/interfaces/IItemList.java new file mode 100644 index 0000000..90da19c --- /dev/null +++ b/src/core/data/interfaces/IItemList.java @@ -0,0 +1,9 @@ +package core.data.interfaces; + +import core.data.Product; + +import java.util.Map; + +public interface IItemList { + Map getContent(); +} diff --git a/src/core/data/interfaces/ISeller.java b/src/core/data/interfaces/ISeller.java index 7e7dd7f..5a988ce 100644 --- a/src/core/data/interfaces/ISeller.java +++ b/src/core/data/interfaces/ISeller.java @@ -1,7 +1,8 @@ package core.data.interfaces; import core.data.Product; +import estorePojo.exceptions.UnknownItemException; public interface ISeller { - public double getPrice(Product product); + double getPrice(Product product) throws UnknownItemException; } \ No newline at end of file diff --git a/src/core/service/AccountService.java b/src/core/service/AccountService.java deleted file mode 100644 index 0a46582..0000000 --- a/src/core/service/AccountService.java +++ /dev/null @@ -1,17 +0,0 @@ -package core.service; - -import core.data.Account; -import estorePojo.exceptions.InsufficientBalanceException; - -public class AccountService { - - public void credit(Account account, double amount) { - account.setAmount(account.getAmount()+amount); - } - - public void withdraw(Account account, double amount) throws InsufficientBalanceException { - if ( account.getAmount() < amount ) - throw new InsufficientBalanceException(account.getOwner()); - credit(account, -amount); - } -} diff --git a/src/core/service/BankService.java b/src/core/service/BankService.java index 13b5a42..379b929 100644 --- a/src/core/service/BankService.java +++ b/src/core/service/BankService.java @@ -1,58 +1,26 @@ package core.service; import core.data.Account; +import core.service.interfaces.IBankService; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.UnknownAccountException; -public class BankService { +import java.util.List; - private Account estore; - private Account anne, bob; - - public BankService() { - estore = new Account(); - anne = new Account(); - bob = new Account(); - - estore.setOwner("Estore"); - estore.setAmount(0); - anne.setOwner("Anne"); - anne.setAmount(30); - bob.setOwner("Bob"); - bob.setAmount(100); +public class BankService implements IBankService { + @Override + public void trasnfert(Account sender, Account receiver, double amount) { + withdraw(sender, amount); + credit(receiver, amount); } - public void transfert(String from, String to, double amount) - throws InsufficientBalanceException, UnknownAccountException { - Account Afrom = null, Ato = null; - - if (from.equals("E-Store")) - Afrom = estore; - if (from.equals("Anne")) - Afrom = anne; - if (from.equals("Bob")) - Afrom = bob; - - if (to.equals("E-Store")) - Ato = estore; - if (to.equals("Anne")) - Ato = anne; - if (to.equals("Bob")) - Ato = bob; - - // Get the balance of the account to widthdraw - double fromBalance = Afrom.getAmount(); - - // Check whether the account is sufficiently balanced - if (fromBalance < amount) - throw new InsufficientBalanceException(from.toString()); - - // Get the balance of the account to credit - double toBalance = Ato.getAmount(); - - // Perform the transfert - Afrom.setAmount(fromBalance - amount); - Ato.setAmount(toBalance + amount); + @Override + public void credit(Account account, double amount) { + account.setAmount(account.getAmount()+amount); } + @Override + public void withdraw(Account account, double amount) { + account.setAmount(account.getAmount()-amount); + } } diff --git a/src/core/service/CartService.java b/src/core/service/CartService.java index 70dfd4e..1103fd9 100644 --- a/src/core/service/CartService.java +++ b/src/core/service/CartService.java @@ -1,17 +1,38 @@ package core.service; -import core.data.Cart; +import core.data.Product; +import core.data.interfaces.IItemList; +import core.data.interfaces.ISeller; +import core.service.interfaces.IItemService; +import estorePojo.exceptions.UnknownItemException; -public class CartService { +public class CartService implements IItemService { - public void addItem(Cart cart, Object item, int qty ) { - int oldQty = 0; - if ( cart.getItems().containsKey(item) ) { - // The item has already been put in the cart - // Increase the number - oldQty = ((Integer) cart.getItems().get(item)).intValue(); - } - cart.getItems().put( item, qty+oldQty ); + private final StoreService storeService; + public CartService() { + storeService = new StoreService(); + } + + @Override + public void addItem(Product product, int quantity, IItemList itemsContent) { + itemsContent.getContent().put(product, quantity); } + @Override + public void setQuantity(Product product, int quantity, IItemList itemsContent) { + itemsContent.getContent().replace(product, quantity); + } + + @Override + public double computeAmount(IItemList itemsContent, ISeller store) { + double total = 0; + for(Product p : itemsContent.getContent().keySet()) { + try { + total += itemsContent.getContent().get(p) * store.getPrice(p); + } catch (UnknownItemException e) { + throw new RuntimeException(e); + } + } + return total; + } } diff --git a/src/core/service/ItemInStockService.java b/src/core/service/ItemInStockService.java deleted file mode 100644 index 9d14884..0000000 --- a/src/core/service/ItemInStockService.java +++ /dev/null @@ -1,12 +0,0 @@ -package core.service; - -import core.data.ItemInStock; - -public class ItemInStockService { - - public void changeQuantity(ItemInStock item, int qtyToAddOrRemove) { - if ((qtyToAddOrRemove >= 0 ) || (item.getQuantity() >= -qtyToAddOrRemove)) { - item.setQuantity(item.getQuantity() + qtyToAddOrRemove); - } - } -} diff --git a/src/core/service/OrderService.java b/src/core/service/OrderService.java index d65d82a..7f528a3 100644 --- a/src/core/service/OrderService.java +++ b/src/core/service/OrderService.java @@ -1,51 +1,43 @@ package core.service; import core.data.Order; +import core.data.Product; +import core.data.interfaces.IItemList; +import core.data.interfaces.ISeller; +import core.service.interfaces.IItemService; +import core.service.interfaces.ISellerService; import estorePojo.exceptions.UnknownItemException; -public class OrderService { - - /** - * Add an item to the order. - * - * @param item - * @param qty - * @param price - * @throws UnknownItemException - */ - public void addItem(Order order, Object item, int qty, double price) throws UnknownItemException { - - if (order.getItemPrices().containsKey(item)) { - double oldPrice = ((Double) order.getItemPrices().get(item)).doubleValue(); - if (oldPrice != price) - throw new UnknownItemException( - "Item " + item + " price (" + price + ") added to cart is different from the price (" + oldPrice - + ") of the same item already in the cart"); - } +import java.util.Map; - order.getItems().add(item); - order.getItemPrices().put(item, price); +public class OrderService implements IItemService { - int newQty = qty; - if (order.getItemQuantities().containsKey(item)) { - newQty += ((Integer) order.getItemQuantities().get(item)).intValue(); - } - order.getItemQuantities().put(item, newQty); + private final StoreService storeService; + + public OrderService() { + storeService = new StoreService(); } - /** - * Compute the total amount of the order - */ - public double computeAmount(Order order) { + @Override + public void addItem(Product product, int quantity, IItemList itemsContent) { + itemsContent.getContent().put(product, quantity); + } - double amount = 0; + @Override + public void setQuantity(Product product, int quantity, IItemList itemsContent) { + itemsContent.getContent().replace(product, quantity); + } - for (Object item : order.getItems()) { - int qty = ((Integer) order.getItemQuantities().get(item)).intValue(); - double price = ((Double) order.getItemPrices().get(item)).doubleValue(); - amount += qty * price; + @Override + public double computeAmount(IItemList itemsContent, ISeller store) { + double total = 0; + for (Product p : itemsContent.getContent().keySet()) { + try { + total += itemsContent.getContent().get(p) * store.getPrice(p); + } catch (UnknownItemException e) { + throw new RuntimeException(e); + } } - - return amount; + return total; } } diff --git a/src/core/service/ProviderService.java b/src/core/service/ProviderService.java index d07ea32..d5e4b32 100644 --- a/src/core/service/ProviderService.java +++ b/src/core/service/ProviderService.java @@ -1,4 +1,4 @@ -package core.service; +/*package core.service; import core.data.Provider; import core.data.Store; @@ -6,7 +6,7 @@ public class ProviderService { - /** + *//** * Emit an order for items. The provider returns the delay for delivering the * items. * @@ -14,7 +14,7 @@ public class ProviderService { * @param item the item ordered * @param qty the quantity ordered * @return the delay (in hours) - */ + *//* public int order(Provider provider, Store store, Object item, int qty) throws UnknownItemException { if (!provider.getItemPrices().containsKey(item)) @@ -25,4 +25,4 @@ public int order(Provider provider, Store store, Object item, int qty) throws Un double r = Math.random() * 10 * qty; return (int) r; } -} +}*/ diff --git a/src/core/service/StoreService.java b/src/core/service/StoreService.java index d54f7f5..8e76fa5 100644 --- a/src/core/service/StoreService.java +++ b/src/core/service/StoreService.java @@ -1,222 +1,49 @@ package core.service; -import core.Client; import core.data.*; +import core.service.interfaces.IBankService; +import core.service.interfaces.IItemService; +import core.service.interfaces.ISellerService; import estorePojo.exceptions.InsufficientBalanceException; import estorePojo.exceptions.InvalidCartException; import estorePojo.exceptions.UnknownAccountException; import estorePojo.exceptions.UnknownItemException; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +import java.util.Date; -public class StoreService { +public class StoreService implements ISellerService { + + private final IItemService cartService; + private final IItemService orderService; + + private final IBankService bankService; + + public StoreService() { + cartService = new CartService(); + orderService = new OrderService(); + bankService = new BankService(); + } /** - * @param item a given item + * @param product a given product * @param qty a given quantity * @return * true if the given quantity of the given item is available * directly from the store * i.e. without having to re-order it from the provider */ - public boolean isAvailable(Store store, Object item, int qty ) + public boolean isAvailable(Store store, Product product, int qty ) throws UnknownItemException { - if ( ! store.getItemsInStock().containsKey(item) ) - throw new UnknownItemException( - "Item "+item+ - " does not correspond to any known reference"); - - ItemInStock iis = (ItemInStock) store.getItemsInStock().get(item); - boolean isAvailable = (iis.getQuantity() >= qty); - - return isAvailable; - } - - /** - * Add an item to a cart. - * If the cart does not exist yet, create a new one. - * This method is called for each item one wants to add to the cart. - * - * @param cart a previously created cart or null - * @param client - * @param item - * @param qty - * @return - * Implementation dependant. - * Either a new cart at each call or the same cart updated. - * - * @throws UnknownItemException - * //@throws MismatchClientCartException - * if the given client does not own the given cart - */ - public Cart addItemToCart( - Cart cart, - Client client, - Object item, - int qty ) - throws UnknownItemException, InvalidCartException { - - if ( cart == null ) { - // If no cart is provided, create a new one - cart = new Cart(client); - } - else { - if ( client != cart.getClient() ) - throw new InvalidCartException( - "Cart "+cart+" does not belong to "+client); - } - - new CartService().addItem(cart, item, qty); - - return cart; + return store.getItemsInStock().containsKey(product) && store.getItemsInStock().get(product) >= qty; } - /** - * Once all the items have been added to the cart, - * this method finish make the payment - * - * @param cart - * @param address - * @param bankAccountRef - * @return the order - * - * @throws UnknownItemException - */ - public Order pay(Store store, Cart cart, String address, String bankAccountRef ) - throws - InvalidCartException, UnknownItemException, - InsufficientBalanceException, UnknownAccountException { - - if ( cart == null ) - throw new InvalidCartException("Cart shouldn't be null"); - - // Create a new order - Order order = new Order( cart.getClient(), address, bankAccountRef ); - store.getOrders().put(order.getKey(), order ); - - // Order all the items of the cart - Set entries = cart.getItems().entrySet(); - for (Iterator iter = entries.iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - Object item = entry.getKey(); - int qty = ((Integer) entry.getValue()).intValue(); - - treatOrder(store, order,item,qty); - } - double amount = new OrderService().computeAmount(order); - - // Make the payment - // Throws InsuffisiantBalanceException if the client account is - // not sufficiently balanced - store.getBank().transfert(bankAccountRef,toString(),amount); - + @Override + public Order order(Store store, Cart cart, String deliveryAddress, Account clientAccount, Date deliveryDate, int deliveryDelay) throws InvalidCartException, UnknownItemException, InsufficientBalanceException, UnknownAccountException { + double cartTotal = cartService.computeAmount(cart, store); + bankService.trasnfert(clientAccount, store.getAccount(), cartTotal); + Order order = new Order(clientAccount, deliveryAddress, store, deliveryDate, deliveryDelay); + order.setContent(cart.getCartContent()); return order; } - - /** - * Used by a client to order an item. - * The whole process of ordering is encapsulated by this method. - * If several items need to be ordered, this method needs to be - * called several times, but the items will appear in separate orders. - * - * @param client - * @param item - * @param qty - * @param address - * @param bankAccountRef - * @return the order - * - * @throws UnknownItemException - * @throws InsufficientBalanceException - * @throws UnknownAccountException - */ - public Order oneShotOrder( - Store store, - Client client, - Object item, - int qty, - String address, - String bankAccountRef - ) - throws - UnknownItemException, - InsufficientBalanceException, UnknownAccountException { - - // Create a new order - Order order = new Order( client, address, bankAccountRef ); - store.getOrders().put(order.getKey(), order ); - - // Treat the item ordered - treatOrder(store, order,item,qty); - double amount = new OrderService().computeAmount(order); - - // Make the payment - // Throws InsuffisiantBalanceException if the client account is - // not sufficiently balanced - store.getBank().transfert(bankAccountRef,toString(),amount); - - return order; - } - - /** - * Treat an item ordered by a client and update the corresponding order. - * - * @param order - * @param item - * @param qty - * @return - * - * @throws UnknownItemException - * @throws InsufficientBalanceException - * @throws UnknownAccountException - */ - private void treatOrder( Store store, Order order, Object item, int qty ) - throws UnknownItemException { - - // The number of additional item to order - // in case we need to place an order to the provider - final int more = 10; - - // The price of the ordered item - // Throws UnknownItemException if the item does not exist - final double price = store.getProvider().getPrice(item); - - final double totalAmount = price*qty; - - // The delay (in hours) for delivering the order - // By default, it takes 2 hours to ship items from the stock - // This delay increases if an order is to be placed to the provider - int delay = 2; - - // Check whether the item is available in the stock - // If not, place an order for it to the provider - ItemInStock iis = (ItemInStock) store.getItemsInStock().get(item); - if ( iis == null ) { - int quantity = qty + more; - delay += new ProviderService().order(store.getProvider(), store, item, quantity); - ItemInStock newItem = new ItemInStock(item,more,price,store.getProvider()); - store.getItemsInStock().put(item,newItem); - } - else { - // The item is in the stock - // Check whether there is a sufficient number of them - // to match the order - if ( iis.getQuantity() >= qty ) { - new ItemInStockService().changeQuantity(iis, qty); - } - else { - // An order to the provider needs to be issued - int quantity = qty + more; - new ProviderService().order(store.getProvider(), store, item, quantity); - new ItemInStockService().changeQuantity(iis, more); - } - } - - // Update the order - new OrderService().addItem(order, item, qty, price); - order.setDelay(delay); - } } diff --git a/src/core/service/interfaces/IBankService.java b/src/core/service/interfaces/IBankService.java index 0622b6c..f2bde11 100644 --- a/src/core/service/interfaces/IBankService.java +++ b/src/core/service/interfaces/IBankService.java @@ -4,7 +4,7 @@ public interface IBankService { - void trasnfert(Account sender, Account receiver); + void trasnfert(Account sender, Account receiver, double amount); void credit(Account account, double amount); diff --git a/src/core/service/interfaces/IItemService.java b/src/core/service/interfaces/IItemService.java index 8753eb8..d4bdedc 100644 --- a/src/core/service/interfaces/IItemService.java +++ b/src/core/service/interfaces/IItemService.java @@ -1,9 +1,16 @@ package core.service.interfaces; import core.data.Product; +import core.data.interfaces.IItemList; +import core.data.interfaces.ISeller; + +import java.util.Map; public interface IItemService { - void addItem(Product product, int quantity, double price); - void setQuantity(Product product, int quantity); - double computeAmount(Product product); + + void addItem(Product product, int quantity, IItemList itemsContent); + + void setQuantity(Product product, int quantity, IItemList itemsContent); + + double computeAmount(IItemList itemsContent, ISeller store); } diff --git a/src/core/service/interfaces/ISellerService.java b/src/core/service/interfaces/ISellerService.java index 8dae29d..719446e 100644 --- a/src/core/service/interfaces/ISellerService.java +++ b/src/core/service/interfaces/ISellerService.java @@ -1,11 +1,15 @@ package core.service.interfaces; -import core.data.Account; -import core.data.Cart; -import core.data.Product; +import core.data.*; +import core.data.interfaces.IItemList; import core.data.interfaces.ISeller; +import estorePojo.exceptions.InsufficientBalanceException; +import estorePojo.exceptions.InvalidCartException; +import estorePojo.exceptions.UnknownAccountException; +import estorePojo.exceptions.UnknownItemException; + +import java.util.Date; public interface ISellerService { - void pay(ISeller seller, Cart cart, String address, Account account); - void order(ISeller provider, ISeller store, Product product, int quantity); + Order order(Store store, Cart cart, String deliveryAddress, Account clientAccount, Date deliveryDate, int deliveryDelay) throws InvalidCartException, UnknownItemException, InsufficientBalanceException, UnknownAccountException; } diff --git a/src/main/Main.java b/src/main/Main.java index 899faf2..2444f15 100644 --- a/src/main/Main.java +++ b/src/main/Main.java @@ -1,19 +1,89 @@ -package main; - -import core.Client; -import core.data.Provider; -import core.data.Store; - -public class Main { - - public static void main(String[] args) { - Provider prov = new Provider(); - Bank bank = new Bank(); - Store store = new Store(prov,bank); - Client cl = new Client(store); - - cl.run(); - - } - -} +package main; + +import core.data.*; +import core.service.StoreService; +import estorePojo.exceptions.InsufficientBalanceException; +import estorePojo.exceptions.InvalidCartException; +import estorePojo.exceptions.UnknownAccountException; +import estorePojo.exceptions.UnknownItemException; + +public class Main implements Runnable { + + private Store store; + + // ----------------------------------------------------- + // Implementation of the Runnable interface + // ----------------------------------------------------- + + public void run() { + + Provider provider = new Provider(); + Account storeAccount = new Account(); + Store s = new Store(provider, storeAccount); + + // Scenario 1 + // Direct ordering of an item + // The scenario is run twice + System.out.println("Scenario 1"); + scenario1("CD",2,"Lille","Bob"); + scenario1("CD",1,"Lille","Anne"); + System.out.println(); + + // Scenario 2 + // Ordering of several items by using a cart + System.out.println("Scenario 2"); + scenario2(new String[]{"DVD","CD"},new int[]{2,1},"Lille","Bob"); + System.out.println(); + } + + private void scenario1( + String item, int qty, String address, String account ) { + + try { + _scenario1(item,qty,address,account); + } + catch (Exception e) { + System.err.println("Exception: "+e.getMessage()); + e.printStackTrace(); + } + } + + private void _scenario1( + String item, int qty, String address, String account ) + throws + UnknownItemException, + InsufficientBalanceException, UnknownAccountException{ + + System.out.println("Ordering "+qty+" "+item+" for "+account+"..."); + Order order = new StoreService().oneShotOrder(store, this,item,qty,address,account); + System.out.println(order); + } + + private void scenario2( + String[] items, int[] qties, String address, String account ) { + + try { + _scenario2(items,qties,address,account); + } + catch (Exception e) { + System.err.println("Exception: "+e.getMessage()); + e.printStackTrace(); + } + } + + private void _scenario2( + String[] items, int[] qties, String address, String account ) + throws + InsufficientBalanceException, UnknownAccountException, + UnknownItemException, InvalidCartException{ + + System.out.println("Ordering for "+account+"..."); + Cart cart = null; + for (int i = 0; i < items.length; i++) { + System.out.println("Item: "+items[i]+", quantity: "+qties[i]); + cart = new StoreService().addItemToCart(cart,this,items[i],qties[i]); + } + Order order = new StoreService().pay(store, cart,address,account); + System.out.println(order); + } +}