new Long(orderId))));
}
@Transactional
public PurchaseOrderUI update(PurchaseOrderUI uiBean) {
PurchaseOrder po = poMapper.toPersistenceBean(uiBean);
Set<PurchaseOrderItems> items = po.getItems();
PurchaseOrder existing = poRepository
.findByOrderId(uiBean.getOrderId());
if (existing == null) {
return null;
}
existing.setComments(po.getComments());
existing.setDiscount(po.getDiscount());
existing.setDueDate(po.getDueDate());
existing.setOrderDate(po.getOrderDate());
existing.setReferenceNumber(po.getReferenceNumber());
User user = userRepository.findByUsername(uiBean.getUserName());
existing.setUser(user);
existing.setItems(null);
PurchaseOrder saved = poRepository.save(existing);
long total = 0;
if (items != null && items.size() > 0) {
List<PurchaseOrderItems> existingItems = itemsRepository
.findByPo(saved);
Map<String, PurchaseOrderItems> purchasedItemsMap = new HashMap<String, PurchaseOrderItems>();
for (PurchaseOrderItems pim : items) {
purchasedItemsMap.put(pim.getProduct().getProductName(), pim);
}
Map<String, PurchaseOrderItems> existingItemsMap = new HashMap<String, PurchaseOrderItems>();
for (PurchaseOrderItems i : existingItems) {
existingItemsMap.put(i.getProduct().getProductName(), i);
}
/* Delete Purchase Order Items */
List<PurchaseOrderItems> deleteItems = new ArrayList<PurchaseOrderItems>();
for (PurchaseOrderItems deleteItem : existingItems) {
if (!purchasedItemsMap.containsKey(deleteItem.getProduct()
.getProductName())) {
deleteItems.add(deleteItem);
}
}
itemsRepository.delete(deleteItems);
/* Updating/Inserting Purchase Order Items */
List<PurchaseOrderItems> toBeSavedItems = new ArrayList<PurchaseOrderItems>();
for (PurchaseOrderItems item : items) {
PurchaseOrderItems existingItem = existingItemsMap.get(item
.getProduct().getProductName());
Product product = productRepository.findByProductName(item
.getProduct().getProductName());
PurchaseOrder order = poRepository.findByOrderId(uiBean
.getOrderId());
if (existingItem != null) {
existingItem.setQuantity(item.getQuantity());
existingItem.setUnitPrice(item.getUnitPrice());
existingItem.setDiscount(item.getDiscount());