Subversion Repositories SmartDukaan

Rev

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