Subversion Repositories SmartDukaan

Rev

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