Rev 21617 | 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.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.Scan;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 static final long DUMMY_VENDOR_ID = 40;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 String selectItemType;private File scanDataFile;private String invoiceNumber;private Double freightCharges ;private String purchaseComments;private Long poId;private String fileNameVal;private String purchaseId;private String purchaseOrderId;private Long warehouseId;private Long transferWarehouseId;private Warehouse warehouse;private Warehouse thirdPartyWarehouse;private Map<Long, Double> unfulfilledMap = new HashMap<Long, Double>();private Map<Long, Item> nonserializedMap = new HashMap<Long, Item>();private Map<Long, Item> serializedMap = new HashMap<Long, Item>();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+ " purchaseComments="+purchaseComments);PurchaseClient purchaseClient = new PurchaseClient();in.shop2020.purchase.PurchaseService.Client client = purchaseClient.getClient();id = "" + client.startPurchase(poId, invoiceNumber, freightCharges, purchaseComments);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(Map<String, LineItem> serialNumbersMap) throws Exception {Client warehouseClient = new WarehouseClient().getClient();List<String> serialNumbers = new ArrayList<String>(serialNumbersMap.keySet());List<InventoryItem> inventoryItems = warehouseClient.getInventoryItemsBySerailNumbers(serialNumbers);for(InventoryItem inventoryItem : inventoryItems) {log.info("serialNumber - --" + inventoryItem.getSerialNumber());if(inventoryItem.getLastScanType()!=ScanType.PURCHASE_RETURN && inventoryItem.getLastScanType()!=ScanType.DOA_REPLACED&& !inventoryItem.getLastScanType().equals(ScanType.SALE)) {LineItem lineItem = serialNumbersMap.remove(inventoryItem.getSerialNumber());exceptionList.add("Item exist 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()) {Item it = catalogClient.getItem(lineItem.getItemId());if(it.getType()==ItemType.SERIALIZED){serializedMap.put(it.getId(), it);}else{nonserializedMap.put(it.getId(), it);}items.add(it);unfulfilledMap.put(lineItem.getItemId(), lineItem.getUnfulfilledQuantity());}in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = new InventoryClient().getClient();thirdPartyWarehouse = inventoryClient.getWarehouse(warehouseId);if(thirdPartyWarehouse.getVendor().getId()==DUMMY_VENDOR_ID && thirdPartyWarehouse.getInventoryType()==InventoryType.GOOD && thirdPartyWarehouse.getWarehouseType()==WarehouseType.OURS_THIRDPARTY){warehouse = thirdPartyWarehouse;} else {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(selectItemType.equalsIgnoreCase("SERIALIZED")){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.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();//Logic to create transfer lot pending yetif(!transferLotCreate(po)){return create();}Map<String, LineItem> serialNumbersMap = new HashMap<String, LineItem>();if(selectItemType.equalsIgnoreCase("SERIALIZED")){Item item = serializedMap.get(Long.parseLong(bulkScanUploadItem));itemType = item.getType();for(in.shop2020.purchase.LineItem pItem : poLineItems){if(pItem.getItemId() == item.getId()){poLineItem = pItem;if (poLineItem.getUnfulfilledQuantity() == 0) {errorMsg = "Error occurred"+ "<br> Item uploaded is already fulfilled";addActionError(errorMsg);return create();}break;}}BufferedReader br = new BufferedReader(new FileReader(fileToCreate));long line = 1;String strLine;String[] values;while((strLine = br.readLine())!=null){if(strLine.trim().isEmpty()){continue;}if(line==1){values = strLine.split("\t");if(values.length !=3){errorMsg = errorMsg + "<br> File contains Inappropriate Content ";addActionError(errorMsg);return create();}line++;continue;// Maximum upload for an item is 500} else if (line > 501) {errorMsg = "Error Occurred"+ "<br> Can process upto 500 records only";addActionError(errorMsg);return create();} else if (poLineItem.getUnfulfilledQuantity() < line - 1){errorMsg = "Error occurred"+ "<br> SerialNumbers uploaded should not be greater than unfulfilled Quantity";addActionError(errorMsg);return create();}values = strLine.split("\t");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);logger.info(serialNumbersMap.size() + " ------ " + lineItem.getSerial_number());if (serialNumbersMap.containsKey(lineItem.getSerial_number())){errorRowsMap.put(line, "Error: Serial Number is duplicate in sheet");line++;continue;} else {serialNumbersMap.put(lineItem.getSerial_number(), lineItem);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(correctRowsMap.containsKey(line) && !errorRowsMap.containsKey(line)){lineItems.add(lineItem);}line++;}areValidSerializedItems(serialNumbersMap);}if(errorRowsMap!=null && errorRowsMap.size()>0){for(Long row : errorRowsMap.keySet()){exceptionList.add("At Row "+ row +" "+ errorRowsMap.get(row));}}if(correctRowsMap.size()==0){exceptionList.add("-- File Contains Zero Correct Records --");if(errorRowsMap!=null && errorRowsMap.size()>0){exceptionList.add("-- Data in uploaded sheet is Inappropriate --");}}if(!checkForException()) {return null;}if(id == null || Long.parseLong(id)==0) {if(!createPurchase()) {if(!checkForException()){return create();}}}WarehouseClient warehouseClient = new WarehouseClient();Client client = warehouseClient.getClient();InventoryService.Client inventoryClient = new InventoryClient().getClient();boolean checkDirectScanWarehouse = false;if(thirdPartyWarehouse.getVendor().getId()==DUMMY_VENDOR_ID && thirdPartyWarehouse.getInventoryType()==InventoryType.GOOD && thirdPartyWarehouse.getWarehouseType()==WarehouseType.OURS_THIRDPARTY){checkDirectScanWarehouse = true;}long currentWarehouseId = 0;if(!checkDirectScanWarehouse){Warehouse fulfilmentWarehouse = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, po.getSupplierId(), po.getWarehouseId(), 0).get(0);currentWarehouseId = fulfilmentWarehouse.getId();}List<InventoryItem> inventoryItems = new ArrayList<InventoryItem>();for (LineItem lineItem : serialNumbersMap.values()) {InventoryItem inventoryItem = new InventoryItem();inventoryItem.setItemId(lineItem.getItem_id());inventoryItem.setPurchaseId(Long.parseLong(id));inventoryItem.setCurrentQuantity(1);inventoryItem.setItemNumber(lineItem.getItem_number());inventoryItem.setSerialNumber(lineItem.getSerial_number());log.info("inventory Item serial number --- " + lineItem.getSerial_number());inventoryItem.setInitialQuantity(1);inventoryItem.setLastScanType(ScanType.PURCHASE);if(checkDirectScanWarehouse){inventoryItem.setPhysicalWarehouseId(po.getWarehouseId());inventoryItem.setCurrentWarehouseId(po.getWarehouseId());}else{inventoryItem.setPhysicalWarehouseId(po.getWarehouseId());inventoryItem.setCurrentWarehouseId(currentWarehouseId);}inventoryItems.add(inventoryItem);}try{client.scanPurchaseBulk(inventoryItems);successMsg = "Items scanned Successfully.<br>Check the unfulfilled Quantity for further details";addActionMessage(successMsg);}catch(Exception e){addActionError("Error - Could not scan in items due to " + e.getMessage());}} catch (Exception e) {errorMsg = errorMsg + " <br> Error while scanning items";logger.error(errorMsg, e);e.printStackTrace();}}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 String getSelectItemType() {return selectItemType;}public void setSelectItemType(String selectItemType) {this.selectItemType = selectItemType;}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;}public String getPurchaseComments() {return purchaseComments;}public void setPurchaseComments(String purchaseComments) {this.purchaseComments = purchaseComments;}public Warehouse getThirdPartyWarehouse() {return thirdPartyWarehouse;}public void setThirdPartyWarehouse(Warehouse thirdPartyWarehouse) {this.thirdPartyWarehouse = thirdPartyWarehouse;}}