for (OrderItem oi : request.getOisToDelete()) {
order.getOrderItems().remove(oi);
orderItemService.delete(oi);
if (oi.getParentOrderItem() != null) {
OrderItem parentItem = oi.getParentOrderItem();
parentItem.getChildOrderItems().remove(oi);
}
}
// We need to build up a map of OrderItem to which FulfillmentGroupItems reference that particular OrderItem.
// We'll also save the order item and build up a map of the unsaved items to their saved counterparts.
Map<OrderItem, List<FulfillmentGroupItem>> oiFgiMap = new HashMap<OrderItem, List<FulfillmentGroupItem>>();
Map<OrderItem, OrderItem> savedOrderItems = new HashMap<OrderItem, OrderItem>();
for (OrderItem oi : order.getOrderItems()) {
if (oi instanceof BundleOrderItem) {
// We first need to save the discrete order items that are part of this bundle. Once they're saved, we'll
// mark them and remove them from this bundle.
List<DiscreteOrderItem> doisToAdd = new ArrayList<DiscreteOrderItem>();
ListIterator<DiscreteOrderItem> li = ((BundleOrderItem) oi ).getDiscreteOrderItems().listIterator();
while (li.hasNext()) {
DiscreteOrderItem doi = li.next();
getOiFgiMap(order, oiFgiMap, doi);
DiscreteOrderItem savedDoi = (DiscreteOrderItem) orderItemService.saveOrderItem(doi);
savedOrderItems.put(doi, savedDoi);
li.remove();
doisToAdd.add(savedDoi);
}
// After the discrete order items are saved, we can re-add the saved versions to our bundle and then
// save the bundle as well.
((BundleOrderItem) oi).getDiscreteOrderItems().addAll(doisToAdd);
BundleOrderItem savedBoi = (BundleOrderItem) orderItemService.saveOrderItem(oi);
savedOrderItems.put(oi, savedBoi);
// Lastly, we'll want to go through our saved discrete order items and update the bundle that they relate
// to to the saved version of the bundle.
for (DiscreteOrderItem doi : savedBoi.getDiscreteOrderItems()) {
doi.setBundleOrderItem(savedBoi);
}
} else {
getOiFgiMap(order, oiFgiMap, oi);
savedOrderItems.put(oi, orderItemService.saveOrderItem(oi));
}
}
// Now, we'll update the orderitems in the order to their saved counterparts
ListIterator<OrderItem> li = order.getOrderItems().listIterator();
List<OrderItem> oisToAdd = new ArrayList<OrderItem>();
while (li.hasNext()) {
OrderItem oi = li.next();
OrderItem savedOi = savedOrderItems.get(oi);
oisToAdd.add(savedOi);
li.remove();
}
order.getOrderItems().addAll(oisToAdd);