/**
   * Returns list of all items that are in cart for that user.
   *
   * @param userId
   * @return
   */
  public List<CartItem> getCartItemsFromUserId(int userId) {
    // Declare mapper
    DynamoDBMapper mapper = this.conn.getMapper();

    // Create hash key values which to form a query
    CartItem hashKeyValues = new CartItem();
    hashKeyValues.setUserId(userId);

    // Form a query
    DynamoDBQueryExpression<CartItem> queryExpression =
        new DynamoDBQueryExpression<CartItem>()
            .withHashKeyValues(hashKeyValues)
            .withQueryFilterEntry(
                "IsOrdered",
                new Condition()
                    .withComparisonOperator(ComparisonOperator.EQ)
                    .withAttributeValueList(new AttributeValue().withN("0")));
    // add query filter

    queryExpression.setHashKeyValues(hashKeyValues);

    // execute that query
    List<CartItem> itemList = mapper.query(CartItem.class, queryExpression);

    for (int i = 0; i < itemList.size(); i++) {
      System.out.println(itemList.get(i).getUserId());
      System.out.println(itemList.get(i).getCartId());
      System.out.println(itemList.get(i).getProductId());
      System.out.println(itemList.get(i).getQuantity());
    }

    // return the first item (we will have only one item)
    return itemList;
  }
 public double getTotalCost() {
   double total = 0;
   for (Iterator li = getItems(); li.hasNext(); ) {
     CartItem item = (CartItem) li.next();
     total += item.getTotalCost();
   }
   return total;
 }
 public List<CartItem> placeOrder(int userId) {
   List<CartItem> cartItems = getCartItemsFromUserId(userId);
   DynamoDBMapper mapper = this.conn.getMapper();
   for (CartItem cartItem : cartItems) {
     cartItem.setIsOrdered(1);
     mapper.save(cartItem);
   }
   return cartItems;
 }
 public static double calculateSubTotalPrice(List<CartItem> cartItems) {
   double totalPrice = 0.0;
   if (cartItems != null) {
     for (CartItem item : cartItems) {
       totalPrice += item.getPrice();
     }
   }
   return totalPrice;
 }
 public Item removeItemById(String itemId) {
   CartItem cartItem = (CartItem) itemMap.remove(itemId);
   if (cartItem == null) {
     return null;
   } else {
     itemList.remove(cartItem);
     return cartItem.getItem();
   }
 }
 public BigDecimal getCartItemTotal() {
   BigDecimal cartItemsTotal = new BigDecimal("0");
   for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext(); ) {
     final CartItem cartItem = (CartItem) iterator.next();
     cartItemsTotal =
         cartItemsTotal.add(cartItem.getTotalAmountCartItem(getMarketAreaId(), getRetailerId()));
   }
   return cartItemsTotal;
 }
 public void addItem(Item item, boolean isInStock) {
   CartItem cartItem = (CartItem) itemMap.get(item.getItemId());
   if (cartItem == null) {
     cartItem = new CartItem();
     cartItem.setItem(item);
     cartItem.setQuantity(0);
     cartItem.setInStock(isInStock);
     itemMap.put(item.getItemId(), cartItem);
     itemList.add(cartItem);
   }
 }
  private CartItem findCartItemForProduct(String cartId, String productId) {
    synchronized (lock) {
      final List<CartItem> itemsForCart = carts.get(cartId);

      if (itemsForCart != null)
        for (CartItem cartItem : itemsForCart)
          if (cartItem.getProductId().equals(productId)) return cartItem;

      return null;
    }
  }
 public BigDecimal getSubTotal() {
   BigDecimal subTotal = new BigDecimal("0");
   Iterator<CartItem> items = getAllCartItems();
   while (items.hasNext()) {
     CartItem cartItem = (CartItem) items.next();
     Item item = cartItem.getItem();
     BigDecimal listPrice = item.getListPrice();
     BigDecimal quantity = new BigDecimal(String.valueOf(cartItem.getQuantity()));
     subTotal = subTotal.add(listPrice.multiply(quantity));
   }
   return subTotal;
 }
  public void removeFromCart(String cartId, String productId, int quantity) {
    synchronized (lock) {
      List<CartItem> itemsForCart = carts.get(cartId);
      if (itemsForCart == null) return;

      final CartItem cartItem = findCartItemForProduct(cartId, productId);
      if (cartItem == null) return;

      cartItem.decreaseQuantity(quantity);
      if (cartItem.getQuantity() == 0) itemsForCart.remove(cartItem);
    }
  }
Exemple #11
0
  public void addCartItem(CartItem cartItem) {
    String productId = cartItem.getProduct().getProductId();

    if (cartItems.containsKey(productId)) {
      CartItem existingCartItem = cartItems.get(productId);
      existingCartItem.setQuantity(existingCartItem.getQuantity() + cartItem.getQuantity());
      cartItems.put(productId, existingCartItem);
    } else {
      cartItems.put(productId, cartItem);
    }

    updateGrandTotal();
  }
  @Test
  public void testSingleItemDiscountPromotion() throws Exception {

    final PromotionService promotionService =
        ctx().getBean("promotionService", PromotionService.class);

    MutableShoppingCart shoppingCart = new ShoppingCartImpl();
    shoppingCart.initialise(
        ctx().getBean("amountCalculationStrategy", AmountCalculationStrategy.class));
    final ShoppingCartCommandFactory commands =
        ctx().getBean("shoppingCartCommandFactory", ShoppingCartCommandFactory.class);

    // basic init
    commands.execute(shoppingCart, (Map) singletonMap(ShoppingCartCommand.CMD_SETSHOP, 10));
    commands.execute(
        shoppingCart, (Map) singletonMap(ShoppingCartCommand.CMD_CHANGECURRENCY, "EUR"));

    // create discount promotion
    final Promotion amount50 =
        promotionService.getGenericDao().getEntityFactory().getByIface(Promotion.class);
    amount50.setCode("ORDER_50");
    amount50.setShopCode(shoppingCart.getShoppingContext().getShopCode());
    amount50.setCurrency("EUR");
    amount50.setName("50 off on orders over 200");
    amount50.setPromoType(Promotion.TYPE_ORDER);
    amount50.setPromoAction(Promotion.ACTION_FIXED_AMOUNT_OFF);
    amount50.setEligibilityCondition("shoppingCartItemTotal.priceSubTotal > 200.00");
    amount50.setPromoActionContext("50");
    amount50.setEnabled(true);

    promotionService.create(amount50);

    try {
      // add qualifying items
      Map<String, String> param = new HashMap<String, String>();
      param.put(ShoppingCartCommand.CMD_SETQTYSKU, "CC_TEST4");
      param.put(ShoppingCartCommand.CMD_SETQTYSKU_P_QTY, "2.00");
      commands.execute(shoppingCart, (Map) param);

      assertEquals(1, shoppingCart.getCartItemList().size());

      final CartItem cc_test4 = shoppingCart.getCartItemList().get(0);

      assertEquals("CC_TEST4", cc_test4.getProductSkuCode());
      assertFalse(cc_test4.isPromoApplied());
      assertNull(cc_test4.getAppliedPromo());
      assertEquals("2", cc_test4.getQty().toString());
      assertEquals("123.00", cc_test4.getListPrice().toString());
      assertEquals("123.00", cc_test4.getSalePrice().toString());
      assertEquals("123.00", cc_test4.getPrice().toString());

      assertEquals("246.00", shoppingCart.getTotal().getListSubTotal().toString());
      assertEquals("196.00", shoppingCart.getTotal().getSubTotal().toString());
      assertTrue(shoppingCart.getTotal().isOrderPromoApplied());
      assertEquals("ORDER_50", shoppingCart.getTotal().getAppliedOrderPromo());
    } finally {
      // clean test
      promotionService.delete(amount50);
    }
  }
  public void addToCart(String cartId, String productId, String productName, int quantity) {
    synchronized (lock) {
      List<CartItem> itemsForCart = carts.get(cartId);

      if (itemsForCart == null) {
        itemsForCart = new ArrayList<>();
        carts.put(cartId, itemsForCart);
      }

      final CartItem cartItem = findCartItemForProduct(cartId, productId);
      if (cartItem == null) itemsForCart.add(new CartItem(productId, productName, quantity));
      else cartItem.increaseQuantity(quantity);
    }
  }
  // returns list of items ordered so far by the user
  public CartItem decreaseQuantity(Long cartId) {
    DynamoDBMapper mapper = this.conn.getMapper();
    DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
    Map<String, Condition> scanFilter = new HashMap<String, Condition>();
    Condition scanCondition =
        new Condition()
            .withComparisonOperator(ComparisonOperator.EQ.toString())
            .withAttributeValueList(new AttributeValue().withN(cartId.toString()));

    scanFilter.put("CartId", scanCondition);
    scanExpression.setScanFilter(scanFilter);
    PaginatedScanList<CartItem> items = mapper.scan(CartItem.class, scanExpression);
    CartItem item = items.get(0);
    item.setQuantity(item.getQuantity() - 1);
    mapper.save(item);
    return item;
  }
  private List<CartItem> addCount(String str, List<CartItem> cartitemList) throws IOException {

    String[] fields = str.split("-");
    String barcode = fields[0];
    double count = this.getCount(fields);

    Product product = this.getProduct(barcode);
    int index = this.getIndex(barcode, cartitemList);

    if (index == -1) {
      CartItem cartitem = new CartItem(product, count);
      cartitemList.add(cartitem);
    } else {
      CartItem cartitem = cartitemList.get(index);
      cartitem.setCount(cartitem.getCount() + 1);
      cartitemList.set(index, cartitem);
    }
    return cartitemList;
  }
 /**
  * Saves Item into the cart. - DynamoDB.
  *
  * @param form
  */
 public void saveCartItem(AddToCartForm form) {
   DynamoDBMapper mapper = this.conn.getMapper();
   CartItem item = new CartItem();
   item.setCartId(UUID.randomUUID().getLeastSignificantBits());
   item.setProductId(form.getProductId());
   item.setQuantity(form.getQuantity());
   item.setUserId(form.getUserId());
   item.setIsOrdered(form.getIsOrdered());
   mapper.save(item);
 }
Exemple #17
0
 public void removeCartItem(CartItem cartItem) {
   String productId = cartItem.getProduct().getProductId();
   cartItems.remove(productId);
   updateGrandTotal();
 }
 public void incrementQuantityByItemId(String itemId) {
   CartItem cartItem = (CartItem) itemMap.get(itemId);
   cartItem.incrementeQuantity();
 }
Exemple #19
0
 /**
  * Goes trough the table auction and checks which auctions are over. If the auction is over, finds
  * all bids for that auction, selects the highest bid and sends winning message, also sends to all
  * other users message that auction is over.
  */
 public static void checkAuctionOutcome() {
   // Declaring list of all auctions.
   List<Auction> auctions = finder.all();
   // Declaring variable that represents current date.
   Date currentDate = new Date();
   // Going trough all auctions.
   for (int i = 0; i < auctions.size(); i++) {
     // Declaring variable that represents auction ending date.
     Date auctionEndingDate = auctions.get(i).endingDate;
     // Checking if the auction is active and if the auction ending date is before current date.
     if (auctions.get(i).isActive && auctionEndingDate.before(currentDate)) {
       // Finding all auction bids.
       List<Bid> bids = Bid.getAuctionBids(auctions.get(i));
       // Declaring variable that represents highest bid.
       Bid highestBid = bids.get(0);
       // Declaring string variable that represents winning message.
       String winningMessage =
           "Congratulations!!! You won bitBay auction for item #"
               + auctions.get(i).product.id
               + " - "
               + auctions.get(i).product.name
               + ".\n\r \n\r To proceed with transaction please contact: "
               + auctions.get(i).product.user.email;
       // Declaring and saving winning message.
       Message message =
           new Message(
               CommonHelpers.serviceUser(), highestBid.user, "Auction Winning", winningMessage);
       message.save();
       // Sending SMS notification to auction winner.
       String sms =
           "Congratulations!!! You won bitBay auction for item #"
               + auctions.get(i).product.id
               + " - "
               + auctions.get(i).product.name
               + ". "
               + "This product has been sent to your cart";
       if (highestBid.user.phoneNumber != null) {
         SmsHelper.sendSms(sms, highestBid.user.phoneNumber);
       }
       // After user won on auction create new cart if user don't have one, and put auction item to
       // his cart
       Cart cart = Cart.findCartByUser(highestBid.user);
       if (cart == null) {
         Cart newCart = new Cart();
         newCart.user = highestBid.user;
         newCart.save();
         CartItem cartItem = new CartItem(auctions.get(i).product, highestBid.user, newCart);
         cartItem.save();
       } else {
         CartItem cartItem = new CartItem(auctions.get(i).product, highestBid.user, cart);
         cartItem.save();
       }
       // Declaring string set that will contain emails of all users that have not had highest bid.
       Set<String> bidUsers = new HashSet<>();
       // Adding all user emails to the set.
       for (int j = 0; j < bids.size(); j++) {
         bidUsers.add(bids.get(j).user.email);
       }
       // Removing email of highest bit user from the set.
       bidUsers.remove(highestBid.user.email);
       // Declaring string variable that represents losing message.
       String losingMessage =
           "Biding for item #"
               + auctions.get(i).product.id
               + " - "
               + auctions.get(i).product.name
               + " is over.\n\r \n\r We are sorry to inform you that your bid was not enough.";
       // Declaring iterator list of all user emails.
       Iterator<String> iter = bidUsers.iterator();
       // Going trough all emails and sending message.
       while (iter.hasNext()) {
         User receiver = User.getUserByEmail(iter.next());
         Message msg =
             new Message(CommonHelpers.serviceUser(), receiver, "Auction results", losingMessage);
         msg.save();
       }
       // Setting auction status to inactive.
       auctions.get(i).isActive = false;
       auctions.get(i).update();
     }
   }
 }
 public void setQuantityByItemId(String itemId, int quantity) {
   CartItem cartItem = (CartItem) itemMap.get(itemId);
   cartItem.setQuantity(quantity);
 }
Exemple #21
0
 private void updateGrandTotal() {
   grandTotal = new BigDecimal(0);
   for (CartItem cartItem : cartItems.values()) {
     grandTotal = grandTotal.add(cartItem.getTotalPrice());
   }
 }
Exemple #22
0
  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    // Enable list saving
    if (evt.getPropertyName() == "account_signedin") {
      txtListName.setEnabled(!model.getAccountHandler().getCurrentAccount().isAnonymous());
      btnSave.setEnabled(!model.getAccountHandler().getCurrentAccount().isAnonymous());
    }

    // Disable list saving
    if (evt.getPropertyName() == "account_signout") {
      txtListName.setEnabled(!model.getAccountHandler().getCurrentAccount().isAnonymous());
      btnSave.setEnabled(!model.getAccountHandler().getCurrentAccount().isAnonymous());
    }

    // Add item to cart
    if (evt.getPropertyName() == "cart_additem") {
      btnCheckout.setEnabled(true);
      btnClearCart.setEnabled(true);
      pnlItem.add(new CartItem((ShoppingItem) evt.getNewValue(), model), "wrap,growx");

      lblTotalPrice.setText(
          Constants.currencyFormat.format(model.getShoppingCart().getTotal())
              + Constants.currencySuffix);
      updateColors();
    }

    // Remove item from cart
    if (evt.getPropertyName() == "cart_removeitem") {
      btnCheckout.setEnabled(!model.getShoppingCart().getItems().isEmpty());
      btnClearCart.setEnabled(!model.getShoppingCart().getItems().isEmpty());

      for (Component component : pnlItem.getComponents()) {
        if (((CartItem) component).getShoppingItem() == (ShoppingItem) evt.getNewValue()) {
          pnlItem.remove(component);
          break;
        }
      }

      lblTotalPrice.setText(
          Constants.currencyFormat.format(model.getShoppingCart().getTotal())
              + Constants.currencySuffix);
      updateColors();
    }

    // Update cart
    if (evt.getPropertyName() == "cart_updateitem") {
      for (Component component : pnlItem.getComponents()) {
        if (((CartItem) component).getShoppingItem() == (ShoppingItem) evt.getNewValue()) {
          ((CartItem) component)
              .getShoppingItem()
              .setAmount(((ShoppingItem) evt.getNewValue()).getAmount());
          break;
        }
      }

      lblTotalPrice.setText(
          Constants.currencyFormat.format(model.getShoppingCart().getTotal())
              + Constants.currencySuffix);
    }

    // Clear cart
    if (evt.getPropertyName() == "cart_clear") {
      pnlItem.removeAll();
      pnlItem.revalidate();
      repaint();
      lblTotalPrice.setText(
          Constants.currencyFormat.format(model.getShoppingCart().getTotal())
              + Constants.currencySuffix);
    }

    if (evt.getPropertyName() == "list_save") {
      @SuppressWarnings("unchecked")
      List<String> errors = (List<String>) evt.getNewValue();

      resetError(txtListName);

      if (!errors.isEmpty()) {
        if (errors.contains("name_tooshort")) {
          setError(txtListName);
        }
      }
    }
  }