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