Subversion Repositories SmartDukaan

Rev

Rev 4878 | Rev 4914 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3364 chandransh 1
package in.shop2020.support.controllers;
2
 
3
import java.io.ByteArrayOutputStream;
4
import java.io.File;
5
import java.io.FileNotFoundException;
6
import java.io.FileOutputStream;
7
import java.io.IOException;
8
import java.util.ArrayList;
9
import java.util.Calendar;
10
import java.util.GregorianCalendar;
4878 rajveer 11
import java.util.HashMap;
12
import java.util.LinkedHashMap;
3364 chandransh 13
import java.util.List;
14
import java.util.Map;
4878 rajveer 15
import java.util.Map.Entry;
3364 chandransh 16
 
4823 rajveer 17
import in.shop2020.logistics.DeliveryType;
18
import in.shop2020.logistics.LogisticsService.Client;
19
import in.shop2020.logistics.LogisticsServiceException;
3364 chandransh 20
import in.shop2020.model.v1.catalog.InventoryServiceException;
21
import in.shop2020.model.v1.catalog.Item;
4823 rajveer 22
import in.shop2020.model.v1.catalog.ItemInventory;
3364 chandransh 23
import in.shop2020.model.v1.catalog.status;
24
import in.shop2020.support.utils.FileUtils;
25
import in.shop2020.support.utils.ReportsUtils;
26
import in.shop2020.thrift.clients.CatalogClient;
4823 rajveer 27
import in.shop2020.thrift.clients.LogisticsClient;
4878 rajveer 28
import in.shop2020.utils.CategoryManager;
3364 chandransh 29
 
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletOutputStream;
32
import javax.servlet.http.HttpServletRequest;
33
import javax.servlet.http.HttpServletResponse;
34
import javax.servlet.http.HttpSession;
35
 
36
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
4913 rajveer 37
import org.apache.poi.ss.usermodel.Cell;
3364 chandransh 38
import org.apache.poi.ss.usermodel.Row;
39
import org.apache.poi.ss.usermodel.Sheet;
40
import org.apache.poi.ss.usermodel.Workbook;
41
import org.apache.struts2.convention.annotation.InterceptorRef;
42
import org.apache.struts2.convention.annotation.InterceptorRefs;
3936 chandransh 43
import org.apache.struts2.convention.annotation.Result;
44
import org.apache.struts2.convention.annotation.Results;
3364 chandransh 45
import org.apache.struts2.interceptor.ServletRequestAware;
46
import org.apache.struts2.interceptor.ServletResponseAware;
47
import org.apache.struts2.util.ServletContextAware;
48
import org.apache.thrift.TException;
49
import org.apache.thrift.transport.TTransportException;
50
import org.slf4j.Logger;
51
import org.slf4j.LoggerFactory;
52
 
53
 
54
@InterceptorRefs({
55
    @InterceptorRef("defaultStack"),
56
    @InterceptorRef("login")
57
})
3936 chandransh 58
@Results({
59
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
60
})
3364 chandransh 61
public class StockReportsController implements ServletRequestAware, ServletResponseAware, ServletContextAware{
62
 
63
    private static Logger logger = LoggerFactory.getLogger(StockReportsController.class);    
64
 
65
    private static final String REPORT_DIR = "/inventory-report";
66
 
4823 rajveer 67
    private static final String DEFAULT_PINCODE = "110001"; 
68
    private static final long REPORT_GENERATION_INTERVAL = 1;
4830 rajveer 69
    private static final long CUT_OFF_TIME = 15;
70
    private static long NEXT_DAY_DELAY = 1;
4823 rajveer 71
 
4830 rajveer 72
    private static final int ID = 0, BRAND = 1, MODEL_NUMBER = 2, MODEL_NAME = 3, COLOR = 4, DELIVERY_DAYS = 5, TOTAL_AVAILABILITY = 6, TOTAL_RESERVED = 7;
4913 rajveer 73
	private static final int WH1_AVAILABILITY = 8, WH1_RESERVED = 9, WH5_AVALABILITY = 10, WH5_RESERVED = 11, WH7_AVALABILITY = 12, WH7_RESERVED = 13, SIMILAR_ITEMS = 14;
4823 rajveer 74
 
3364 chandransh 75
    private HttpSession session;
76
    private HttpServletRequest request;
77
    private HttpServletResponse response;
78
    private ServletContext context;
79
 
80
    private String errorMsg = "";
81
 
82
    public String index(){
83
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath())) {
3936 chandransh 84
            return "authfail";
3364 chandransh 85
        }
86
        return "index";
87
    }
88
 
4823 rajveer 89
    public String create() throws NumberFormatException, IOException{
3364 chandransh 90
 
91
        Calendar date = new GregorianCalendar();
92
        int year = date.get(Calendar.YEAR);
93
        int month = date.get(Calendar.MONTH) +1;
94
        int day = date.get(Calendar.DAY_OF_MONTH);
4830 rajveer 95
        int hour = date.get(Calendar.HOUR_OF_DAY);
4823 rajveer 96
        long currentTimestamp = date.getTimeInMillis();
4824 rajveer 97
        String lastTimestampString = org.apache.commons.io.FileUtils.readFileToString(new File(REPORT_DIR + File.separator + "last.timestamp"));
98
        lastTimestampString = lastTimestampString.replace("\"", "").replace("\n", "");
99
        long lastTimestamp = Long.parseLong(lastTimestampString);
3364 chandransh 100
 
4823 rajveer 101
        String filename = "inventory-report." + year + "-" + month + "-" + day + "-" + lastTimestamp + ".xls";
4830 rajveer 102
        if(hour >= CUT_OFF_TIME){
103
        	NEXT_DAY_DELAY = 2;
104
        }else{
105
        	NEXT_DAY_DELAY = 1;
106
        }
4825 rajveer 107
        if(currentTimestamp - lastTimestamp > REPORT_GENERATION_INTERVAL*60*60*1000){
4823 rajveer 108
        	filename = "inventory-report." + year + "-" + month + "-" + day + "-" + currentTimestamp + ".xls";
109
        	File inventoryReportFile = new File(REPORT_DIR + File.separator + filename);
3364 chandransh 110
            ByteArrayOutputStream baosXLS = generateInventoryStockReport();
111
            if (baosXLS == null) {
112
                errorMsg = "Could not get output";
113
                return "index";
114
            }
115
 
116
            try {
117
                FileOutputStream f = new FileOutputStream(inventoryReportFile);
118
                baosXLS.writeTo(f);
119
                f.close();
4823 rajveer 120
                org.apache.commons.io.FileUtils.writeStringToFile(new File(REPORT_DIR + File.separator + "last.timestamp"), currentTimestamp+"");
3364 chandransh 121
            } catch (FileNotFoundException e) {
122
                logger.error("Error while writing the inventory report", e);
123
                return "index";
124
            } catch (IOException e) {
125
                logger.error("Error while writing the inventory report", e);
126
                return "index";
127
            }
128
        }
129
 
130
        response.setContentType("application/vnd.ms-excel");
131
        response.setHeader("Content-disposition", "inline; filename=" + filename);
132
        try {
133
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
134
            baos.write(FileUtils.getBytesFromFile(new File(REPORT_DIR + File.separator + filename)));
135
            ServletOutputStream sos = response.getOutputStream();
136
            baos.writeTo(sos);
137
            sos.flush();
138
            errorMsg = "Report generated";
139
        } catch (IOException e) {
140
            logger.error("Unable to stream the inventory stock report", e);
141
            errorMsg = "Failed to write to response.";
142
        }
143
        return "index";
144
    }
145
 
146
    private ByteArrayOutputStream generateInventoryStockReport(){
4878 rajveer 147
    	Map<String, Map<String, List<RowItem>>> categoryWiseStock = new LinkedHashMap<String, Map<String, List<RowItem>>>();
148
    	String nextDay = "Deliverable on Next Day";
149
    	String notNextDay = "Not Deliverable on Next Day";
150
    	String notAvailable = "Out of Stock";
4823 rajveer 151
        LogisticsClient logisticsServiceClient;
3364 chandransh 152
        CatalogClient catalogClientService;
153
        try {
154
            catalogClientService = new CatalogClient();
4823 rajveer 155
            logisticsServiceClient = new LogisticsClient();
3364 chandransh 156
            in.shop2020.model.v1.catalog.InventoryService.Client client = catalogClientService.getClient();
157
            List<Item> items = client.getAllItems(false);
4823 rajveer 158
			Client logisticsClient = logisticsServiceClient.getClient();
3364 chandransh 159
 
4878 rajveer 160
			CategoryManager catm = CategoryManager.getCategoryManager();
4823 rajveer 161
			for(Item item : items){
4878 rajveer 162
				status state = item.getItemStatus();
3364 chandransh 163
                switch(state){
164
                case IN_PROCESS:
165
                case CONTENT_COMPLETE:
166
                case DELETED:
167
                case PHASED_OUT:
168
                    continue;
169
                case PAUSED:
170
                case PAUSED_BY_RISK:
171
                case ACTIVE:
4878 rajveer 172
                	if(item.getCategory() == -1 || item.getCategory() == 0){
173
                		continue;
174
                	}
175
                	String category = catm.getCategory(catm.getCategory(item.getCategory()).getParent_category_id()).getLabel();
176
 
177
                	Map<String, List<RowItem>> sheetsMap = categoryWiseStock.get(category);
178
                	if(sheetsMap ==  null){
179
                		sheetsMap = new HashMap<String, List<RowItem>>();
180
                		categoryWiseStock.put(category, sheetsMap);
181
                		sheetsMap.put(nextDay, new ArrayList<RowItem>());
182
                		sheetsMap.put(notNextDay, new ArrayList<RowItem>());
183
                		sheetsMap.put(notAvailable, new ArrayList<RowItem>());
184
                	}
185
 
186
 
187
                	long deliveryDays = 3;
4830 rajveer 188
                	try{
4878 rajveer 189
 
4830 rajveer 190
                		deliveryDays = logisticsClient.getLogisticsEstimation(item.getId(), DEFAULT_PINCODE, DeliveryType.PREPAID).getDeliveryTime();
191
                	}catch (LogisticsServiceException e) {
192
                		logger.error("Error while getting estimate of the inventory for item " + item.getId(), e);
193
                	}
194
                	RowItem rowItem = new RowItem(item, deliveryDays);
195
                	if(state == status.ACTIVE){
196
                    	if(deliveryDays == NEXT_DAY_DELAY)
4878 rajveer 197
                    		sheetsMap.get(nextDay).add(rowItem);
3364 chandransh 198
                        else
4878 rajveer 199
                        	sheetsMap.get(notNextDay).add(rowItem);    
4913 rajveer 200
                    }else{
4878 rajveer 201
                    	sheetsMap.get(notAvailable).add(rowItem);
4913 rajveer 202
                    	List<Item> similaritems= client.getAllSimilarItems(item.getId());
203
                    	if(similaritems!=null){
204
                    		boolean isFirst = true;
205
                    		for(Item item1: similaritems){
206
                    			if(!isFirst) rowItem.similarItems += "\n";
207
                    			rowItem.similarItems = rowItem.similarItems + item1.getBrand() + " " + item1.getModelName() + " " + item1.getModelNumber() + " " + item1.getColor();
208
                    		}
209
                    	}
210
                    }
3364 chandransh 211
                }
212
            }
213
        } catch (TTransportException e) {
214
            logger.error("Unable to get the items from the inventory", e);
215
            return null;
216
        } catch (InventoryServiceException e) {
217
            logger.error("Error while getting the items from the inventory", e);
218
            return null;
219
        } catch (TException e) {
220
            logger.error("Error while getting the items from the inventory", e);
221
            return null;
4823 rajveer 222
		}
3364 chandransh 223
 
224
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
225
 
226
        Workbook wb = new HSSFWorkbook();
227
 
4878 rajveer 228
//        for(String category: categoryWiseStock.keySet()){
229
//        	Map<String, List<RowItem>> value = categoryWiseStock.get(category);  
230
//        	createSheet(wb, category + " - " + nextDay, value.get(nextDay));
231
//        	createSheet(wb, category + " - " + notNextDay, value.get(notNextDay));
232
//        	createSheet(wb, category + " - " + notAvailable, value.get(notAvailable));
233
//        }
3364 chandransh 234
 
4878 rajveer 235
        //Hardcoding to maintain category
236
        List<String> categories = new ArrayList<String>();
237
        categories.add("Mobile Phones");
238
        categories.add("Tablets");
239
        categories.add("Mobile Accessories");
240
        categories.add("Laptops");
241
        categories.add("Laptop Accessories");
242
        for(String category: categories){
243
        	Map<String, List<RowItem>> value = categoryWiseStock.get(category);  
244
        	createSheet(wb, category + " - " + nextDay, value.get(nextDay));
245
        	createSheet(wb, category + " - " + notNextDay, value.get(notNextDay));
246
        	createSheet(wb, category + " - " + notAvailable, value.get(notAvailable));
247
        }
248
 
249
 
3364 chandransh 250
        try {
251
            wb.write(baosXLS);
252
            baosXLS.close();
253
        } catch (IOException e) {
254
            logger.error("Error while streaming inventory stock report", e);
255
            return null;
256
        }
257
        return baosXLS;
258
    }
259
 
260
    private void createSheet(Workbook wb, String name, List<RowItem> items){
261
        Sheet sheet = wb.createSheet(name);
262
        short serialNo = 0;
263
        Row headerRow = sheet.createRow(serialNo++);
264
        headerRow.createCell(ID).setCellValue("Item Id");
265
        headerRow.createCell(BRAND).setCellValue("Brand");
266
        headerRow.createCell(MODEL_NUMBER).setCellValue("Model Number");
267
        headerRow.createCell(MODEL_NAME).setCellValue("Model Name");
268
        headerRow.createCell(COLOR).setCellValue("Color");
4830 rajveer 269
        headerRow.createCell(DELIVERY_DAYS).setCellValue("Delivery Days");
4823 rajveer 270
        headerRow.createCell(TOTAL_AVAILABILITY).setCellValue("Total Availability");
271
        headerRow.createCell(TOTAL_RESERVED).setCellValue("Total Reserved");
4830 rajveer 272
        headerRow.createCell(WH1_AVAILABILITY).setCellValue("901 Availabality");
273
        headerRow.createCell(WH1_RESERVED).setCellValue("901 Reserved");
274
        headerRow.createCell(WH5_AVALABILITY).setCellValue("9D2 Availabality");
275
        headerRow.createCell(WH5_RESERVED).setCellValue("9D2 Reserved");
276
        headerRow.createCell(WH7_AVALABILITY).setCellValue("MP Availabality");
277
        headerRow.createCell(WH7_RESERVED).setCellValue("MP Reserved");
4913 rajveer 278
        headerRow.createCell(SIMILAR_ITEMS).setCellType(Cell.CELL_TYPE_STRING);
279
        headerRow.getCell(SIMILAR_ITEMS).setCellValue("Similar Items");
280
 
4823 rajveer 281
        //        headerRow.createCell(WH2_A).setCellValue("WH2 Availabality");
282
        //        headerRow.createCell(WH3_A).setCellValue("WH3 Availabality");
283
        //        headerRow.createCell(WH4_A).setCellValue("WH4 Availabality");     
284
        //        headerRow.createCell(WH2_R).setCellValue("WH2 Reserved");
285
        //        headerRow.createCell(WH3_R).setCellValue("WH3 Reserved");
286
        //        headerRow.createCell(WH4_R).setCellValue("WH4 Reserved");
287
 
3364 chandransh 288
        for(RowItem item : items){
289
            Row contentRow = sheet.createRow(serialNo++);
290
            contentRow.createCell(ID).setCellValue(item.id);
291
            contentRow.createCell(BRAND).setCellValue(item.brand);
292
            contentRow.createCell(MODEL_NUMBER).setCellValue(item.modelNumber);
293
            contentRow.createCell(MODEL_NAME).setCellValue(item.modelName);
294
            contentRow.createCell(COLOR).setCellValue(item.color);
4830 rajveer 295
            contentRow.createCell(DELIVERY_DAYS).setCellValue(item.deliveryEstimate);
4823 rajveer 296
            contentRow.createCell(TOTAL_AVAILABILITY).setCellValue(item.totalAvailability);
297
            contentRow.createCell(TOTAL_RESERVED).setCellValue(item.totalReserved);
298
            contentRow.createCell(WH1_AVAILABILITY).setCellValue(item.wh1Availability);
299
            contentRow.createCell(WH1_RESERVED).setCellValue(item.wh1Reserved);
300
            contentRow.createCell(WH5_AVALABILITY).setCellValue(item.wh5Availability);
301
            contentRow.createCell(WH5_RESERVED).setCellValue(item.wh5Reserved);
302
            contentRow.createCell(WH7_AVALABILITY).setCellValue(item.wh7Availability);
303
            contentRow.createCell(WH7_RESERVED).setCellValue(item.wh7Reserved);
4913 rajveer 304
            contentRow.createCell(SIMILAR_ITEMS).setCellValue(item.similarItems);
3364 chandransh 305
        }
4913 rajveer 306
        sheet.autoSizeColumn(SIMILAR_ITEMS);
307
 
3364 chandransh 308
    }
309
 
310
    public String getErrorMsg() {
311
        return errorMsg;
312
    }
313
 
314
    @Override
315
    public void setServletRequest(HttpServletRequest req) {
316
        this.request = req;
317
        this.session = req.getSession();
318
    }
319
 
320
    @Override
321
    public void setServletResponse(HttpServletResponse res) {
322
        this.response = res;
323
    }
324
 
325
    @Override
326
    public void setServletContext(ServletContext context) {
327
        this.context = context;
328
    }
329
 
330
    public String getServletContextPath() {
331
        return context.getContextPath();
332
    }
333
 
334
    public static void main(String[] args) {
335
        StockReportsController src = new StockReportsController();
336
        try {
337
            String userHome = System.getProperty("user.home");
338
            FileOutputStream f = new FileOutputStream(userHome + "/stock-report.xls");
339
            ByteArrayOutputStream baosXLS = src.generateInventoryStockReport();
340
            baosXLS.writeTo(f);
341
            f.close();
342
        } catch (FileNotFoundException e) {
343
            logger.error("Error creating inventory stock report", e);
344
        } catch (IOException e) {
345
            logger.error("IO error while creating inventory stock report", e);
346
        }
347
        System.out.println("Successfully generated the inventory stock report");
348
    }
349
 
350
    class RowItem {
351
        public long id;
352
        public String brand;
353
        public String modelNumber;
354
        public String modelName;
355
        public String color;
4830 rajveer 356
        public long deliveryEstimate = 0;
4823 rajveer 357
        public long totalAvailability = 0;
358
        public long totalReserved = 0;
359
        public long wh1Availability = 0;
360
        public long wh1Reserved = 0;
361
        public long wh5Availability = 0;
362
        public long wh5Reserved = 0;
363
        public long wh7Availability = 0;
364
        public long wh7Reserved = 0;
4913 rajveer 365
        public String similarItems = "";
3364 chandransh 366
 
4830 rajveer 367
        public RowItem(Item item, long estimate){
3364 chandransh 368
           id = item.getId();
369
           brand = item.getBrand();
370
           modelNumber = item.getModelNumber();
371
           modelName = item.getModelName();
372
           color = item.getColor();
4830 rajveer 373
           deliveryEstimate = estimate;
4823 rajveer 374
           totalAvailability = 0;
375
           ItemInventory itemInventory = item.getItemInventory();
376
           for(Map.Entry<Long, Long> entry : itemInventory.getAvailability().entrySet()){
377
        	   long value = entry.getValue();
378
        	   switch (entry.getKey().intValue()) {
379
        	   case 1:
380
        		   wh1Availability = value;
381
        		   break;
382
        	   case 5:
383
        		   wh5Availability = value;
384
        		   break;
385
        	   case 7:
386
        		   wh7Availability = value;
387
        		   break;
388
        	   default:
389
        		   break;
390
        	   }
391
        	   totalAvailability += value;
3364 chandransh 392
           }
4823 rajveer 393
           for(Map.Entry<Long, Long> entry : itemInventory.getReserved().entrySet()){
394
        	   long value = entry.getValue();
395
        	   switch (entry.getKey().intValue()) {
396
        	   case 1:
397
        		   wh1Reserved = value;
398
        		   break;
399
        	   case 5:
400
        		   wh5Reserved = value;
401
        		   break;
402
        	   case 7:
403
        		   wh7Reserved = value;
404
        		   break;
405
        	   default:
406
        		   break;
407
        	   }
408
        	   totalReserved += value;
409
           }
3364 chandransh 410
        }
411
    }
412
}