You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.6 KiB

  1. package utils;
  2. import Math;
  3. using Lambda;
  4. import Common;
  5. class CartUtils {
  6. public static function addToCart(order:OrderSimple, productToAdd:ProductInfo, quantity:Int):OrderSimple {
  7. var products = order.products.copy();
  8. var total = order.total;
  9. var existingProduct = products.find(function(p) {
  10. return p.product.id == productToAdd.id;
  11. });
  12. if (existingProduct == null)
  13. products.push({
  14. product: productToAdd,
  15. quantity: quantity
  16. });
  17. else
  18. existingProduct.quantity += quantity;
  19. total += quantity * productToAdd.price;
  20. total = Math.round(total * 100) / 100; // to avoid calculation errors
  21. return {
  22. products: products,
  23. total: total
  24. };
  25. }
  26. public static function removeFromCart(order:OrderSimple, productToRemove:ProductInfo, ?quantity:Int):OrderSimple {
  27. var products = order.products.copy();
  28. var total = order.total;
  29. var existingProduct = products.find(function(p) {
  30. return p.product.id == productToRemove.id;
  31. });
  32. if (quantity == null)
  33. quantity = existingProduct.quantity;
  34. if (existingProduct == null)
  35. throw "Can't remove a non existing product";
  36. else if (quantity >= existingProduct.quantity)
  37. products.remove(existingProduct)
  38. else
  39. existingProduct.quantity -= quantity;
  40. if (products.length == 0)
  41. total = 0;
  42. else {
  43. total -= Math.min(quantity, existingProduct.quantity) * productToRemove.price;
  44. total = Math.round(total * 100) / 100; // to avoid calculation errors
  45. }
  46. return {
  47. products: products,
  48. total: total
  49. };
  50. }
  51. }