Subversion Repositories SmartDukaan

Rev

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