Subversion Repositories SmartDukaan

Rev

Rev 4824 | Rev 4826 | 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){
4823 rajveer 162
                    	long deliveryDays = logisticsClient.getLogisticsEstimation(item.getId(), DEFAULT_PINCODE, DeliveryType.PREPAID).getDeliveryTime();
163
                        if(deliveryDays == 1)
3364 chandransh 164
                            itemsDeliverableNextDay.add(rowItem);
165
                        else
166
                            itemsNotDeliverableNextDay.add(rowItem);    
167
                    }else
168
                        outOfStockItems.add(rowItem);
169
                }
170
            }
171
        } catch (TTransportException e) {
172
            logger.error("Unable to get the items from the inventory", e);
173
            return null;
174
        } catch (InventoryServiceException e) {
175
            logger.error("Error while getting the items from the inventory", e);
176
            return null;
177
        } catch (TException e) {
178
            logger.error("Error while getting the items from the inventory", e);
179
            return null;
4823 rajveer 180
		} catch (LogisticsServiceException e) {
181
	        logger.error("Error while getting estimate of the inventory", e);
182
            return null;
183
 
184
		}
3364 chandransh 185
 
186
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
187
 
188
        Workbook wb = new HSSFWorkbook();
189
 
190
        createSheet(wb, "Items Deliverable on Next Day", itemsDeliverableNextDay);
191
        createSheet(wb, "Items Not Deliverable on Next Day", itemsNotDeliverableNextDay);
192
        createSheet(wb, "Out of Stock Items", outOfStockItems);
193
 
194
        try {
195
            wb.write(baosXLS);
196
            baosXLS.close();
197
        } catch (IOException e) {
198
            logger.error("Error while streaming inventory stock report", e);
199
            return null;
200
        }
201
        return baosXLS;
202
    }
203
 
204
    private void createSheet(Workbook wb, String name, List<RowItem> items){
205
        Sheet sheet = wb.createSheet(name);
206
        short serialNo = 0;
207
        Row headerRow = sheet.createRow(serialNo++);
208
        headerRow.createCell(ID).setCellValue("Item Id");
209
        headerRow.createCell(BRAND).setCellValue("Brand");
210
        headerRow.createCell(MODEL_NUMBER).setCellValue("Model Number");
211
        headerRow.createCell(MODEL_NAME).setCellValue("Model Name");
212
        headerRow.createCell(COLOR).setCellValue("Color");
4823 rajveer 213
        headerRow.createCell(TOTAL_AVAILABILITY).setCellValue("Total Availability");
214
        headerRow.createCell(TOTAL_RESERVED).setCellValue("Total Reserved");
215
        headerRow.createCell(WH1_AVAILABILITY).setCellValue("WH1 Availabality");
216
        headerRow.createCell(WH1_RESERVED).setCellValue("WH1 Reserved");
217
        headerRow.createCell(WH5_AVALABILITY).setCellValue("WH5 Availabality");
218
        headerRow.createCell(WH5_RESERVED).setCellValue("WH5 Reserved");
219
        headerRow.createCell(WH7_AVALABILITY).setCellValue("WH7 Availabality");
220
        headerRow.createCell(WH7_RESERVED).setCellValue("WH7 Reserved");
221
 
222
        //        headerRow.createCell(WH2_A).setCellValue("WH2 Availabality");
223
        //        headerRow.createCell(WH3_A).setCellValue("WH3 Availabality");
224
        //        headerRow.createCell(WH4_A).setCellValue("WH4 Availabality");     
225
        //        headerRow.createCell(WH2_R).setCellValue("WH2 Reserved");
226
        //        headerRow.createCell(WH3_R).setCellValue("WH3 Reserved");
227
        //        headerRow.createCell(WH4_R).setCellValue("WH4 Reserved");
228
 
3364 chandransh 229
        for(RowItem item : items){
230
            Row contentRow = sheet.createRow(serialNo++);
231
            contentRow.createCell(ID).setCellValue(item.id);
232
            contentRow.createCell(BRAND).setCellValue(item.brand);
233
            contentRow.createCell(MODEL_NUMBER).setCellValue(item.modelNumber);
234
            contentRow.createCell(MODEL_NAME).setCellValue(item.modelName);
235
            contentRow.createCell(COLOR).setCellValue(item.color);
4823 rajveer 236
            contentRow.createCell(TOTAL_AVAILABILITY).setCellValue(item.totalAvailability);
237
            contentRow.createCell(TOTAL_RESERVED).setCellValue(item.totalReserved);
238
            contentRow.createCell(WH1_AVAILABILITY).setCellValue(item.wh1Availability);
239
            contentRow.createCell(WH1_RESERVED).setCellValue(item.wh1Reserved);
240
            contentRow.createCell(WH5_AVALABILITY).setCellValue(item.wh5Availability);
241
            contentRow.createCell(WH5_RESERVED).setCellValue(item.wh5Reserved);
242
            contentRow.createCell(WH7_AVALABILITY).setCellValue(item.wh7Availability);
243
            contentRow.createCell(WH7_RESERVED).setCellValue(item.wh7Reserved);
3364 chandransh 244
        }
245
    }
246
 
247
    public String getErrorMsg() {
248
        return errorMsg;
249
    }
250
 
251
    @Override
252
    public void setServletRequest(HttpServletRequest req) {
253
        this.request = req;
254
        this.session = req.getSession();
255
    }
256
 
257
    @Override
258
    public void setServletResponse(HttpServletResponse res) {
259
        this.response = res;
260
    }
261
 
262
    @Override
263
    public void setServletContext(ServletContext context) {
264
        this.context = context;
265
    }
266
 
267
    public String getServletContextPath() {
268
        return context.getContextPath();
269
    }
270
 
271
    public static void main(String[] args) {
272
        StockReportsController src = new StockReportsController();
273
        try {
274
            String userHome = System.getProperty("user.home");
275
            FileOutputStream f = new FileOutputStream(userHome + "/stock-report.xls");
276
            ByteArrayOutputStream baosXLS = src.generateInventoryStockReport();
277
            baosXLS.writeTo(f);
278
            f.close();
279
        } catch (FileNotFoundException e) {
280
            logger.error("Error creating inventory stock report", e);
281
        } catch (IOException e) {
282
            logger.error("IO error while creating inventory stock report", e);
283
        }
284
        System.out.println("Successfully generated the inventory stock report");
285
    }
286
 
287
    class RowItem {
288
        public long id;
289
        public String brand;
290
        public String modelNumber;
291
        public String modelName;
292
        public String color;
4823 rajveer 293
        public long totalAvailability = 0;
294
        public long totalReserved = 0;
295
        public long wh1Availability = 0;
296
        public long wh1Reserved = 0;
297
        public long wh5Availability = 0;
298
        public long wh5Reserved = 0;
299
        public long wh7Availability = 0;
300
        public long wh7Reserved = 0;
3364 chandransh 301
 
302
        public RowItem(Item item){
303
           id = item.getId();
304
           brand = item.getBrand();
305
           modelNumber = item.getModelNumber();
306
           modelName = item.getModelName();
307
           color = item.getColor();
4823 rajveer 308
           totalAvailability = 0;
309
           ItemInventory itemInventory = item.getItemInventory();
310
           for(Map.Entry<Long, Long> entry : itemInventory.getAvailability().entrySet()){
311
        	   long value = entry.getValue();
312
        	   switch (entry.getKey().intValue()) {
313
        	   case 1:
314
        		   wh1Availability = value;
315
        		   break;
316
        	   case 5:
317
        		   wh5Availability = value;
318
        		   break;
319
        	   case 7:
320
        		   wh7Availability = value;
321
        		   break;
322
        	   default:
323
        		   break;
324
        	   }
325
        	   totalAvailability += value;
3364 chandransh 326
           }
4823 rajveer 327
           for(Map.Entry<Long, Long> entry : itemInventory.getReserved().entrySet()){
328
        	   long value = entry.getValue();
329
        	   switch (entry.getKey().intValue()) {
330
        	   case 1:
331
        		   wh1Reserved = value;
332
        		   break;
333
        	   case 5:
334
        		   wh5Reserved = value;
335
        		   break;
336
        	   case 7:
337
        		   wh7Reserved = value;
338
        		   break;
339
        	   default:
340
        		   break;
341
        	   }
342
        	   totalReserved += value;
343
           }
3364 chandransh 344
        }
345
    }
346
}