Rev 13089 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.inventory.controllers;import in.shop2020.model.v1.catalog.Item;import in.shop2020.model.v1.catalog.ItemType;import in.shop2020.model.v1.inventory.InventoryService;import in.shop2020.model.v1.inventory.InventoryType;import in.shop2020.model.v1.inventory.Warehouse;import in.shop2020.model.v1.inventory.WarehouseType;import in.shop2020.model.v1.order.LineItem;import in.shop2020.purchase.Invoice;import in.shop2020.purchase.PurchaseOrder;import in.shop2020.purchase.PurchaseServiceException;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.InventoryClient;import in.shop2020.thrift.clients.PurchaseClient;import in.shop2020.thrift.clients.WarehouseClient;import in.shop2020.utils.ModelUtils;import in.shop2020.warehouse.InventoryItem;import in.shop2020.warehouse.ScanType;import in.shop2020.warehouse.WarehouseService;import in.shop2020.warehouse.WarehouseService.Client;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.ServletContext;import javax.servlet.ServletOutputStream;import org.apache.commons.io.FileUtils;import org.apache.commons.lang.StringUtils;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@SuppressWarnings("serial")@Results({ @Result(name = "redirect", type = "redirectAction", params = {"actionName", "warehouse" }) })public class BulkPurchaseController extends BaseController {private static Logger logger = LoggerFactory.getLogger(BulkPurchaseController.class);private List<String> exceptionList = new ArrayList<String>();private static final int NUM_BULK__SCAN_ITEMS = 10;private ServletContext context;private String id="";private Long transferLotId;private String itemId;private String itemNo;private String errorMsg = "";private String successMsg = "";private List<Item> items;private List<LineItem> lineItems;private String bulkScanUploadItem;private File scanDataFile;private String invoiceNumber;private Double freightCharges ;private Long poId;private String fileNameVal;private String purchaseId;private String purchaseOrderId;private Long warehouseId;private Long transferWarehouseId;private Warehouse warehouse;private Map<Long, Double> unfulfilledMap = new HashMap<Long, Double>();public String show() {resetLineItems();setItemsFromPO();return SHOW;}private void resetLineItems() {lineItems = new ArrayList<LineItem>();for (int i = 0; i < NUM_BULK__SCAN_ITEMS; i++) {LineItem lineItem = new LineItem();lineItem.setId(i);lineItem.setExtra_info("");lineItem.setSerial_number("");lineItem.setItem_number("");lineItem.setQuantity(1);lineItem.setItem_id(-1);lineItems.add(lineItem);}}public String create() {this.purchaseOrderId = request.getParameter("poId");poId = Long.parseLong(purchaseOrderId);invoiceNumber = request.getParameter("invoiceNumber");String fc = request.getParameter("freightCharges").trim();freightCharges = 0D;if(id == null ||StringUtils.isEmpty(id))id = "0";if (fc != null && !fc.isEmpty())freightCharges = Double.parseDouble(fc);return show();//return "create";}public boolean createPurchase(){try {logger.info("poId="+poId+" invoiceNumber="+invoiceNumber+" freightCharges="+freightCharges);PurchaseClient purchaseClient = new PurchaseClient();in.shop2020.purchase.PurchaseService.Client client = purchaseClient.getClient();id = "" + client.startPurchase(poId, invoiceNumber, freightCharges);logger.info("id = "+id);} catch (TTransportException e) {errorMsg = errorMsg + "<br> Error while establishing connection to the warehouse server";exceptionList.add("Error while establishing connection to the warehouse server");logger.error(errorMsg, e);} catch (TException e) {errorMsg = errorMsg+ "<br> Error while scanning in the item";exceptionList.add("Error while strating purchase");logger.error(errorMsg, e);} catch (PurchaseServiceException e) {errorMsg = errorMsg+ e.getMessage();exceptionList.add(e.getMessage());logger.error(errorMsg, e);}if (errorMsg.isEmpty())return true;else {addActionError(errorMsg);return false;}}public File getScanFileToRead(){File fileToCreate = null;if(scanDataFile!=null & fileNameVal !=null && !fileNameVal.isEmpty()){logger.info("File Name "+scanDataFile.getName());System.out.println("File Name "+scanDataFile.getName());logger.info("File Name Value "+fileNameVal);System.out.println("File Name Value "+fileNameVal);String fileName = fileNameVal;try {if(!fileName.substring(fileName.lastIndexOf(".")+1).equalsIgnoreCase("txt")){throw new Exception("File is not in expected TXT Format");}fileToCreate = new File("/tmp/", fileName);FileUtils.copyFile(this.scanDataFile, fileToCreate);} catch (Exception e) {logger.error("Error while writing file used to the local file system", e);errorMsg = e.getMessage();//addActionError(errorMsg);return null;}} else {errorMsg = errorMsg + "<br>Either No File Uploaded or file name is blank";}return fileToCreate;}public boolean transferLotCreate(PurchaseOrder po){String errMsg = "";try{if(transferLotId==null || transferLotId==0) {if(transferWarehouseId!=null && transferWarehouseId!=0) {WarehouseClient warehouseClient = new WarehouseClient();Client client = warehouseClient.getClient();InventoryService.Client inventoryClient = new InventoryClient().getClient();Warehouse fulfilmentWarehouse = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, po.getSupplierId(), po.getWarehouseId(), 0L).get(0);transferLotId = client.createTransferLot(po.getWarehouseId(), transferWarehouseId);}}} catch(Exception e){errMsg = "<br> Error while creating Transfer Lot due to : "+ e.getMessage();}if (errMsg.isEmpty()){return true;}else {errorMsg = errMsg;addActionError(errorMsg);return false;}}public File createErrorFile(List<String> errorList){try{String tmpDir = System.getProperty("java.io.tmpdir");File file = new File(tmpDir + "/ScanRecordResult.xls");BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));bufferedWriter.write(StringUtils.join(new String[] { "----Scan Response----"}, '\t'));//bufferedWriter.newLine();for(String record : errorList){bufferedWriter.newLine();bufferedWriter.write(StringUtils.join(new String[] { record }, '\t'));}bufferedWriter.close();return file;} catch (Exception e) {logger.error("Could not create file for Scan Record Result", e);return null;}}public void setResponseErrorFile(File errorFile) throws IOException{byte[] buffer = null;buffer = new byte[(int) errorFile.length()];InputStream input = null;try {int totalBytesRead = 0;input = new BufferedInputStream(new FileInputStream(errorFile));while (totalBytesRead < buffer.length) {int bytesRemaining = buffer.length - totalBytesRead;// input.read() returns -1, 0, or more :int bytesRead = input.read(buffer, totalBytesRead,bytesRemaining);if (bytesRead > 0) {totalBytesRead = totalBytesRead + bytesRead;}}/** the above style is a bit tricky: it places bytes into the* 'buffer' array; 'buffer' is an output parameter; the while* loop usually has a single iteration only.*/} finally {input.close();}response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "inline; filename="+ errorFile.getName());ServletOutputStream sos = response.getOutputStream();sos.write(buffer);sos.flush();}public boolean checkForException() throws IOException{if(exceptionList!=null && exceptionList.size()>0){File errorFile = createErrorFile(exceptionList);if(errorFile.isFile()){setResponseErrorFile(errorFile);return false;}}return true;}private void areValidSerializedItems() throws Exception {Client warehouseClient = new WarehouseClient().getClient();for (LineItem lineItem : lineItems) {if (StringUtils.isNotBlank(lineItem.getSerial_number())) {InventoryItem inventoryItem = new InventoryItem();try{inventoryItem = warehouseClient.getInventoryItem(lineItem.getSerial_number());} catch(Exception e){continue;}if(inventoryItem.getLastScanType()!=ScanType.PURCHASE_RETURN && inventoryItem.getLastScanType()!=ScanType.DOA_REPLACED) {lineItem.setExtra_info("Item scanned already.");exceptionList.add("Items Scanned already : "+ lineItem.getSerial_number());continue;}}}}private void setItemsFromPO() {try {items = new ArrayList<Item>();in.shop2020.purchase.PurchaseService.Client purchaseClient = new PurchaseClient().getClient();//PurchaseOrder purchaseOrder = purchaseClient.getPurchaseOrderForPurchase(id);PurchaseOrder purchaseOrder = purchaseClient.getPurchaseOrder(poId);warehouseId = purchaseOrder.getWarehouseId();in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = new CatalogClient().getClient();for (in.shop2020.purchase.LineItem lineItem : purchaseOrder.getLineitems()) {items.add(catalogClient.getItem(lineItem.getItemId()));unfulfilledMap.put(lineItem.getItemId(), lineItem.getUnfulfilledQuantity());}in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = new InventoryClient().getClient();warehouse = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, purchaseOrder.getSupplierId(), warehouseId, warehouseId).get(0);} catch (Exception e) {logger.error("Could not find items in PO with purchase: " + id, e);}}public String update() {if(("-1").equalsIgnoreCase(bulkScanUploadItem)){errorMsg = errorMsg +" <br> No Item Selected to Scan In";return show();}File fileToCreate = getScanFileToRead();Map<Long, String> correctRowsMap = new HashMap<Long, String>();Map<Long, String> errorRowsMap = new HashMap<Long, String>();if(fileToCreate==null){errorMsg = errorMsg +" <br> No File to read";return create();}ItemType itemType = ItemType.SERIALIZED;setItemsFromPO();lineItems = new ArrayList<LineItem>();if(fileToCreate.isFile()){try{in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = new CatalogClient().getClient();Item item = catalogClient.getItem(Long.parseLong(bulkScanUploadItem));itemType = item.getType();in.shop2020.purchase.PurchaseService.Client purchaseClient = new PurchaseClient().getClient();PurchaseOrder po = purchaseClient.getPurchaseOrder(poId);List<in.shop2020.purchase.LineItem> poLineItems = po.getLineitems();in.shop2020.purchase.LineItem poLineItem = new in.shop2020.purchase.LineItem();for(in.shop2020.purchase.LineItem pItem : poLineItems){if(pItem.getItemId() == item.getId()){poLineItem = pItem;break;}}if(!transferLotCreate(po)){return create();}BufferedReader br = new BufferedReader(new FileReader(fileToCreate));long line = 1;String strLine;String[] values;while((strLine = br.readLine())!=null){if(line==1){values = strLine.split("\t");if(values.length !=3){errorMsg = errorMsg + "<br> File contains Inappropriate Content ";addActionError(errorMsg);return create();}line++;continue;}values = strLine.split("\t");for(String s : values){logger.info("Row No "+line+" :"+s);System.out.println("Row No "+line+" :"+s);}LineItem lineItem = new LineItem();lineItem.setId(line);lineItem.setItem_id(item.getId());lineItem.setBrand(item.getBrand());lineItem.setColor(item.getColor());lineItem.setModel_name(item.getModelName());lineItem.setModel_number(item.getModelNumber());lineItem.setProductGroup(item.getProductGroup());lineItem.setNlc(poLineItem.getNlc());lineItem.setTransfer_price(poLineItem.getUnitPrice());lineItem.setUnit_price(poLineItem.getUnitPrice());if(itemType==ItemType.SERIALIZED){if(StringUtils.isNotBlank(values[0]) && StringUtils.isNotEmpty(values[0])){if(StringUtils.isNotBlank(values[1]) && StringUtils.isNotEmpty(values[1])){lineItem.setItem_number(values[0].trim());lineItem.setSerial_number(values[1].trim());lineItem.setQuantity(1);correctRowsMap.put(line, "Entries are correct in the row");}else{errorRowsMap.put(line, "Error: Serial Number Missing ");line++;continue;}}else{errorRowsMap.put(line, "Error: Item Number Missing ");line++;continue;}}if(itemType==ItemType.NON_SERIALIZED){if(StringUtils.isNotBlank(values[0]) && StringUtils.isNotEmpty(values[0])){lineItem.setItem_number(values[0].trim());lineItem.setSerial_number("");if(StringUtils.isNotBlank(values[2]) && StringUtils.isNumeric(values[2]) && Double.parseDouble(values[2]) > 0){lineItem.setQuantity(Double.parseDouble(values[2].trim()));correctRowsMap.put(line, "Entries are correct in the row ");}else{errorRowsMap.put(line, "Error: Invalid Item Quantity ");line++;continue;}} else{errorRowsMap.put(line, "Error: Item Number Missing ");line++;continue;}}if(correctRowsMap.containsKey(line) && !errorRowsMap.containsKey(line)){lineItems.add(lineItem);}line++;}if(correctRowsMap!=null && correctRowsMap.size()>0){if(errorRowsMap!=null && errorRowsMap.size()>0){for(Long row : errorRowsMap.keySet()){exceptionList.add("At Row "+ row +" "+ errorRowsMap.get(row));}}}else{exceptionList.add("-- File Contains Zero Correct Records --");if(errorRowsMap!=null && errorRowsMap.size()>0){exceptionList.add("-- Data in uploaded sheet is Inappropriate --");}}if(itemType==ItemType.SERIALIZED){areValidSerializedItems();}if(id == null || Long.parseLong(id)==0) {if(!createPurchase()) {if(!checkForException()){return create();}}}WarehouseClient warehouseClient = new WarehouseClient();Client client = warehouseClient.getClient();for (LineItem lineItem : lineItems) {InventoryItem inventoryItem = new InventoryItem();inventoryItem.setItemId(lineItem.getItem_id());inventoryItem.setPurchaseId(Long.parseLong(id));inventoryItem.setCurrentQuantity(0);inventoryItem.setItemNumber(lineItem.getItem_number());inventoryItem.setSerialNumber(lineItem.getSerial_number());inventoryItem.setInitialQuantity(new Double(lineItem.getQuantity()).longValue());inventoryItem.setPhysicalWarehouseId(po.getWarehouseId());if(!client.isAlive()){client = warehouseClient.getClient();}try{client.scan(inventoryItem, ScanType.PURCHASE, new Double(lineItem.getQuantity()).longValue(), warehouseId, (transferLotId!=null)?transferLotId:0L);if(lineItem.getSerial_number()!=null && !lineItem.getSerial_number().isEmpty()){exceptionList.add("Item with Serial Number "+ lineItem.getSerial_number() + " Scanned Successfully");}else{exceptionList.add("Item with Item Number "+ lineItem.getItem_number() + " with "+ lineItem.getQuantity() + " units Scanned Successfully");}}catch(Exception e){exceptionList.add("Error "+lineItem.getId()+" "+e.getMessage());continue;}}if(lineItems!= null && lineItems.size()!=exceptionList.size()){if(!checkForException()){return null;}}else{successMsg = "Items scanned Successfully.<br>Check the unfulfilled Quantity for further details";}} catch(Exception e){errorMsg = errorMsg + " <br> Error while scanning items";logger.error(errorMsg, e);}}return create();}public String destroy() {long id = Long.parseLong(this.id);try {PurchaseClient warehouseClient = new PurchaseClient();in.shop2020.purchase.PurchaseService.Client client = warehouseClient.getClient();client.closePurchase(id);} catch (TTransportException e) {errorMsg = errorMsg + "<br> Error while establishing connection to the warehouse server";logger.error(errorMsg, e);} catch (TException e) {errorMsg = errorMsg + "<br> Error while scanning in the item";logger.error(errorMsg, e);} catch (PurchaseServiceException e) {errorMsg = errorMsg + e.getMessage();logger.error(errorMsg, e);}return "redirect";}public List<Warehouse> getAllowedDestinationWarehousesForTransfer(long originWarehouseId){try {WarehouseService.Client warehouseClient = new WarehouseClient().getClient();List<Long> allowedWarehouseIds = warehouseClient.getAllowedDestinationWarehousesForTransfer(originWarehouseId);List<Warehouse> allowedWarehouses = new ArrayList<Warehouse>();InventoryService.Client inventoryClient = new InventoryClient().getClient();for(Long allowedWarehouseId : allowedWarehouseIds) {allowedWarehouses.add(inventoryClient.getWarehouse(allowedWarehouseId));}return allowedWarehouses;} catch(Exception e) {logger.error("Error while getting all destination warehouses for warehouseId " + warehouseId, e);return new ArrayList<Warehouse>();}}public boolean isItemScannedIn(long id){if(unfulfilledMap.get(id)> 0){return true;}return false;}public String getName(Item item){return ModelUtils.extractProductNameFromItem(item);}public void setId(String id) {this.id = id;}public String getId() {return id;}public String getErrorMessage() {return errorMsg;}public String getPurchaseOrderId() {return purchaseOrderId;}public String getServletContextPath() {return context.getContextPath();}public String getItemId() {return itemId;}public void setItemId(String itemId) {this.itemId = itemId;}public String getItemNo() {return itemNo;}public void setItemNo(String itemNo) {this.itemNo = itemNo;}public List<Item> getItems() {return items;}public void setItems(List<Item> items) {this.items = items;}public List<LineItem> getLineItems() {return lineItems;}public void setLineItems(List<LineItem> lineItems) {this.lineItems = lineItems;}public Warehouse getWarehouse() {return warehouse;}public String getInvoiceNumber() {return invoiceNumber;}public void setInvoiceNumber(String invoiceNumber) {this.invoiceNumber = invoiceNumber;}public Double getFreightCharges() {return freightCharges;}public void setFreightCharges(Double freightCharges) {this.freightCharges = freightCharges;}public Long getPoId() {return poId;}public void setPoId(Long poId) {this.poId = poId;}public Long getWarehouseId() {return warehouseId;}public void setWarehouseId(Long warehouseId) {this.warehouseId = warehouseId;}public Long getTransferWarehouseId() {return transferWarehouseId;}public void setTransferWarehouseId(Long transferWarehouseId) {this.transferWarehouseId = transferWarehouseId;}public Long getTransferLotId() {return transferLotId;}public void setTransferLotId(Long transferLotId) {this.transferLotId = transferLotId;}public String getBulkScanUploadItem() {return bulkScanUploadItem;}public void setBulkScanUploadItem(String bulkScanUploadItem) {this.bulkScanUploadItem = bulkScanUploadItem;}public File getScanDataFile() {return scanDataFile;}public void setScanDataFile(File scanDataFile) {this.scanDataFile = scanDataFile;}public String getPurchaseId() {return purchaseId;}public void setPurchaseId(String purchaseId) {this.purchaseId = purchaseId;}public String getFileNameVal() {return fileNameVal;}public void setFileNameVal(String fileNameVal) {this.fileNameVal = fileNameVal;}public String getSuccessMsg() {return successMsg;}public void setSuccessMsg(String successMsg) {this.successMsg = successMsg;}}