Subversion Repositories SmartDukaan

Rev

Rev 3488 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3444 vikas 1
package in.shop2020.web;
2
 
3
import in.shop2020.model.Item;
4
import in.shop2020.model.ItemActivityWithSource;
5
import in.shop2020.server.ItemActivityWithSourceRepository;
6
import in.shop2020.server.ItemRepository;
7
 
8
import java.text.ParseException;
9
import java.text.SimpleDateFormat;
10
import java.util.ArrayList;
11
import java.util.Calendar;
12
import java.util.Date;
13
import java.util.HashMap;
14
import java.util.HashSet;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Map.Entry;
18
import java.util.Set;
19
import java.util.TimeZone;
20
 
21
import javax.servlet.http.HttpServlet;
22
import javax.servlet.http.HttpServletRequest;
23
import javax.servlet.http.HttpServletResponse;
24
 
25
import com.google.appengine.api.datastore.DatastoreService;
26
import com.google.appengine.api.datastore.DatastoreServiceFactory;
27
import com.google.appengine.api.datastore.Entity;
28
import com.google.appengine.api.datastore.PreparedQuery;
29
import com.google.appengine.api.datastore.Query;
30
 
31
public class DailyProductWithSourceAggregatorServlet extends HttpServlet {
32
    private static final long serialVersionUID = -8236918415987438049L;
33
    private static final String KIND = "DataLog";
34
    private static final String SESSION_ID_FILED = "sessionId";
35
    private static final String ITEMID_FILED = "itemId";
36
    private static final String ITEMIDS_FILED = "itemIds";
37
    private static final String PRODUCTNAME_FILED = "productName";
38
    private static final String EVENTTYPE_FILED = "eventType";
39
    private static final String DATE_FILED = "date";
40
    private static final String FIRST_SOURCE_FILED = "firstSource";
41
    private static final String SESSION_SOURCE_FILED = "source";
42
 
43
 
44
    private static final String PRODUCT_VIEW_EVENT = "PRODUCT_VIEW";
45
    private static final String ADD_TO_CART_EVENT = "ADD_TO_CART";
46
    private static final String DELETE_FROM_CART_EVENT = "DELETE_FROM_CART";
47
    private static final String RESEARCH_ADD_EVENT = "RESEARCH_ADD";
48
    private static final String RESEARCH_DELETE_EVENT = "RESEARCH_DELETE";
49
    private static final String SHIPPING_ACCESS_EVENT = "SHIPPINIG_ACCESS";
50
    private static final String PAYMENT_SUCCESS_EVENT = "PAYMENT_SUCCESS";
51
    private static final String ORDER_CREATION_EVENT = "ORDER_CREATION";
52
    private static final String PAYMENT_FAILURE_EVENT = "PAYMENT_FAILURE";
53
    private static final String PROCEED_TO_PAY_EVENT = "PROCEED_TO_PAY";
54
    private static final String NEW_SESSION_EVENT = "NEW_SESSION";
55
 
56
    private static final String VIEW_COUNT_KEY = "ViewCount";
57
    private static final String UNIQUE_VIEW_COUNT_KEY = "UniqueViewCount";
58
    private static final String ADD_TO_CART_COUNT_KEY = "AddToCartCount";
59
    private static final String UNIQUE_ADD_TO_CART_COUNT_KEY = "UniqueAddToCartCount";
60
    private static final String DELETE_FROM_CART_COUNT_KEY = "DeleteFromCartCount";
61
    private static final String UNIQUE_DELETE_FROM_CART_COUNT_KEY = "UniqueDeleteFromCartCount";
62
    private static final String ADD_TO_RESEARCH_COUNT_KEY = "AddToResearchCount";
63
    private static final String UNIQUE_ADD_TO_RESEARCH_COUNT_KEY = "UniqueAddToResearchCount";
64
    private static final String DELETE_FROM_RESEARCH_COUNT_KEY = "DeleteFromResearchCount";
65
    private static final String UNIQUE_DELETE_FROM_RESEARCH_COUNT_KEY = "UniqueDeleteFromResearchCount";
66
    private static final String SHIPPING_ACCESS_COUNT_KEY = "ShippingAccessCount";
67
    private static final String UNIQUE_SHIPPING_ACCESS_COUNT_KEY = "UniqueShippingAccessCount";
68
    private static final String PAYMENT_SUCCESS_COUNT_KEY = "PaymentSuccessCount";
69
    private static final String UNIQUE_PAYMENT_SUCCESS_COUNT_KEY = "UniquePaymentSuccessCount";
70
    private static final String ORDER_CREATION_COUNT_KEY = "OrderCreationCount";
71
    private static final String UNIQUE_ORDER_CREATION_COUNT_KEY = "UniqueOrderCreationCount";
72
    private static final String PAYMENT_FAILURE_COUNT_KEY = "PaymentFailureCount";
73
    private static final String UNIQUE_PAYMENT_FAILURE_COUNT_KEY = "UniquePaymentFailureCount";
74
    private static final String PROCEED_TO_PAY_COUNT_KEY = "ProceedToPayCount";
75
    private static final String UNIQUE_PROCEED_TO_PAY_COUNT_KEY = "UniqueProceedToPayCount";
76
 
77
    private static final String FIRST_SOURCE_KEY = "FirstSource";
78
    private static final String SESSION_SOURCE_KEY = "SessionSource";
79
 
80
    private Map<Long, Item> itemsMap = new HashMap<Long, Item>();
81
    private Map<Long, Item> itemsCatalogIdMap = new HashMap<Long, Item>();
82
    private Map<String, Item> itemsNameMap = new HashMap<String, Item>();
83
    private Map<String, Map<String, Long>> itemsResultMap = new HashMap<String, Map<String, Long>>();
84
 
85
    private Map<String, Map<String, String>> sessionIdSourceMap = new HashMap<String, Map<String,String>>();
86
 
87
    private Date fromDate;
88
    private Date toDate;
89
    private DatastoreService datastore;
90
 
91
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
92
        datastore = DatastoreServiceFactory.getDatastoreService();
93
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
94
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("IST"));
95
        String dateStr = req.getParameter("date");  
96
        if (dateStr != null && !dateStr.isEmpty()) {
97
            try {
98
                cal.setTime(sdf.parse(dateStr));
99
                cal.add(Calendar.DAY_OF_MONTH, 1);
100
            } catch (ParseException e) {
101
                e.printStackTrace();
102
            }
103
        }
104
        cal.set(Calendar.HOUR_OF_DAY, 0);  
105
        cal.set(Calendar.MINUTE, 0);  
106
        cal.set(Calendar.SECOND, 0);  
107
        cal.set(Calendar.MILLISECOND, 0);
108
        toDate = cal.getTime();
109
        cal.add(Calendar.DAY_OF_MONTH, -1);
110
        fromDate = cal.getTime();
111
 
112
        ItemRepository itemRepository = new ItemRepository();
113
        List<Item> items = itemRepository.getAll();
114
        for (Item item : items) {
115
            itemsMap.put(item.getId(), item);
116
            itemsCatalogIdMap.put(item.getCatalogId(), item);
117
            itemsNameMap.put(item.getName().trim(), item);
118
        }
119
 
120
        UpdateViewCount(PRODUCT_VIEW_EVENT, VIEW_COUNT_KEY, UNIQUE_VIEW_COUNT_KEY);
121
 
122
        UpdateItemIdEventCount(ADD_TO_CART_EVENT, ADD_TO_CART_COUNT_KEY, UNIQUE_ADD_TO_CART_COUNT_KEY, false);
123
        UpdateItemIdEventCount(DELETE_FROM_CART_EVENT, DELETE_FROM_CART_COUNT_KEY, UNIQUE_DELETE_FROM_CART_COUNT_KEY, false);
124
        UpdateItemIdEventCount(RESEARCH_ADD_EVENT, ADD_TO_RESEARCH_COUNT_KEY, UNIQUE_ADD_TO_RESEARCH_COUNT_KEY, true);
125
        UpdateItemIdEventCount(RESEARCH_DELETE_EVENT, DELETE_FROM_RESEARCH_COUNT_KEY, UNIQUE_DELETE_FROM_RESEARCH_COUNT_KEY, true);
126
 
127
        UpdateItemIdEventCount(SHIPPING_ACCESS_EVENT, SHIPPING_ACCESS_COUNT_KEY, UNIQUE_SHIPPING_ACCESS_COUNT_KEY, false);
128
        UpdateItemIdEventCount(PAYMENT_SUCCESS_EVENT, PAYMENT_SUCCESS_COUNT_KEY, UNIQUE_PAYMENT_SUCCESS_COUNT_KEY, false);
129
        UpdateItemIdEventCount(ORDER_CREATION_EVENT, ORDER_CREATION_COUNT_KEY, UNIQUE_ORDER_CREATION_COUNT_KEY, false);
130
        UpdateItemIdEventCount(PAYMENT_FAILURE_EVENT, PAYMENT_FAILURE_COUNT_KEY, UNIQUE_PAYMENT_FAILURE_COUNT_KEY, false);
131
        UpdateItemIdEventCount(PROCEED_TO_PAY_EVENT, PROCEED_TO_PAY_COUNT_KEY, UNIQUE_PROCEED_TO_PAY_COUNT_KEY, false);
132
 
133
        List<ItemActivityWithSource> itemActivities = new ArrayList<ItemActivityWithSource>();
134
        ItemActivityWithSourceRepository itemActivityRepository = new ItemActivityWithSourceRepository();
135
        for (Entry<String, Map<String, Long>> entry : itemsResultMap.entrySet()) {
136
            String key = (String)entry.getKey();
137
            Map<String, Long> itemMap = (Map<String, Long>)entry.getValue();
138
 
139
            String [] keyItems = key.split("_");
140
 
141
            Boolean isPaidFirstSource = keyItems[0].equals("0")? false : true;
142
            String firstSource = keyItems[1];
143
            Boolean isPaidSessionSource = keyItems[2].equals("0")? false : true;
144
            String sessionSource = keyItems[3];
145
            Long catalogItemId = Long.parseLong(keyItems[4]);
146
 
147
            ItemActivityWithSource itemActivity = new ItemActivityWithSource();
148
            itemActivity.setIsPaidFirstSource(isPaidFirstSource);
149
            itemActivity.setFirstSource(firstSource);
150
            itemActivity.setIsPaidSessionSource(isPaidSessionSource);
151
            itemActivity.setSessionSource(sessionSource);
152
            itemActivity.setCatalogId(catalogItemId);
153
            itemActivity.setDate(fromDate);
154
 
155
            itemActivity.setView(itemMap.get(VIEW_COUNT_KEY));
156
            itemActivity.setAddToCart(itemMap.get(ADD_TO_CART_COUNT_KEY));
157
            itemActivity.setAddToResearch(itemMap.get(ADD_TO_RESEARCH_COUNT_KEY));
158
            itemActivity.setDeleteFromCart(itemMap.get(DELETE_FROM_CART_COUNT_KEY));
159
            itemActivity.setDeleteFromResearch(itemMap.get(DELETE_FROM_RESEARCH_COUNT_KEY));
160
            itemActivity.setShippingAccess(itemMap.get(SHIPPING_ACCESS_COUNT_KEY));
161
            itemActivity.setPaymentSuccess(itemMap.get(PAYMENT_SUCCESS_COUNT_KEY));
162
            itemActivity.setOrderCreation(itemMap.get(ORDER_CREATION_COUNT_KEY));
163
            itemActivity.setPaymentFailure(itemMap.get(PAYMENT_FAILURE_COUNT_KEY));
164
            itemActivity.setProceedToPay(itemMap.get(PROCEED_TO_PAY_COUNT_KEY));
165
 
166
            itemActivity.setUniqueView(itemMap.get(UNIQUE_VIEW_COUNT_KEY));
167
            itemActivity.setUniqueAddToCart(itemMap.get(UNIQUE_ADD_TO_CART_COUNT_KEY));
168
            itemActivity.setUniqueAddToResearch(itemMap.get(UNIQUE_ADD_TO_RESEARCH_COUNT_KEY));
169
            itemActivity.setUniqueDeleteFromCart(itemMap.get(UNIQUE_DELETE_FROM_CART_COUNT_KEY));
170
            itemActivity.setUniqueDeleteFromResearch(itemMap.get(UNIQUE_ADD_TO_RESEARCH_COUNT_KEY));
171
            itemActivity.setUniqueShippingAccess(itemMap.get(UNIQUE_SHIPPING_ACCESS_COUNT_KEY));
172
            itemActivity.setUniquePaymentSuccess(itemMap.get(UNIQUE_PAYMENT_SUCCESS_COUNT_KEY));
173
            itemActivity.setUniqueOrderCreation(itemMap.get(UNIQUE_ORDER_CREATION_COUNT_KEY));
174
            itemActivity.setUniquePaymentFailure(itemMap.get(UNIQUE_PAYMENT_FAILURE_COUNT_KEY));
175
            itemActivity.setUniqueProceedToPay(itemMap.get(UNIQUE_PROCEED_TO_PAY_COUNT_KEY));
176
 
177
            itemActivities.add(itemActivity);
178
        }
179
        itemActivityRepository.createAll(itemActivities);
180
    }
181
 
182
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
183
        doPost(req, resp);
184
    }
185
 
186
    private void UpdateViewCount(String event, String viewCountKey, String uniqueViewCountKey) {
187
        Query query = new Query(KIND);
188
        query.addFilter(EVENTTYPE_FILED, Query.FilterOperator.EQUAL, event);
189
        query.addFilter(DATE_FILED, Query.FilterOperator.GREATER_THAN_OR_EQUAL, fromDate);
190
        query.addFilter(DATE_FILED, Query.FilterOperator.LESS_THAN, toDate);
191
        PreparedQuery pq = datastore.prepare(query);
192
        Set<String> uniqueSet = new HashSet<String>();
193
        for (Entity result : pq.asIterable()) {
194
            String sessionId = (String)result.getProperty(SESSION_ID_FILED);
195
            String firstSource = getSource(sessionId, FIRST_SOURCE_KEY);
196
            String sessionSource = getSource(sessionId, SESSION_SOURCE_KEY);
197
            String paidFirstSource = "0";
198
            String paidSessionSource = "0";
199
            if (firstSource.startsWith("PAID :")) {
200
                paidFirstSource = "1";
201
            }
202
            if (sessionSource.startsWith("PAID :")) {
203
                paidSessionSource = "1";
204
            }
205
            firstSource = firstSource.replaceAll(".*http[s]?://", "").replaceAll("/.*", "");
206
            sessionSource = sessionSource.replaceAll(".*http[s]?://", "").replaceAll("/.*", "");
207
            Long catalogItemId = (Long)result.getProperty(ITEMID_FILED);
208
            if(catalogItemId == null) {
209
                String name = (String)result.getProperty(PRODUCTNAME_FILED);
210
                if (itemsNameMap.containsKey(name.trim())) {
211
                    catalogItemId = itemsNameMap.get(name.trim()).getCatalogId();
212
                }
213
            }
214
            String key = paidFirstSource + "_" + firstSource + "_"
215
                    + paidSessionSource + "_" + sessionSource + "_"
216
                    + catalogItemId;
217
            if (itemsResultMap.containsKey(key)) {
218
                Map<String, Long> itemMap = itemsResultMap.get(key);
219
                if (itemMap.containsKey(VIEW_COUNT_KEY)) {
220
                    Long count = itemMap.get(VIEW_COUNT_KEY);
221
                    itemMap.put(VIEW_COUNT_KEY, ++count);
222
                }
223
                else {
224
                    itemMap.put(VIEW_COUNT_KEY, 1l);
225
                }
226
            }
227
            else {
228
                Map<String, Long> itemMap = new HashMap<String, Long>();
229
                itemMap.put(VIEW_COUNT_KEY, 1l);
230
                itemsResultMap.put(key, itemMap);
231
            }
232
            String uniqueKey = sessionId + "_" + catalogItemId;
233
            if (!uniqueSet.contains(uniqueKey)) {
234
                Map<String, Long> itemMap = itemsResultMap.get(key);
235
                if (itemMap.containsKey(UNIQUE_VIEW_COUNT_KEY)) {
236
                    Long count = itemMap.get(UNIQUE_VIEW_COUNT_KEY);
237
                    itemMap.put(UNIQUE_VIEW_COUNT_KEY, ++count);
238
                }
239
                else {
240
                    itemMap.put(UNIQUE_VIEW_COUNT_KEY, 1l);
241
                }
242
                uniqueSet.add(uniqueKey);
243
            }
244
        }
245
    }
246
 
247
    private String getSource(String sessionId, String sourceKey) {
248
        if (sessionIdSourceMap.isEmpty()) {
249
            Query sessionQuery = new Query(KIND);
250
            sessionQuery.addFilter(EVENTTYPE_FILED, Query.FilterOperator.EQUAL,
251
                    NEW_SESSION_EVENT);
252
            sessionQuery.addFilter(DATE_FILED, Query.FilterOperator.GREATER_THAN_OR_EQUAL, fromDate);
253
            sessionQuery.addFilter(DATE_FILED, Query.FilterOperator.LESS_THAN, toDate);
254
 
255
            PreparedQuery sessionPq = datastore.prepare(sessionQuery);
256
            for (Entity sessionResult : sessionPq.asIterable()) {
257
                String firstSource = "";
258
                String sessionSource = "";
259
                if (sessionResult != null) {
260
                    if (sessionResult.hasProperty(FIRST_SOURCE_FILED)) {
261
                        firstSource = sessionResult.getProperty(FIRST_SOURCE_FILED).toString();
262
                    }
263
                    if (sessionResult.hasProperty(SESSION_SOURCE_FILED)) {
264
                        sessionSource = sessionResult.getProperty(SESSION_SOURCE_FILED).toString();
265
                    }
266
                }
267
                Map<String, String> sessionSourcesMap = new HashMap<String, String>();
268
                sessionSourcesMap.put(FIRST_SOURCE_KEY, firstSource);
269
                sessionSourcesMap.put(SESSION_SOURCE_KEY, sessionSource);
270
                sessionIdSourceMap.put(sessionId, sessionSourcesMap);
271
            }
272
        }
273
        if (sessionIdSourceMap.containsKey(sessionId)) {
274
            return sessionIdSourceMap.get(sessionId).get(sourceKey);
275
        }
276
        Query sessionQuery = new Query(KIND);
277
        sessionQuery.addFilter(EVENTTYPE_FILED, Query.FilterOperator.EQUAL,
278
                NEW_SESSION_EVENT);
279
        sessionQuery.addFilter(SESSION_ID_FILED, Query.FilterOperator.EQUAL, sessionId);
280
 
281
        PreparedQuery sessionPq = datastore.prepare(sessionQuery);
282
        for (Entity sessionResult : sessionPq.asIterable()) {
283
            String firstSource = "";
284
            String sessionSource = "";
285
            if (sessionResult != null) {
286
                if (sessionResult.hasProperty(FIRST_SOURCE_FILED)) {
287
                    firstSource = sessionResult.getProperty(FIRST_SOURCE_FILED).toString();
288
                }
289
                if (sessionResult.hasProperty(SESSION_SOURCE_FILED)) {
290
                    sessionSource = sessionResult.getProperty(SESSION_SOURCE_FILED).toString();
291
                }
292
            }
293
            Map<String, String> sessionSourcesMap = new HashMap<String, String>();
294
            sessionSourcesMap.put(FIRST_SOURCE_KEY, firstSource);
295
            sessionSourcesMap.put(SESSION_SOURCE_KEY, sessionSource);
296
            sessionIdSourceMap.put(sessionId, sessionSourcesMap);
297
        }
298
        if (sessionIdSourceMap.containsKey(sessionId)) {
299
            return sessionIdSourceMap.get(sessionId).get(sourceKey);
300
        }
301
        return "";
302
    }
303
 
304
    private void UpdateItemIdEventCount(String event, String countKey, String uniqueCountKey, boolean isCatalogIdEvent) {
305
        Query query = new Query(KIND);
306
        query.addFilter(EVENTTYPE_FILED, Query.FilterOperator.EQUAL, event);
307
        query.addFilter(DATE_FILED, Query.FilterOperator.GREATER_THAN_OR_EQUAL, fromDate);
308
        query.addFilter(DATE_FILED, Query.FilterOperator.LESS_THAN, toDate);
309
        PreparedQuery pq = datastore.prepare(query);
310
        Set<String> uniqueSet = new HashSet<String>();
311
        for (Entity result : pq.asIterable()) {
312
            String sessionId = (String)result.getProperty(SESSION_ID_FILED);
313
            String firstSource = getSource(sessionId, FIRST_SOURCE_KEY);
314
            String sessionSource = getSource(sessionId, SESSION_SOURCE_KEY);
315
            String paidFirstSource = "0";
316
            String paidSessionSource = "0";
317
            if (firstSource.startsWith("PAID :")) {
318
                paidFirstSource = "1";
319
            }
320
            if (sessionSource.startsWith("PAID :")) {
321
                paidSessionSource = "1";
322
            }
323
            firstSource = firstSource.replaceAll(".*http[s]?://", "").replaceAll("/.*", "");
324
            sessionSource = sessionSource.replaceAll(".*http[s]?://", "").replaceAll("/.*", "");
325
            List<Long> itemIds = null;
326
            if (!result.hasProperty(ITEMIDS_FILED)) {
327
                continue;
328
            }
329
            try {
330
                itemIds = (List<Long>)result.getProperty(ITEMIDS_FILED);
331
            } catch (ClassCastException e) {
332
                try {
333
                    itemIds = new ArrayList<Long>();
334
                    itemIds.add((Long)result.getProperty(ITEMIDS_FILED));
335
                }
336
                catch(Exception ex) {
337
                    log(e.getMessage());
338
                }
339
            }
340
 
341
            if (itemIds == null) {
342
                continue;
343
            }
344
            for (Long itemId : itemIds) {
345
                if (itemId == null) {
346
                    continue;
347
                }
348
                if (!isCatalogIdEvent) {
349
                    if (itemsMap.containsKey(itemId)) {
350
                        itemId = itemsMap.get(itemId).getCatalogId();
351
                    }
352
                }
353
                String key = paidFirstSource + "_" + firstSource + "_"
354
                    + paidSessionSource + "_" + sessionSource + "_"
355
                    + itemId;
356
                if (itemsResultMap.containsKey(key)) {
357
                    Map<String, Long> itemMap = itemsResultMap.get(key);
358
                    if (itemMap.containsKey(countKey)) {
359
                        Long count = itemMap.get(countKey);
360
                        itemMap.put(countKey, ++count);
361
                    }
362
                    else {
363
                        itemMap.put(countKey, 1l);
364
                    }
365
                }
366
                else {
367
                    Map<String, Long> itemMap = new HashMap<String, Long>();
368
                    itemMap.put(countKey, 1l);
369
                    itemsResultMap.put(key, itemMap);
370
                }
371
                String uniqueKey = sessionId + itemId;
372
                if (!uniqueSet.contains(uniqueKey)) {
373
                    Map<String, Long> itemMap = itemsResultMap.get(key);
374
                    if (itemMap.containsKey(uniqueCountKey)) {
375
                        Long count = itemMap.get(uniqueCountKey);
376
                        itemMap.put(uniqueCountKey, ++count);
377
                    }
378
                    else {
379
                        itemMap.put(uniqueCountKey, 1l);
380
                    }
381
                    uniqueSet.add(uniqueKey);
382
                }
383
            }
384
        }
385
    }
386
}