@RequestMapping(
     value = "/purchaseOrders/client",
     method = RequestMethod.GET,
     produces = MediaType.APPLICATION_JSON_VALUE)
 public List<PurchaseOrder> getClientPurchaseOrders() {
   log.debug("REST request to get all PurchaseOrders");
   List<PurchaseOrder> byClientIsCurrentUser = purchaseOrderRepository.findByClientIsCurrentUser();
   for (PurchaseOrder p : byClientIsCurrentUser) {
     ArtWorkPiece a = p.getArtWorkPiece();
     a.setOrders(null);
   }
   return byClientIsCurrentUser;
 }
 private static void processDelete(String type, String id) {
   if ("LineItem".equals(type)) {
     LineItem lineitem = LineItem.findById(new Long(id));
     lineitem.purchaseOrder.lineItems.remove(lineitem);
     lineitem.delete();
     setCurrentUseCaseName("Line Item deleted");
   } else if ("Order".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     order.customer.purchaseOrders.remove(order);
     order.delete();
     setCurrentUseCaseName("Order deleted");
   }
 }
 private void sendMailIfChangeIsInTransit(PurchaseOrder orderOriginal, PurchaseOrder result) {
   if (orderOriginal.getState() == OrderStatus.Confirmed
       && result.getState() == OrderStatus.InProgress) {
     mailService.sentArt(orderOriginal.getClient());
   }
   if (orderOriginal.getState() == OrderStatus.InProgress
       && result.getState() == OrderStatus.Delivered) {
     mailService.deliveredArt(
         orderOriginal.getArtist(), orderOriginal.getArtWorkPiece().getTitle());
   }
 }
  /** PUT /purchaseOrders -> Updates an existing purchaseOrder. */
  @RequestMapping(
      value = "/purchaseOrders",
      method = RequestMethod.PUT,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @Timed
  public ResponseEntity<List<PurchaseOrder>> updatePurchaseOrder(
      @RequestBody PurchaseOrder purchaseOrder) throws URISyntaxException {
    log.debug("REST request to update PurchaseOrder : {}", purchaseOrder);
    if (purchaseOrder.getId() == null) {
      // return createPurchaseOrder(purchaseOrders);
    }
    PurchaseOrder orderOriginal = purchaseOrderRepository.findOne(purchaseOrder.getId());
    orderOriginal.setFollowUpId(purchaseOrder.getFollowUpId());
    orderOriginal.setState(purchaseOrder.getState());
    orderOriginal.setNotes(purchaseOrder.getNotes());
    PurchaseOrder result = purchaseOrderRepository.save(orderOriginal);
    sendMailIfChangeIsInTransit(orderOriginal, result);

    return ResponseEntity.ok()
        .headers(
            HeaderUtil.createEntityUpdateAlert("purchaseOrder", purchaseOrder.getId().toString()))
        .body(null);
  }
 private static void processUpdate(String type, String id, String att, String value) {
   if (type == null || type.trim().length() == 0) return;
   if ("Order".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     if ("paid".equals(att)) {
       Boolean oldValue = order.paid;
       if (oldValue == null) oldValue = Boolean.FALSE;
       order.paid = !oldValue;
       if (oldValue) setCurrentUseCaseName("Order unpaid");
       else setCurrentUseCaseName("Order paid");
     } else if ("customer".equals(att)) {
       if (value == null
           || value.startsWith(
               "- ")) // Do nothing if somehow the "- select a customer -" item was selected
       return;
       Customer customer = Customer.findById(new Long(value));
       order.customer = customer;
       Flash.current().success("The order has been reassigned to customer " + customer.name);
       setCurrentUseCaseName("Order reassigned");
     } else if ("notes".equals(att)) {
       order.notes = value;
       setCurrentUseCaseName("Order notes updated");
     }
     order.save();
   } else if ("Customer".equals(type)) {
     Customer customer = Customer.findById(new Long(id));
     if ("creditLimit".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       customer.creditLimit = val;
       setCurrentUseCaseName("Customer credit limit updated");
     }
     customer.save();
   } else if ("LineItem".equals(type)) {
     LineItem lineitem = LineItem.findById(new Long(id));
     if ("quantity".equals(att)) {
       Integer val = NumberFormat.parseNumber(value);
       lineitem.qtyOrdered = val;
       setCurrentUseCaseName("Line Item quantity updated");
     } else if ("unitPrice".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       lineitem.productPrice = val;
       setCurrentUseCaseName("Line Item unit price updated");
     } else if ("product".equals(att)) {
       Product product = Product.findById(new Long(value));
       lineitem.product = product;
       setCurrentUseCaseName("Line Item product changed");
     }
     lineitem.save();
   }
 }
 private static void processInsert(
     String custId, String type, String id, String att, String value) {
   if (type == null || type.trim().length() == 0) return;
   if ("LineItem".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     Product product = Product.findById(new Long(1));
     LineItem newItem = new LineItem();
     newItem.purchaseOrder = order;
     order.lineItems.add(newItem);
     newItem.product = product;
     product.lineItems.add(newItem);
     newItem.qtyOrdered = 1;
     setCurrentUseCaseName("New Line Item created");
     newItem.save();
   } else if ("Order".equals(type)) {
     Customer customer = Customer.findById(new Long(custId));
     PurchaseOrder newOrder = new PurchaseOrder();
     newOrder.customer = customer;
     newOrder.paid = Boolean.FALSE;
     newOrder.notes = "";
     setCurrentUseCaseName("New Order created");
     newOrder.save();
   }
 }
  /** POST /purchaseOrders -> Create a new purchaseOrder. */
  @RequestMapping(
      value = "/purchaseOrders",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @Timed
  public ResponseEntity<?> createPurchaseOrder(@RequestBody List<PurchaseOrder> purchaseOrders)
      throws URISyntaxException, JsonProcessingException {

    log.debug("REST request to save PurchaseOrder : {}", purchaseOrders);
    if (purchaseOrders.size() == 0) {
      return ResponseEntity.badRequest()
          .headers(HeaderUtil.createFailureAlert("purchaseOrder", "noitems", "No items selected"))
          .body("{\"error\":\"NoItems\"}");
    }
    // if (purchaseOrder.getId() != null) {
    //
    // }
    User loggedUser = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get();
    List<PurchaseOrder> initializedOrders = new ArrayList<PurchaseOrder>();
    List<PurchaseOrder> result = new ArrayList<PurchaseOrder>();
    String concatId = "";

    Iterator<PurchaseOrder> it = purchaseOrders.iterator();
    while (it.hasNext()) {
      PurchaseOrder order = it.next();
      order.setState(OrderStatus.Initial);

      order.setCreationDate(ZonedDateTime.now());

      ArtWorkPiece work = artWorkPieceRepository.findOne(order.getArtWorkPiece().getId());
      if (work.getCommercialState() != CommercialState.ForSale
          || work.getApprovalState() != ApprovalState.Approved) {
        loggedUser = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get();
        ObjectMapper mapper = new ObjectMapper();
        Set<WorkPiece> cart = loggedUser.getShoppingCart();
        String cartJSON = mapper.writeValueAsString(cart);
        return ResponseEntity.badRequest()
            .headers(
                HeaderUtil.createFailureAlert(
                    "purchaseOrder",
                    "WorkNotForSale",
                    "An artwork not for sale is trying to be selled"))
            .body("{\"error\":\"WorkNotForSale\",\"cart\":" + cartJSON + "}");
      }

      User artist = userRepository.findOneByLogin(work.getProfile().getUser().getLogin()).get();
      User client = loggedUser;
      order.setArtWorkPiece(work);
      order.setArtist(artist);
      order.setClient(client);

      Address origin;

      if (order.getArtist().getAddresses().size() > 0) {
        origin = order.getArtist().getAddresses().stream().findFirst().get();
      } else {
        loggedUser = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get();
        return ResponseEntity.badRequest()
            .headers(
                HeaderUtil.createFailureAlert(
                    "purchaseOrder", "ArtistAddressNotFound", "The artist has no address."))
            .body("{\"error\":\"ArtistAddressNotFound\"}");
      }

      Address destination = order.getDestination();
      Address billing = order.getBilling();
      origin.setId(null);
      destination.setId(null);
      billing.setId(null);
      origin = addressRepository.save(origin);
      destination = addressRepository.save(destination);
      billing = addressRepository.save(billing);
      order.setAddress(origin);
      order.setDestination(destination);
      order.setBilling(billing);

      BigDecimal price = new BigDecimal(work.getPrice());
      Long random = System.currentTimeMillis();

      BigDecimal shippingCost =
          rateWebServiceClient.send(
              random.toString(),
              origin.getCountry().getCountryCode(),
              origin.getZipPostalCode(),
              destination.getCountry().getCountryCode(),
              destination.getZipPostalCode(),
              work.getHeight().toString(),
              work.getWidth().toString(),
              (work.getDepth() != null ? work.getDepth().toString() : "1"),
              work.getPrice().toString());
      work.setShippingCost(shippingCost);
      order.setShippingCosts(shippingCost);
      BigDecimal total = price.add(shippingCost);
      order.setTotal(total);

      initializedOrders.add(order);
    }

    Iterator<PurchaseOrder> itInitialized = initializedOrders.iterator();
    ArrayList<String> createdIds = new ArrayList<>();
    while (itInitialized.hasNext()) {
      PurchaseOrder order = itInitialized.next();
      PurchaseOrder saved = purchaseOrderRepository.save(order);
      result.add(saved);
      createdIds.add(saved.getId().toString());
      concatId += "_" + saved.getId().toString();

      ArtWorkPiece artwork = order.getArtWorkPiece();
      loggedUser.getShoppingCart().remove(artwork);
      artwork.setCommercialState(CommercialState.Sold);
      artWorkPieceRepository.save(artwork);
    }

    // loggedUser.setShoppingCart(null);
    userRepository.save(loggedUser);

    String location = payPalResource.checkout(createdIds);
    ResponseEntity error = checkErrors(location);
    if (error != null) {
      return error;
    }

    return ResponseEntity.created(new URI("/api/purchaseOrders/" + concatId))
        .headers(HeaderUtil.createEntityCreationAlert("purchaseOrder", concatId))
        .body("{\"location\":\"" + location + "\"}");
  }