Subversion Repositories SmartDukaan

Rev

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